-
Notifications
You must be signed in to change notification settings - Fork 0
Getting Started Configure the Web Part
In the Command Prompt (Windows) or Terminal (macOS) run:
Windows
md jQueryUI-Webpart
macOS
mkdir jQueryUI-Webpart
In the Command Prompt or Terminal run the following command to navigate to the project directory created in the previous step:
Windows
cd /Users/<user>/jQueryUI-Webpart
macOS
cd /Users/<user>/jQueryUI-Webpart
Create a new base web part by running the Yeoman SharePoint Generator from the Command Prompt or Terminal:
Windows
yo @microsoft/sharepoint
macOS
yo @microsoft/sharepoint
NOTE
-
Accept the default No javascript web framework as the framework you would like to use and choose Enter.
-
Accept the default JQueryUI as your web part name and choose Enter.
-
Accept the default JQueryUI description as your web part description and choose Enter.
Yeoman will install the required dependencies and scaffold the solution files in addition to the jQueryUI web part. Once complete the web part can be opened in a code editor.
In the Command Prompt or Terminal, enter the following code to install jQuery npm package:
npm install --save jquery
Next , enter the following code to install jQueryUI npm package:
npm install --save jqueryui
Install the typings for the project. Beginning with TypeScript 2.0, you can use npm to install the necessary typings.
In the Command Prompt or Terminal, enter the following code to install needed types:
npm install --save @types/jquery
npm install --save @types/jqueryui
By default, any dependencies you add are bundled into the web part bundle. In some cases, this is not ideal. You can choose to unbundle these dependencies from the web part bundle.
In your code editor, open the file config\config.json.
This file contains information about your bundle(s) and any external dependencies.
The entries region contains the default bundle information - in this case, the jQuery web part bundle. When you add more web parts to your solution, you will see one entry per web part.
"entries": [
{
"entry": "./lib/webparts/jQuery/jQueryWebPart.js",
"manifest": "./src/webparts/jQuery/jQueryWebPart.manifest.json",
"outputPath": "./dist/j-query.bundle.js",
}
]
You can use the externals section contains the libraries that are not bundled with the default bundle.
"externals": {},
To exclude jQuery and jQueryUI from the default bundle, add the modules to the externals section:
"jquery":"node_modules/jquery/dist/jquery.min.js",
"jqueryui":"node_modules/jqueryui/jquery-ui.min.js"
Now when you build your project, jQuery and jQueryUI will not be bundled into your default web part bundle.
To work with SharePoint List data the jQueryUI web part needs to define a list model. To retrieve the lists, you need two models.
Open a code editor and navigate to src\webparts\jQueryUI\JQueryUIWebPart.ts and define the following interface models just above the jQueryWebPart class:
export interface ISPLists {
value: ISPList[];
}
export interface ISPList {
Title: string;
Description: string;
}
The ISPList interface holds the SharePoint list information the web part connects to.
To work with the jQueryUI web part in the local SharePoint Workbench you will need a mock store that returns mock data.
Create a new file inside the src\webparts\jQueryUI folder named MockHttpClient.ts.
Copy the following code into MockHttpClient.ts:
import { ISPList } from './jQueryUIWebPart';
export default class MockHttpClient {
private static _items: ISPList[] = [{ Title: 'Mock List', Description: '1' },
{ Title: 'Mock List 2', Description: '2' },
{ Title: 'Mock List 3', Description: '3' }];
public static get(): Promise<ISPList[]> {
return new Promise<ISPList[]>((resolve) => {
resolve(MockHttpClient._items);
});
}
}
To use the MockHttpClient class in the JQueryUIWebPart class you will need to import the MockHttpClient module.
To import the MockHttpClient module, open the JQueryUIWebPart.ts file and copy and paste the following code just below import { IHelloWorldWebPartProps }
from './IJQueryUIWebPartProps';.
import MockHttpClient from './MockHttpClient';
Next add the following private method that mocks the list retrieval inside the JQueryUIWebPart class.
private _getMockListData(): Promise<ISPLists> {
return MockHttpClient.get()
.then((data: ISPList[]) => {
var listData: ISPLists = { value: data };
return listData;
}) as Promise<ISPLists>;
}
Save JQueryUIWebPart.ts.
To retrieve List data from the current site you will need use SharePoint REST APIs to retrieve the lists and their respective data from the site, located at https://.sharepoint.com/_api/web/lists.
The SharePoint Framework includes a helper class spHttpClient
to execute REST API requests against SharePoint. It adds default headers, manages the digest needed for writes, and collects telemetry that helps the service to monitor the performance of an application.
To use the spHttpClient helper class, you will first need to import them from the @microsoft/sp-http module
.
Open JQueryUIWebPart.ts if not already open and scroll to the top of the file.
Copy and paste the following code just below import MockHttpClient from './MockHttpClient';
:
import {
SPHttpClient,
SPHttpClientResponse
} from '@microsoft/sp-http';
Add the following private method to retrieve List data from SharePoint inside the JQueryUIWebPart class:
private _getListData(): Promise<ISPLists> {
return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists/GetByTitle('` + this.properties.list + `')/items`, SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
return response.json();
});
}
The method uses the spHttpClient helper class and issues a get request. It uses the ISPLists model and also applies a filter to not retrieve hidden lists.
Next, immediately following the _getListData() method above, add the following private method to retrieve a List of Lists from SharePoint inside the JQueryUIWebPart class:
private _getLists(): Promise<ISPLists> {
return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists?$filter=Hidden eq false`, SPHttpClient.configurations.v1)
.then((response: Response) => {
return response.json();
});
}
Save JQueryUIWebpart.ts.
Open the JQueryUIWebPart class.
The SharePoint Workbench provides the flexibility to test web parts in a local environment and from a SharePoint site. The SharePoint Framework supports this capability by helping you understand which environment your web part is running from using an EnvironmentType module.
To use the module, you first need to import the Environment and the EnvironmentType modules from the @microsoft/sp-core-library
bundle and add it to the import section at the top as shown in the following code:
import {
Environment,
EnvironmentType
} from '@microsoft/sp-core-library';
Add the following private method inside the HelloWorldWebPart class to call the respective methods to retrieve List data:
// Call methods for list data retrieval
private _renderListAsync(): void {
// Mock List data
if (Environment.type === EnvironmentType.Local) {
this._getMockListData().then((response) => {
this._renderList(response.value);
}); }
else {
const list: string = this.properties.list;
// Check if a list is selected
if (!list || list.toString == null) {
this.domElement.innerHTML = `
<div class="${styles.container}">
<span>${escape(this.properties.description)}</span>
<p>No list has been selected. Open the tool pane and select a list.</p>
</div>
`;
return;
}
this._getListData()
.then((response) => {
this._renderList(response.value);
});
}
}
Save JQueryUIWebPart.ts.
At the top of the file, where you can find other imports, add the following imports:
import * as jQuery from 'jquery';
import 'jqueryui';
Next, you'll load some external css files. To do that, use the module loader. Add the following import:
import { SPComponentLoader } from '@microsoft/sp-loader';
To load the jQueryUI styles, in the JQueryWebPart web part class, you'll need to add a constructor and use the newly imported SPComponentLoader documented later in this tutorial.
Now you need to render the List data with the value fetched from the REST API.
Add the following private method inside the JQueryUIWebPart class:
// Render the list data with the values fetched from the REST API
private _renderList(items: ISPList[]): void {
// Clear the container for initial configuration
this.domElement.innerHTML = ``;
// Reset the Accordion to handle property changes
$('#accordion').remove();
// Set up html for the jQuery UI Accordion Widget to display collapsible content panels
// Learn more about the Accordion Widget at http://jqueryui.com/accordion/
let html: string = '';
html += `<div id='accordion'>`;
items.forEach((item: ISPList) => {
html += `
<div class='group'>
<h3>${item.Title}</h3>
<div>
<p> ${item.Description} </p>
</div>
</div>`;
});
this.domElement.innerHTML += html;
html += `</div>`;
To configure the base Accordion widget options when the web part is initially rendered add the following code below the _renderList method:
// Set up base Accordion options
const accordionOptions: JQueryUI.AccordionOptions = {
header: "> div > h3",
animate: this.properties.speed,
collapsible: true,
icons: {
header: 'ui-icon-circle-arrow-e',
activeHeader: 'ui-icon-circle-arrow-s'
}
};
Save JQueryUIWebPart.ts.
To provide a set of configurable jQueryUI effects and interactions, add the following code below the accordionOptions constructor:
// Set up configurable jQueryUI effects and interactions
if (this.properties.resize == false) {
jQuery(this.domElement).children('#accordion').accordion(accordionOptions);
} else {
jQuery(this.domElement).children('#accordion').accordion(accordionOptions).resizable({ghost: true, animate: true, autoHide: true, helper: 'ui-resizable-helper'});
}
if (this.properties.sort == false) {
jQuery(this.domElement).children('#accordion').accordion(accordionOptions);
} else {
jQuery(this.domElement).children('#accordion').accordion(accordionOptions).sortable();
}
}
public constructor() {
super();
// Load remote stylesheet
SPComponentLoader.loadCss('//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css');
}
public render(): void {
this._renderListAsync();
}
// Setup the Web Part Property Pane Dropdown options
private _dropdownOptions: IPropertyPaneDropdownOption[] = [];
public onInit<T>(): Promise<T> {
this._getLists()
.then((response) => {
this._dropdownOptions = response.value.map((list: ISPList) => {
return {
key: list.Title,
text: list.Title
};
});
});
return Promise.resolve();
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
// Set up core Property Pane options
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.SharePointOptions,
groupFields: [
PropertyPaneDropdown('list', {
label: 'List',
options: this._dropdownOptions
})
]
},
{
groupName: strings.JQueryOptions,
groupFields: [
PropertyPaneSlider('speed', {
label: 'Animation Speed',
min: 1,
max: 500
}),
PropertyPaneToggle('resize', {
label: 'Resizable',
onText: 'Enable',
offText: 'Disable'
}),
PropertyPaneToggle('sort', {
label: 'Sortable',
onText: 'Enable',
offText: 'Disable'
})
]
}
]
}
]
};
}
// Set Property Pane settings to non-reactive
protected get disableReactivePropertyChanges(): boolean {
return true;
}
}
Save and close JQueryUIWebPart.ts.