Page Sections Navigation (#797)

* basic interaction between web parts

* final desktop-ready version

* web parts icons

* readme

* configuration gif in readme

* custom css updates and example
This commit is contained in:
Alex Terentiev 2019-03-09 02:59:15 -08:00 committed by Vesa Juvonen
parent 16e7afd05f
commit 060dd3438a
31 changed files with 18545 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,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,11 @@
{
"@microsoft/generator-sharepoint": {
"isCreatingSolution": false,
"environment": "spo",
"version": "1.7.1",
"libraryName": "page-sections-navigation",
"libraryId": "bf7b299c-3bac-47cc-9f44-43eb180335d8",
"packageManager": "npm",
"componentType": "webpart"
}
}

View File

@ -0,0 +1,55 @@
# Page Sections Navigation
Sample web parts allowing to add sections navigation to the SharePoint page.
![Navigation configuration](./assets/page-nav.gif)
## Used SharePoint Framework Version
![drop](https://img.shields.io/badge/drop-1.7.1-green.svg)
## Applies to
* [SharePoint Framework](http://dev.office.com/sharepoint/docs/spfx/sharepoint-framework-overview)
* [Office 365 developer tenant](http://dev.office.com/sharepoint/docs/spfx/set-up-your-developer-tenant)
## Solution
Solution|Author(s)
--------|---------
page-sections-navigation|Alex Terentiev (MVP, [Sharepointalist Inc.](http://www.sharepointalist.com), [AJIXuMuK](https://github.com/AJIXuMuK), [@alexaterentiev](https://twitter.com/alexaterentiev))
## Version history
Version|Date|Comments
-------|----|--------
1.0|February 27, 2019|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 repo
* move to right folder
* in the command line run:
* `npm install`
* `gulp bundle --ship`
* `gulp package-solution --ship`
* from the _sharepoint/solution_ folder, deploy the .sppkg file to the App catalog in your tenant
* in the site where you want to test this solution
* add the app named _page-sections-navigation-client-side-solution_
* edit a page
* add _Page Sections Navigation_ web part
* add as much _Page Sections Navigation Anchor_ web parts as you want - each anchor adds an item to the navigation
* configure web parts
## Features
This sample illustrates how to use SharePoint Framework Dynamic Data features to connect web parts on the page.
It also can be used as ready-to-go solution to add page sections navigation to SharePoint pages.
## Custom CSS
The web parts in the sample allow to use custom CSS to override the styles. You can set _Custom CSS URL_ property of *Page Sections Navigation* web part and include css classes for both Navigation and Anchor in referenced file.
Please, refer [custom css sample](./assets/psn-custom.css) for the CSS sample.

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 MiB

View File

@ -0,0 +1,42 @@
/* --------------- */
/* Page Navigation */
/* --------------- */
/* Root container that breaks DOM flow. Use it for additional offsets */
.psn-layer {
}
/* Main container for navigation */
.psn-container {
background: red !important;
}
/* navigation list (ul) */
.psn-nav {
margin: 10px 0 !important;
}
/* navigation item (li) */
.psn-navItem {
margin-right: 50px !important;
}
/* navigation link */
.psn-navItemLink:hover {
border-bottom: 2px solid #f4f4f4;
}
/* --------------- */
/* Page Nav Anchor */
/* --------------- */
/* Container */
.psn-anchorTitle {
margin: 20px;
}
.psn-anchorTitleText {
font-size: 30px;
font-weight: 700;
}

View File

@ -0,0 +1,26 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"page-sections-navigation-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/pageSectionsNavigation/PageSectionsNavigationWebPart.js",
"manifest": "./src/webparts/pageSectionsNavigation/PageSectionsNavigationWebPart.manifest.json"
}
]
},
"page-sections-navigation-anchor-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/pageSectionsNavigationAnchor/PageSectionsNavigationAnchorWebPart.js",
"manifest": "./src/webparts/pageSectionsNavigationAnchor/PageSectionsNavigationAnchorWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"PageSectionsNavigationStrings": "lib/loc/{locale}.js"
}
}

View File

@ -0,0 +1,4 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/copy-assets.schema.json",
"deployCdnPath": "temp/deploy"
}

