Skip to content

Instantly share code, notes, and snippets.

/cpm.tsx Secret

Created June 19, 2017 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/44b70cdcba0d119282bdba40937b0b6b to your computer and use it in GitHub Desktop.
Save anonymous/44b70cdcba0d119282bdba40937b0b6b to your computer and use it in GitHub Desktop.
import * as React from 'react';
import { ICloudPartManagerProps } from './ICloudPartManagerProps';
import { ICloudPartManagerState } from './ICloudPartManagerState';
import { escape } from '@microsoft/sp-lodash-subset';
import { SPComponentLoader } from '@microsoft/sp-loader';
import { Environment, EnvironmentType } from '@microsoft/sp-core-library';
export default class CloudPartManager extends React.Component<ICloudPartManagerProps, ICloudPartManagerState> {
constructor(props: ICloudPartManagerProps){
super(props);
this.state = {
loadingScripts: true,
error: null
};
}
public render(): React.ReactElement<ICloudPartManagerProps> {
return (
<div id="appContainer">
<div className="ms-font-l ms-fontColor-black" id={escape(this.props.name)}><p>Application to Load:</p> </div>
</div>
);
}
private componentDidMount(): void {
console.log('Environment type is: ' + Environment.type);
// only load the scripts on the new spfx pages.
if(Environment.type == EnvironmentType.SharePoint){
console.log("SharePoint: ", EnvironmentType.SharePoint);
console.log("Loading SharePoint scripts");
SPComponentLoader.loadScript('/_layouts/15/init.js', { globalExportsName: '$_global_init' })
.then((): Promise<{}> => { return SPComponentLoader.loadScript('/_layouts/15/MicrosoftAjax.js', { globalExportsName: 'Sys' }); })
.then((): Promise<{}> => { return SPComponentLoader.loadScript('/_layouts/15/SP.Runtime.js', { globalExportsName: 'SP' }); })
.then((): Promise<{}> => { return SPComponentLoader.loadScript('/_layouts/15/SP.js', { globalExportsName: 'SP' }); })
.then((): void => {
this.setState((prevState: ICloudPartManagerState, props: ICloudPartManagerProps): ICloudPartManagerState => {
prevState.loadingScripts = false;
return prevState;
});
});
} else if(Environment.type.toString() == EnvironmentType.SharePoint.toString()){
console.log("Classic SharePoint: ", EnvironmentType.ClassicSharePoint);
console.log("Not loading scripts since they already are loaded");
}
}
}
// Begin Closure
(function() {
// Insert HTML (required so it can be tokenized for multi use on same page)
var html = "<div id='metroContainer'>" +
"<ul id='wmatared' class='trains'>" +
"<li><div style='float: right; padding-right: 20px;'><a id='metroRefresh' href='#'>Refresh</a></div>" +
"<strong>RED LINE TRAINS:</strong></li>" +
"</ul>" +
"<ul id='wmatayel' class='trains'>" +
"<strong>YELLOW/GREEN LINE TRAINS:</strong>" +
"</ul> " +
"</div>" +
"<style> .trains { margin: 0; padding: 10px;} .trains li { list-style: none; margin: 0; padding; 0;} </style>";
var token = Math.random() * 100000000000000000;
console.log("using token: " + token);
html = tokenize(html, "metrocontainer", token);
//html = tokenize(html, "metrorefresh", token);
html = tokenize(html, "wmatared", token);
html = tokenize(html, "wmatayel", token);
console.log(html);
//document.write(html);
document.getElementById('metro').innerHTML = html;
// Register jQuery for script on demand (avoids double loading and allow async load)
//RegisterSod("jquery.js", "https:\u002f\u002fcode.jquery.com\u002fjquery-1.12.4.min.js" );
var pathname = window.location.pathname.split('/');
var relativeUrl = '';
if(pathname[1] == 'sites'){
relativeUrl = "/sites/" + pathname[2];
}
loadJQuery();
prepOnClick();
function loadJQuery(){
console.log('Relative URL: ', relativeUrl);
var jsFile = document.createElement("script");
jsFile.type = "application/javascript";
jsFile.src = relativeUrl + "/SiteAssets/spxRpp/jquery-1.12.4.min.js";
document.body.appendChild(jsFile);
}
function prepOnClick(){
document.getElementById('metroRefresh').onclick = metroRefresh;
}
// Call function ensuring jQuery is already loaded.
SP.SOD.executeFunc(relativeUrl + '/SiteAssets/spxRpp/jquery-1.12.4.min.js', null, function(){
//myscript1 is loaded now! its functions are available to use.
formatMetro();
});
function formatMetro(){
loadMetro()
$('#metroRefresh').click(metroRefresh);
}
function metroRefresh(e){
console.log("Clicked the refresh link")
if(typeof e !== 'undefined'){
e.preventDefault();
}
loadMetro();
}
function tokenize(source, find, token)
{
return source.replace(new RegExp(find, 'g'), find + token);
}
//formatMetro();
function loadMetro() {
$(".trainEntry").remove();
var redLine = $("#wmatared" + token);
var yellowLine = $("#wmatayel" + token);
var wmataAPI = "https://api.wmata.com/StationPrediction.svc/json/GetPrediction/B01,F01";
$.ajax({
data: "api_key=67te5y756nwun3x584v6hy3k",
url: wmataAPI,
success: function(parsed_json) {
console.log("Results are in");
var k = parsed_json["Trains"].length;
$.each(parsed_json["Trains"], function(k, v) {
var line = v["Line"];
var car = v["Car"];
var dest = v["DestinationName"];
var mins = v["Min"];
if(line == 'RD') {
redLine.append("<li class='trainEntry' data-id=" + car + ">" + dest + " - Minutes: " + mins + "</li>");
}
if(line == 'YL' || line == 'GR') {
yellowLine.append("<li class='trainEntry' data-id=" + car + ">" + dest + " - Minutes: " + mins + "</li>");
}
});
},
error: function() {
$("#wmata").append("Error receiving data from WMATA web service.");
}
});
}
// End Closure
})();
import * as React from 'react';
import * as ReactDom from 'react-dom';
import * as http from '@microsoft/sp-http';
import * as strings from 'cloudPartManagerStrings';
import CloudPartManager from './components/CloudPartManager';
import { Version } from '@microsoft/sp-core-library';
import { ICloudPartManagerWebPartProps } from './ICloudPartManagerWebPartProps';
import { BaseClientSideWebPart, IPropertyPaneConfiguration, PropertyPaneDropdown, IPropertyPaneDropdownOption } from '@microsoft/sp-webpart-base';
export default class CloudPartManagerWebPart extends BaseClientSideWebPart<ICloudPartManagerWebPartProps> {
private dropdownOptions: IPropertyPaneDropdownOption[];
private listsFetched: boolean;
public render(): void {
let pathname = window.location.pathname.split('/');
let relativeUrl = '';
if(pathname[1] == 'sites'){
relativeUrl = "/sites/" + pathname[2];
}
console.log('Relative URL: ', relativeUrl);
if(this.properties.name == 'Cloud Part Manager'){
this.properties.name = "Please select an application from the configuration panel.";
}
const scriptTag = document.createElement("script"), // create a script tag
firstScriptTag = document.getElementsByTagName("script")[0]; // find the first script tag in the document
//scriptTag.defer = true;
scriptTag.src = relativeUrl + '/SiteAssets/spxRpp/' + this.properties.name + '/main.js';
firstScriptTag.parentNode.insertBefore(scriptTag, firstScriptTag); // append the script to the DOM
console.log("Injected URL: ", scriptTag.src);
const element: React.ReactElement<ICloudPartManagerWebPartProps> = React.createElement(CloudPartManager, { name: this.properties.name } );
ReactDom.render(element, this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.1');
}
protected onPropertyPaneConfigurationStart(): void {
if(this.listsFetched){
return;
}
this.context.statusRenderer.displayLoadingIndicator(this.domElement, 'Folders');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
if (!this.listsFetched) {
this.fetchOptions().then((response) => {
this.dropdownOptions = response;
this.listsFetched = true;
//this.onDispose();
this.context.propertyPane.refresh();
});
}
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneDropdown('name', {
label: strings.RPPFieldLabel
, options: this.dropdownOptions
})
]
}]
}
]
};
} // end of property pane config
private fetchFolders(url: string): Promise<any> {
return this.context.spHttpClient.get(url, http.SPHttpClient.configurations.v1).then((response: http.SPHttpClientResponse) => {
this.context.statusRenderer.clearLoadingIndicator(this.domElement);
if (response.ok) {
return response.json();
} else {
console.log("WARNING - failed to hit URL " + url + ". Error = " + response.statusText);
return null;
}
});
}
private getSiteCollectionUrl(): string {
let relativeUrl = this.context.pageContext.web.serverRelativeUrl;
if(relativeUrl == '/'){
relativeUrl = "";
}
return relativeUrl;
}
private fetchOptions(): Promise<IPropertyPaneDropdownOption[]> {
let targetUrl = this.context.pageContext.web.absoluteUrl;
let siteColUrl = this.getSiteCollectionUrl();
const api = "/_api/web/GetFolderByServerRelativeUrl('" + siteColUrl + "/SiteAssets/spxRpp')/Folders";
targetUrl += api;
let url = targetUrl;
console.info("The relative path is: " + siteColUrl);
console.info("Hitting API for URL: " + url);
return this.fetchFolders(url).then((response) => {
var options: Array<IPropertyPaneDropdownOption> = new Array<IPropertyPaneDropdownOption>();
if(!response){
return;
}
response.value.map((list) => {
console.log("Found list with title = " + list.Name);
options.push({ key: list.Name, text: list.Name });
});
return options;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment