Script editor web part for a modern page (#151)

* Initial commit

* Added one more sample
This commit is contained in:
Mikael Svenson 2017-03-12 13:25:26 +01:00 committed by Vesa Juvonen
parent a7e61b7a5d
commit eab018013b
27 changed files with 637 additions and 0 deletions

View File

@ -0,0 +1,25 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org
root = true
[*]
# change these settings to your own preference
indent_style = space
indent_size = 2
# we recommend you to keep these unchanged
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[{package,bower}.json]
indent_style = space
indent_size = 2

View File

@ -0,0 +1 @@
* text=auto

32
samples/react-script-editor/.gitignore vendored Normal file
View File

@ -0,0 +1,32 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules
# Build generated files
dist
lib
solution
temp
*.sppkg
# Coverage directory used by tools like istanbul
coverage
# OSX
.DS_Store
# Visual Studio files
.ntvs_analysis.dat
.vs
bin
obj
# Resx Generated Code
*.resx.ts
# Styles Generated Code
*.scss.ts

View File

@ -0,0 +1,14 @@
# Folders
.vscode
coverage
node_modules
sharepoint
src
temp
# Files
*.csproj
.git*
.yo-rc.json
gulpfile.js
tsconfig.json

View File

@ -0,0 +1,8 @@
{
"@microsoft/generator-sharepoint": {
"libraryName": "pzl-script-editor",
"framework": "react",
"version": "1.0.0",
"libraryId": "1425175f-3ed8-44d2-8fc4-dd1497191294"
}
}

View File

@ -0,0 +1,85 @@
# Script editor web part for modern pages built in React
## Summary
Coming from old classic SharePoint pages you might have existing script solutions you want to re-use on a modern page
without having to repackage it as a new SharePoint Framework web part. This web part is similar to the classic
Script Editor Web Part, and allows you do drop arbitrary script or html on a modern page.
As an example add the following scripts to the web part in order to show weather info on your page. First *jQuery* is loaded, then the *simpleWeather* extension, and finally the last script block is executed to show the weather.
```html
<div id="weather"></div>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.simpleWeather/3.1.0/jquery.simpleWeather.min.js"></script>
<script>
jQuery.simpleWeather({
location: 'Oslo, Norway',
woeid: '',
unit: 'c',
success: function(weather) {
html = '<h2>'+weather.temp+'&deg;'+weather.units.temp+'</h2>';
html += '<ul><li>'+weather.city+', '+weather.region+'</li>';
html += '<li>'+weather.currently+'</li></ul>';
jQuery("#weather").html(html);
},
error: function(error) {
jQuery("#weather").html('<p>'+error+'</p>');
}
});
</script>
```
The web part works by loading each script in a `<script src>` tag sequentially in the order they are specified, then any other `<script>` block is executed.
![site page header configurator web part](./assets/modern-script-editor-wp.gif)
If all you want is to add markup on the page, you can do that as well. Adding the following html would show a headline and a list.
```html
<h2>My header</h2>
<ul>
<li>One
<li>Two
<li>Three
</ul>
```
## Used SharePoint Framework Version
![drop](https://img.shields.io/badge/version-GA-green.svg)
## Applies to
* [SharePoint Framework Release GA](https://blogs.office.com/2017/02/23/sharepoint-framework-reaches-general-availability-build-and-deploy-engaging-web-parts-today/)
* [Office 365 tenant](https://dev.office.com/sharepoint/docs/spfx/set-up-your-development-environment)
## Solution
Solution|Author(s)
--------|---------
react-script-editor | Mikael Svenson ([@mikaelsvenson](http://www.twitter.com/mikaelsvenson), [techmikael.com](techmikael.com))
## Version history
Version|Date|Comments
-------|----|--------
1.0|March 10th, 2017|Initial release
## 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.**
---
## Minimal Path to Awesome
- Clone this repository
- In the command line run:
- `npm install`
- `gulp serve`
## Features
This web part illustrates the following concepts on top of the SharePoint Framework:
- Re-use existing JavaScript solutions on a modern page
- Office UI Fabric
- React

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 MiB

View File

@ -0,0 +1,10 @@
{
"entries": [
{
"entry": "./lib/webparts/scriptEditor/ScriptEditorWebPart.js",
"manifest": "./src/webparts/scriptEditor/ScriptEditorWebPart.manifest.json",
"outputPath": "./dist/script-editor.bundle.js"
}
],
"externals": {}
}

View File

@ -0,0 +1,3 @@
{
"deployCdnPath": "temp/deploy"
}

View File

@ -0,0 +1,6 @@
{
"workingDir": "./temp/deploy/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "pzl-script-editor",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,10 @@
{
"solution": {
"name": "Modern Script Editor web part by Puzzlepart",
"id": "1425175f-3ed8-44d2-8fc4-dd1497191294",
"version": "1.0.0.0"
},
"paths": {
"zippedPackage": "solution/pzl-script-editor.sppkg"
}
}

View File

@ -0,0 +1,9 @@
{
"port": 4321,
"initialPage": "https://localhost:5432/workbench",
"https": true,
"api": {
"port": 5432,
"entryPath": "node_modules/@microsoft/sp-webpart-workbench/lib/api/"
}
}

View File

@ -0,0 +1,46 @@
{
// Display errors as warnings
"displayAsWarning": true,
// The TSLint task may have been configured with several custom lint rules
// before this config file is read (for example lint rules from the tslint-microsoft-contrib
// project). If true, this flag will deactivate any of these rules.
"removeExistingRules": true,
// When true, the TSLint task is configured with some default TSLint "rules.":
"useDefaultConfigAsBase": false,
// Since removeExistingRules=true and useDefaultConfigAsBase=false, there will be no lint rules
// which are active, other than the list of rules below.
"lintConfig": {
// Opt-in to Lint rules which help to eliminate bugs in JavaScript
"rules": {
"class-name": false,
"export-name": false,
"forin": false,
"label-position": false,
"member-access": true,
"no-arg": false,
"no-console": false,
"no-construct": false,
"no-duplicate-case": true,
"no-duplicate-variable": true,
"no-eval": false,
"no-function-expression": true,
"no-internal-module": true,
"no-shadowed-variable": true,
"no-switch-case-fall-through": true,
"no-unnecessary-semicolons": true,
"no-unused-expression": true,
"no-unused-imports": true,
"no-use-before-declare": true,
"no-with-statement": true,
"semicolon": true,
"trailing-comma": false,
"typedef": false,
"typedef-whitespace": false,
"use-named-parameter": true,
"valid-typeof": true,
"variable-name": false,
"whitespace": false,
"prefer-const": true
}
}
}

View File

@ -0,0 +1,3 @@
{
"cdnBasePath": "<!-- PATH TO CDN -->"
}

View File

@ -0,0 +1,6 @@
'use strict';
const gulp = require('gulp');
const build = require('@microsoft/sp-build-web');
build.initialize(gulp);

View File

@ -0,0 +1,34 @@
{
"name": "pzl-script-editor",
"version": "0.0.1",
"private": true,
"engines": {
"node": ">=0.10.0"
},
"dependencies": {
"@microsoft/sp-client-base": "~1.0.0",
"@microsoft/sp-core-library": "~1.0.0",
"@microsoft/sp-webpart-base": "~1.0.0",
"@types/react": "0.14.46",
"@types/react-addons-shallow-compare": "0.14.17",
"@types/react-addons-test-utils": "0.14.15",
"@types/react-addons-update": "0.14.14",
"@types/react-dom": "0.14.18",
"@types/webpack-env": ">=1.12.1 <1.14.0",
"react": "15.4.2",
"react-dom": "15.4.2"
},
"devDependencies": {
"@microsoft/sp-build-web": "~1.0.0",
"@microsoft/sp-module-interfaces": "~1.0.0",
"@microsoft/sp-webpart-workbench": "~1.0.0",
"gulp": "~3.9.1",
"@types/chai": ">=3.4.34 <3.6.0",
"@types/mocha": ">=2.2.33 <2.6.0"
},
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
}
}

View File

@ -0,0 +1,3 @@
export interface IScriptEditorWebPartProps {
script: string;
}

View File

@ -0,0 +1,20 @@
{
"$schema": "../../../node_modules/@microsoft/sp-module-interfaces/lib/manifestSchemas/jsonSchemas/clientSideComponentManifestSchema.json",
"id": "3a328f0a-99c4-4b28-95ab-fe0847f657a3",
"alias": "ScriptEditorWebPart",
"componentType": "WebPart",
"version": "0.0.1",
"manifestVersion": 2,
"preconfiguredEntries": [{
"groupId": "3a328f0a-99c4-4b28-95ab-fe0847f657a3",
"group": { "default": "Puzzlepart" },
"title": { "default": "Modern Script Editor" },
"description": { "default": "Add arbitrary script to a page" },
"officeFabricIconFontName": "JS",
"properties": {
"script": ""
}
}]
}

View File

@ -0,0 +1,158 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version, DisplayMode } from '@microsoft/sp-core-library';
import { SPComponentLoader } from '@microsoft/sp-loader';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneCustomField
} from '@microsoft/sp-webpart-base';
import ScriptEditor from './components/ScriptEditor';
import { IScriptEditorProps } from './components/IScriptEditorProps';
import { IScriptEditorWebPartProps } from './IScriptEditorWebPartProps';
export default class ScriptEditorWebPart extends BaseClientSideWebPart<IScriptEditorWebPartProps> {
public save: (script: string) => void = (script: string) => {
this.properties.script = script;
this.render();
}
public render(): void {
const element: React.ReactElement<IScriptEditorProps> = React.createElement(
ScriptEditor,
{
script: this.properties.script,
save: this.save
}
);
if (this.displayMode == DisplayMode.Read) {
this.domElement.innerHTML = this.properties.script;
this.executeScript(this.domElement);
} else {
ReactDom.render(element, this.domElement);
}
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected renderLogo(domElement: HTMLElement) {
domElement.innerHTML = '<div style="margin-top: 30px"><img src="//www.puzzlepart.com/wp-content/uploads/2017/02/Puzzlepart-Logo-Digital-webheader200.png" onerror="this.style.display = \'none\'";" style="width:50%; float:right">';
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: 'No settings to change for this web part.'
},
groups: [
{
groupFields: [
PropertyPaneCustomField({
onRender: this.renderLogo,
key: "logo"
})
]
}
]
}
]
};
}
// Finds and executes scripts in a newly added element's body.
// Needed since innerHTML does not run scripts.
//
// Argument element is an element in the dom.
private executeScript(element: HTMLElement) {
// Define global name to tack scripts on in case script to be loaded is not AMD/UMD
(<any>window).ScriptGlobal = {};
function nodeName(elem, name) {
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
}
function evalScript(elem) {
var data = (elem.text || elem.textContent || elem.innerHTML || ""),
head = document.getElementsByTagName("head")[0] ||
document.documentElement,
script = document.createElement("script");
script.type = "text/javascript";
if (elem.src && elem.src.length > 0) {
return;
}
if (elem.onload && elem.onload.length > 0) {
script.onload = elem.onload;
}
try {
// doesn't work on ie...
script.appendChild(document.createTextNode(data));
} catch (e) {
// IE has funky script nodes
script.text = data;
}
head.insertBefore(script, head.firstChild);
head.removeChild(script);
}
// main section of function
var scripts = [],
script,
children_nodes = element.childNodes,
child,
i;
for (i = 0; children_nodes[i]; i++) {
child = children_nodes[i];
if (nodeName(child, "script") &&
(!child.type || child.type.toLowerCase() === "text/javascript")) {
scripts.push(child);
}
}
const urls = [];
const onLoads = [];
for (i = 0; scripts[i]; i++) {
script = scripts[i];
if (script.src && script.src.length > 0) {
urls.push(script.src);
}
if (script.onload && script.onload.length > 0) {
onLoads.push(script.onload);
}
}
// Execute promises in sequentially - https://hackernoon.com/functional-javascript-resolving-promises-sequentially-7aac18c4431e
// Use "ScriptGlobal" as the global namein case script is AMD/UMD
const allFuncs = urls.map(url => () => SPComponentLoader.loadScript(url, { globalExportsName: "ScriptGlobal" }));
const promiseSerial = funcs =>
funcs.reduce((promise, func) =>
promise.then(result => func().then(Array.prototype.concat.bind(result))),
Promise.resolve([]));
// execute Promises in serial
promiseSerial(allFuncs)
.then(() => {
// execute any onload people have added
for (i = 0; onLoads[i]; i++) {
onLoads[i]();
}
// execute script blocks
for (i = 0; scripts[i]; i++) {
script = scripts[i];
if (script.parentNode) { script.parentNode.removeChild(script); }
evalScript(scripts[i]);
}
}).catch(console.error);
};
}

View File

@ -0,0 +1,4 @@
export interface IScriptEditorProps {
script: string;
save(script: string): void;
}

View File

@ -0,0 +1,54 @@
@import url('overrides.css');
.scriptEditor {
.container {
max-width: 700px;
margin: 0px auto;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);
}
.row {
padding: 20px;
}
.listItem {
max-width: 715px;
margin: 5px auto 5px auto;
box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);
}
.button {
// Our button
text-decoration: none;
height: 32px;
// Primary Button
min-width: 80px;
background-color: #0078d7;
border-color: #0078d7;
color: #ffffff;
// Basic Button
outline: transparent;
position: relative;
font-family: "Segoe UI WestEuropean","Segoe UI",-apple-system,BlinkMacSystemFont,Roboto,"Helvetica Neue",sans-serif;
-webkit-font-smoothing: antialiased;
font-size: 14px;
font-weight: 400;
border-width: 0;
text-align: center;
cursor: pointer;
display: inline-block;
padding: 0 16px;
.label {
font-weight: 600;
font-size: 14px;
height: 32px;
line-height: 32px;
margin: 0 4px;
vertical-align: top;
display: inline-block;
}
}
}

