Renamed folder, fixed minor typos, gulpfile, container

This commit is contained in:
Hugo Bernier 2023-09-19 09:38:49 -04:00
parent 87eacf5190
commit e80ea2b9d3
34 changed files with 24605 additions and 24401 deletions

View File

@ -1,29 +0,0 @@
'use strict';
// check if gulp dist was called
if (process.argv.indexOf('dist') !== -1) {
// add ship options to command call
process.argv.push('--ship');
}
const path = require('path');
const gulp = require('gulp');
const build = require('@microsoft/sp-build-web');
const gulpSequence = require('gulp-sequence');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
// Create clean distrubution package
gulp.task('dist', gulpSequence('clean', 'bundle', 'package-solution'));
// Create clean development package
gulp.task('dev', gulpSequence('clean', 'bundle', 'package-solution'));
/**
* Custom Framework Specific gulp tasks
*/
build.tslintCmd.enabled = false
build.initialize(gulp);

View File

@ -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.13.1",
"image": "docker.io/m365pnp/spfx:1.13.1",
// 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"
}

View File

@ -0,0 +1,33 @@
echo
echo -e "\e[1;94mInstalling Node dependencies\e[0m"
npm install
## commands to create dev certificate and copy it to the root folder of the project
echo
echo -e "\e[1;94mGenerating dev certificate\e[0m"
gulp trust-dev-cert
# Convert the generated PEM certificate to a CER certificate
openssl x509 -inform PEM -in ~/.rushstack/rushstack-serve.pem -outform DER -out ./spfx-dev-cert.cer
# Copy the PEM ecrtificate for non-Windows hosts
cp ~/.rushstack/rushstack-serve.pem ./spfx-dev-cert.pem
## add *.cer to .gitignore to prevent certificates from being saved in repo
if ! grep -Fxq '*.cer' ./.gitignore
then
echo "# .CER Certificates" >> .gitignore
echo "*.cer" >> .gitignore
fi
## add *.pem to .gitignore to prevent certificates from being saved in repo
if ! grep -Fxq '*.pem' ./.gitignore
then
echo "# .PEM Certificates" >> .gitignore
echo "*.pem" >> .gitignore
fi
echo
echo -e "\e[1;92mReady!\e[0m"
echo -e "\n\e[1;94m**********\nOptional: if you plan on using gulp serve, don't forget to add the container certificate to your local machine. Please visit https://aka.ms/spfx-devcontainer for more information\n**********"

View File

@ -0,0 +1 @@
v14.21.2

View File