View File

@ -0,0 +1,7 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
"workingDir": "./temp/deploy/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "page-sections-navigation",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,13 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "page-sections-navigation-client-side-solution",
"id": "bf7b299c-3bac-47cc-9f44-43eb180335d8",
"version": "1.0.0.4",
"includeClientSideAssets": true,
"skipFeatureDeployment": true
},
"paths": {
"zippedPackage": "solution/page-sections-navigation.sppkg"
}
}

View File

@ -0,0 +1,10 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/core-build/serve.schema.json",
"port": 4321,
"https": true,
"initialPage": "https://localhost:5432/workbench",
"api": {
"port": 5432,
"entryPath": "node_modules/@microsoft/sp-webpart-workbench/lib/api/"
}
}

View File

@ -0,0 +1,4 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json",
"cdnBasePath": "<!-- PATH TO CDN -->"
}

View File

@ -0,0 +1,7 @@
'use strict';
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.`);
build.initialize(gulp);

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,40 @@
{
"name": "page-sections-navigation",
"version": "0.0.1",
"private": true,
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"@microsoft/sp-core-library": "1.7.1",
"@microsoft/sp-lodash-subset": "1.7.1",
"@microsoft/sp-office-ui-fabric-core": "1.7.1",
"@microsoft/sp-webpart-base": "1.7.1",
"@types/es6-promise": "0.0.33",
"@types/react": "16.4.2",
"@types/react-dom": "16.0.5",
"@types/webpack-env": "1.13.1",
"react": "16.3.2",
"react-dom": "16.3.2",
"scrollparent": "^2.0.1",
"smoothscroll-polyfill": "^0.4.3"
},
"resolutions": {
"@types/react": "16.4.2"
},
"devDependencies": {
"@microsoft/sp-build-web": "1.7.1",
"@microsoft/sp-tslint-rules": "1.7.1",
"@microsoft/sp-module-interfaces": "1.7.1",
"@microsoft/sp-webpart-workbench": "1.7.1",
"gulp": "~3.9.1",
"@types/chai": "3.4.34",
"@types/mocha": "2.2.38",
"ajv": "~5.2.2"
}
}

View File

@ -0,0 +1,6 @@
export interface IAnchorItem {
title?: string;
uniqueId?: string;
//scrollTop?: number;
domElement?: HTMLElement;
}

View File

@ -0,0 +1,3 @@
export type NavPosition = 'section' | 'top';
export type NavTheme = 'light' | 'dark';
export type NavAlign = 'flex-start' | 'center' | 'flex-end';

View File

@ -0,0 +1 @@
// A file is required to be in the root of the /src directory by the TypeScript compiler

View File

@ -0,0 +1,26 @@
define([], function () {
return {
"NavGroupName": "Navigation Settings",
"ScrollBehaviorFieldLabel": "Scroll behavior",
"AutoScrollBehavior": "Auto",
"SmoothScrollBehavior": "Smooth",
"PositionLabel": "Navigation position",
"PositionSection": "Inside section",
"PositionTop": "Top of page content",
"ThemeLabel": "Navigation Theme color",
"ThemeLight": "Light",
"ThemeDark": "Dark",
"AlignLabel": "Navigation align",
"AlignLeft": "Left",
"AlignCenter": "Center",
"AlignRight": "Right",
"HomeNavItemCbxLabel": "Show \"Home\" navigation item",
"HomeNavItemTextLabel": "\"Home\" navigation item text",
"HomeNavItemDefaultText": "Home",
"CustomCSSLabel": "Custom CSS URL",
"NavigationWebPartPlaceholderText": "This text is visible in Edit mode only to allow easier edit web part properties.",
"NavAnchorGroupName": "Anchor Settings",
"ShowTitleFieldLabel": "Show anchor title in Read mode",
"AnchorTitlePlaceholder": "Enter a title to be displayed in the page navigation",
}
});

View File

@ -0,0 +1,29 @@
declare interface IPageSectionsNavigationStrings {
NavGroupName: string;
ScrollBehaviorFieldLabel: string;
AutoScrollBehavior: string;
SmoothScrollBehavior: string;
PositionLabel: string;
PositionSection: string;
PositionTop: string;
ThemeLabel: string;
ThemeLight: string;
ThemeDark: string;
AlignLabel: string;
AlignLeft: string;
AlignCenter: string;
AlignRight: string;
HomeNavItemCbxLabel: string;
HomeNavItemTextLabel: string;
HomeNavItemDefaultText: string;
CustomCSSLabel: string;
NavigationWebPartPlaceholderText: string;
NavAnchorGroupName: string;
ShowTitleFieldLabel: string;
AnchorTitlePlaceholder: string;
}
declare module 'PageSectionsNavigationStrings' {
const strings: IPageSectionsNavigationStrings;
export = strings;
}

View File

@ -0,0 +1,3 @@
declare module "scrollparent" {
export default function Scrollparent(node: Element): Element;
}

View File

@ -0,0 +1,30 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "54bf2203-2546-44b4-ab33-61aee56349ff",
"alias": "PageSectionsNavigationWebPart",
"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,
"supportsFullBleed": true,
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
"group": { "default": "Other" },
"title": { "default": "Page Sections Navigation" },
"description": { "default": "Master web part to display Page Sections Navigation menu" },
"officeFabricIconFontName": "Favicon",
"properties": {
"scrollBehavior": "auto",
"position": "section",
"isDark": false,
"align": "left"
}
}]
}

View File

@ -0,0 +1,275 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version, DisplayMode } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneDropdown,
PropertyPaneToggle,
PropertyPaneChoiceGroup,
PropertyPaneCheckbox,
PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
//import { SPComponentLoader } from '@microsoft/sp-loader';
import * as strings from 'PageSectionsNavigationStrings';
import { PageSectionsNavigation, IPageSectionsNavigationProps } from './components/PageSectionsNavigation';
import { IDynamicDataSource, IDynamicDataCallables, IDynamicDataPropertyDefinition } from '@microsoft/sp-dynamic-data';
import { IAnchorItem } from '../../common/model';
import { NavPosition, NavAlign } from '../../common/types';
export interface IPageSectionsNavigationWebPartProps {
scrollBehavior: ScrollBehavior;
position: NavPosition;
isDark: boolean;
align: NavAlign;
showHomeItem: boolean;
homeItemText: string;
customCssUrl: string;
}
export default class PageSectionsNavigationWebPart extends BaseClientSideWebPart<IPageSectionsNavigationWebPartProps> implements IDynamicDataCallables {
private _dataSources: IDynamicDataSource[] = [];
//private _anchors: IAnchorItem[];
protected onInit(): Promise<void> {
const { customCssUrl } = this.properties;
this._onAnchorChanged = this._onAnchorChanged.bind(this);
this._initDataSources();
this.context.dynamicDataProvider.registerAvailableSourcesChanged(this._initDataSources.bind(this, true));
this._addCustomCss(customCssUrl);
this.context.dynamicDataSourceManager.initializeSource(this);
return super.onInit();
}
public render(): void {
const anchors = this._dataSources && this._dataSources.map(ds => ds.getPropertyValue('anchor') as IAnchorItem);
const {
scrollBehavior,
position,
isDark,
align,
showHomeItem,
homeItemText
} = this.properties;
const element: React.ReactElement<IPageSectionsNavigationProps> = React.createElement(
PageSectionsNavigation,
{
anchors: anchors,
scrollBehavior: scrollBehavior,
position: position,
theme: isDark ? 'dark' : 'light',
align: align,
isEditMode: this.displayMode === DisplayMode.Edit,
homeItem: showHomeItem && homeItemText
}
);
ReactDom.render(element, this.domElement);
}
public getPropertyDefinitions(): ReadonlyArray<IDynamicDataPropertyDefinition> {
return [{
id: 'position',
title: 'position'
}];
}
public getPropertyValue(propertyId: string): NavPosition {
switch (propertyId) {
case 'position':
return this.properties.position;
}
throw new Error('Bad property id');
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected onPropertyPaneFieldChanged(propertyPath: string, oldValue: any, newValue: any) {
if (propertyPath === 'position') {
this.context.dynamicDataSourceManager.notifyPropertyChanged('position');
}
else if (propertyPath === 'customCssUrl') {
//
// removing prev css
//
if (oldValue) {
const oldCssLink = this._getCssLink(oldValue);
if (oldCssLink) {
oldCssLink.parentElement.removeChild(oldCssLink);
}
}
this._addCustomCss(newValue);
}
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
const align = this.properties.align || 'left';
return {
pages: [
{
header: {
description: ''
},
groups: [
{
groupName: strings.NavGroupName,
groupFields: [
PropertyPaneDropdown('scrollBehavior', {
label: strings.ScrollBehaviorFieldLabel,
options: [{
key: 'auto',
text: strings.AutoScrollBehavior
}, {
key: 'smooth',
text: strings.SmoothScrollBehavior
}],
selectedKey: this.properties.scrollBehavior || 'auto'
}),
PropertyPaneDropdown('position', {
label: strings.PositionLabel,
options: [{
key: 'section',
text: strings.PositionSection
}, {
key: 'top',
text: strings.PositionTop
}],
selectedKey: this.properties.position || 'top'
}),
PropertyPaneToggle('isDark', {
label: strings.ThemeLabel,
offText: strings.ThemeLight,
onText: strings.ThemeDark,
checked: !!this.properties.isDark
}),
PropertyPaneChoiceGroup('align', {
label: strings.AlignLabel,
options: [{
key: 'flex-start',
text: strings.AlignLeft,
checked: align === 'flex-start',
iconProps: {
officeFabricIconFontName: 'AlignLeft'
}
}, {
key: 'center',
text: strings.AlignCenter,
checked: align === 'center',
iconProps: {
officeFabricIconFontName: 'AlignCenter'
}
}, {
key: 'flex-end',
text: strings.AlignRight,
checked: align === 'flex-end',
iconProps: {
officeFabricIconFontName: 'AlignRight'
}
}]
}),
PropertyPaneCheckbox('showHomeItem', {
text: strings.HomeNavItemCbxLabel,
checked: this.properties.showHomeItem
}),
PropertyPaneTextField('homeItemText', {
label: strings.HomeNavItemTextLabel,
value: this.properties.homeItemText || strings.HomeNavItemDefaultText
}),
PropertyPaneTextField('customCssUrl', {
label: strings.CustomCSSLabel,
value: this.properties.customCssUrl
})
]
}
]
}
]
};
}
private _initDataSources(reRender?: boolean) {
const availableDataSources = this.context.dynamicDataProvider.getAvailableSources();
if (availableDataSources && availableDataSources.length) {
const dataSources = this._dataSources;
//
// removing deleted data sources if any
//
const availableDataSourcesIds = availableDataSources.map(ds => ds.id);
for (let i = 0, len = dataSources.length; i < len; i++) {
let dataSource = dataSources[i];
if (availableDataSourcesIds.indexOf(dataSource.id) == -1) {
dataSources.splice(i, 1);
try {
this.context.dynamicDataProvider.unregisterPropertyChanged(dataSource.id, 'anchor', this._onAnchorChanged);
}
catch (err) { }
i--;
len--;
}
}
//
// adding new data sources
//
for (let i = 0, len = availableDataSources.length; i < len; i++) {
let dataSource = availableDataSources[i];
if (!dataSource.getPropertyDefinitions().filter(pd => pd.id === 'anchor').length) {
continue; // we don't need data sources other than anchors
}
if (!dataSources || !dataSources.filter(ds => ds.id === dataSource.id).length) {
dataSources.push(dataSource);
this.context.dynamicDataProvider.registerPropertyChanged(dataSource.id, 'anchor', this._onAnchorChanged);
//this._anchors.push(dataSource.getPropertyValue('anchor') as IAnchorItem);
}
}
}
// TODO: unregister events for deleted data sources
//this._dataSources = availableDataSources;
if (reRender) {
this.render();
}
}
private _onAnchorChanged() {
this.render();
//console.log(ds.getPropertyValue('anchor'));
}
private _addCustomCss(customCssUrl: string) {
if (customCssUrl) {
//SPComponentLoader doesn't work on Comm Sites: https://github.com/SharePoint/sp-dev-docs/issues/3503
//SPComponentLoader.loadCss(this.properties.customCssUrl);
const head = document.head;
let styleEl = this._getCssLink(customCssUrl);
if (!styleEl) {
styleEl = document.createElement('link');
styleEl.setAttribute('rel', 'stylesheet');
styleEl.setAttribute('href', customCssUrl);
head.appendChild(styleEl);
}
}
}
private _getCssLink(customCssUrl: string): Element | null {
const head = document.head;
return head.querySelector(`link[href="${customCssUrl}"]`);
}
}

View File

@ -0,0 +1,57 @@
@import '~@microsoft/sp-office-ui-fabric-core/dist/sass/SPFabricCore.scss';
.psnLayer {
position: sticky;
top: 0;
z-index: 500;
.pageSectionsNavigation {
border-bottom: 1px solid;
border-bottom-color: "[theme:neutralLighter, default: #f4f4f4]";
background: "[theme:white, default: #fff]";
.nav {
list-style: none;
display: flex;
height: 40px;
padding-inline-start: 40px;
padding-inline-end: 40px;
margin: 0;
.navItem {
margin-right: 20px;
display: flex;
align-items: center;
height: 100%;
.navItemLink {
cursor: pointer;
min-width: 20px;
text-align: center;
display: inline-block;
color: "[theme:neutralSecondary, default: #666666]";
&:hover {
color: "[theme:linkHovered, default: #004578]";
}
}
}
}
&.dark {
background: "[theme: neutralDark, default: #212121]";
border-bottom-color: "[theme:white, default: #fff]";
.nav {
.navItem {
.navItemLink {
color: "[theme:white, default: #fff]";
&:hover {
color: "[theme:neutralLighter, default: #f4f4f4]";
}
}
}
}
}
}
}

View File

@ -0,0 +1,197 @@
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import styles from './PageSectionsNavigation.module.scss';
import { IAnchorItem } from '../../../common/model';
import { css, getDocument, ICssInput } from 'office-ui-fabric-react/lib/Utilities';
import * as strings from 'PageSectionsNavigationStrings';
import Scrollparent from 'scrollparent';
import smoothscroll from 'smoothscroll-polyfill';
import { NavTheme, NavAlign, NavPosition } from '../../../common/types';
// kick off the polyfill!
smoothscroll.polyfill();
export interface IPageSectionsNavigationProps {
anchors: IAnchorItem[];
scrollBehavior: ScrollBehavior;
position: NavPosition;
theme: NavTheme;
align: NavAlign;
isEditMode: boolean;
homeItem?: string;
}
export interface IPageSectionsNavigationState {
isMounted?: boolean;
}
export class PageSectionsNavigation extends React.Component<IPageSectionsNavigationProps, IPageSectionsNavigationState> {
private _layerElement: HTMLElement | undefined;
private _host: Node;
private _sectionHostSpanRef = React.createRef<HTMLSpanElement>();
private _scrollableParent: Element;
private readonly _pageCanvasId = 'spPageCanvasContent';
private readonly _pageLayoutSelector = '[class*="layoutWrapper_"]';
constructor(props: IPageSectionsNavigationProps) {
super(props);
this.state = {
isMounted: false
};
}
public componentWillMount() {
this._layerElement = this._getLayerElement();
}
public componentWillUpdate(nextProps: IPageSectionsNavigationProps) {
if (nextProps.position !== this.props.position) {
this._removeLayerElement();
this._layerElement = this._getLayerElement(nextProps.position);
}
else if (!this._layerElement) {
this._layerElement = this._getLayerElement();
}
}
public componentDidMount() {
this.setState({
isMounted: true
});
}
public componentWillUnmount() {
this._removeLayerElement();
}
public render(): React.ReactElement<IPageSectionsNavigationProps> {
const { align, theme, isEditMode, homeItem } = this.props;
const { isMounted } = this.state;
const rootDivClassNames: ICssInput = {
'psn-container': true
};
rootDivClassNames[styles.pageSectionsNavigation] = true;
if (theme === 'dark') {
rootDivClassNames[styles.dark] = true;
}
const navItems: JSX.Element[] = this.props.anchors.map((anchor, index) => {
return <li className={css(styles.navItem, 'psn-navItem')}>
<a className={css(styles.navItemLink, 'psn-navItemLink')} onClick={this._onClick.bind(this, anchor)}>{anchor.title}</a>
</li>;
});
if (homeItem) {
navItems.unshift(<li className={css(styles.navItem, 'psn-navItem')}>
<a className={css(styles.navItemLink, 'psn-navItemLink')} onClick={this._onHomeClick.bind(this)}>{homeItem}</a>
</li>);
}
return (
<span ref={this._sectionHostSpanRef}>
{
isEditMode && <span>{strings.NavigationWebPartPlaceholderText}</span>
}
{
this._layerElement &&
isMounted &&
ReactDOM.createPortal(
<div className={css(rootDivClassNames)}>
<ul className={css(styles.nav, 'psn-nav')} style={{ justifyContent: align }}>
{navItems}
</ul>
</div>,
this._layerElement
)
}
</span>
);
}
private _onHomeClick() {
if (!this._scrollableParent) {
this._initScrollParent();
}
this._scrollableParent.scroll({
top: 0,
behavior: this.props.scrollBehavior
});
}
private _onClick(anchor: IAnchorItem, index: number) {
if (anchor.domElement) {
anchor.domElement.scrollIntoView({
behavior: this.props.scrollBehavior,
block: 'start'
});
}
}
private _getLayerElement(position?: NavPosition): HTMLElement | undefined {
const host = this._getHost(position);
if (host !== this._host) {
this._removeLayerElement();
}
if (host) {
this._host = host;
if (!this._layerElement) {
const doc = getDocument();
if (!doc) {
return;
}
this._layerElement = doc.createElement('div');
this._layerElement.className = css(styles.psnLayer, 'psn-layer');
host.insertBefore(this._layerElement, host.firstChild);
}
}
return this._layerElement;
}
private _removeLayerElement(): void {
if (this._layerElement) {
const parentNode = this._layerElement.parentNode;
if (parentNode) {
parentNode.removeChild(this._layerElement);
}
this._layerElement = undefined;
}
}
private _getHost(position: NavPosition): Node | undefined {
const navPos = position || this.props.position;
const doc = getDocument();
let hostNode: Node;
if (navPos === 'section') {
hostNode = doc.getElementById(this._pageCanvasId) as Node;
}
else {
hostNode = doc.querySelector(this._pageLayoutSelector) as Node;
}
return hostNode;
}
private _initScrollParent() {
if (this._sectionHostSpanRef.current) {
this._scrollableParent = Scrollparent(this._sectionHostSpanRef.current);
}
}
}

View File

@ -0,0 +1,27 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "a4e172ec-a30d-456c-b81a-f38e043db5ae",
"alias": "PageSectionsNavigationAnchorWebPart",
"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,
"supportsFullBleed": true,
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
"group": { "default": "Other" },
"title": { "default": "Page Sections Navigation Anchor" },
"description": { "default": "Web part to create an anchor for Page Sections Navigation" },
"officeFabricIconFontName": "MiniLink",
"properties": {
"description": "Page Sections Navigation Anchor"
}
}]
}

View File

@ -0,0 +1,152 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField,
PropertyPaneCheckbox
} from '@microsoft/sp-webpart-base';
import * as strings from 'PageSectionsNavigationStrings';
import {
PageSectionsNavigationAnchor,
IPageSectionsNavigationAnchorProps
} from './components/PageSectionsNavigationAnchor';
import { IDynamicDataPropertyDefinition, IDynamicDataCallables, IDynamicDataSource } from '@microsoft/sp-dynamic-data';
import { IAnchorItem } from '../../common/model';
import { NavPosition } from '../../common/types';
export interface IPageSectionsNavigationAnchorWebPartProps {
title: string;
uniqueId: string;
showTitle: boolean;
}
export default class PageSectionsNavigationAnchorWebPart extends BaseClientSideWebPart<IPageSectionsNavigationAnchorWebPartProps> implements IDynamicDataCallables {
private _anchor: IAnchorItem;
private _pageNavDataSource: IDynamicDataSource;
protected onInit(): Promise<void> {
const {
title,
uniqueId
} = this.properties;
this._anchor = {
title: title,
uniqueId: uniqueId
};
this._initDataSource();
this.context.dynamicDataProvider.registerAvailableSourcesChanged(this._initDataSource.bind(this));
this.context.dynamicDataSourceManager.initializeSource(this);
if (!uniqueId) {
this._anchor.uniqueId = this.properties.uniqueId = `pagenavanchor-${this.context.instanceId}`;
this.context.dynamicDataSourceManager.notifyPropertyChanged('anchor');
}
return super.onInit();
}
public render(): void {
const { title, showTitle } = this.properties;
const position: NavPosition = this._pageNavDataSource ? this._pageNavDataSource.getPropertyValue('position') : 'top';
const element: React.ReactElement<IPageSectionsNavigationAnchorProps> = React.createElement(
PageSectionsNavigationAnchor,
{
displayMode: this.displayMode,
title: title,
showTitle: showTitle,
updateProperty: this._onTitleChanged.bind(this),
anchorElRef: (el => {
this._anchor.domElement = el; //this.domElement;
//this._anchor.scrollTop = this.domElement.scrollTop;
this.context.dynamicDataSourceManager.notifyPropertyChanged('anchor');
}),
navPosition: position
}
);
ReactDom.render(element, this.domElement);
}
public getPropertyDefinitions(): ReadonlyArray<IDynamicDataPropertyDefinition> {
return [{
id: 'anchor',
title: 'Anchor'
}];
}
public getPropertyValue(propertyId: string): IAnchorItem {
switch (propertyId) {
case 'anchor':
return this._anchor;
}
throw new Error('Bad property id');
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: ''
},
groups: [
{
groupName: strings.NavAnchorGroupName,
groupFields: [
PropertyPaneCheckbox('showTitle', {
text: strings.ShowTitleFieldLabel,
checked: this.properties.showTitle
})
]
}
]
}
]
};
}
private _onTitleChanged(title: string) {
this._anchor.title = this.properties.title = title;
this.context.dynamicDataSourceManager.notifyPropertyChanged('anchor');
}
private _initDataSource(): void {
const availableDataSources = this.context.dynamicDataProvider.getAvailableSources();
let hasPageNavDataSource = false;
for (let i = 0, len = availableDataSources.length; i < len; i++) {
let dataSource = availableDataSources[i];
if (dataSource.getPropertyDefinitions().filter(pd => pd.id === 'position').length) {
this._pageNavDataSource = dataSource;
this.context.dynamicDataProvider.registerPropertyChanged(dataSource.id, 'position', this._onPageNavPositionChanged.bind(this));
hasPageNavDataSource = true;
break;
}
}
if (!hasPageNavDataSource && this._pageNavDataSource) {
this._pageNavDataSource = undefined;
}
}
private _onPageNavPositionChanged() {
this.render();
}
}

View File

@ -0,0 +1,50 @@
.webPartTitle {
position: relative;
font-size: 14px;
font-weight: 100;
margin-bottom: 11px;
color: "[theme:neutralPrimary, default: #333333]";
@media (min-width: 320px) {
font-size: 21px;
}
@media (min-width: 480px) {
font-size: 24px;
}
// Edit mode
textarea {
background-color: transparent;
border: none;
box-sizing: border-box;
color: inherit;
display: block;
font-family: inherit;
font-size: inherit;
font-weight: inherit;
height: 40px;
line-height: inherit;
margin: 0;
outline: 0;
overflow: hidden;
resize: none;
text-align: inherit;
white-space: pre;
width: 100%;
}
// View mode
span {
font-weight: 300;
}
.anchorEl {
position: absolute;
top: 0;
&.offset {
top: -40px;
}
}
}

View File

@ -0,0 +1,61 @@
import * as React from 'react';
import styles from './PageSectionsNavigationAnchor.module.scss';
import { DisplayMode } from '@microsoft/sp-core-library';
import * as strings from 'PageSectionsNavigationStrings';
import { css, ICssInput } from 'office-ui-fabric-react/lib/Utilities';
import { NavPosition } from '../../../common/types';
export interface IPageSectionsNavigationAnchorProps {
displayMode: DisplayMode;
title: string;
updateProperty: (value: string) => void;
showTitle: boolean;
anchorElRef: (el: HTMLDivElement) => void;
navPosition: NavPosition;
}
export class PageSectionsNavigationAnchor extends React.Component<IPageSectionsNavigationAnchorProps, {}> {
constructor(props: IPageSectionsNavigationAnchorProps) {
super(props);
this._onChange = this._onChange.bind(this);
}
/**
* Default React component render method
*/
public render(): React.ReactElement<IPageSectionsNavigationAnchorProps> {
const { title, displayMode, showTitle, anchorElRef, navPosition } = this.props;
const anchorElClassNames: ICssInput = {};
anchorElClassNames[styles.anchorEl] = true;
if (navPosition === 'section') {
anchorElClassNames[styles.offset] = true;
}
if (displayMode === DisplayMode.Edit || showTitle) {
return (
<div className={css(styles.webPartTitle, 'psn-anchorTitle')}>
<div className={css(anchorElClassNames)} ref={anchorElRef}></div>
{
displayMode === DisplayMode.Edit
? <textarea
placeholder={strings.AnchorTitlePlaceholder}
aria-label={strings.AnchorTitlePlaceholder}
onChange={this._onChange}
defaultValue={title}></textarea>
: <span className={'psn-anchorTitleText'}>{title}</span>}
</div>
);
}
return null;
}
/**
* Process the text area change
*/
private _onChange(event: React.ChangeEvent<HTMLTextAreaElement>) {
this.props.updateProperty(event.target.value as string);
}
}

View File

@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"outDir": "lib",
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"es6-promise",
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection"
]
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules",
"lib"
]
}

View File

@ -0,0 +1,30 @@
{
"extends": "@microsoft/sp-tslint-rules/base-tslint.json",
"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-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-use-before-declare": true,
"no-with-statement": true,
"semicolon": true,
"trailing-comma": false,
"typedef": false,
"typedef-whitespace": false,
"use-named-parameter": true,
"variable-name": false,
"whitespace": false
}
}