View File

@ -0,0 +1,69 @@
import * as React from 'react';
import styles from './ScriptEditor.module.scss';
import { IScriptEditorProps } from './IScriptEditorProps';
import { Dialog, DialogType, DialogFooter, Button, ButtonType, TextField } from 'office-ui-fabric-react';
export default class ScriptEditor extends React.Component<IScriptEditorProps, any> {
constructor() {
super();
this.state = {
showDialog: false
};
}
public componentDidMount(): void {
this.setState({ script: this.props.script, loaded: this.props.script });
}
private _showDialog() {
this.setState({ showDialog: true });
}
private _closeDialog() {
this.setState({ showDialog: false });
this.props.save(this.state.script);
}
private _cancelDialog() {
this.setState({ showDialog: false });
this.state.script = this.state.loaded;
}
private _onScriptEditorTextChanged(text: string) {
this.setState({ script: text });
}
public render(): React.ReactElement<IScriptEditorProps> {
const viewMode = <span dangerouslySetInnerHTML={{ __html: this.state.script }}></span>;
return (
<div>
<div className={styles.scriptEditor}>
<div className={styles.container}>
<div className={`ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}`}>
<div className="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
<span className="ms-font-xl ms-fontColor-white">The Modern Script Editor web part!</span>
<p className="ms-font-l ms-fontColor-white"></p>
<Button description='Opens the Sample Dialog' onClick={this._showDialog.bind(this)}>Edit snippet</Button>
</div>
</div>
</div>
</div>
<Dialog
isOpen={this.state.showDialog}
type={DialogType.normal}
onDismiss={this._closeDialog.bind(this)}
title='Embed'
subText='Paste your script, markup or embed code below. Note that scripts will only run in view mode.'
isBlocking={true}
className={'ScriptPart'}
>
<TextField multiline rows={15} onChanged={this._onScriptEditorTextChanged.bind(this)} value={this.state.script} />
<DialogFooter>
<Button buttonType={ButtonType.primary} onClick={this._closeDialog.bind(this)}>Save</Button>
<Button onClick={this._cancelDialog.bind(this)}>Cancel</Button>
</DialogFooter>
{viewMode}
</Dialog>
</div>);
}
}

View File

@ -0,0 +1,4 @@
.ScriptPart .ms-Dialog-main {
width: 65%;
max-width: 65%;
}

View File

@ -0,0 +1,9 @@
/// <reference types="mocha" />
import { assert } from 'chai';
describe('ScriptEditorWebPart', () => {
it('should do something', () => {
assert.ok(true);
});
});

View File

@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "commonjs",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"types": [
"es6-promise",
"es6-collections",
"webpack-env"
]
}
}

View File

@ -0,0 +1,8 @@
// Type definitions for Microsoft ODSP projects
// Project: ODSP
/* Global definition for UNIT_TEST builds
Code that is wrapped inside an if(UNIT_TEST) {...}
block will not be included in the final bundle when the
--ship flag is specified */
declare const UNIT_TEST: boolean;

View File

@ -0,0 +1 @@
/// <reference path="@ms/odsp.d.ts" />