@ -1,22 +1,21 @@
# Advanced IFrame Webpart
# Advanced IFrame web part
## Summary
This webpart allows users to add a webpage in an iframe to a modern SharePoint page.
This web part allows users to add a webpage in an IFrame to a modern SharePoint page.
Main features include:
- The webpart can be embedded in a "Full-Width" section.
- The webpart only allows pages to be embedded that have been added to the "Allow external iframes" in "HTML Field Security"
- The webpart resizes the iframe to automatically fit the given space on the page. It keeps the aspect ratio.
- The webpart can add additional dynamic parameters to the iframe url. These parameters include
- Color codes of the current color scheme
- Query string parameters
- Information about the logged in user
- Information about the current page and site
![Advanced Iframe Webpart](./images/iframewebpart.png)
- The web part can be embedded in a "Full-Width" section.
- The web part only allows pages to be embedded that have been added to the "Allow external iframes" in "HTML Field Security"
- The web part resizes the IFrame to automatically fit the given space on the page. It keeps the aspect ratio.
- The web part can add additional dynamic parameters to the IFrame URL. These parameters include
- Color codes of the current color scheme
- Query string parameters
- Information about the logged in user
- Information about the current page and site
![Advanced IFrame web part](./images/iframeweb part.png)
## Compatibility
@ -39,13 +38,12 @@ Tested with: Node.js v14.21.2
## Applies to
* [SharePoint Framework](https://learn.microsoft.com/sharepoint/dev/spfx/sharepoint-framework-overview)
* [Microsoft 365 tenant](https://learn.microsoft.com/sharepoint/dev/spfx/set-up-your-development-environment)
- [SharePoint Framework](https://learn.microsoft.com/sharepoint/dev/spfx/sharepoint-framework-overview)
- [Microsoft 365 tenant](https://learn.microsoft.com/sharepoint/dev/spfx/set-up-your-development-environment)
## Contributors
* [Sven Sieverding](https://github.com/365knoten)
- [Sven Sieverding](https://github.com/365knoten)
## Version history
@ -68,7 +66,8 @@ Version|Date|Comments
- `gulp package-solution --ship`
### Create a sample PowerApp to test the functions
First create a new canvas app, then set "Screen1.Fill" to
First create a new canvas app, then set "Screen1.Fill" to
```PowerFX
ColorValue("#"&Param("bodyBackground"))
@ -80,64 +79,58 @@ This will set the background color of the app to the same color as the section i
"Hello "&Param("greeting")
```
and it's "Color" property to
and it's "Color" property to
```PowerFX
ColorValue("#"&Param("bodySubtext"))
```
This will set the text color of the label to the text color in the section in SharePoint and the value of the label to "Hello" concatenated with what has been passed with the query string parameter "greeting".
Finally publish the app and copy the app url.
Finally publish the app and copy the app URL.
Create a new page in SharePoint and add a new Full-Width section. Set the background color of your section to anything else but white.
Add the "Advanced Iframe Webpart" here and configure it with the PowerApp url. Append this to the URL
Add the "Advanced IFrame web part" here and configure it with the PowerApp URL. Append this to the URL
```Url
```url
&bodyBackground={{color.bodyBackground}}&bodySubtext={{color.bodySubtext}}&greeting={{query.greeting}}
```
Publish the Page
![Advanced Iframe Webpart](./images/advancediframewebpart.gif)
![Advanced IFrame web part](./images/advancediframeweb part.gif)
## Web Parts Configuration
### Advanced IFrame Webpart
### Advanced IFrame web part
![Property Pane](./images/propertypane.png)
#### Settings
Remember that only urls are supported that have been allowed by the site collection administrator in "HTML Field Security"
Remember that only URLs are supported that have been allowed by the site collection administrator in "HTML Field Security"
Setting | Description
Setting | Description
-------|----
Aspect Ratio | The aspect ratio that the iframe should use. Valid values are "16/09" (Default) and "09/16"
Iframe Url | Enter the url to the page you want to embed using this webpart. You can use Handlebars syntax to pass additional parameters to the url
Aspect Ratio | The aspect ratio that the IFrame should use. Valid values are "16/09" (Default) and "09/16"
IFrame URL | Enter the URL to the page you want to embed using this web part. You can use Handlebars syntax to pass additional parameters to the URL
#### Query string parameters
You can append any query string parameter "param" as "{{query.param}}" to the url
You can append any query string parameter "param" as "{{query.param}}" to the URL
#### User parameters
You can add these parameters to the url to pass information about the current user to the page
You can add these parameters to the URL to pass information about the current user to the page
|Key | Example |
-------|----
{{user.name}} |Sven Sieverding
{{user.email}} |Sven@domain.com
{{user.loginName}} | sven@domain.com
{{user.email}} |<Sven@domain.com>
{{user.loginName}} | <sven@domain.com>
#### Site parameters
You can add these parameters to the url to pass information about the current site to the page
You can add these parameters to the URL to pass information about the current site to the page
|Key | Example |
-------|----
@ -146,16 +139,15 @@ You can add these parameters to the url to pass information about the current si
#### UI culture parameters
You can add these parameters to the url to pass information about the current ui culture to the page
You can add these parameters to the URL to pass information about the current ui culture to the page
|Key | Example |
-------|----
{{culture.currentCultureName}} | de-DE
#### Theme parameters
You can add these parameters to the url to pass information about the current ui theme to the page
You can add these parameters to the URL to pass information about the current ui theme to the page
|Key | Example |
-------|----
@ -263,20 +255,17 @@ You can add these parameters to the url to pass information about the current ui
{{color.listTextColor}} | 323130
{{color.warningText}} | 323130
## Features
This Web Part illustrates the following concepts on top of the SharePoint Framework:
- Get the current section theme and react to theme changes.
- Get the current webpart width and react to width changes.
- Get the current web part width and react to width changes.
- Retrieve information about the current user from the page context.
- Retrieve information about the current UI culture from the page context.
- Retrieve information about the current site from the page context.
- Creating and using a service
- Fetching the "ScriptSaveDomains", the collection of all domains where iframes are allowed from.
- Fetching the "ScriptSaveDomains", the collection of all domains where IFrames are allowed from.
## Help
@ -284,18 +273,18 @@ We do not support samples, but we this community is always willing to help, and
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/labels/advanced-iframe-webpart) to see if anybody else is having the same issues.
You can try looking at [issues related to this sample](<https://github.com/pnp/sp-dev-fx-webparts/labels/react-advanced-iframe) 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=advanced-iframe-webpart) and see what the community is saying.
You can also try looking at [discussions related to this sample](<https://github.com/pnp/sp-dev-fx-webparts/discussions?discussions_q=react-advanced-iframe) and see what the community is saying.
If you encounter any issues while using this sample, [create a new issue](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Abug-suspected%2Csample%3A%20advanced-iframe-webpart&template=bug-report.yml&sample=advanced-iframe-webpart&authors=@365knoten&title=advanced-iframe-webpart%20-%20).
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-advanced-iframe-&template=bug-report.yml&sample=react-advanced-iframe&authors=@365knoten&title=react-advanced-iframe%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%20advanced-iframe-webpart&template=question.yml&sample=advanced-iframe-webpart&authors=@365knoten&title=advanced-iframe-webpart%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-advanced-iframe-web&template=question.yml&sample=react-advanced-iframe&authors=@365knoten&title=react-advanced-iframe%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%20advanced-iframe-webpart&template=question.yml&sample=advanced-iframe-webpart&authors=@365knoten&title=advanced-iframe-webpart%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-advanced-iframe&template=question.yml&sample=react-advanced-iframe&authors=@365knoten&title=react-advanced-iframe%20-%20).
## Disclaimer
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**
<img src="https://m365-visitor-stats.azurewebsites.net/sp-dev-fx-webparts/samples/advanced-iframe-webpart" />
<img src="https://m365-visitor-stats.azurewebsites.net/sp-dev-fx-web parts/samples/react-advanced-iframe" />

View File

Before

Width:  |  Height:  |  Size: 378 KiB

After

Width:  |  Height:  |  Size: 378 KiB

View File

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 76 KiB

View File

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

View File

@ -1,51 +1,51 @@
[
{
"name": "pnp-sp-dev-spfx-web-parts-advanced-iframe-webpart",
"source": "pnp",
"title": "Advanced IFrame Webpart",
"shortDescription": "This webpart allows users to add a webpage in an IFrame to a modern SharePoint page.",
"url": "https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/advanced-iframe-webpart",
"longDescription": [
"This web part demonstrates the following features: Adding a webpart to a 'Full-Width' section, resizing the webpart to fit the given space of the page, fetching dynamic parameters like the current theme or querystring and passing them to the IFrame."
],
"creationDateTime": "2024-08-27",
"updateDateTime": "2024-08-27",
"products": [
"SharePoint"
],
"metadata": [
{
"key": "CLIENT-SIDE-DEV",
"value": "Javascript"
},
{
"key": "SPFX-VERSION",
"value": "1.13.1"
}
],
"thumbnails": [
{
"type": "image",
"order": 100,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/advanced-iframe-webpart/assets/advancediframewebpart.gif",
"alt": "Advanced IFrame Webpart"
}
],
"authors": [
{
"gitHubAccount": "365knoten",
"company": "Storm Technology Ltd",
"pictureUrl": "https://github.com/365knoten.png",
"name": "Sven Sieverding",
"twitter": "365knoten"
}
],
"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://learn.microsoft.com/sharepoint/dev/spfx/web-parts/get-started/build-a-hello-world-web-part"
}
]
}
[
{
"name": "pnp-sp-dev-spfx-web-parts-react-advanced-iframe",
"source": "pnp",
"title": "Advanced IFrame",
"shortDescription": "This web part allows users to add a webpage in an IFrame to a modern SharePoint page.",
"url": "https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-advanced-iframe",
"longDescription": [
"This web part demonstrates the following features: Adding a web part to a 'Full-Width' section, resizing the web part to fit the given space of the page, fetching dynamic parameters like the current theme or querystring and passing them to the IFrame."
],
"creationDateTime": "2024-08-27",
"updateDateTime": "2024-08-27",
"products": [
"SharePoint"
],
"metadata": [
{
"key": "CLIENT-SIDE-DEV",
"value": "Javascript"
},
{
"key": "SPFX-VERSION",
"value": "1.13.1"
}
],
"thumbnails": [
{
"type": "image",
"order": 100,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-advanced-iframe/assets/advancediframewebpart.gif",
"alt": "Advanced IFrame Web part"
}
],
"authors": [
{
"gitHubAccount": "365knoten",
"company": "Storm Technology Ltd",
"pictureUrl": "https://github.com/365knoten.png",
"name": "Sven Sieverding",
"twitter": "365knoten"
}
],
"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://learn.microsoft.com/sharepoint/dev/spfx/web-parts/get-started/build-a-hello-world-web-part"
}
]
}
]

View File

@ -1,18 +1,18 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"advanced-iframe-webpart": {
"components": [
{
"entrypoint": "./lib/webparts/advancediframewebpart/AdvancedIFrameWebpart.js",
"manifest": "./src/webparts/advancediframewebpart/AdvancedIFrameWebpart.manifest.json"
}
]
}
},
"localizedResources": {
"AdvancedIFrameWebpartStrings": "lib/webparts/advancediframewebpart/loc/{locale}.js",
"PropertyControlStrings": "node_modules/@pnp/spfx-property-controls/lib/loc/{locale}.js"
}
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"advanced-iframe-webpart": {
"components": [
{
"entrypoint": "./lib/webparts/advancediframewebpart/AdvancedIFrameWebpart.js",
"manifest": "./src/webparts/advancediframewebpart/AdvancedIFrameWebpart.manifest.json"
}
]
}
},
"localizedResources": {
"AdvancedIFrameWebpartStrings": "lib/webparts/advancediframewebpart/loc/{locale}.js",
"PropertyControlStrings": "node_modules/@pnp/spfx-property-controls/lib/loc/{locale}.js"
}
}

View File

@ -0,0 +1,14 @@
const gulp = require('gulp');
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.tslintCmd.enabled = false
build.initialize(gulp);

View File

@ -1,37 +1,37 @@
{
"name": "advanced-iframe-webpart",
"version": "0.0.1",
"private": true,
"main": "lib/index.js",
"scripts": {
"tasks": "gulp --tasks",
"serve": "gulp serve-deprecated",
"dist": "gulp clean && gulp build --ship && gulp bundle --ship && gulp package-solution --ship",
"tslint:autofix": "tslint --fix -c ./tslint.json 'src/**/*{.ts,.tsx}'",
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test",
"preversion": "node ./tools/pre-version.js",
"postversion": "gulp dist"
},
"dependencies": {
"@microsoft/rush-stack-compiler-4.2": "^0.3.1",
"@microsoft/sp-core-library": "1.13.1",
"@microsoft/sp-lodash-subset": "1.13.1",
"@microsoft/sp-office-ui-fabric-core": "1.13.1",
"@microsoft/sp-property-pane": "1.13.1",
"@microsoft/sp-webpart-base": "1.13.1",
"@pnp/sp": "^3.17.0",
"@pnp/spfx-property-controls": "3.14.0",
"handlebars": "^4.7.8"
},
"devDependencies": {
"@microsoft/sp-build-web": "1.13.1",
"@microsoft/sp-module-interfaces": "1.13.1",
"@microsoft/sp-tslint-rules": "1.13.1",
"@types/webpack-env": "1.13.1",
"ajv": "~5.2.2",
"gulp": "~4.0.2",
"gulp-sequence": "1.0.0"
}
}
{
"name": "advanced-iframe-webpart",
"version": "0.0.1",
"private": true,
"main": "lib/index.js",
"scripts": {
"tasks": "gulp --tasks",
"serve": "gulp serve-deprecated",
"dist": "gulp clean && gulp build --ship && gulp bundle --ship && gulp package-solution --ship",
"tslint:autofix": "tslint --fix -c ./tslint.json 'src/**/*{.ts,.tsx}'",
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test",
"preversion": "node ./tools/pre-version.js",
"postversion": "gulp dist"
},
"dependencies": {
"@microsoft/rush-stack-compiler-4.2": "^0.3.1",
"@microsoft/sp-core-library": "1.13.1",
"@microsoft/sp-lodash-subset": "1.13.1",
"@microsoft/sp-office-ui-fabric-core": "1.13.1",
"@microsoft/sp-property-pane": "1.13.1",
"@microsoft/sp-webpart-base": "1.13.1",
"@pnp/sp": "^3.17.0",
"@pnp/spfx-property-controls": "3.14.0",
"handlebars": "^4.7.8"
},
"devDependencies": {
"@microsoft/sp-build-web": "1.13.1",
"@microsoft/sp-module-interfaces": "1.13.1",
"@microsoft/sp-tslint-rules": "1.13.1",
"@types/webpack-env": "1.13.1",
"ajv": "~5.2.2",
"gulp": "~4.0.2",
"gulp-sequence": "1.0.0"
}
}

View File

@ -1,192 +1,192 @@
import { Version } from '@microsoft/sp-core-library';
import {
IPropertyPaneConfiguration, PropertyPaneChoiceGroup
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import * as strings from 'AdvancedIFrameWebpartStrings';
import * as Handlebars from 'handlebars';
import { PropertyFieldCodeEditor, PropertyFieldCodeEditorLanguages } from '@pnp/spfx-property-controls/lib/PropertyFieldCodeEditor';
import {
ThemeProvider,
ThemeChangedEventArgs,
IReadonlyTheme,
ISemanticColors
} from '@microsoft/sp-component-base';
import { IFrameDataModel } from './models/IFrameDataModel';
import { createHTMLDescription } from './helpers/createHTMLDescription';
import "@pnp/sp/sites";
import "@pnp/sp/";
import "@pnp/sp/webs";
import { IScriptSaveDomainService, ScriptSaveDomainService } from './services/ScriptSaveDomainService';
export interface AdvancedIFrameWebpartProps {
aspectratio: string;
url: string;
}
export default class AdvancedIFrameWebpart extends BaseClientSideWebPart<AdvancedIFrameWebpartProps> {
private _ScriptSaveDomainService: IScriptSaveDomainService;
private _themeProvider: ThemeProvider;
private _themeVariant: IReadonlyTheme | undefined;
private _IFramewidth: number = 640;
/**
* The onInit method
*/
protected async onInit(): Promise<void> {
await super.onInit();
this._ScriptSaveDomainService = this.context.serviceScope.consume(ScriptSaveDomainService.serviceKey);
this._themeProvider = this.context.serviceScope.consume(ThemeProvider.serviceKey);
this._themeVariant = this._themeProvider.tryGetTheme();
this._themeProvider.themeChangedEvent.add(this, this._handleThemeChangedEvent);
}
/**
* The render method
*/
public render(): void {
// get variables that can be used
const data = this.getVariables()
if (this.properties.url == null || this.properties.url.length == 0) {
// no url provided in property pane, so render description
this.domElement.innerHTML = createHTMLDescription(strings, data);
return;
}
// Compile and render the variables into the url
const renderHandlebars = Handlebars.compile(this.properties.url);
const renderedUrl = renderHandlebars(data);
if (!this._ScriptSaveDomainService.isInSaveDomain(renderedUrl)) {
// the rendered URL is not a safe url, so show not allowed message
this.domElement.innerHTML = strings.UrlNotAllowedMessage;
return;
}
const aspectratio = this.properties.aspectratio == "as0916" ? "9 / 16" : "16 / 9";
this.domElement.innerHTML = `<iframe style="aspect-ratio: ${aspectratio};height: 100%;width: 100%;" src="${renderedUrl}" width="${this._IFramewidth}" frameborder="0" allow="autoplay; fullscreen; picture-in-picture"></iframe>`;
}
/**
* This Method is called whenever the theme of the site has been changed
* @param args
*/
private _handleThemeChangedEvent(args: ThemeChangedEventArgs): void {
this._themeVariant = args.theme;
this.render;
}
/**
* Returns the variables that can be used in the handlebars template
* @returns
*/
private getVariables() {
// get all current theme colors
const semanticColors: Partial<ISemanticColors> | undefined = this._themeVariant && this._themeVariant.semanticColors;
// get all current query string parameters and put them into a "query" object
const entries = (new URLSearchParams(window.location.search) as any).entries();
const query: any = {};
let value = null;
while (value = entries.next(), !value.done) {
query[value.value[0]] = value.value[1];
}
// initialize the data object that will be passed to handlebars renderer
const data: IFrameDataModel = {
query: query,
culture: {
currentCultureName: this.context.pageContext.cultureInfo.currentCultureName
},
site: {
id: this.context.pageContext.site.id,
serverRelativeUrl: this.context.pageContext.site.serverRelativeUrl
},
page: {
pageUrl: this.context.pageContext.site.serverRequestPath
},
user: {
name: this.context.pageContext.user.displayName,
email: this.context.pageContext.user.email,
loginName: this.context.pageContext.user.loginName,
},
// remove the pound sign from every color... It does not work as a query string parameter
color: Object.keys(semanticColors).reduce((obj, key) => { obj[key] = semanticColors[key].replace("#", ""); return obj }, {}) || {}
};
return data;
}
/**
* This is called whenever the webpart resizes and provides the new width
* @param newWidth
*/
protected onAfterResize(newWidth: number) {
this._IFramewidth = newWidth;
}
/**
* Returns the dataVersion
*/
protected get dataVersion(): Version {
return Version.parse('1.0');
}
/**
* This configures the property pane
* @returns
*/
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneChoiceGroup('aspectratio', {
label: strings.AspectRatioLabel,
options: [
{ key: 'as1609', text: '16 / 09', checked: true },
{ key: 'as0916', text: '09 / 16' }
],
}),
PropertyFieldCodeEditor('url', {
label: strings.UrlFieldLabel,
panelTitle: strings.EditUrlLabel,
initialValue: this.properties.url,
onPropertyChange: this.onPropertyPaneFieldChanged,
properties: this.properties,
disabled: false,
key: 'codeEditorFieldId',
language: PropertyFieldCodeEditorLanguages.Handlebars,
options: {
wrap: true,
fontSize: 20,
mode: "text"
// more options
}
})
]
}
]
}
]
};
}
import { Version } from '@microsoft/sp-core-library';
import {
IPropertyPaneConfiguration, PropertyPaneChoiceGroup
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import * as strings from 'AdvancedIFrameWebpartStrings';
import * as Handlebars from 'handlebars';
import { PropertyFieldCodeEditor, PropertyFieldCodeEditorLanguages } from '@pnp/spfx-property-controls/lib/PropertyFieldCodeEditor';
import {
ThemeProvider,
ThemeChangedEventArgs,
IReadonlyTheme,
ISemanticColors
} from '@microsoft/sp-component-base';
import { IFrameDataModel } from './models/IFrameDataModel';
import { createHTMLDescription } from './helpers/createHTMLDescription';
import "@pnp/sp/sites";
import "@pnp/sp/";
import "@pnp/sp/webs";
import { IScriptSaveDomainService, ScriptSaveDomainService } from './services/ScriptSaveDomainService';
export interface AdvancedIFrameWebpartProps {
aspectratio: string;
url: string;
}
export default class AdvancedIFrameWebpart extends BaseClientSideWebPart<AdvancedIFrameWebpartProps> {
private _ScriptSaveDomainService: IScriptSaveDomainService;
private _themeProvider: ThemeProvider;
private _themeVariant: IReadonlyTheme | undefined;
private _IFramewidth: number = 640;
/**
* The onInit method
*/
protected async onInit(): Promise<void> {
await super.onInit();
this._ScriptSaveDomainService = this.context.serviceScope.consume(ScriptSaveDomainService.serviceKey);
this._themeProvider = this.context.serviceScope.consume(ThemeProvider.serviceKey);
this._themeVariant = this._themeProvider.tryGetTheme();
this._themeProvider.themeChangedEvent.add(this, this._handleThemeChangedEvent);
}
/**
* The render method
*/
public render(): void {
// get variables that can be used
const data = this.getVariables()
if (this.properties.url == null || this.properties.url.length == 0) {
// no url provided in property pane, so render description
this.domElement.innerHTML = createHTMLDescription(strings, data);
return;
}
// Compile and render the variables into the url
const renderHandlebars = Handlebars.compile(this.properties.url);
const renderedUrl = renderHandlebars(data);
if (!this._ScriptSaveDomainService.isInSaveDomain(renderedUrl)) {
// the rendered URL is not a safe url, so show not allowed message
this.domElement.innerHTML = strings.UrlNotAllowedMessage;
return;
}
const aspectratio = this.properties.aspectratio == "as0916" ? "9 / 16" : "16 / 9";
this.domElement.innerHTML = `<iframe style="aspect-ratio: ${aspectratio};height: 100%;width: 100%;" src="${renderedUrl}" width="${this._IFramewidth}" frameborder="0" allow="autoplay; fullscreen; picture-in-picture"></iframe>`;
}
/**
* This Method is called whenever the theme of the site has been changed
* @param args
*/
private _handleThemeChangedEvent(args: ThemeChangedEventArgs): void {
this._themeVariant = args.theme;
this.render;
}
/**
* Returns the variables that can be used in the handlebars template
* @returns
*/
private getVariables() {
// get all current theme colors
const semanticColors: Partial<ISemanticColors> | undefined = this._themeVariant && this._themeVariant.semanticColors;
// get all current query string parameters and put them into a "query" object
const entries = (new URLSearchParams(window.location.search) as any).entries();
const query: any = {};
let value = null;
while (value = entries.next(), !value.done) {
query[value.value[0]] = value.value[1];
}
// initialize the data object that will be passed to handlebars renderer
const data: IFrameDataModel = {
query: query,
culture: {
currentCultureName: this.context.pageContext.cultureInfo.currentCultureName
},
site: {
id: this.context.pageContext.site.id,
serverRelativeUrl: this.context.pageContext.site.serverRelativeUrl
},
page: {
pageUrl: this.context.pageContext.site.serverRequestPath
},
user: {
name: this.context.pageContext.user.displayName,
email: this.context.pageContext.user.email,
loginName: this.context.pageContext.user.loginName,
},
// remove the pound sign from every color... It does not work as a query string parameter
color: Object.keys(semanticColors).reduce((obj, key) => { obj[key] = semanticColors[key].replace("#", ""); return obj }, {}) || {}
};
return data;
}
/**
* This is called whenever the webpart resizes and provides the new width
* @param newWidth
*/
protected onAfterResize(newWidth: number) {
this._IFramewidth = newWidth;
}
/**
* Returns the dataVersion
*/
protected get dataVersion(): Version {
return Version.parse('1.0');
}
/**
* This configures the property pane
* @returns
*/
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneChoiceGroup('aspectratio', {
label: strings.AspectRatioLabel,
options: [
{ key: 'as1609', text: '16 / 09', checked: true },
{ key: 'as0916', text: '09 / 16' }
],
}),
PropertyFieldCodeEditor('url', {
label: strings.UrlFieldLabel,
panelTitle: strings.EditUrlLabel,
initialValue: this.properties.url,
onPropertyChange: this.onPropertyPaneFieldChanged,
properties: this.properties,
disabled: false,
key: 'codeEditorFieldId',
language: PropertyFieldCodeEditorLanguages.Handlebars,
options: {
wrap: true,
fontSize: 20,
mode: "text"
// more options
}
})
]
}
]
}
]
};
}
}

View File

@ -1,79 +1,79 @@
/**
* A Helper Class.
* This helps building an easy html-structure in a fluent manner.
*/
export class HTMLDescriptionBuilder {
private _html = "";
/**
*
* @returns the resulting HTML
*/
public toString() {
return this._html;
}
/**
* Appends html to the current document
* @param html
* @returns
*/
public add(html: string) {
this._html += html;
return this;
}
/**
* Appends an HTML tag to the current document
* @param tag
* @param value
* @returns
*/
public addTag(tag: string, value: string) {
return this.add(`<${tag}>${value}</${tag}>`);
}
/**
* Adds an h3 tag to the current document
* @param value
* @returns
*/
public addHeadline3(value: string) {
return this.addTag("h3", value);
}
/**
* Adds an h2 tag to the current document
* @param value
* @returns
*/
public addHeadline2(value: string) {
return this.addTag("h2", value);
}
/**
* Adds an p tag to the current document
* @param value
* @returns
*/
public addParagraph(value: string) {
return this.addTag("p", value);
}
/**
* Iterates over all properties of an object and displays them in an HTML table
* @returns
*/
public addPropertyTable(obj: any, keyPrefix = "", keyColumnTitle = "Key", valueColumnTitle = "Value") {
return this.add(`<table>
<tr><th>${keyColumnTitle}</th><th>${valueColumnTitle}</th></tr>
${Object.keys(obj).reduce((propstring: string, prop: string) => {
return propstring += `<tr><td>{{${keyPrefix}${prop}}}</td><td>${obj[prop]}</td></tr>\n`;
}, "")}
</table>`
);
}
/**
* A Helper Class.
* This helps building an easy html-structure in a fluent manner.
*/
export class HTMLDescriptionBuilder {
private _html = "";
/**
*
* @returns the resulting HTML
*/
public toString() {
return this._html;
}
/**
* Appends html to the current document
* @param html
* @returns
*/
public add(html: string) {
this._html += html;
return this;
}
/**
* Appends an HTML tag to the current document
* @param tag
* @param value
* @returns
*/
public addTag(tag: string, value: string) {
return this.add(`<${tag}>${value}</${tag}>`);
}
/**
* Adds an h3 tag to the current document
* @param value
* @returns
*/
public addHeadline3(value: string) {
return this.addTag("h3", value);
}
/**
* Adds an h2 tag to the current document
* @param value
* @returns
*/
public addHeadline2(value: string) {
return this.addTag("h2", value);
}
/**
* Adds an p tag to the current document
* @param value
* @returns
*/
public addParagraph(value: string) {
return this.addTag("p", value);
}
/**
* Iterates over all properties of an object and displays them in an HTML table
* @returns
*/
public addPropertyTable(obj: any, keyPrefix = "", keyColumnTitle = "Key", valueColumnTitle = "Value") {
return this.add(`<table>
<tr><th>${keyColumnTitle}</th><th>${valueColumnTitle}</th></tr>
${Object.keys(obj).reduce((propstring: string, prop: string) => {
return propstring += `<tr><td>{{${keyPrefix}${prop}}}</td><td>${obj[prop]}</td></tr>\n`;
}, "")}
</table>`
);
}
}

View File

@ -1,30 +1,30 @@
import { IFrameDataModel } from "../models/IFrameDataModel";
import { HTMLDescriptionBuilder } from "./HTMLDescriptionBuilder";
/**
* Creates the Description for this webpart
* @param strings
* @param data
* @returns
*/
export const createHTMLDescription = (strings: IAdvancedIFrameWebpartStrings, data: IFrameDataModel) => {
return new HTMLDescriptionBuilder()
.addHeadline2(strings.WebpartTitle)
.addParagraph(strings.DescriptionGeneral1)
.addParagraph(strings.DescriptionGeneral2)
.addHeadline3(strings.DescriptionHeaderQuery)
.addParagraph(strings.DescriptionDetailsQuery)
.addPropertyTable(data.query, "query.")
.addHeadline3(strings.DescriptionHeaderUser)
.addPropertyTable(data.user, "user.")
.addHeadline3(strings.DescriptionHeaderSite)
.addPropertyTable(data.site, "site.")
.addHeadline3(strings.DescriptionHeaderColors)
.addPropertyTable(data.color, "color.")
.addHeadline3(strings.DescriptionHeaderCulture)
.addPropertyTable(data.culture, "culture.")
.toString();
import { IFrameDataModel } from "../models/IFrameDataModel";
import { HTMLDescriptionBuilder } from "./HTMLDescriptionBuilder";
/**
* Creates the Description for this webpart
* @param strings
* @param data
* @returns
*/
export const createHTMLDescription = (strings: IAdvancedIFrameWebpartStrings, data: IFrameDataModel) => {
return new HTMLDescriptionBuilder()
.addHeadline2(strings.WebpartTitle)
.addParagraph(strings.DescriptionGeneral1)
.addParagraph(strings.DescriptionGeneral2)
.addHeadline3(strings.DescriptionHeaderQuery)
.addParagraph(strings.DescriptionDetailsQuery)
.addPropertyTable(data.query, "query.")
.addHeadline3(strings.DescriptionHeaderUser)
.addPropertyTable(data.user, "user.")
.addHeadline3(strings.DescriptionHeaderSite)
.addPropertyTable(data.site, "site.")
.addHeadline3(strings.DescriptionHeaderColors)
.addPropertyTable(data.color, "color.")
.addHeadline3(strings.DescriptionHeaderCulture)
.addPropertyTable(data.culture, "culture.")
.toString();
};

View File

@ -1,13 +1,13 @@
define([], function () {
return {
"WebpartTitle":"Advanced IFrame Webpart",
"PropertyPaneDescription": "This webpart displays an IFrame, but keeps the aspect ratio and reacts responsive to width changes.\n You can also add dynamic parameters to the IFrame url.",
"WebpartTitle":"Advanced IFrame Web part",
"PropertyPaneDescription": "This web part displays an IFrame, but keeps the aspect ratio and reacts responsive to width changes.\n You can also add dynamic parameters to the IFrame URL.",
"BasicGroupName": "Settings",
"UrlFieldLabel": "IFrame Url",
"AspectRatioLabel": "Aspect Ratio",
"EditUrlLabel": "Edit Url",
"DescriptionGeneral1": "Open the property pane to enter the url of the page you want to display in the IFrame.",
"DescriptionGeneral2": "You can use th following variables in the url:",
"DescriptionGeneral1": "Open the property pane to enter the URL of the page you want to display in the IFrame.",
"DescriptionGeneral2": "You can use the following variables in the URL:",
"DescriptionHeaderQuery": "Query string parameters",
"DescriptionDetailsQuery": "You can use each query string parameter \"param\" as \"{{query.param}}\"",
"DescriptionHeaderSite": "Site Parameters",

View File

@ -1,8 +1,8 @@
export interface IFrameDataModel {
query: any;
color: any;
culture: any;
site: any;
user: any;
page: any;
export interface IFrameDataModel {
query: any;
color: any;
culture: any;
site: any;
user: any;
page: any;
}

View File

@ -1,93 +1,93 @@
import { Log, ServiceKey, ServiceScope } from "@microsoft/sp-core-library";
import { spfi, SPFI, SPFx as spSPFx } from "@pnp/sp";
import "@pnp/sp/webs";
import { PageContext } from "@microsoft/sp-page-context";
const LOG_SOURCE: string = "'advanced-iframe-webpart:ScriptSaveDomainService";
/**
* A service that tells us if a given domain is save to display in an IFrame
*/
export interface IScriptSaveDomainService {
/**
* Returns true if the given url is a safe url
* @param url
* @returns
*/
isInSaveDomain: (url: string) => Promise<boolean>;
}
/**
* A service that tells us if a given domain is save to display in an IFrame
*/
export class ScriptSaveDomainService implements IScriptSaveDomainService {
/**
* Stores the downloaded script save domains
*/
private _scriptSaveDomains: string[] = null;
/**
* The pnpjs spfi object
*/
private _spfi: SPFI;
//Create a ServiceKey which will be used to consume the service.
public static readonly serviceKey: ServiceKey<IScriptSaveDomainService> =
ServiceKey.create<IScriptSaveDomainService>(LOG_SOURCE, ScriptSaveDomainService);
/**
* Constructor
* @param serviceScope the servicescipe
*/
constructor(serviceScope: ServiceScope) {
serviceScope.whenFinished(() => {
Log.info(LOG_SOURCE, "Begin constructing ScriptSaveDomainService");
const pageContext = serviceScope.consume(PageContext.serviceKey);
this._spfi = spfi().using(spSPFx({ pageContext }));
Log.info(LOG_SOURCE, "Constructed ScriptSaveDomainService");
});
}
/**
* Fetches an array of all script save domains
* @returns
*/
private async fetchScriptSaveDomains() {
// If we don't have already downloaded the domains
if (this._scriptSaveDomains == null) {
Log.info(LOG_SOURCE, "Downloading Property Bag");
// get the Script Save Domains from the site's property bag
const props = await this._spfi.web.allProperties();
//parse and split them into an array
this._scriptSaveDomains = `${props["OData__x005f__x005f_ScriptSafeDomains"]}`
.split(";")
.filter((d: string) => d != null && d.length > 0)
;
// Always allow IFrames from the current domain
this._scriptSaveDomains.push(window.location.host);
Log.info(LOG_SOURCE, "Created script safe domains array");
}
return this._scriptSaveDomains;
}
/**
* Returns true if the given url is a safe url
* @param url
* @returns
*/
public async isInSaveDomain(url: string) {
const result = (await this.fetchScriptSaveDomains()).reduce((value, domain) => {
if (url.indexOf(domain) != -1) {
return true;
}
return value;
}, false)
Log.info(LOG_SOURCE, `Domain ${url} is a save domain? ${result}`);
return result;
}
}
import { Log, ServiceKey, ServiceScope } from "@microsoft/sp-core-library";
import { spfi, SPFI, SPFx as spSPFx } from "@pnp/sp";
import "@pnp/sp/webs";
import { PageContext } from "@microsoft/sp-page-context";
const LOG_SOURCE: string = "'advanced-iframe-webpart:ScriptSaveDomainService";
/**
* A service that tells us if a given domain is save to display in an IFrame
*/
export interface IScriptSaveDomainService {
/**
* Returns true if the given url is a safe url
* @param url
* @returns
*/
isInSaveDomain: (url: string) => Promise<boolean>;
}
/**
* A service that tells us if a given domain is save to display in an IFrame
*/
export class ScriptSaveDomainService implements IScriptSaveDomainService {
/**
* Stores the downloaded script save domains
*/
private _scriptSaveDomains: string[] = null;
/**
* The pnpjs spfi object
*/
private _spfi: SPFI;
//Create a ServiceKey which will be used to consume the service.
public static readonly serviceKey: ServiceKey<IScriptSaveDomainService> =
ServiceKey.create<IScriptSaveDomainService>(LOG_SOURCE, ScriptSaveDomainService);
/**
* Constructor
* @param serviceScope the servicescipe
*/
constructor(serviceScope: ServiceScope) {
serviceScope.whenFinished(() => {
Log.info(LOG_SOURCE, "Begin constructing ScriptSaveDomainService");
const pageContext = serviceScope.consume(PageContext.serviceKey);
this._spfi = spfi().using(spSPFx({ pageContext }));
Log.info(LOG_SOURCE, "Constructed ScriptSaveDomainService");
});
}
/**
* Fetches an array of all script save domains
* @returns
*/
private async fetchScriptSaveDomains() {
// If we don't have already downloaded the domains
if (this._scriptSaveDomains == null) {
Log.info(LOG_SOURCE, "Downloading Property Bag");
// get the Script Save Domains from the site's property bag
const props = await this._spfi.web.allProperties();
//parse and split them into an array
this._scriptSaveDomains = `${props["OData__x005f__x005f_ScriptSafeDomains"]}`
.split(";")
.filter((d: string) => d != null && d.length > 0)
;
// Always allow IFrames from the current domain
this._scriptSaveDomains.push(window.location.host);
Log.info(LOG_SOURCE, "Created script safe domains array");
}
return this._scriptSaveDomains;
}
/**
* Returns true if the given url is a safe url
* @param url
* @returns
*/
public async isInSaveDomain(url: string) {
const result = (await this.fetchScriptSaveDomains()).reduce((value, domain) => {
if (url.indexOf(domain) != -1) {
return true;
}
return value;
}, false)
Log.info(LOG_SOURCE, `Domain ${url} is a save domain? ${result}`);
return result;
}
}

View File

@ -1,36 +1,36 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-4.2/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,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection",
"es2015.promise"
],
"esModuleInterop": true
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
]
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-4.2/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,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection",
"es2015.promise"
],
"esModuleInterop": true
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
]
}