diff --git a/samples/react-pnpjs-spsite-er-diagram/.devcontainer/devcontainer.json b/samples/react-pnpjs-spsite-er-diagram/.devcontainer/devcontainer.json new file mode 100644 index 000000000..5c924ea0b --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/.devcontainer/devcontainer.json @@ -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.15.2", + "image": "docker.io/m365pnp/spfx:1.15.2", + // 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" +} \ No newline at end of file diff --git a/samples/react-pnpjs-spsite-er-diagram/.devcontainer/spfx-startup.sh b/samples/react-pnpjs-spsite-er-diagram/.devcontainer/spfx-startup.sh new file mode 100644 index 000000000..456d6aea8 --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/.devcontainer/spfx-startup.sh @@ -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**********" \ No newline at end of file diff --git a/samples/react-pnpjs-spsite-er-diagram/.eslintrc.js b/samples/react-pnpjs-spsite-er-diagram/.eslintrc.js new file mode 100644 index 000000000..6ebb2a10f --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/.eslintrc.js @@ -0,0 +1,378 @@ +require('@rushstack/eslint-config/patch/modern-module-resolution'); +module.exports = { + extends: ['@microsoft/eslint-config-spfx/lib/profiles/react'], + parserOptions: { tsconfigRootDir: __dirname }, + overrides: [ + { + files: ['*.ts', '*.tsx'], + parser: '@typescript-eslint/parser', + 'parserOptions': { + 'project': './tsconfig.json', + 'ecmaVersion': 2018, + 'sourceType': 'module' + }, + rules: { + // Prevent usage of the JavaScript null value, while allowing code to access existing APIs that may require null. https://www.npmjs.com/package/@rushstack/eslint-plugin + '@rushstack/no-new-null': 1, + // Require Jest module mocking APIs to be called before any other statements in their code block. https://www.npmjs.com/package/@rushstack/eslint-plugin + '@rushstack/hoist-jest-mock': 1, + // Require regular expressions to be constructed from string constants rather than dynamically building strings at runtime. https://www.npmjs.com/package/@rushstack/eslint-plugin-security + '@rushstack/security/no-unsafe-regexp': 1, + // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json + '@typescript-eslint/adjacent-overload-signatures': 1, + // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json + // + // CONFIGURATION: By default, these are banned: String, Boolean, Number, Object, Symbol + '@typescript-eslint/ban-types': [ + 1, + { + 'extendDefaults': false, + 'types': { + 'String': { + 'message': 'Use \'string\' instead', + 'fixWith': 'string' + }, + 'Boolean': { + 'message': 'Use \'boolean\' instead', + 'fixWith': 'boolean' + }, + 'Number': { + 'message': 'Use \'number\' instead', + 'fixWith': 'number' + }, + 'Object': { + 'message': 'Use \'object\' instead, or else define a proper TypeScript type:' + }, + 'Symbol': { + 'message': 'Use \'symbol\' instead', + 'fixWith': 'symbol' + }, + 'Function': { + 'message': 'The \'Function\' type accepts any function-like value.\nIt provides no type safety when calling the function, which can be a common source of bugs.\nIt also accepts things like class declarations, which will throw at runtime as they will not be called with \'new\'.\nIf you are expecting the function to accept certain arguments, you should explicitly define the function shape.' + } + } + } + ], + // RATIONALE: Code is more readable when the type of every variable is immediately obvious. + // Even if the compiler may be able to infer a type, this inference will be unavailable + // to a person who is reviewing a GitHub diff. This rule makes writing code harder, + // but writing code is a much less important activity than reading it. + // + // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json + '@typescript-eslint/explicit-function-return-type': [ + 1, + { + 'allowExpressions': true, + 'allowTypedFunctionExpressions': true, + 'allowHigherOrderFunctions': false + } + ], + // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json + // Rationale to disable: although this is a recommended rule, it is up to dev to select coding style. + // Set to 1 (warning) or 2 (error) to enable. + '@typescript-eslint/explicit-member-accessibility': 0, + // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json + '@typescript-eslint/no-array-constructor': 1, + // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json + // + // RATIONALE: The "any" keyword disables static type checking, the main benefit of using TypeScript. + // This rule should be suppressed only in very special cases such as JSON.stringify() + // where the type really can be anything. Even if the type is flexible, another type + // may be more appropriate such as "unknown", "{}", or "Record". + '@typescript-eslint/no-explicit-any': 1, + // RATIONALE: The #1 rule of promises is that every promise chain must be terminated by a catch() + // handler. Thus wherever a Promise arises, the code must either append a catch handler, + // or else return the object to a caller (who assumes this responsibility). Unterminated + // promise chains are a serious issue. Besides causing errors to be silently ignored, + // they can also cause a NodeJS process to terminate unexpectedly. + '@typescript-eslint/no-floating-promises': 2, + // RATIONALE: Catches a common coding mistake. + '@typescript-eslint/no-for-in-array': 2, + // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json + '@typescript-eslint/no-misused-new': 2, + // RATIONALE: The "namespace" keyword is not recommended for organizing code because JavaScript lacks + // a "using" statement to traverse namespaces. Nested namespaces prevent certain bundler + // optimizations. If you are declaring loose functions/variables, it's better to make them + // static members of a class, since classes support property getters and their private + // members are accessible by unit tests. Also, the exercise of choosing a meaningful + // class name tends to produce more discoverable APIs: for example, search+replacing + // the function "reverse()" is likely to return many false matches, whereas if we always + // write "Text.reverse()" is more unique. For large scale organization, it's recommended + // to decompose your code into separate NPM packages, which ensures that component + // dependencies are tracked more conscientiously. + // + // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json + '@typescript-eslint/no-namespace': [ + 1, + { + 'allowDeclarations': false, + 'allowDefinitionFiles': false + } + ], + // RATIONALE: Parameter properties provide a shorthand such as "constructor(public title: string)" + // that avoids the effort of declaring "title" as a field. This TypeScript feature makes + // code easier to write, but arguably sacrifices readability: In the notes for + // "@typescript-eslint/member-ordering" we pointed out that fields are central to + // a class's design, so we wouldn't want to bury them in a constructor signature + // just to save some typing. + // + // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json + // Set to 1 (warning) or 2 (error) to enable the rule + '@typescript-eslint/no-parameter-properties': 0, + // RATIONALE: When left in shipping code, unused variables often indicate a mistake. Dead code + // may impact performance. + // + // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json + '@typescript-eslint/no-unused-vars': [ + 1, + { + 'vars': 'all', + // Unused function arguments often indicate a mistake in JavaScript code. However in TypeScript code, + // the compiler catches most of those mistakes, and unused arguments are fairly common for type signatures + // that are overriding a base class method or implementing an interface. + 'args': 'none' + } + ], + // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json + '@typescript-eslint/no-use-before-define': [ + 2, + { + 'functions': false, + 'classes': true, + 'variables': true, + 'enums': true, + 'typedefs': true + } + ], + // Disallows require statements except in import statements. + // In other words, the use of forms such as var foo = require("foo") are banned. Instead use ES6 style imports or import foo = require("foo") imports. + '@typescript-eslint/no-var-requires': 'error', + // RATIONALE: The "module" keyword is deprecated except when describing legacy libraries. + // + // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json + '@typescript-eslint/prefer-namespace-keyword': 1, + // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json + // Rationale to disable: it's up to developer to decide if he wants to add type annotations + // Set to 1 (warning) or 2 (error) to enable the rule + '@typescript-eslint/no-inferrable-types': 0, + // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json + // Rationale to disable: declaration of empty interfaces may be helpful for generic types scenarios + '@typescript-eslint/no-empty-interface': 0, + // RATIONALE: This rule warns if setters are defined without getters, which is probably a mistake. + 'accessor-pairs': 1, + // RATIONALE: In TypeScript, if you write x["y"] instead of x.y, it disables type checking. + 'dot-notation': [ + 1, + { + 'allowPattern': '^_' + } + ], + // RATIONALE: Catches code that is likely to be incorrect + 'eqeqeq': 1, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'for-direction': 1, + // RATIONALE: Catches a common coding mistake. + 'guard-for-in': 2, + // RATIONALE: If you have more than 2,000 lines in a single source file, it's probably time + // to split up your code. + 'max-lines': ['warn', { max: 2000 }], + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-async-promise-executor': 2, + // RATIONALE: Deprecated language feature. + 'no-caller': 2, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-compare-neg-zero': 2, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-cond-assign': 2, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-constant-condition': 1, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-control-regex': 2, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-debugger': 1, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-delete-var': 2, + // RATIONALE: Catches code that is likely to be incorrect + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-duplicate-case': 2, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-empty': 1, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-empty-character-class': 2, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-empty-pattern': 1, + // RATIONALE: Eval is a security concern and a performance concern. + 'no-eval': 1, + // RATIONALE: Catches code that is likely to be incorrect + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-ex-assign': 2, + // RATIONALE: System types are global and should not be tampered with in a scalable code base. + // If two different libraries (or two versions of the same library) both try to modify + // a type, only one of them can win. Polyfills are acceptable because they implement + // a standardized interoperable contract, but polyfills are generally coded in plain + // JavaScript. + 'no-extend-native': 1, + // Disallow unnecessary labels + 'no-extra-label': 1, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-fallthrough': 2, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-func-assign': 1, + // RATIONALE: Catches a common coding mistake. + 'no-implied-eval': 2, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-invalid-regexp': 2, + // RATIONALE: Catches a common coding mistake. + 'no-label-var': 2, + // RATIONALE: Eliminates redundant code. + 'no-lone-blocks': 1, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-misleading-character-class': 2, + // RATIONALE: Catches a common coding mistake. + 'no-multi-str': 2, + // RATIONALE: It's generally a bad practice to call "new Thing()" without assigning the result to + // a variable. Either it's part of an awkward expression like "(new Thing()).doSomething()", + // or else implies that the constructor is doing nontrivial computations, which is often + // a poor class design. + 'no-new': 1, + // RATIONALE: Obsolete language feature that is deprecated. + 'no-new-func': 2, + // RATIONALE: Obsolete language feature that is deprecated. + 'no-new-object': 2, + // RATIONALE: Obsolete notation. + 'no-new-wrappers': 1, + // RATIONALE: Catches code that is likely to be incorrect + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-octal': 2, + // RATIONALE: Catches code that is likely to be incorrect + 'no-octal-escape': 2, + // RATIONALE: Catches code that is likely to be incorrect + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-regex-spaces': 2, + // RATIONALE: Catches a common coding mistake. + 'no-return-assign': 2, + // RATIONALE: Security risk. + 'no-script-url': 1, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-self-assign': 2, + // RATIONALE: Catches a common coding mistake. + 'no-self-compare': 2, + // RATIONALE: This avoids statements such as "while (a = next(), a && a.length);" that use + // commas to create compound expressions. In general code is more readable if each + // step is split onto a separate line. This also makes it easier to set breakpoints + // in the debugger. + 'no-sequences': 1, + // RATIONALE: Catches code that is likely to be incorrect + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-shadow-restricted-names': 2, + // RATIONALE: Obsolete language feature that is deprecated. + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-sparse-arrays': 2, + // RATIONALE: Although in theory JavaScript allows any possible data type to be thrown as an exception, + // such flexibility adds pointless complexity, by requiring every catch block to test + // the type of the object that it receives. Whereas if catch blocks can always assume + // that their object implements the "Error" contract, then the code is simpler, and + // we generally get useful additional information like a call stack. + 'no-throw-literal': 2, + // RATIONALE: Catches a common coding mistake. + 'no-unmodified-loop-condition': 1, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-unsafe-finally': 2, + // RATIONALE: Catches a common coding mistake. + 'no-unused-expressions': 1, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-unused-labels': 1, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-useless-catch': 1, + // RATIONALE: Avoids a potential performance problem. + 'no-useless-concat': 1, + // RATIONALE: The "var" keyword is deprecated because of its confusing "hoisting" behavior. + // Always use "let" or "const" instead. + // + // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json + 'no-var': 2, + // RATIONALE: Generally not needed in modern code. + 'no-void': 1, + // RATIONALE: Obsolete language feature that is deprecated. + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'no-with': 2, + // RATIONALE: Makes logic easier to understand, since constants always have a known value + // @typescript-eslint\eslint-plugin\dist\configs\eslint-recommended.js + 'prefer-const': 1, + // RATIONALE: Catches a common coding mistake where "resolve" and "reject" are confused. + 'promise/param-names': 2, + // RATIONALE: Catches code that is likely to be incorrect + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'require-atomic-updates': 2, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'require-yield': 1, + // "Use strict" is redundant when using the TypeScript compiler. + 'strict': [ + 2, + 'never' + ], + // RATIONALE: Catches code that is likely to be incorrect + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + 'use-isnan': 2, + // STANDARDIZED BY: eslint\conf\eslint-recommended.js + // Set to 1 (warning) or 2 (error) to enable. + // Rationale to disable: !!{} + 'no-extra-boolean-cast': 0, + // ==================================================================== + // @microsoft/eslint-plugin-spfx + // ==================================================================== + '@microsoft/spfx/import-requires-chunk-name': 1, + '@microsoft/spfx/no-require-ensure': 2, + '@microsoft/spfx/pair-react-dom-render-unmount': 1 + } + }, + { + // For unit tests, we can be a little bit less strict. The settings below revise the + // defaults specified in the extended configurations, as well as above. + files: [ + // Test files + '*.test.ts', + '*.test.tsx', + '*.spec.ts', + '*.spec.tsx', + + // Facebook convention + '**/__mocks__/*.ts', + '**/__mocks__/*.tsx', + '**/__tests__/*.ts', + '**/__tests__/*.tsx', + + // Microsoft convention + '**/test/*.ts', + '**/test/*.tsx' + ], + rules: { + 'no-new': 0, + 'class-name': 0, + 'export-name': 0, + forin: 0, + 'label-position': 0, + 'member-access': 2, + 'no-arg': 0, + 'no-console': 0, + 'no-construct': 0, + 'no-duplicate-variable': 2, + 'no-eval': 0, + 'no-function-expression': 2, + 'no-internal-module': 2, + 'no-shadowed-variable': 2, + 'no-switch-case-fall-through': 2, + 'no-unnecessary-semicolons': 2, + 'no-unused-expression': 2, + 'no-with-statement': 2, + semicolon: 2, + 'trailing-comma': 0, + typedef: 0, + 'typedef-whitespace': 0, + 'use-named-parameter': 2, + 'variable-name': 0, + whitespace: 0 + } + } + ] +}; \ No newline at end of file diff --git a/samples/react-pnpjs-spsite-er-diagram/.gitignore b/samples/react-pnpjs-spsite-er-diagram/.gitignore new file mode 100644 index 000000000..51ca7b9e7 --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/.gitignore @@ -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 diff --git a/samples/react-pnpjs-spsite-er-diagram/.npmignore b/samples/react-pnpjs-spsite-er-diagram/.npmignore new file mode 100644 index 000000000..ae0b487c0 --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/.npmignore @@ -0,0 +1,16 @@ +!dist +config + +gulpfile.js + +release +src +temp + +tsconfig.json +tslint.json + +*.log + +.yo-rc.json +.vscode diff --git a/samples/react-pnpjs-spsite-er-diagram/.yo-rc.json b/samples/react-pnpjs-spsite-er-diagram/.yo-rc.json new file mode 100644 index 000000000..707665e7c --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/.yo-rc.json @@ -0,0 +1,16 @@ +{ + "@microsoft/generator-sharepoint": { + "plusBeta": false, + "isCreatingSolution": true, + "version": "1.15.2", + "libraryName": "react-pnpjs-spsite-er-diagram", + "libraryId": "d0130471-1806-4c7d-a504-9af696d7ed0f", + "environment": "spo", + "packageManager": "npm", + "solutionName": "react-pnpjs-spsite-er-diagram", + "solutionShortDescription": "react-pnpjs-spsite-er-diagram description", + "skipFeatureDeployment": true, + "isDomainIsolated": false, + "componentType": "webpart" + } +} diff --git a/samples/react-pnpjs-spsite-er-diagram/README.md b/samples/react-pnpjs-spsite-er-diagram/README.md new file mode 100644 index 000000000..8eda0e315 --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/README.md @@ -0,0 +1,82 @@ +# SP Site ER Diagram + +## Summary + +This web part loads all lists on a site and display it in a Entity Relationship Diagram (ERD) using [GoJS](https://www.npmjs.com/package/gojs). + +![Best to create a AppPage with the webpart](assets/SPERasAppPage.png) +![ER Webpart in fullscreen](assets/SPERasAppPageFullScreen.png) + +## Compatibility + +![SPFx 1.14](https://img.shields.io/badge/SPFx-1.14-green.svg) +![Node.js v14 | v12](https://img.shields.io/badge/Node.js-v14%20%7C%20v12-green.svg) +![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg) +![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg "SharePoint Server 2019 requires SPFx 1.4.1 or lower") +![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1") +![Local Workbench Unsupported](https://img.shields.io/badge/Local%20Workbench-Unsupported-red.svg "Local workbench is no longer available as of SPFx 1.13 and above") +![Hosted Workbench Compatible](https://img.shields.io/badge/Hosted%20Workbench-Compatible-green.svg) +![Compatible with Remote Containers](https://img.shields.io/badge/Remote%20Containers-Compatible-green.svg) + +## Applies to + +* [SharePoint Framework](https://docs.microsoft.com/sharepoint/dev/spfx/sharepoint-framework-overview) +* [Microsoft 365 tenant](https://docs.microsoft.com/sharepoint/dev/spfx/set-up-your-development-environment) +> Get your own free development tenant by subscribing to [Microsoft 365 developer program](http://aka.ms/o365devprogram) + +## Solution + + +Solution|Author(s) +--------|--------- +react-pnpjs-spsite-er-diagram | [Niklas Wilhelm](https://github.com/ICTNiklasWilhelm) ([@NiklasWilhelm4](https://twitter.com/@NiklasWilhelm4)), NetForce 365 GmbH ([HubSite 365](https://www.hubsite365.com/) [@Hubsite365](https://twitter.com/@Hubsite365)) + +## Version history + +Version|Date|Comments +-------|----|-------- +1.0|October 07, 2022|Initial release + +## Minimal path to awesome + +* Clone this repository (or [download this solution as a .ZIP file](https://pnp.github.io/download-partial/?url=https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-pnpjs-spsite-er-diagram) then unzip it) +* From your command line, change your current directory to the directory containing this sample (`react-pnpjs-spsite-er-diagram`, 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 for further instructions. + +## Features + +This project can be used as a starting point for any visualization of SharePoint Data. Currently it's using GoJS as dependency for the ER Diagram (in productive environment you would need to get a license for it). The data layer is abstract so it's possible to use a different library (like three.js) as presentation layer. + +* the Data gets cached, to see changes made to the lists/lookups a "refresh" is needed +* alerts/warnings for the lists are displayed as well (Versioning/ItemCount/Threshholdlimit/..) +* easy opt/in/out of alerts and fields +* easy switch between Internal-/DisplayName +* Download current canvas as image + +## 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-pnpjs-spsite-er-diagram%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-pnpjs-spsite-er-diagram) 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-pnpjs-spsite-er-diagram&template=bug-report.yml&sample=react-pnpjs-spsite-er-diagram&authors=@YOURGITHUBUSERNAME&title=react-pnpjs-spsite-er-diagram%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-pnpjs-spsite-er-diagram&template=question.yml&sample=react-pnpjs-spsite-er-diagram&authors=@YOURGITHUBUSERNAME&title=react-pnpjs-spsite-er-diagram%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-pnpjs-spsite-er-diagram&template=suggestion.yml&sample=react-pnpjs-spsite-er-diagram&authors=@YOURGITHUBUSERNAME&title=react-pnpjs-spsite-er-diagram%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.** + + \ No newline at end of file diff --git a/samples/react-pnpjs-spsite-er-diagram/assets/SPERasAppPage.png b/samples/react-pnpjs-spsite-er-diagram/assets/SPERasAppPage.png new file mode 100644 index 000000000..fbfd21cdd Binary files /dev/null and b/samples/react-pnpjs-spsite-er-diagram/assets/SPERasAppPage.png differ diff --git a/samples/react-pnpjs-spsite-er-diagram/assets/SPERasAppPageFullScreen.png b/samples/react-pnpjs-spsite-er-diagram/assets/SPERasAppPageFullScreen.png new file mode 100644 index 000000000..b6ace00e3 Binary files /dev/null and b/samples/react-pnpjs-spsite-er-diagram/assets/SPERasAppPageFullScreen.png differ diff --git a/samples/react-pnpjs-spsite-er-diagram/assets/sample.json b/samples/react-pnpjs-spsite-er-diagram/assets/sample.json new file mode 100644 index 000000000..2c8d28fe9 --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/assets/sample.json @@ -0,0 +1,50 @@ +[ + { + "name": "pnp-sp-dev-spfx-web-parts-react-pnpjs-spsite-er-diagram", + "source": "pnp", + "title": "SP Site ER Diagram", + "shortDescription": "This web part loads all lists on a site and display it in a Entity Relationship Diagram (ERD)", + "url": "https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-pnpjs-spsite-er-diagram", + "downloadUrl": "https://pnp.github.io/download-partial/?url=https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-pnpjs-spsite-er-diagram", + "longDescription": [ + "This web part loads all lists on a site and display it in a Entity Relationship Diagram (ERD)" + ], + "creationDateTime": "2022-11-07", + "updateDateTime": "2022-11-07", + "products": [ + "SharePoint" + ], + "metadata": [ + { + "key": "CLIENT-SIDE-DEV", + "value": "React" + }, + { + "key": "SPFX-VERSION", + "value": "1.14" + } + ], + "thumbnails": [ + { + "type": "image", + "order": 100, + "url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-pnpjs-spsite-er-diagram/assets/YOUR-IMAGE-NAME-HERE", + "alt": "Web Part Preview" + } + ], + "authors": [ + { + "gitHubAccount": "ICTNiklasWilhelm", + "pictureUrl": "https://github.com/ICTNiklasWilhelm.png", + "name": "Niklas Wilhelm" + } + ], + "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" + } + ] + } +] \ No newline at end of file diff --git a/samples/react-pnpjs-spsite-er-diagram/config/config.json b/samples/react-pnpjs-spsite-er-diagram/config/config.json new file mode 100644 index 000000000..076b81f81 --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/config/config.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json", + "version": "2.0", + "bundles": { + "sp-site-er-diagram-web-part": { + "components": [ + { + "entrypoint": "./lib/webparts/spSiteErDiagram/SpSiteErDiagramWebPart.js", + "manifest": "./src/webparts/spSiteErDiagram/SpSiteErDiagramWebPart.manifest.json" + } + ] + } + }, + "externals": {}, + "localizedResources": { + "SpSiteErDiagramWebPartStrings": "lib/webparts/spSiteErDiagram/loc/{locale}.js" + } +} diff --git a/samples/react-pnpjs-spsite-er-diagram/config/deploy-azure-storage.json b/samples/react-pnpjs-spsite-er-diagram/config/deploy-azure-storage.json new file mode 100644 index 000000000..501f99cd0 --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/config/deploy-azure-storage.json @@ -0,0 +1,7 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json", + "workingDir": "./release/assets/", + "account": "", + "container": "react-pnpjs-spsite-er-diagram", + "accessKey": "" +} \ No newline at end of file diff --git a/samples/react-pnpjs-spsite-er-diagram/config/package-solution.json b/samples/react-pnpjs-spsite-er-diagram/config/package-solution.json new file mode 100644 index 000000000..7782a812d --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/config/package-solution.json @@ -0,0 +1,40 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json", + "solution": { + "name": "react-pnpjs-spsite-er-diagram-client-side-solution", + "id": "d0130471-1806-4c7d-a504-9af696d7ed0f", + "version": "1.0.0.0", + "includeClientSideAssets": true, + "skipFeatureDeployment": false, + "isDomainIsolated": false, + "developer": { + "name": "", + "websiteUrl": "", + "privacyUrl": "", + "termsOfUseUrl": "", + "mpnId": "Undefined-1.15.2" + }, + "metadata": { + "shortDescription": { + "default": "react-pnpjs-spsite-er-diagram description" + }, + "longDescription": { + "default": "react-pnpjs-spsite-er-diagram description" + }, + "screenshotPaths": [], + "videoUrl": "", + "categories": [] + }, + "features": [ + { + "title": "react-pnpjs-spsite-er-diagram Feature", + "description": "The feature that activates elements of the react-pnpjs-spsite-er-diagram solution.", + "id": "de94efbd-4c84-4259-8847-8ffd802d8166", + "version": "1.0.0.0" + } + ] + }, + "paths": { + "zippedPackage": "solution/react-pnpjs-spsite-er-diagram.sppkg" + } +} diff --git a/samples/react-pnpjs-spsite-er-diagram/config/serve.json b/samples/react-pnpjs-spsite-er-diagram/config/serve.json new file mode 100644 index 000000000..e05918a99 --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/config/serve.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/spfx-serve.schema.json", + "port": 4321, + "https": true, + "initialPage": "https://enter-your-SharePoint-site/_layouts/workbench.aspx" +} diff --git a/samples/react-pnpjs-spsite-er-diagram/config/write-manifests.json b/samples/react-pnpjs-spsite-er-diagram/config/write-manifests.json new file mode 100644 index 000000000..bad352605 --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/config/write-manifests.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json", + "cdnBasePath": "" +} \ No newline at end of file diff --git a/samples/react-pnpjs-spsite-er-diagram/gulpfile.js b/samples/react-pnpjs-spsite-er-diagram/gulpfile.js new file mode 100644 index 000000000..be2918708 --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/gulpfile.js @@ -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')); diff --git a/samples/react-pnpjs-spsite-er-diagram/package.json b/samples/react-pnpjs-spsite-er-diagram/package.json new file mode 100644 index 000000000..3ebcd7ccc --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/package.json @@ -0,0 +1,41 @@ +{ + "name": "react-pnpjs-spsite-er-diagram", + "version": "0.0.1", + "private": true, + "main": "lib/index.js", + "scripts": { + "build": "gulp bundle", + "clean": "gulp clean", + "test": "gulp test" + }, + "dependencies": { + "@microsoft/sp-core-library": "1.15.2", + "@microsoft/sp-lodash-subset": "1.15.2", + "@microsoft/sp-office-ui-fabric-core": "1.15.2", + "@microsoft/sp-property-pane": "1.15.2", + "@microsoft/sp-webpart-base": "1.15.2", + "@pnp/graph": "^3.7.0", + "@pnp/sp": "^3.7.0", + "gojs": "^2.2.15", + "gojs-react": "^1.1.1", + "office-ui-fabric-react": "7.185.7", + "react": "16.13.1", + "react-dom": "16.13.1", + "tslib": "2.3.1" + }, + "devDependencies": { + "@microsoft/rush-stack-compiler-4.5": "0.2.2", + "@rushstack/eslint-config": "2.5.1", + "@microsoft/eslint-plugin-spfx": "1.15.2", + "@microsoft/eslint-config-spfx": "1.15.2", + "@microsoft/sp-build-web": "1.15.2", + "@types/webpack-env": "~1.15.2", + "ajv": "^6.12.5", + "gulp": "4.0.2", + "typescript": "4.5.5", + "@types/react": "16.9.51", + "@types/react-dom": "16.9.8", + "eslint-plugin-react-hooks": "4.3.0", + "@microsoft/sp-module-interfaces": "1.15.2" + } +} diff --git a/samples/react-pnpjs-spsite-er-diagram/src/index.ts b/samples/react-pnpjs-spsite-er-diagram/src/index.ts new file mode 100644 index 000000000..fb81db1e2 --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/src/index.ts @@ -0,0 +1 @@ +// A file is required to be in the root of the /src directory by the TypeScript compiler diff --git a/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/SpSiteErDiagramWebPart.manifest.json b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/SpSiteErDiagramWebPart.manifest.json new file mode 100644 index 000000000..2a595dfad --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/SpSiteErDiagramWebPart.manifest.json @@ -0,0 +1,28 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json", + "id": "44b6930e-0410-456c-b551-d998f4e7279c", + "alias": "SpSiteErDiagramWebPart", + "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": "SPSite ER Diagram" }, + "description": { "default": "SPSite ER Diagram description" }, + "officeFabricIconFontName": "Page", + "properties": { + "description": "SPSite ER Diagram" + } + }] +} diff --git a/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/SpSiteErDiagramWebPart.ts b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/SpSiteErDiagramWebPart.ts new file mode 100644 index 000000000..4c75a2433 --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/SpSiteErDiagramWebPart.ts @@ -0,0 +1,100 @@ +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 'SpSiteErDiagramWebPartStrings'; +import SpSiteErDiagram, { ISpSiteDiagramProps } from './components/SpSiteErDiagram'; + +export interface ISpSiteErDiagramWebPartProps { + description: string; +} + +export default class SpSiteErDiagramWebPart extends BaseClientSideWebPart { + + private _isDarkTheme: boolean = false; + private _environmentMessage: string = ''; + + + public render(): void { + const element: React.ReactElement = React.createElement( + SpSiteErDiagram, + { + context: this.context, + //description: this.properties.description, + //isDarkTheme: this._isDarkTheme, + //environmentMessage: this._environmentMessage, + //hasTeamsContext: !!this.context.sdks.microsoftTeams, + //userDisplayName: this.context.pageContext.user.displayName + } + ); + ReactDom.render(element, this.domElement); + } + + protected onInit(): Promise { + this._environmentMessage = this._getEnvironmentMessage(); + + return super.onInit(); + } + + private _getEnvironmentMessage(): string { + if (!!this.context.sdks.microsoftTeams) { // running in Teams + return this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentTeams : strings.AppTeamsTabEnvironment; + } + + return this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentSharePoint : strings.AppSharePointEnvironment; + } + + protected onThemeChanged(currentTheme: IReadonlyTheme | undefined): void { + if (!currentTheme) { + return; + } + + this._isDarkTheme = !!currentTheme.isInverted; + const { + semanticColors + } = currentTheme; + + if (semanticColors) { + this.domElement.style.setProperty('--bodyText', semanticColors.bodyText || null); + this.domElement.style.setProperty('--link', semanticColors.link || null); + this.domElement.style.setProperty('--linkHovered', semanticColors.linkHovered || null); + } + + } + + protected onDispose(): void { + ReactDom.unmountComponentAtNode(this.domElement); + } + + protected get dataVersion(): Version { + return Version.parse('1.0'); + } + + protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { + return { + pages: [ + { + header: { + description: strings.PropertyPaneDescription + }, + groups: [ + { + groupName: strings.BasicGroupName, + groupFields: [ + PropertyPaneTextField('description', { + label: strings.DescriptionFieldLabel + }) + ] + } + ] + } + ] + }; + } +} diff --git a/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/assets/welcome-dark.png b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/assets/welcome-dark.png new file mode 100644 index 000000000..42f0b8d24 Binary files /dev/null and b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/assets/welcome-dark.png differ diff --git a/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/assets/welcome-light.png b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/assets/welcome-light.png new file mode 100644 index 000000000..69eb3b48c Binary files /dev/null and b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/assets/welcome-light.png differ diff --git a/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/components/SpSiteErDiagram.module.scss b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/components/SpSiteErDiagram.module.scss new file mode 100644 index 000000000..4f042c29d --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/components/SpSiteErDiagram.module.scss @@ -0,0 +1,40 @@ +@import '~office-ui-fabric-react/dist/sass/References.scss'; + +.spSiteErDiagram { + overflow: hidden; + padding: 1em; + color: "[theme:bodyText, default: #323130]"; + color: var(--bodyText); + &.teams { + font-family: $ms-font-family-fallbacks; + } + + :global { + .diagram-component { + height: 100% + } + } +} + +.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 + } + } +} \ No newline at end of file diff --git a/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/components/SpSiteErDiagram.tsx b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/components/SpSiteErDiagram.tsx new file mode 100644 index 000000000..10d7358ef --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/components/SpSiteErDiagram.tsx @@ -0,0 +1,84 @@ +import * as React from 'react'; +import styles from './SpSiteErDiagram.module.scss'; +import { ReactDiagram } from 'gojs-react'; +import getSPSiteData from './helpers/SPSiteData'; +import { initDiagram } from './helpers/GoJSHelper'; +import getGoJSNodesFromSPSiteData from './helpers/SPSiteDataToGoJSER'; +import { CommandBar, ProgressIndicator } from 'office-ui-fabric-react'; +import { WebPartContext } from '@microsoft/sp-webpart-base'; + +export interface ISpSiteDiagramProps { + context: WebPartContext +} +const SpSiteErDiagram: React.FC = (props: ISpSiteDiagramProps) => { + // Refs + const diagramRef = React.useRef(); + // State: Data + const [loadingProgress, setLoadingProgress] = React.useState(0); + const [nodeDataArray, setNodeDataArray] = React.useState([]); + const [linkDataArray, setLinkDataArray] = React.useState([]); + // State: Options + const [optionRelationOnly, setOptionRelationOnly] = React.useState(true); + const [useInternalName, setUseInternalName] = React.useState(true); + const [alertsActive, setAlertsActive] = React.useState(true); + const [fieldsActive, setFieldsActive] = React.useState(true); + + const loadDiagram = async (refresh: boolean):Promise => { + if(refresh) { setLoadingProgress(0); setNodeDataArray([]); } + // Get SP SiteData for ER Diagram + const spSiteData = await getSPSiteData(props.context, refresh, (progress) => {setLoadingProgress(progress);}); + console.log("SPSiteData", spSiteData); + // Transform to GoJS Model + const goJSNodes = getGoJSNodesFromSPSiteData(spSiteData, useInternalName ? "name" : "displayName", alertsActive, fieldsActive); + // Set State + setNodeDataArray(goJSNodes.nodeDataArray.filter((n) => + optionRelationOnly && goJSNodes.linkDataArray.some(l => l.from === n.key || l.to === n.key) || !optionRelationOnly // Filter optionRelationOnly + )); + setLinkDataArray(goJSNodes.linkDataArray); + } + + // "ComponentDitMount" + React.useEffect(() => { + loadDiagram(false); + }, [optionRelationOnly, useInternalName, alertsActive, fieldsActive]); + + const downloadAsImage = ():void => { + if(diagramRef && diagramRef.current) { + const canvas = (diagramRef.current as any).divRef.current.firstChild; + console.log((diagramRef.current as any).divRef.current); + const link = document.createElement('a'); + link.download = props.context.pageContext.web.title + '_ERDiagram.png'; + link.href = canvas.toDataURL() + link.click(); + } + } + + return ( +
+ { loadDiagram(true); }}, + {key: '2', text: 'Only lists with relations', iconProps: { iconName: optionRelationOnly ? 'CheckboxComposite' : 'Checkbox' }, onClick: () => { setOptionRelationOnly(!optionRelationOnly); }}, + {key: '2', text: 'Show alerts', iconProps: { iconName: alertsActive ? 'CheckboxComposite' : 'Checkbox' }, onClick: () => { setAlertsActive(!alertsActive); }}, + {key: '2', text: 'Show fields', iconProps: { iconName: fieldsActive ? 'CheckboxComposite' : 'Checkbox' }, onClick: () => { setFieldsActive(!fieldsActive); }}, + {key: '3', text: useInternalName ? "InternalName" : "DisplayName", iconProps: { iconName: useInternalName ? 'ToggleLeft' : 'ToggleRight' }, onClick: () => { setUseInternalName(!useInternalName); }}, + {key: '4', text: "Download as image", iconProps: { iconName: 'Share' }, onClick: () => { downloadAsImage() }} + ]} /> +
+ { loadingProgress !== 100 && nodeDataArray.length === 0 ? +
+ +
: + + } +
+
+ ); +} + +export default SpSiteErDiagram; diff --git a/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/components/helpers/GoJSHelper.ts b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/components/helpers/GoJSHelper.ts new file mode 100644 index 000000000..6fbf9e59f --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/components/helpers/GoJSHelper.ts @@ -0,0 +1,147 @@ +import * as go from 'gojs'; + +export const initDiagram = () => { + const $ = go.GraphObject.make; + + const diagram = $(go.Diagram, // must name or refer to the DIV HTML element + { + allowDelete: false, + allowCopy: false, + initialAutoScale: go.Diagram.Uniform, + layout: $(go.ForceDirectedLayout), + model: $(go.GraphLinksModel, + { + linkKeyProperty: 'key', // IMPORTANT! must be defined for merges and data sync when using GraphLinksModel + // positive keys for nodes + makeUniqueKeyFunction: (m: go.Model, data: any) => { + let k = data.key || 1; + while (m.findNodeDataForKey(k)) k++; + data.key = k; + return k; + }, + // negative keys for links + makeUniqueLinkKeyFunction: (m: go.GraphLinksModel, data: any) => { + let k = data.key || -1; + while (m.findLinkDataForKey(k)) k--; + data.key = k; + return k; + } + }), + "undoManager.isEnabled": true + }); + + diagram.nodeTemplate = + $(go.Node, 'Auto', // the Shape will go around the TextBlock + $(go.Shape, 'RoundedRectangle', { strokeWidth: 0, fill: 'white' }, + // Shape.fill is bound to Node.data.color + new go.Binding('fill', 'color')), + $(go.TextBlock, + { margin: 8 }, // some room around the text + // TextBlock.text is bound to Node.data.key + new go.Binding('text', 'key')) + ); + + // the template for each attribute in a node's array of item data + var itemTempl = + $(go.Panel, "Horizontal", + $(go.Shape, + { desiredSize: new go.Size(15, 15), strokeJoin: "round", strokeWidth: 3, stroke: null, margin: 2 }, + new go.Binding("figure", "figure"), + new go.Binding("fill", "color"), + new go.Binding("stroke", "color")), + $(go.TextBlock, + { + stroke: "#333333", + font: "bold 14px sans-serif" + }, + new go.Binding("text", "name")) + ); + + + // define the Node template, representing an entity + diagram.nodeTemplate = + $(go.Node, "Auto", // the whole node panel + { + selectionAdorned: true, + resizable: true, + layoutConditions: go.Part.LayoutStandard & ~go.Part.LayoutNodeSized, + fromSpot: go.Spot.AllSides, + toSpot: go.Spot.AllSides, + isShadowed: true, + shadowOffset: new go.Point(3, 3), + shadowColor: "#C5C1AA" + }, + new go.Binding("location", "location").makeTwoWay(), + // whenever the PanelExpanderButton changes the visible property of the "LIST" panel, + // clear out any desiredSize set by the ResizingTool. + new go.Binding("desiredSize", "visible", v => new go.Size(NaN, NaN)).ofObject("LIST"), + // define the node's outer shape, which will surround the Table + $(go.Shape, "RoundedRectangle", + { fill: 'white', stroke: "#eeeeee", strokeWidth: 3 }), + $(go.Panel, "Table", + { margin: 8, stretch: go.GraphObject.Fill }, + $(go.RowColumnDefinition, { row: 0, sizing: go.RowColumnDefinition.None }), + // the table header + $(go.TextBlock, + { + row: 0, alignment: go.Spot.Center, + margin: new go.Margin(0, 24, 0, 2), // leave room for Button + font: "bold 16px sans-serif" + }, + new go.Binding("text", "key")), + // the collapse/expand button + $("PanelExpanderButton", "LIST", // the name of the element whose visibility this button toggles + { row: 0, alignment: go.Spot.TopRight }), + // the list of Panels, each showing an attribute + $(go.Panel, "Vertical", + { + name: "LIST", + row: 1, + padding: 3, + alignment: go.Spot.TopLeft, + defaultAlignment: go.Spot.Left, + stretch: go.GraphObject.Horizontal, + itemTemplate: itemTempl + }, + new go.Binding("itemArray", "items")) + ) // end Table Panel + ); // end Node + + // define the Link template, representing a relationship + diagram.linkTemplate = + $(go.Link, // the whole link panel + { + selectionAdorned: true, + layerName: "Foreground", + reshapable: true, + routing: go.Link.AvoidsNodes, + corner: 5, + curve: go.Link.JumpOver + }, + $(go.Shape, // the link shape + { stroke: "#303B45", strokeWidth: 2.5 }), + $(go.TextBlock, // the "from" label + { + textAlign: "center", + font: "bold 16px sans-serif", + stroke: "#333333", + segmentIndex: 0, + segmentOffset: new go.Point(NaN, NaN), + segmentOrientation: go.Link.OrientUpright + }, + new go.Binding("text", "text")), + $(go.TextBlock, // the "to" label + { + textAlign: "center", + font: "bold 16px sans-serif", + stroke: "#333333", + segmentIndex: -1, + segmentOffset: new go.Point(NaN, NaN), + segmentOrientation: go.Link.OrientUpright + }, + new go.Binding("text", "toText")) + ); + + + return diagram; +} \ No newline at end of file diff --git a/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/components/helpers/SPSiteData.ts b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/components/helpers/SPSiteData.ts new file mode 100644 index 000000000..5b27c375a --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/components/helpers/SPSiteData.ts @@ -0,0 +1,127 @@ +/* + Hit 'ctrl + d' or 'cmd + d' to run the code, view console for results +*/ +import { spfi, SPFx } from "@pnp/sp"; +import "@pnp/sp/webs"; +import "@pnp/sp/lists/web"; +import "@pnp/sp/fields"; + +export interface SPSiteData { + tables: SPTable[], + relations: SPRelation[] +} +export interface SPTable { + id: string, + title: string, + fields: SPTableField[], + alerts: SPTableAlert[] +} +export interface SPTableField { + name: string, + displayName: string, + iskey: boolean, + isunique: boolean, + type: string +} +export interface SPTableAlert { + type: "Warning" | "Error" | "Info", + title: string, +} +export interface SPRelation { + fromTableTitle: string, + toTableTitle: string, + fromX: number | "n", + toX: number | "m" +} +const storageKey = "reactpnpjsdiagram_sitegraphdata" +const getSPSiteData = async (spfxContext: any, force?: boolean, progress?: (number: number) => void) : Promise => { + + // return from cache + let spSiteDataFromCache = JSON.parse(localStorage.getItem(storageKey)); + if (spSiteDataFromCache && !force) { + progress(100); + return spSiteDataFromCache; + } + + // Load from site + const spSiteData: SPSiteData = { + relations: [], + tables: [] + } + const tmp_listNames: any = {}; + + const sp = spfi().using(SPFx(spfxContext)); + const lists = await sp.web.lists.filter("Hidden ne 1")(); + + const totalCount = lists.filter(l => !l.Hidden).length; + let loadedCount = 0; + + for(const list of lists) { + if(!list.Hidden) { + loadedCount++; + progress && progress(loadedCount/totalCount * 100); + + // save names for later + tmp_listNames[`{${list.Id.toLocaleLowerCase()}}`] = list.Title; + + // Tables/Lists + const table: SPTable = { id: list.Id, title: list.Title, fields: [], alerts: [] }; + // Fields + const fields = (await sp.web.lists.getById(list.Id).fields.filter("Hidden ne 1")()) + .filter(f => !f.Hidden && (f as any).LookupList !== "AppPrincipals" && + ((f as any).CanBeDeleted || (f as any).InternalName === "Title" || (f as any).InternalName === "Id") + ) + //.sort((a,b) => a.InternalName.charCodeAt(0) - b.InternalName.charCodeAt(0) ); + table.fields = fields.map(f => { + f.InternalName.indexOf("_") > -1 && console.log(f); + return { + name: f.InternalName, + displayName: f.Title, + iskey: (f as any).TypeDisplayName === "Lookup" && (f as any).IsRelationship && (f as any).LookupList !== '' && (f as any).LookupList !== "AppPrincipals", + isunique: f.EnforceUniqueValues, + type: f.TypeDisplayName + } + }); + + // Table Alerts + list.ItemCount > 3500 && list.ItemCount < 5000 && table.alerts.push({ title: `Itemcount (${list.ItemCount}) will reach soon 5k => check if all necessary columns are indexed !!`, type:"Error" }); + list.ItemCount > 5000 && table.alerts.push({ title: `Itemcount (${list.ItemCount}) > 5k. Filter or sorting might not work anymore`, type:"Error" }); + !list.EnableVersioning && table.alerts.push({ title: "no versioning activated", type: "Warning" }); + list.MajorVersionLimit && list.MajorVersionLimit > 100 && table.alerts.push({ title: `high max. version limit (${list.MajorVersionLimit})`, type: "Warning" }); + // Infos + table.alerts.push({ title: `Crawling is ${list.NoCrawl ? 'inactive' : 'active'}`, type:"Info" }); + table.alerts.push({ title: `Item Count: ${list.ItemCount}`, type:"Info" }); + table.alerts.push({ title: `ContentTypes ${list.ContentTypesEnabled ? 'enabled' : 'disabled'}`, type:"Info" }); + + // add Table + spSiteData.tables.push(table); + + // Links/Lookups + const relations: SPRelation[] = fields.filter(f => f.TypeDisplayName === "Lookup" && + (f as any).IsRelationship && + (f as any).LookupList !== '' && (f as any).LookupList !== "AppPrincipals" + ).map(f => + { + return { + fromTableTitle: list.Title, + toTableTitle: (f as any).LookupList!, + fromX: "n", + toX: 1 + } + }); + + spSiteData.relations = [...spSiteData.relations, ...relations]; + } + } + + // resolve Ids + console.log("tmp_listNames",tmp_listNames); + console.log("asd", [...spSiteData.relations]); + spSiteData.relations = spSiteData.relations.map((r) => {return {...r, toTableTitle: tmp_listNames[r.toTableTitle.toLocaleLowerCase()]}}) + + localStorage.setItem(storageKey, JSON.stringify(spSiteData)); + + return spSiteData +} + +export default getSPSiteData; \ No newline at end of file diff --git a/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/components/helpers/SPSiteDataToGoJSER.ts b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/components/helpers/SPSiteDataToGoJSER.ts new file mode 100644 index 000000000..73fd1aa85 --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/components/helpers/SPSiteDataToGoJSER.ts @@ -0,0 +1,101 @@ +import { List } from "@pnp/sp/lists"; +import { SPSiteData, SPTableAlert, SPTableField } from "./SPSiteData"; + + +const colors = { + 'red': '#be4b15', + 'green': '#52ce60', + 'blue': '#186ddf', + 'lightred': '#fd8852', + 'lightblue': '#afd4fe', + 'lightgreen': '#b9e986', + 'pink': '#f31eaf', + 'darkPink': '#7c158a', + 'purple': '#881798', + 'orange': '#fddb01', + 'keycolor': '#fdb400', +} +const configByFieldType: any = { + 'default': { color: colors.purple, figure: "Ellipse" }, + 'Lookup': { color: colors.purple, figure: "TriangleLeft" }, + 'Counter': { color: colors.keycolor, figure: "Diamond" }, + "Attachments": { color: colors.blue, figure: "Circle" }, + "Person or Group": { color: colors.green, figure: "Circle" }, + "Single line of text": { color: colors.blue, figure: "Circle" }, + "Multiple lines of text": { color: colors.blue, figure: "Circle" }, + "Computed": { color: colors.blue, figure: "Circle" }, + "Date and Time": { color: colors.pink, figure: "Circle" }, + "Choice": { color: colors.blue, figure: "Circle" }, + "Number": { color: colors.darkPink, figure: "Circle" }, + "Hyperlink or Picture": { color: colors.blue, figure: "Circle" } +} +const getNodeItemFromField = (f: SPTableField, fieldNameProperty: string = "name") : GoJSNodeItem => { + const c = configByFieldType[f.type] || configByFieldType['default']; + const prefix = f.type === "Counter" ? "PK | " : (f.iskey && f.type === "Lookup" ? "FK | " : ""); + return { + name: prefix + (f as any)[fieldNameProperty] + ` (${f.type})`, + iskey: f.iskey, + figure: c.figure, + color: f.iskey ? colors.keycolor : c.color, + order: f.type === "Counter" ? "1" : + f.type === "Lookup" && f.iskey ? "2" : + f.type === "Lookup" ? "3" : + f.type + }; +} +const configByAlert = { + 'Info': { color: colors.lightblue, figure: "Rectangle" }, + 'Warning': { color: colors.orange, figure: "Rectangle" }, + 'Error': { color: colors.red, figure: "Rectangle" }, +} +const getNodeItemFromAlert = (a: SPTableAlert) : GoJSNodeItem => { + const c = configByAlert[a.type]; + return { + name: "#" + a.type + " | " + a.title, + iskey: false, + figure: c.figure, + color: c.color, + order: "#" + }; +} + +export interface GoJSNode { + key: string, + items: GoJSNodeItem[] +} +export interface GoJSNodeItem { + order: string, + name: string, + iskey: boolean, + figure: string, + color: string +} +export interface GoJSLink { + from: string, + to: string, + text: string, + toText: string +} +const getGoJSNodesFromSPSiteData = (spSiteData: SPSiteData, fieldNameProperty: string = "name", alertsActive = true, fieldsActive = true) : { nodeDataArray: GoJSNode[], linkDataArray: GoJSLink[] } => { + + let nodeDataArray: GoJSNode[] = []; + let linkDataArray: GoJSLink[] = []; + + nodeDataArray = spSiteData.tables.map(t => { return { + key: t.title, + items: [ + ...(alertsActive ? t.alerts.map(a => getNodeItemFromAlert(a)) : []), + ...(fieldsActive ? t.fields.map(f => getNodeItemFromField(f, fieldNameProperty)) : []) + ].sort((a,b) => a.order.charCodeAt(0) - b.order.charCodeAt(0)) + }}) + + linkDataArray = spSiteData.relations.map(r => { return { + from: r.fromTableTitle, + to: r.toTableTitle, + text: r.fromX+":"+r.toX, + toText: "1" + }}) + + return { nodeDataArray, linkDataArray } +} +export default getGoJSNodesFromSPSiteData; \ No newline at end of file diff --git a/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/loc/en-us.js b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/loc/en-us.js new file mode 100644 index 000000000..7efbd643f --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/loc/en-us.js @@ -0,0 +1,11 @@ +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", + "AppSharePointEnvironment": "The app is running on SharePoint page", + "AppTeamsTabEnvironment": "The app is running in Microsoft Teams" + } +}); \ No newline at end of file diff --git a/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/loc/mystrings.d.ts b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/loc/mystrings.d.ts new file mode 100644 index 000000000..c9a0e40f7 --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/src/webparts/spSiteErDiagram/loc/mystrings.d.ts @@ -0,0 +1,14 @@ +declare interface ISpSiteErDiagramWebPartStrings { + PropertyPaneDescription: string; + BasicGroupName: string; + DescriptionFieldLabel: string; + AppLocalEnvironmentSharePoint: string; + AppLocalEnvironmentTeams: string; + AppSharePointEnvironment: string; + AppTeamsTabEnvironment: string; +} + +declare module 'SpSiteErDiagramWebPartStrings' { + const strings: ISpSiteErDiagramWebPartStrings; + export = strings; +} diff --git a/samples/react-pnpjs-spsite-er-diagram/teams/44b6930e-0410-456c-b551-d998f4e7279c_color.png b/samples/react-pnpjs-spsite-er-diagram/teams/44b6930e-0410-456c-b551-d998f4e7279c_color.png new file mode 100644 index 000000000..0e1f764fa Binary files /dev/null and b/samples/react-pnpjs-spsite-er-diagram/teams/44b6930e-0410-456c-b551-d998f4e7279c_color.png differ diff --git a/samples/react-pnpjs-spsite-er-diagram/teams/44b6930e-0410-456c-b551-d998f4e7279c_outline.png b/samples/react-pnpjs-spsite-er-diagram/teams/44b6930e-0410-456c-b551-d998f4e7279c_outline.png new file mode 100644 index 000000000..892868fab Binary files /dev/null and b/samples/react-pnpjs-spsite-er-diagram/teams/44b6930e-0410-456c-b551-d998f4e7279c_outline.png differ diff --git a/samples/react-pnpjs-spsite-er-diagram/tsconfig.json b/samples/react-pnpjs-spsite-er-diagram/tsconfig.json new file mode 100644 index 000000000..cb3c4af63 --- /dev/null +++ b/samples/react-pnpjs-spsite-er-diagram/tsconfig.json @@ -0,0 +1,37 @@ +{ + "extends": "./node_modules/@microsoft/rush-stack-compiler-4.5/includes/tsconfig-web.json", + "compilerOptions": { + "target": "es5", + "forceConsistentCasingInFileNames": true, + "module": "esnext", + "moduleResolution": "node", + "jsx": "react", + "declaration": true, + "sourceMap": true, + "experimentalDecorators": true, + "skipLibCheck": true, + "outDir": "lib", + "inlineSources": false, + "strictNullChecks": false, + "noUnusedLocals": false, + "noImplicitAny": true, + + "typeRoots": [ + "./node_modules/@types", + "./node_modules/@microsoft" + ], + "types": [ + "webpack-env" + ], + "lib": [ + "es5", + "dom", + "es2015.collection", + "es2015.promise" + ] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx" + ] +}