Merge branch 'main' into dependabot/npm_and_yarn/samples/react-appinsights-usage/multi-e1fe25fca3

This commit is contained in:
Hugo Bernier 2024-08-09 10:23:23 -04:00 committed by GitHub
commit 3893df985f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
156 changed files with 103634 additions and 64834 deletions

View File

@ -11942,7 +11942,7 @@
"This Web Part allows you to manage events in a calendar. Uses a list of existing calendars on any website. The location and name of the list and the dates of the events to be displayed are defined in the properties of the web part."
],
"creationDateTime": "2020-12-04",
"updateDateTime": "2023-12-29",
"updateDateTime": "2024-06-28",
"products": [
"SharePoint"
],
@ -14228,7 +14228,7 @@
"At the time of developing this sample, the Office 365 UI fabric does not have any control for displaying hierarchical information. This web part helps to display the hierarchical information from SharePoint list."
],
"creationDateTime": "2020-11-21",
"updateDateTime": "2020-11-21",
"updateDateTime": "2024-06-28",
"products": [
"SharePoint"
],
@ -14239,7 +14239,7 @@
},
{
"key": "SPFX-VERSION",
"value": "1.11.0"
"value": "1.18.2"
}
],
"thumbnails": [
@ -18740,10 +18740,10 @@
"shortDescription": "This solution contains an SPFx web part which shows a Kanban board using jqxKanban ReactJS component (from JQWidgets). The web part uses the default columns of the SharePoint Tasks list for showing the board's columns and the tasks.",
"url": "https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-kanban-board",
"longDescription": [
"This solution contains an SPFx web part which shows a Kanban board using jqxKanban ReactJS component (from JQWidgets). The web part uses the default columns of the SharePoint Tasks list for showing the board's columns and the tasks."
"This solution contains an SPFx web part which shows a Kanban board. The web part uses the default columns of the SharePoint Tasks list for showing the board's columns and the tasks."
],
"creationDateTime": "2020-07-02",
"updateDateTime": "2020-07-02",
"updateDateTime": "2024-05-26",
"products": [
"SharePoint"
],
@ -18754,7 +18754,7 @@
},
{
"key": "SPFX-VERSION",
"value": "1.13.0"
"value": "1.19.0"
},
{
"key": "SPFX-TEAMSTAB",
@ -18770,7 +18770,25 @@
"type": "image",
"order": 100,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-kanban-board/assets/kanbanofficeUI.gif",
"alt": "Kanban Board Web part"
"alt": "Kanban Board Web part in action"
},
{
"type": "image",
"order": 101,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-kanban-board/assets/kanbanimg1.png",
"alt": "Kanban Board Web part configuration of a bucket"
},
{
"type": "image",
"order": 102,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-kanban-board/assets/kanbanimg2.png",
"alt": "Kanban Board Web part item View"
},
{
"type": "image",
"order": 103,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-kanban-board/assets/kanbanimg3.png",
"alt": "Kanban Board Web part task list selection and status column order as bucket"
}
],
"authors": [
@ -18790,7 +18808,7 @@
},
{
"gitHubAccount": "petkir",
"company": "Cubido Business Solutions GmbH",
"company": "ACP CUBIDO Digital Solutions GmbH",
"pictureUrl": "https://github.com/petkir.png",
"name": "Peter Paul Kirschner",
"twitter": "petkir_at"
@ -26229,6 +26247,53 @@
}
]
},
{
"name": "pnp-sp-dev-spfx-web-parts-react-site-secure-function-call",
"source": "pnp",
"title": "Site Secure Function Call",
"shortDescription": "This combined SharePoint Framework and Azure Function solution is to provide the potentially most secure access from SharePoint Framework to any kind of third party API or Microsoft Graph.",
"url": "https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-office-offer-creation",
"longDescription": [
"This combined SharePoint Framework and Azure Function solution is to provide the potentially most secure access from SharePoint Framework to any kind of third party API, in fact here Microsoft Graph. It shows that AadHttpClient should be preferred over MSGraphClient."
],
"creationDateTime": "2024-07-12",
"updateDateTime": "2024-07-12",
"products": [
"SharePoint"
],
"metadata": [
{
"key": "CLIENT-SIDE-DEV",
"value": "React"
},
{
"key": "SPFX-VERSION",
"value": "1.18.2"
}
],
"thumbnails": [
{
"type": "image",
"order": 100,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-site-secure-function-call/assets/SetSiteDescreption.gif",
"alt": "App in action"
}
],
"authors": [
{
"gitHubAccount": "mmsharepoint",
"pictureUrl": "https://github.com/mmsharepoint.png",
"name": "Markus Moeller"
}
],
"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-sitepages-metadata",
"source": "pnp",

View File

@ -1 +1 @@
v14.17.6
v12.13.0

View File

@ -115,6 +115,7 @@ Version|Date|Comments
1.0.16|December 21, 2021|Upgraded to SPFx 1.12.1
1.0.17|October 25, 2022|Fixed issue deleting events (#2693)
1.0.18|December 29, 2022|Fixed stylelint issue (#4029)| Cleaned up old Type script versions and Upgraded Type script version
1.0.19|June 28, 2024| added filter by category | fixed the packages.json issues which prevent solution to build successfully.
## Minimal Path to Awesome

View File

@ -9,7 +9,7 @@
"This Web Part allows you to manage events in a calendar. Uses a list of existing calendars on any website. The location and name of the list and the dates of the events to be displayed are defined in the properties of the web part."
],
"creationDateTime": "2020-12-04",
"updateDateTime": "2023-12-29",
"updateDateTime": "2024-06-28",
"products": [
"SharePoint"
],

View File

@ -3,7 +3,7 @@
"solution": {
"name": "react-calendar-client-side-solution",
"id": "3a13208b-3874-4036-9262-4edd22e88187",
"version": "1.0.18.0",
"version": "1.0.19.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -3,6 +3,9 @@
"main": "lib/index.js",
"version": "1.0.12",
"private": true,
"engines": {
"node": ">=12.13.0"
},
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
@ -23,39 +26,40 @@
"@pnp/spfx-property-controls": "1.14.1",
"@types/draft-js": "^0.10.30",
"@types/globalize": "0.0.34",
"@types/jquery": "^3.3.29",
"@types/jquery": "3.5.30",
"@types/react-big-calendar": "^0.24.6",
"@uifabric/fluent-theme": "^0.16.7",
"browserslist": "^4.12.0",
"browserslist": "4.23.1",
"draft-js": "^0.10.5",
"draftjs-to-html": "^0.8.4",
"globalize": "^1.4.2",
"immutable": "^4.0.0-rc.12",
"jquery": "^3.5.0",
"moment": "^2.29.2",
"immutable": "4.3.6",
"jquery": "3.7.1",
"moment": "2.30.1",
"office-ui-fabric-react": "7.156.0",
"react": "16.9.0",
"react-big-calendar": "^0.24.6",
"react-dom": "16.9.0",
"react-draft-wysiwyg": "^1.13.2",
"react-draft-wysiwyg": "1.15.0",
"react-select": "^4.3.1",
"spfx-uifabric-themes": "^0.6.0",
"string-format": "^2.0.0",
"typescript": "^3.2.4",
"xml2js": "^0.5.0"
"typescript": "3.9.10",
"xml2js": "^0.4.19"
},
"resolutions": {
"@types/react": "16.7.22"
},
"devDependencies": {
"@microsoft/rush-stack-compiler-3.9": "0.4.47",
"@microsoft/sp-build-web": "1.18.2",
"@microsoft/sp-build-web": "1.20.1",
"@microsoft/sp-module-interfaces": "1.12.1",
"@microsoft/sp-tslint-rules": "1.12.1",
"@microsoft/sp-webpart-workbench": "1.12.1",
"@types/es6-promise": "0.0.33",
"@types/react": "16.9.36",
"@types/react-dom": "16.9.8",
"@types/webpack-env": "1.13.1",
"@types/xml2js": "^0.4.4",
"@types/xml2js": "0.4.14",
"@voitanos/jest-preset-spfx-react16": "^1.1.0",
"ajv": "~5.2.2",
"gulp": "4.0.2",
@ -63,9 +67,12 @@
"gulp-stylelint": "^8.0.0",
"jest": "^23.6.0",
"karma-junit-reporter": "^1.2.0",
"spfx-uifabric-themes": "^0.6.0",
"tslint-microsoft-contrib": "6.2.0",
"webpack-bundle-analyzer": "^4.10.2"
"stylelint": "^9.10.1",
"stylelint-config-standard": "^18.2.0",
"stylelint-scss": "^3.5.4",
"tslint": "^6.1.3",
"tslint-microsoft-contrib": "^6.2.0",
"webpack-bundle-analyzer": "^3.1.0"
},
"solution": {
"developer": {

View File

@ -0,0 +1,73 @@
import * as strings from "CalendarWebPartStrings";
import { IDatePickerStrings } from "office-ui-fabric-react";
export const Constants = {
CategoryColumn: "Category",
MetaDataFieldType: "SP.Taxonomy.TaxonomyFieldValue",
EventResult_LocalStorage: "eventResult",
CalendarEventsWithLocalTime_LocalStorage: "calendarEventsWithLocalTime",
AndConditionStart: "<And>",
AndConditionEnd: "</And>",
OrConditionStart: "<Or>",
OrConditionEnd: "</Or>",
latitude: 58.485601,
longitude: 19.807854,
eventLayoutOverviewPageURL: `{0}/_layouts/15/Event.aspx?ListGuid={1}&ItemId={2}`
};
export const DayPickerStrings: IDatePickerStrings = {
months: [
strings.January,
strings.February,
strings.March,
strings.April,
strings.May,
strings.June,
strings.July,
strings.August,
strings.September,
strings.October,
strings.November,
strings.December,
],
shortMonths: [
strings.Jan,
strings.Feb,
strings.Mar,
strings.Apr,
strings.May,
strings.Jun,
strings.Jul,
strings.Aug,
strings.Sep,
strings.Oct,
strings.Nov,
strings.Dez,
],
days: [
strings.Sunday,
strings.Monday,
strings.Tuesday,
strings.Wednesday,
strings.Thursday,
strings.Friday,
strings.Saturday,
],
shortDays: [
strings.ShortDay_S,
strings.ShortDay_M,
strings.ShortDay_T,
strings.ShortDay_W,
strings.ShortDay_Thursday,
strings.ShortDay_Friday,
strings.ShortDay_Sunday,
],
goToToday: strings.GoToDay,
prevMonthAriaLabel: strings.PrevMonth,
nextMonthAriaLabel: strings.NextMonth,
prevYearAriaLabel: strings.PrevYear,
nextYearAriaLabel: strings.NextYear,
closeButtonAriaLabel: strings.CloseDate,
isRequiredErrorMessage: strings.IsRequired,
invalidInputErrorMessage: strings.InvalidDateFormat,
};

View File

@ -0,0 +1,4 @@
export interface IOption {
key: string;
text: string;
}

View File

@ -10,6 +10,9 @@ import * as moment from 'moment';
import { SiteUser } from "@pnp/sp/src/siteusers";
import { IUserPermissions } from './IUserPermissions';
import parseRecurrentEvent from './parseRecurrentEvent';
import { IComboBoxOption } from '@fluentui/react';
import { Constants } from "../common/Constants";
import { Text } from "@microsoft/sp-core-library";
// Class Services
export default class spservices {
@ -450,7 +453,7 @@ export default class spservices {
* @returns {Promise< IEventData[]>}
* @memberof spservices
*/
public async getEvents(siteUrl: string, listId: string, eventStartDate: Date, eventEndDate: Date): Promise<IEventData[]> {
public async getEvents(siteUrl: string, listId: string, eventStartDate: Date, eventEndDate: Date, categories: IComboBoxOption[]): Promise<IEventData[]> {
let events: IEventData[] = [];
if (!siteUrl) {
@ -463,28 +466,13 @@ export default class spservices {
for (const cat of categoryDropdownOption) {
categoryColor.push({ category: cat.text, color: await this.colorGenerate() });
}
let camlQueryExpression = this.setUpQueryExpression(eventStartDate, eventEndDate, categories);
const web = new Web(siteUrl);
const results = await web.lists.getById(listId).usingCaching().renderListDataAsStream(
{
DatesInUtc: true,
ViewXml: `<View><ViewFields><FieldRef Name='RecurrenceData'/><FieldRef Name='Duration'/><FieldRef Name='Author'/><FieldRef Name='Category'/><FieldRef Name='Description'/><FieldRef Name='ParticipantsPicker'/><FieldRef Name='Geolocation'/><FieldRef Name='ID'/><FieldRef Name='EndDate'/><FieldRef Name='EventDate'/><FieldRef Name='ID'/><FieldRef Name='Location'/><FieldRef Name='Title'/><FieldRef Name='fAllDayEvent'/><FieldRef Name='EventType'/><FieldRef Name='UID' /><FieldRef Name='fRecurrence' /></ViewFields>
<Query>
<Where>
<And>
<Geq>
<FieldRef Name='EventDate' />
<Value IncludeTimeValue='false' Type='DateTime'>${moment(eventStartDate).format('YYYY-MM-DD')}</Value>
</Geq>
<Leq>
<FieldRef Name='EventDate' />
<Value IncludeTimeValue='false' Type='DateTime'>${moment(eventEndDate).format('YYYY-MM-DD')}</Value>
</Leq>
</And>
</Where>
</Query>
<RowLimit Paged=\"FALSE\">2000</RowLimit>
</View>`
ViewXml: camlQueryExpression
}
);
@ -571,6 +559,86 @@ export default class spservices {
}
}
/**
*
* @private
* @param {Date} eventStartDate
* @param {Date} eventEndDate
* @param {IOption[]} departments
* @returns {string} camlQuery
* @memberof spservices
*/
private setUpQueryExpression(
eventStartDate: Date,
eventEndDate: Date,
categories: IComboBoxOption[]
) {
let camlQuery = `
<View>
<ViewFields>
<FieldRef Name='RecurrenceData'/>
<FieldRef Name='Duration'/>
<FieldRef Name='Author'/>
<FieldRef Name='Category'/>
<FieldRef Name='Description'/>
<FieldRef Name='ParticipantsPicker'/>
<FieldRef Name='Geolocation'/>
<FieldRef Name='ID'/>
<FieldRef Name='EndDate'/>
<FieldRef Name='EventDate'/>
<FieldRef Name='Location'/>
<FieldRef Name='Title'/>
<FieldRef Name='fAllDayEvent'/>
<FieldRef Name='EventType'/>
<FieldRef Name='UID' />
<FieldRef Name='fRecurrence' />
</ViewFields>
<Query>
<Where>
<And>
<Geq>
<FieldRef Name='EventDate' />
<Value IncludeTimeValue='false' Type='DateTime'>${moment(eventStartDate).format("YYYY-MM-DD")}</Value>
</Geq>
{0}
<Leq>
<FieldRef Name='EventDate' />
<Value IncludeTimeValue='false' Type='DateTime'>${moment(eventEndDate).format("YYYY-MM-DD")}</Value>
</Leq>
{1}
{2}
</And>
</Where>
</Query>
<RowLimit Paged=\"FALSE\">2000</RowLimit>
</View>`;
let categoryCondition = `
<Eq>
<FieldRef Name='Category' />
<Value Type='Choice'>{0}</Value>
</Eq>`;
const deptsLength: number = categories.length;
let queryResult: string = "";
if (deptsLength > 0) {
if (deptsLength == 1) {
return Text.format(camlQuery, Constants.AndConditionStart, Text.format(categoryCondition, categories[0].key), Constants.AndConditionEnd);
} else {
let orCondition: string = `${Constants.OrConditionStart}{0}{1}${Constants.OrConditionEnd}`;
queryResult = Text.format(orCondition, Text.format(categoryCondition, categories[0].key), Text.format(categoryCondition, categories[1]));
for (let i = 2; i < categories.length; i++) {
const category = categories[i];
queryResult = Text.format(orCondition, Text.format(categoryCondition, category.key), queryResult);
}
}
return Text.format(camlQuery, Constants.AndConditionStart, queryResult, Constants.AndConditionEnd);
}
return Text.format(camlQuery, "", queryResult, "");
}
/**
*
* @private

View File

@ -11,8 +11,8 @@ import {
} from '@microsoft/sp-property-pane';
import * as strings from 'CalendarWebPartStrings';
import Calendar from './components/Calendar';
import { ICalendarProps } from './components/ICalendarProps';
import Calendar from './components/Calendar/Calendar';
import { ICalendarProps } from './components/Calendar/ICalendarProps';
import { PropertyFieldDateTimePicker, DateConvention, TimeConvention, IDateTimeFieldValue } from '@pnp/spfx-property-controls/lib/PropertyFieldDateTimePicker';
import { BaseClientSideWebPart } from "@microsoft/sp-webpart-base";
@ -299,4 +299,4 @@ export default class CalendarWebPart extends BaseClientSideWebPart<ICalendarWebP
]
};
}
}
}

View File

@ -1,7 +1,7 @@
@import "~@microsoft/sp-office-ui-fabric-core/dist/sass/SPFabricCore.scss";
@import "~office-ui-fabric-react/dist/sass/References.scss";
@import "./node_modules/spfx-uifabric-themes/office.theme.vars";
@import "../../themes";
@import "../../../themes";
:export {
/* stylelint-disable property-case */

View File

@ -8,7 +8,7 @@ import * as strings from 'CalendarWebPartStrings';
import 'react-big-calendar/lib/css/react-big-calendar.css';
require('./calendar.css');
import { CommunicationColors, FluentCustomizations, FluentTheme } from '@uifabric/fluent-theme';
import Year from './Year';
import Year from '../Year/Year';
import { Calendar as MyCalendar, momentLocalizer } from 'react-big-calendar';
@ -36,22 +36,23 @@ import {
Spinner,
SpinnerSize,
MessageBar,
MessageBarType,
MessageBarType
} from 'office-ui-fabric-react';
import { IComboBoxOption, SelectableOptionMenuItemType } from '@fluentui/react';
import { EnvironmentType } from '@microsoft/sp-core-library';
import { mergeStyleSets } from 'office-ui-fabric-react/lib/Styling';
import { WebPartTitle } from "@pnp/spfx-controls-react/lib/WebPartTitle";
import { Placeholder } from "@pnp/spfx-controls-react/lib/Placeholder";
import { WebPartContext } from "@microsoft/sp-webpart-base";
import { DisplayMode } from '@microsoft/sp-core-library';
import spservices from '../../../services/spservices';
import spservices from '../../../../services/spservices';
import { stringIsNullOrEmpty } from '@pnp/common';
import { Event } from '../../../controls/Event/event';
import { IPanelModelEnum } from '../../../controls/Event/IPanelModeEnum';
import { IEventData } from './../../../services/IEventData';
import { IUserPermissions } from './../../../services/IUserPermissions';
import { Event } from '../../../../controls/Event/event';
import { IPanelModelEnum } from '../../../../controls/Event/IPanelModeEnum';
import { IEventData } from './../../../../services/IEventData';
import { IUserPermissions } from './../../../../services/IUserPermissions';
import Category from '../Category/Category';
import { IOption } from '../../../../services/IOption';
//const localizer = BigCalendar.momentLocalizer(moment);
@ -64,11 +65,14 @@ const localizer = momentLocalizer(moment);
export default class Calendar extends React.Component<ICalendarProps, ICalendarState> {
private spService: spservices = null;
private userListPermissions: IUserPermissions = undefined;
public constructor(props) {
super(props);
this.state = {
showDialog: false,
categories: [],
selectedCategories: [],
eventData: [],
selectedEvent: undefined,
isloading: true,
@ -79,11 +83,31 @@ export default class Calendar extends React.Component<ICalendarProps, ICalendarS
this.onDismissPanel = this.onDismissPanel.bind(this);
this.onSelectEvent = this.onSelectEvent.bind(this);
this.onSelectSlot = this.onSelectSlot.bind(this);
this.onChangeCategories = this.onChangeCategories.bind(this);
this.spService = new spservices(this.props.context);
moment.locale(this.props.context.pageContext.cultureInfo.currentUICultureName);
}
/**
* @private
* @param {*} selectedCatogries
* @memberof Calendar
*/
private async onChangeCategories(selectedCategories: IComboBoxOption[]) {
try {
this.setState({
selectedCategories: selectedCategories
});
await this.loadEvents();
} catch (error) {
this.setState({
hasError: true,
errorMessage: error.message,
isloading: false,
});
}
}
private onDocumentCardClick(ev: React.SyntheticEvent<HTMLElement, Event>) {
ev.preventDefault();
ev.stopPropagation();
@ -118,12 +142,20 @@ export default class Calendar extends React.Component<ICalendarProps, ICalendarS
*/
private async loadEvents() {
try {
// Teste Properties
if (!this.props.list || !this.props.siteUrl || !this.props.eventStartDate.value || !this.props.eventEndDate.value) return;
this.userListPermissions = await this.spService.getUserPermissions(this.props.siteUrl, this.props.list);
const eventsData: IEventData[] = await this.spService.getEvents(escape(this.props.siteUrl), escape(this.props.list), this.props.eventStartDate.value, this.props.eventEndDate.value);
let eventsData: IEventData[] = [];
if (this.state.selectedCategories.length > 0) {
eventsData = await this.spService.getEvents(
escape(this.props.siteUrl),
escape(this.props.list),
this.props.eventStartDate.value,
this.props.eventEndDate.value,
this.state.selectedCategories
);
}
this.setState({ eventData: eventsData, hasError: false, errorMessage: "" });
} catch (error) {
@ -134,7 +166,9 @@ export default class Calendar extends React.Component<ICalendarProps, ICalendarS
* @memberof Calendar
*/
public async componentDidMount() {
this.setState({ isloading: true });
const categories: IOption[] = await this.spService.getChoiceFieldOptions(this.props.siteUrl, this.props.list, 'Category');
this.setState({ isloading: true, categories: categories, selectedCategories: categories});
await this.loadEvents();
this.setState({ isloading: false });
}
@ -296,7 +330,6 @@ export default class Calendar extends React.Component<ICalendarProps, ICalendarS
};
}
/**
*
* @param {*} date
@ -342,6 +375,11 @@ export default class Calendar extends React.Component<ICalendarProps, ICalendarS
<div>
{this.state.isloading ? <Spinner size={SpinnerSize.large} label={strings.LoadingEventsLabel} /> :
<div className={styles.container}>
<Category
catogries={this.state.categories}
selectedCategories={this.state.selectedCategories}
onChangeCategories={this.onChangeCategories}
></Category>
<MyCalendar
dayPropGetter={this.dayPropGetter}
localizer={localizer}

View File

@ -0,0 +1,16 @@
import { IPanelModelEnum} from '../../../../controls/Event/IPanelModeEnum';
import { IEventData } from './../../../../services/IEventData';
import { IComboBoxOption } from '@fluentui/react';
export interface ICalendarState {
showDialog: boolean;
categories: IComboBoxOption[];
selectedCategories: IComboBoxOption[];
eventData: IEventData[];
selectedEvent: IEventData;
panelMode?: IPanelModelEnum;
startDateSlot?: Date;
endDateSlot?:Date;
isloading: boolean;
hasError: boolean;
errorMessage: string;
}

View File

@ -0,0 +1,80 @@
import React from 'react';
import { ICategoryProps, ICategoryState } from "./ICategory";
import { ComboBox, IComboBoxOption, SelectableOptionMenuItemType } from '@fluentui/react';
export default class Category extends React.PureComponent<ICategoryProps, ICategoryState> {
private selectableOptions = this.props.catogries.filter(
option =>
(option.itemType === SelectableOptionMenuItemType.Normal || option.itemType === undefined) && !option.disabled,
);
public constructor(props) {
super(props);
this.state = {
selectedKeys: this.props.selectedCategories.length == 0 ?
[String('selectAll'), ...this.props.catogries.map(o => o.key as string)] :
[String('selectAll'), ...this.props.selectedCategories.map(o => o.key as string)]
};
}
private onChange = (event, option, index, value) => {
const selected = option?.selected;
const { selectedKeys } = this.state;
const currentSelectedOptionKeys = selectedKeys.filter(key => key !== 'selectAll');
const selectAllState = currentSelectedOptionKeys.length === this.selectableOptions.length;
if (option) {
if (option?.itemType === SelectableOptionMenuItemType.SelectAll) {
selectAllState
? this.setState({ selectedKeys: [] }, () => { this.updateSelectableCategories(); })
: this.setState({ selectedKeys: ['selectAll', ...this.selectableOptions.map(o => o.key as string)] }, () => { this.updateSelectableCategories(); });
}
else {
const updatedKeys = selected
? [...currentSelectedOptionKeys, option!.key as string]
: currentSelectedOptionKeys.filter(k => k !== option.key);
if (updatedKeys.length === this.selectableOptions.length) {
updatedKeys.push('selectAll');
}
this.setState({ selectedKeys: updatedKeys, }, () => { this.updateSelectableCategories(); });
}
}
}
private updateSelectableCategories() {
const currentSelectedCategories: IComboBoxOption[] = [];
if (this.state.selectedKeys.length >= 0) {
this.state.selectedKeys.forEach(key => {
const category: IComboBoxOption[] = this.selectableOptions.filter(opt => opt.key === key);
if (category.length > 0) {
currentSelectedCategories.push(category[0]);
}
});
}
this.props.onChangeCategories(currentSelectedCategories);
}
public render(): React.ReactElement {
return (
<div>
<ComboBox
label="Select Category"
multiSelect
options={[
{ key: 'selectAll', text: 'Select All', itemType: SelectableOptionMenuItemType.SelectAll },
...this.props.catogries
]}
selectedKey={this.state.selectedKeys}
onChange={this.onChange}
/>
</div>
);
}
}

View File

@ -0,0 +1,10 @@
import { IComboBoxOption } from '@fluentui/react';
export interface ICategoryProps {
catogries: IComboBoxOption[];
selectedCategories: IComboBoxOption[];
onChangeCategories: (onChangeCategories: IComboBoxOption[]) => void;
}
export interface ICategoryState {
selectedKeys: string[];
}

View File

@ -1,13 +0,0 @@
import { IPanelModelEnum} from '../../../controls/Event/IPanelModeEnum';
import { IEventData } from './../../../services/IEventData';
export interface ICalendarState {
showDialog: boolean;
eventData: IEventData[];
selectedEvent: IEventData;
panelMode?: IPanelModelEnum;
startDateSlot?: Date;
endDateSlot?:Date;
isloading: boolean;
hasError: boolean;
errorMessage: string;
}

View File

@ -14,13 +14,14 @@
"inlineSources": false,
"strictNullChecks": false,
"noUnusedLocals": false,
"allowSyntheticDefaultImports":true,
"allowSyntheticDefaultImports": true,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"webpack-env"
"webpack-env",
"@types/jest"
],
"lib": [
"es5",
@ -33,4 +34,4 @@
"src/**/*.ts",
"src/**/*.tsx"
]
}
}

View File

@ -0,0 +1,38 @@
{
"name": "SPFx 1.18.2",
"image": "docker.io/m365pnp/spfx:1.18.2",
"customizations": {
"vscode": {
"extensions": [
"editorconfig.editorconfig",
"dbaeumer.vscode-eslint"
]
}
},
"forwardPorts": [
4321,
35729,
5432
],
"portsAttributes": {
"4321": {
"protocol": "https",
"label": "Manifest",
"onAutoForward": "silent",
"requireLocalPort": true
},
"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,352 @@
require('@rushstack/eslint-config/patch/modern-module-resolution');
module.exports = {
extends: ['@microsoft/eslint-config-spfx/lib/profiles/react'],
parserOptions: { tsconfigRootDir: __dirname },
overrides: [
{
files: ['*.ts', '*.tsx'],
parser: '@typescript-eslint/parser',
'parserOptions': {
'project': './tsconfig.json',
'ecmaVersion': 2018,
'sourceType': 'module'
},
rules: {
// Prevent usage of the JavaScript null value, while allowing code to access existing APIs that may require null. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/no-new-null': 1,
// Require Jest module mocking APIs to be called before any other statements in their code block. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/hoist-jest-mock': 1,
// Require regular expressions to be constructed from string constants rather than dynamically building strings at runtime. https://www.npmjs.com/package/@rushstack/eslint-plugin-security
'@rushstack/security/no-unsafe-regexp': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/adjacent-overload-signatures': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// CONFIGURATION: By default, these are banned: String, Boolean, Number, Object, Symbol
'@typescript-eslint/ban-types': [
1,
{
'extendDefaults': false,
'types': {
'String': {
'message': 'Use \'string\' instead',
'fixWith': 'string'
},
'Boolean': {
'message': 'Use \'boolean\' instead',
'fixWith': 'boolean'
},
'Number': {
'message': 'Use \'number\' instead',
'fixWith': 'number'
},
'Object': {
'message': 'Use \'object\' instead, or else define a proper TypeScript type:'
},
'Symbol': {
'message': 'Use \'symbol\' instead',
'fixWith': 'symbol'
},
'Function': {
'message': 'The \'Function\' type accepts any function-like value.\nIt provides no type safety when calling the function, which can be a common source of bugs.\nIt also accepts things like class declarations, which will throw at runtime as they will not be called with \'new\'.\nIf you are expecting the function to accept certain arguments, you should explicitly define the function shape.'
}
}
}
],
// RATIONALE: Code is more readable when the type of every variable is immediately obvious.
// Even if the compiler may be able to infer a type, this inference will be unavailable
// to a person who is reviewing a GitHub diff. This rule makes writing code harder,
// but writing code is a much less important activity than reading it.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/explicit-function-return-type': [
1,
{
'allowExpressions': true,
'allowTypedFunctionExpressions': true,
'allowHigherOrderFunctions': false
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: although this is a recommended rule, it is up to dev to select coding style.
// Set to 1 (warning) or 2 (error) to enable.
'@typescript-eslint/explicit-member-accessibility': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-array-constructor': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// RATIONALE: The "any" keyword disables static type checking, the main benefit of using TypeScript.
// This rule should be suppressed only in very special cases such as JSON.stringify()
// where the type really can be anything. Even if the type is flexible, another type
// may be more appropriate such as "unknown", "{}", or "Record<k,V>".
'@typescript-eslint/no-explicit-any': 1,
// RATIONALE: The #1 rule of promises is that every promise chain must be terminated by a catch()
// handler. Thus wherever a Promise arises, the code must either append a catch handler,
// or else return the object to a caller (who assumes this responsibility). Unterminated
// promise chains are a serious issue. Besides causing errors to be silently ignored,
// they can also cause a NodeJS process to terminate unexpectedly.
'@typescript-eslint/no-floating-promises': 2,
// RATIONALE: Catches a common coding mistake.
'@typescript-eslint/no-for-in-array': 2,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-misused-new': 2,
// RATIONALE: The "namespace" keyword is not recommended for organizing code because JavaScript lacks
// a "using" statement to traverse namespaces. Nested namespaces prevent certain bundler
// optimizations. If you are declaring loose functions/variables, it's better to make them
// static members of a class, since classes support property getters and their private
// members are accessible by unit tests. Also, the exercise of choosing a meaningful
// class name tends to produce more discoverable APIs: for example, search+replacing
// the function "reverse()" is likely to return many false matches, whereas if we always
// write "Text.reverse()" is more unique. For large scale organization, it's recommended
// to decompose your code into separate NPM packages, which ensures that component
// dependencies are tracked more conscientiously.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-namespace': [
1,
{
'allowDeclarations': false,
'allowDefinitionFiles': false
}
],
// RATIONALE: Parameter properties provide a shorthand such as "constructor(public title: string)"
// that avoids the effort of declaring "title" as a field. This TypeScript feature makes
// code easier to write, but arguably sacrifices readability: In the notes for
// "@typescript-eslint/member-ordering" we pointed out that fields are central to
// a class's design, so we wouldn't want to bury them in a constructor signature
// just to save some typing.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/parameter-properties': 0,
// RATIONALE: When left in shipping code, unused variables often indicate a mistake. Dead code
// may impact performance.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-unused-vars': [
1,
{
'vars': 'all',
// Unused function arguments often indicate a mistake in JavaScript code. However in TypeScript code,
// the compiler catches most of those mistakes, and unused arguments are fairly common for type signatures
// that are overriding a base class method or implementing an interface.
'args': 'none'
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-use-before-define': [
2,
{
'functions': false,
'classes': true,
'variables': true,
'enums': true,
'typedefs': true
}
],
// Disallows require statements except in import statements.
// In other words, the use of forms such as var foo = require("foo") are banned. Instead use ES6 style imports or import foo = require("foo") imports.
'@typescript-eslint/no-var-requires': 'error',
// RATIONALE: The "module" keyword is deprecated except when describing legacy libraries.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/prefer-namespace-keyword': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: it's up to developer to decide if he wants to add type annotations
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/no-inferrable-types': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: declaration of empty interfaces may be helpful for generic types scenarios
'@typescript-eslint/no-empty-interface': 0,
// RATIONALE: This rule warns if setters are defined without getters, which is probably a mistake.
'accessor-pairs': 1,
// RATIONALE: In TypeScript, if you write x["y"] instead of x.y, it disables type checking.
'dot-notation': [
1,
{
'allowPattern': '^_'
}
],
// RATIONALE: Catches code that is likely to be incorrect
'eqeqeq': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'for-direction': 1,
// RATIONALE: Catches a common coding mistake.
'guard-for-in': 2,
// RATIONALE: If you have more than 2,000 lines in a single source file, it's probably time
// to split up your code.
'max-lines': ['warn', { max: 2000 }],
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-async-promise-executor': 2,
// RATIONALE: Deprecated language feature.
'no-caller': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-compare-neg-zero': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-cond-assign': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-constant-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-control-regex': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-debugger': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-delete-var': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-duplicate-case': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-character-class': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-pattern': 1,
// RATIONALE: Eval is a security concern and a performance concern.
'no-eval': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-ex-assign': 2,
// RATIONALE: System types are global and should not be tampered with in a scalable code base.
// If two different libraries (or two versions of the same library) both try to modify
// a type, only one of them can win. Polyfills are acceptable because they implement
// a standardized interoperable contract, but polyfills are generally coded in plain
// JavaScript.
'no-extend-native': 1,
// Disallow unnecessary labels
'no-extra-label': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-fallthrough': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-func-assign': 1,
// RATIONALE: Catches a common coding mistake.
'no-implied-eval': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-invalid-regexp': 2,
// RATIONALE: Catches a common coding mistake.
'no-label-var': 2,
// RATIONALE: Eliminates redundant code.
'no-lone-blocks': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-misleading-character-class': 2,
// RATIONALE: Catches a common coding mistake.
'no-multi-str': 2,
// RATIONALE: It's generally a bad practice to call "new Thing()" without assigning the result to
// a variable. Either it's part of an awkward expression like "(new Thing()).doSomething()",
// or else implies that the constructor is doing nontrivial computations, which is often
// a poor class design.
'no-new': 1,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-func': 2,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-object': 2,
// RATIONALE: Obsolete notation.
'no-new-wrappers': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-octal': 2,
// RATIONALE: Catches code that is likely to be incorrect
'no-octal-escape': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-regex-spaces': 2,
// RATIONALE: Catches a common coding mistake.
'no-return-assign': 2,
// RATIONALE: Security risk.
'no-script-url': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-self-assign': 2,
// RATIONALE: Catches a common coding mistake.
'no-self-compare': 2,
// RATIONALE: This avoids statements such as "while (a = next(), a && a.length);" that use
// commas to create compound expressions. In general code is more readable if each
// step is split onto a separate line. This also makes it easier to set breakpoints
// in the debugger.
'no-sequences': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-shadow-restricted-names': 2,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-sparse-arrays': 2,
// RATIONALE: Although in theory JavaScript allows any possible data type to be thrown as an exception,
// such flexibility adds pointless complexity, by requiring every catch block to test
// the type of the object that it receives. Whereas if catch blocks can always assume
// that their object implements the "Error" contract, then the code is simpler, and
// we generally get useful additional information like a call stack.
'no-throw-literal': 2,
// RATIONALE: Catches a common coding mistake.
'no-unmodified-loop-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unsafe-finally': 2,
// RATIONALE: Catches a common coding mistake.
'no-unused-expressions': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unused-labels': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-useless-catch': 1,
// RATIONALE: Avoids a potential performance problem.
'no-useless-concat': 1,
// RATIONALE: The "var" keyword is deprecated because of its confusing "hoisting" behavior.
// Always use "let" or "const" instead.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'no-var': 2,
// RATIONALE: Generally not needed in modern code.
'no-void': 1,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-with': 2,
// RATIONALE: Makes logic easier to understand, since constants always have a known value
// @typescript-eslint\eslint-plugin\dist\configs\eslint-recommended.js
'prefer-const': 1,
// RATIONALE: Catches a common coding mistake where "resolve" and "reject" are confused.
'promise/param-names': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-atomic-updates': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-yield': 1,
// "Use strict" is redundant when using the TypeScript compiler.
'strict': [
2,
'never'
],
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'use-isnan': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
// Set to 1 (warning) or 2 (error) to enable.
// Rationale to disable: !!{}
'no-extra-boolean-cast': 0,
// ====================================================================
// @microsoft/eslint-plugin-spfx
// ====================================================================
'@microsoft/spfx/import-requires-chunk-name': 1,
'@microsoft/spfx/no-require-ensure': 2,
'@microsoft/spfx/pair-react-dom-render-unmount': 1
}
},
{
// For unit tests, we can be a little bit less strict. The settings below revise the
// defaults specified in the extended configurations, as well as above.
files: [
// Test files
'*.test.ts',
'*.test.tsx',
'*.spec.ts',
'*.spec.tsx',
// Facebook convention
'**/__mocks__/*.ts',
'**/__mocks__/*.tsx',
'**/__tests__/*.ts',
'**/__tests__/*.tsx',
// Microsoft convention
'**/test/*.ts',
'**/test/*.tsx'
],
rules: {}
}
]
};

View File

@ -9,9 +9,11 @@ node_modules
# Build generated files
dist
lib
release
solution
temp
*.sppkg
.heft
# Coverage directory used by tools like istanbul
coverage

View File

@ -0,0 +1,16 @@
!dist
config
gulpfile.js
release
src
temp
tsconfig.json
tslint.json
*.log
.yo-rc.json
.vscode

View File

@ -0,0 +1 @@
v18.18.0

View File

@ -1,12 +1,21 @@
{
"@microsoft/generator-sharepoint": {
"plusBeta": false,
"isCreatingSolution": true,
"nodeVersion": "18.18.0",
"sdksVersions": {
"@microsoft/microsoft-graph-client": "3.0.2",
"@microsoft/teams-js": "2.12.0"
},
"version": "1.18.2",
"libraryName": "spfx-new",
"libraryId": "d89e19bf-7bf0-4ca2-b131-ba9b8f2e5754",
"environment": "spo",
"version": "1.11.0",
"isDomainIsolated": false,
"libraryName": "spfx-react-hierarchy-view",
"libraryId": "2fd9a018-0cd9-4cca-9e84-4fac64b83333",
"packageManager": "npm",
"solutionName": "spfx-new",
"solutionShortDescription": "spfx-new description",
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"componentType": "webpart"
}
}
}

View File

@ -6,28 +6,30 @@ At the time of developing this sample, the Office 365 UI fabric does not have an
![Web part preview][figure1]
The web part is configured to render the mock data when added to the local SharePoint workbench.
![Local SharePoint Workbench Run][figure2]
When added to SharePoint site, the source list containing hierarchical information can be configured from web part properties.
The sample also provisions the list called “Hierarchy” which can be used as an example to start using the web part.
![SharePoint Run][figure3]
![SharePoint Run][figure2]
### SharePoint Asset
A SharePoint list (named Hierarchy) is provisioned to store the hierarchical data. The schema of the list is as below.
![List Schema][figure4]
![List Schema][figure3]
The Parent column is a lookup on same lists Title column.
The solution also provisions sample data to the Hierarchy list.
![List Sample Data][figure5]
![List Sample Data][figure4]
### NPM Packages Used
Below NPM packages are used to develop this sample.
1. sp-pnp-js (https://www.npmjs.com/package/sp-pnp-js)
2. react-orgchart (https://www.npmjs.com/package/react-orgchart)
3. array-to-tree (https://www.npmjs.com/package/array-to-tree)
1. @pnp/sp (https://pnp.github.io/pnpjs/)
2. react-orgchart (https://www.npmjs.com/package/react-orgchart)
3. array-to-tree (https://www.npmjs.com/package/array-to-tree)
## Compatibility
@ -36,16 +38,16 @@ Below NPM packages are used to develop this sample.
| Every SPFx version is only compatible with specific version(s) of Node.js. In order to be able to build this sample, please ensure that the version of Node on your workstation matches one of the versions listed in this section. This sample will not work on a different version of Node.|
|Refer to <https://aka.ms/spfx-matrix> for more information on SPFx compatibility. |
![SPFx 1.11](https://img.shields.io/badge/SPFx-1.11.0-green.svg)
![Node.js v10](https://img.shields.io/badge/Node.js-v10-green.svg)
![SPFx 1.18.2](https://img.shields.io/badge/SPFx-1.18.2-green.svg)
![Node.js v16 | v18](https://img.shields.io/badge/Node.js-v16%20%7C%20v18-green.svg)
![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg)
![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg "SharePoint Server 2019 requires SPFx 1.4.1 or lower")
![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1")
![Teams Incompatible](https://img.shields.io/badge/Teams-Incompatible-lightgrey.svg)
![Local Workbench Incompatible](https://img.shields.io/badge/Local%20Workbench-Incompatible-red.svg "The solution requires access to SharePoint content")
![Local Workbench Unsupported](https://img.shields.io/badge/Local%20Workbench-Unsupported-red.svg "Local workbench is no longer available as of SPFx 1.13 and above")
![Hosted Workbench Compatible](https://img.shields.io/badge/Hosted%20Workbench-Compatible-green.svg)
![Compatible with Remote Containers](https://img.shields.io/badge/Remote%20Containers-Compatible-green.svg)
## Applies to
* [SharePoint Framework Developer Preview](https://learn.microsoft.com/sharepoint/dev/spfx/sharepoint-framework-overview)
@ -55,11 +57,13 @@ Below NPM packages are used to develop this sample.
* [Nanddeep Nachan](https://github.com/nanddeepn)
* [Ravi Kulkarni](https://github.com/ravi16a87)
* [Smita Nachan](https://github.com/SmitaNachan)
## Version history
Version|Date|Comments
-------|----|--------
3.0.0|July 01, 2024|Upgraded to SPFx v1.18.2 (Nanddeep Nachan, Smita Nachan)
2.0.0|November 21, 2020|Upgraded to SPFx v1.11.0 (Nanddeep Nachan)
1.0.0|October 15, 2018|Initial release
@ -87,17 +91,15 @@ This sample web part shows how data stored in SharePoint list can be transformed
- Rendering hierarchical information
- SharePoint assets provisioning
- Creating extensible services
- Using mock data to test the web part locally
- Using @pnp/sp
- Using @react-orgchart
- Using @array-to-tree
[figure1]: ./assets/webpart-preview.png
[figure2]: ./assets/local-sharepoint-workbench-run.png
[figure3]: ./assets/sharepoint-run.gif
[figure4]: ./assets/list-schema.png
[figure5]: ./assets/list-sample-data.png
[figure2]: ./assets/sharepoint-run.gif
[figure3]: ./assets/list-schema.png
[figure4]: ./assets/list-sample-data.png
## Help

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

View File

@ -9,7 +9,7 @@
"At the time of developing this sample, the Office 365 UI fabric does not have any control for displaying hierarchical information. This web part helps to display the hierarchical information from SharePoint list."
],
"creationDateTime": "2020-11-21",
"updateDateTime": "2020-11-21",
"updateDateTime": "2024-06-28",
"products": [
"SharePoint"
],
@ -20,7 +20,7 @@
},
{
"key": "SPFX-VERSION",
"value": "1.11.0"
"value": "1.18.2"
}
],
"thumbnails": [

View File

@ -1,6 +1,6 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
"workingDir": "./temp/deploy/",
"workingDir": "./release/assets/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "spfx-react-hierarchy-view",
"accessKey": "<!-- ACCESS KEY -->"

View File

@ -7,6 +7,24 @@
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"developer": {
"name": "Contoso",
"privacyUrl": "https://contoso.com/privacy",
"termsOfUseUrl": "https://contoso.com/terms-of-use",
"websiteUrl": "https://contoso.com/my-app",
"mpnId": "m365pnp"
},
"metadata": {
"shortDescription": {
"default": "spfx-react-hierarchy-view description"
},
"longDescription": {
"default": "spfx-react-hierarchy-view description"
},
"screenshotPaths": [],
"videoUrl": "",
"categories": []
},
"features": [
{
"title": "react-display-hierarchy-deployment",
@ -22,14 +40,7 @@
]
}
}
],
"developer": {
"name": "Contoso",
"privacyUrl": "https://contoso.com/privacy",
"termsOfUseUrl": "https://contoso.com/terms-of-use",
"websiteUrl": "https://contoso.com/my-app",
"mpnId": "m365pnp"
}
]
},
"paths": {
"zippedPackage": "solution/spfx-react-hierarchy-view.sppkg"

View File

@ -0,0 +1,3 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/core-build/sass.schema.json"
}

View File

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

View File

@ -1,7 +1,16 @@
'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);
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.initialize(require('gulp'));

File diff suppressed because it is too large Load Diff

View File

@ -3,7 +3,7 @@
"version": "0.0.1",
"private": true,
"engines": {
"node": ">=0.10.0"
"node": ">=16.13.0 <17.0.0 || >=18.17.1 <19.0.0"
},
"scripts": {
"build": "gulp bundle",
@ -11,31 +11,39 @@
"test": "gulp test"
},
"dependencies": {
"@microsoft/sp-core-library": "1.11.0",
"@microsoft/sp-lodash-subset": "1.11.0",
"@microsoft/sp-office-ui-fabric-core": "1.11.0",
"@microsoft/sp-property-pane": "1.16.1",
"@microsoft/sp-webpart-base": "1.16.1",
"@pnp/sp": "^2.0.6",
"@fluentui/react": "8.106.4",
"@microsoft/sp-adaptive-card-extension-base": "1.18.2",
"@microsoft/sp-core-library": "1.18.2",
"@microsoft/sp-lodash-subset": "1.18.2",
"@microsoft/sp-office-ui-fabric-core": "1.18.2",
"@microsoft/sp-property-pane": "1.18.2",
"@microsoft/sp-webpart-base": "1.18.2",
"@pnp/sp": "^4.2.0",
"array-to-tree": "^3.3.0",
"office-ui-fabric-react": "6.214.0",
"react": "16.8.5",
"react-dom": "16.8.5",
"react-orgchart": "^1.0.5"
"react": "17.0.1",
"react-dom": "17.0.1",
"react-orgchart": "^1.0.5",
"tslib": "2.3.1"
},
"resolutions": {
"@types/react": "16.8.8"
},
"devDependencies": {
"@microsoft/eslint-config-spfx": "1.18.2",
"@microsoft/eslint-plugin-spfx": "1.18.2",
"@microsoft/rush-stack-compiler-3.3": "0.3.5",
"@microsoft/sp-build-web": "1.16.1",
"@microsoft/sp-module-interfaces": "1.11.0",
"@microsoft/sp-tslint-rules": "1.11.0",
"@microsoft/sp-webpart-workbench": "1.12.1",
"@types/chai": "3.4.34",
"@types/mocha": "2.2.38",
"ajv": "~6.12.3",
"gulp": "~4.0.2"
"@microsoft/rush-stack-compiler-4.7": "0.1.0",
"@microsoft/sp-build-web": "1.18.2",
"@microsoft/sp-module-interfaces": "1.18.2",
"@rushstack/eslint-config": "2.5.1",
"@types/react": "17.0.45",
"@types/react-dom": "17.0.17",
"@types/webpack-env": "1.15.2",
"ajv": "6.12.5",
"eslint": "8.7.0",
"eslint-plugin-react-hooks": "4.3.0",
"gulp": "4.0.2",
"typescript": "4.7.4"
},
"main": "lib/index.js"
}

View File

@ -3,29 +3,17 @@ import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import { BaseClientSideWebPart } from "@microsoft/sp-webpart-base";
import { IPropertyPaneConfiguration, PropertyPaneTextField } from "@microsoft/sp-property-pane";
import * as strings from 'ReactHierarchyViewWebPartStrings';
import ReactHierarchyView from './components/ReactHierarchyView';
import { IReactHierarchyViewProps } from './components/IReactHierarchyViewProps';
import {
Environment,
EnvironmentType,
ServiceScope
} from '@microsoft/sp-core-library';
import { sp } from "@pnp/sp/presets/all";
export interface IReactHierarchyViewWebPartProps {
listName: string;
}
export default class ReactHierarchyViewWebPart extends BaseClientSideWebPart<IReactHierarchyViewWebPartProps> {
public async onInit(): Promise<void> {
return super.onInit().then(_ => {
sp.setup({
spfxContext: this.context
});
});
await super.onInit();
}
public render(): void {

View File

@ -1,8 +1,7 @@
@import '~office-ui-fabric-react/dist/sass/References.scss';
@import '~react-orgchart/index.css';
@import '~@fluentui/react/dist/sass/References.scss';
:global(#workbenchPageContent) {
max-width: initial;
max-width: initial;
}
:global(.initechNode) {
@ -26,12 +25,59 @@
border-top: 2px solid #005a9e;
}
:global(.reactOrgChart .orgNodeChildGroup .nodeGroupLineVerticalMiddle) {
:global(.reactOrgChart .orgNodeChildGroup .nodeGroupLineVerticalMiddle) {
border-right: 2px solid #005a9e;
}
:global(.reactOrgChart) {
margin: 2px;
}
:global(.reactOrgChart .orgNodeChildGroup .node) {
border: solid 1px #000000;
display: inline-block;
padding: 4px;
width: 100px;
}
:global(.reactOrgChart .orgNodeChildGroup .nodeCell) {
text-align: center;
}
:global(.reactOrgChart .orgNodeChildGroup .nodeGroupCell) {
vertical-align: top;
}
:global(.reactOrgChart .orgNodeChildGroup .nodeGroupLineVerticalMiddle) {
height: 25px;
width: 50%;
border-right: 2px solid #000;
}
:global(.reactOrgChart .nodeLineBorderTop) {
border-top: solid 2px #000;
}
:global(.reactOrgChart table) {
border-collapse: collapse;
border: none;
margin: 0 auto;
}
:global(.reactOrgChart td) {
padding: 0;
}
:global(.reactOrgChart table.nodeLineTable) {
width: 100%;
}
:global(.reactOrgChart table td.nodeCell) {
width: 50%;
}
.reactHierarchyView {
.container {
.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);
@ -85,7 +131,7 @@
// Basic Button
outline: transparent;
position: relative;
font-family: "Segoe UI WestEuropean","Segoe UI",-apple-system,BlinkMacSystemFont,Roboto,"Helvetica Neue",sans-serif;
font-family: "Segoe UI WestEuropean", "Segoe UI", -apple-system, BlinkMacSystemFont, Roboto, "Helvetica Neue", sans-serif;
-webkit-font-smoothing: antialiased;
font-size: $ms-font-size-m;
font-weight: $ms-font-weight-regular;

View File

@ -1,16 +1,12 @@
import * as React from 'react';
import styles from './ReactHierarchyView.module.scss';
import { IReactHierarchyViewProps } from './IReactHierarchyViewProps';
import { escape } from '@microsoft/sp-lodash-subset';
import { IHierarchyService } from '../interfaces';
import { IHierarchyItem, Item } from '../interfaces/IHierarchyItem';
import { HierarchyItem, ISPHierarchyItem } from '../interfaces/IHierarchyItem';
import OrgChart from 'react-orgchart';
import { MessageBar, MessageBarType } from 'office-ui-fabric-react/lib/MessageBar';
import { MessageBar, MessageBarType, Spinner } from '@fluentui/react';
import { HierarchyService } from '../services';
import { MockHierarchyService } from '../mocks';
import { ServiceScope, Environment, EnvironmentType } from '@microsoft/sp-core-library';
import { Spinner, SpinnerSize } from 'office-ui-fabric-react/lib/Spinner';
import { ServiceScope } from '@microsoft/sp-core-library';
export interface IReactHierarchyState {
hierarchyItems: any;
@ -32,74 +28,53 @@ export default class ReactHierarchyView extends React.Component<IReactHierarchyV
};
}
public async componentDidMount() {
public async componentDidMount(): Promise<void> {
this.loadHierarchyView(this.props.listName);
}
public componentWillReceiveProps(nextProps: IReactHierarchyViewProps) {
this.loadHierarchyView(nextProps.listName);
public componentDidUpdate(newProps: IReactHierarchyViewProps): void {
this.loadHierarchyView(newProps.listName);
}
private loadHierarchyView(listName: string): void {
let serviceScope: ServiceScope = this.props.serviceScope;
const serviceScope: ServiceScope = this.props.serviceScope;
// Based on the type of environment, return the correct instance of the IHierarchyServiceInstance interface
if (Environment.type == EnvironmentType.SharePoint || Environment.type == EnvironmentType.ClassicSharePoint) {
// Mapping to be used when webpart runs in SharePoint.
this.HierarchyServiceInstance = serviceScope.consume(HierarchyService.serviceKey);
}
else {
// This means webpart is running in the local workbench or from a unit test.
// So we will need a non default implementation of the IHierarchyServiceInstance i.e. MockHierarchyService
this.HierarchyServiceInstance = serviceScope.consume(MockHierarchyService.serviceKey);
}
// Mapping to be used when web part runs in SharePoint.
this.HierarchyServiceInstance = serviceScope.consume(HierarchyService.serviceKey);
this.HierarchyServiceInstance.getHierarchyInfo(listName).then((hierarchyItems: any) => {
if (Environment.type == EnvironmentType.SharePoint || Environment.type == EnvironmentType.ClassicSharePoint) {
if (hierarchyItems.length > 0) {
let hierarchyNodes: Array<Item> = [];
var count: number;
for (count = 0; count < hierarchyItems.length; count++) {
hierarchyNodes.push(new Item(hierarchyItems[count].Id, hierarchyItems[count].Title, hierarchyItems[count].Url, hierarchyItems[count].Parent ? hierarchyItems[count].Parent.Id : undefined));
}
var arrayToTree: any = require('array-to-tree');
var orgChartHierarchyNodes: any = arrayToTree(hierarchyNodes);
var output: any = JSON.stringify(orgChartHierarchyNodes[0]);
this.setState({
hierarchyItems: JSON.parse(output),
isLoading: false,
showErrorMessage: false
});
this.HierarchyServiceInstance.getHierarchyInfo(listName).then((hierarchyItems: ISPHierarchyItem[]) => {
if (hierarchyItems.length > 0) {
const hierarchyNodes: Array<HierarchyItem> = [];
for (let count = 0; count < hierarchyItems.length; count++) {
hierarchyNodes.push(new HierarchyItem(hierarchyItems[count].Id, hierarchyItems[count].Title, hierarchyItems[count].Url!, hierarchyItems[count].Parent ? hierarchyItems[count].Parent.Id : undefined));
}
else {
this.setState({
hierarchyItems: [],
isLoading: false,
showErrorMessage: true,
errorMessage: "No records to be displayed"
});
}
}
else {
const arrayToTree: any = require('array-to-tree');
const orgChartHierarchyNodes: any = arrayToTree(hierarchyNodes);
const output: any = JSON.stringify(orgChartHierarchyNodes[0]);
this.setState({
hierarchyItems: JSON.parse(hierarchyItems),
hierarchyItems: JSON.parse(output),
isLoading: false,
showErrorMessage: false
});
}
})
.catch((error) =>
else {
this.setState({
hierarchyItems: [],
errorMessage: "Please verify web part configuration. Error details: " + error.message,
isLoading: false,
showErrorMessage: true
})
);
showErrorMessage: true,
errorMessage: "No records to be displayed"
});
}
}).catch((error) =>
this.setState({
hierarchyItems: [],
errorMessage: "Please verify web part configuration. Error details: " + error.message,
isLoading: false,
showErrorMessage: true
})
);
}
public render(): React.ReactElement<IReactHierarchyViewProps> {
@ -123,7 +98,7 @@ export default class ReactHierarchyView extends React.Component<IReactHierarchyV
);
}
private MyNodeComponent = ({ node }) => {
private MyNodeComponent = ({ node }: { node: any }): React.ReactElement => {
if (node.url) {
return (
<div className="initechNode">

View File

@ -1,4 +1,4 @@
export interface IHierarchyItem {
export interface ISPHierarchyItem {
Title: string;
Id: number;
parent_id: number;
@ -6,11 +6,12 @@ export interface IHierarchyItem {
Parent: any;
}
export class Item {
private id: number;
private title: string;
private url: string;
private parent_id?: number;
export class HierarchyItem {
id: number;
title: string;
url: string;
parent_id?: number;
children?: HierarchyItem[];
constructor(id: number, title: string, url: string, parent_id?: number) {
this.id = id;

View File

@ -1,6 +1,5 @@
import { ISPHierarchyItem } from "./IHierarchyItem";
export interface IHierarchyService {
getHierarchyInfo: (listName?: string) => Promise<any>;
getHierarchyInfo: (listName?: string) => Promise<ISPHierarchyItem[]>;
}

View File

@ -1,54 +0,0 @@
import { IHierarchyService } from '../interfaces';
import { ServiceScope, ServiceKey } from '@microsoft/sp-core-library';
export class MockHierarchyService implements IHierarchyService {
public static readonly serviceKey: ServiceKey<IHierarchyService> = ServiceKey.create<IHierarchyService>('datacenter:MockHierarchyService', MockHierarchyService);
constructor(serviceScope: ServiceScope) {
}
public getHierarchyInfo(listName: string): Promise<any> {
const initechOrg: any =
{
id: 1,
title: "Microsoft",
url: {Description: "Microsoft", Url: "http://www.microsoft.com"},
children:[
{
id: 2,
title: "CMS",
url: null,
parent_id: 1,
children:[
{ id: 3, title: "SharePoint", parent_id: 2, url: null },
{ id: 5, title: "DotNetNuke", parent_id: 2, url: null },
{ id: 6, title: "Sitefinity", parent_id: 2, url: null }
]
},
{
id: 7,
title: "E-Commerce",
url: null,
parent_id: 1,
children:[
{ id: 8, title: "nopCommerce", parent_id: 7, url: null },
{ id: 9, title: "asp.net storetront", parent_id: 7, url: null }
]
},
{
id: 10,
title: "3rd Party",
url: null,
parent_id: 1,
children:[
{ id: 11, title: "Telerik", parent_id: 10, url: null },
{ id: 12, title: "DevExpress", parent_id: 10, url: null }
]
}
]
}
;
return new Promise<any>((resolve, reject) => {
resolve(JSON.stringify(initechOrg));
});
}
}

View File

@ -1 +0,0 @@
export { MockHierarchyService } from './MockHierarchyService';

View File

@ -1,32 +1,30 @@
import { IHierarchyService } from '../interfaces';
import { ServiceKey, ServiceScope } from '@microsoft/sp-core-library';
import { PageContext } from '@microsoft/sp-page-context';
import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
import { IHierarchyItem } from '../interfaces/IHierarchyItem';
import { sp } from "@pnp/sp/presets/all";
import { IHierarchyService } from '../interfaces';
import { ISPHierarchyItem } from '../interfaces/IHierarchyItem';
import { SPFI, spfi, SPFx as spSPFx } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
export class HierarchyService implements IHierarchyService {
public static readonly serviceKey: ServiceKey<IHierarchyService> = ServiceKey.create<IHierarchyService>('datacenter:hierarchyService', HierarchyService);
private _spHttpClient: SPHttpClient;
private _pageContext: PageContext;
private _currentWebUrl: string;
private _sp: SPFI;
constructor(serviceScope: ServiceScope) {
serviceScope.whenFinished(() => {
this._spHttpClient = serviceScope.consume(SPHttpClient.serviceKey);
this._pageContext = serviceScope.consume(PageContext.serviceKey);
this._currentWebUrl = this._pageContext.web.absoluteUrl;
const pageContext = serviceScope.consume(PageContext.serviceKey);
this._sp = spfi().using(spSPFx({ pageContext }));
});
}
public getHierarchyInfo(listName: string): Promise<IHierarchyItem[]> {
return sp.web.lists.getByTitle(listName)
public getHierarchyInfo(listName: string): Promise<ISPHierarchyItem[]> {
return this._sp.web.lists.getByTitle(listName)
.items
.select('Title,Id,URL,Parent/Id,Parent/Title')
.expand('Parent')
.get()
.then((items: IHierarchyItem[]) => {
.select("Title", "Id", "URL", "Parent/Id", "Parent/Title")
.expand("Parent")()
.then((items: ISPHierarchyItem[]) => {
return Promise.resolve(items);
}).catch((error) => Promise.reject(error));
}

View File

@ -1,5 +1,5 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-3.3/includes/tsconfig-web.json",
"extends": "./node_modules/@microsoft/rush-stack-compiler-4.7/includes/tsconfig-web.json",
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
@ -12,28 +12,24 @@
"skipLibCheck": true,
"outDir": "lib",
"inlineSources": false,
"strictNullChecks": false,
"noUnusedLocals": false,
"noImplicitAny": false,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"es6-promise",
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection"
"es2015.collection",
"es2015.promise"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
],
"exclude": [
"node_modules",
"lib"
]
}

View File

@ -1,30 +0,0 @@
{
"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
}
}

View File

@ -1,7 +1,7 @@
// 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.0",
"image": "docker.io/m365pnp/spfx:1.13.0",
"name": "SPFx 1.19.0",
"image": "docker.io/m365pnp/spfx:1.19.0",
// Set *default* container specific settings.json values on container create.
"settings": {},
// Add the IDs of extensions you want installed when the container is created.

View File

@ -0,0 +1,352 @@
require('@rushstack/eslint-config/patch/modern-module-resolution');
module.exports = {
extends: ['@microsoft/eslint-config-spfx/lib/profiles/react'],
parserOptions: { tsconfigRootDir: __dirname },
overrides: [
{
files: ['*.ts', '*.tsx'],
parser: '@typescript-eslint/parser',
'parserOptions': {
'project': './tsconfig.json',
'ecmaVersion': 2018,
'sourceType': 'module'
},
rules: {
// Prevent usage of the JavaScript null value, while allowing code to access existing APIs that may require null. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/no-new-null': 1,
// Require Jest module mocking APIs to be called before any other statements in their code block. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/hoist-jest-mock': 1,
// Require regular expressions to be constructed from string constants rather than dynamically building strings at runtime. https://www.npmjs.com/package/@rushstack/eslint-plugin-security
'@rushstack/security/no-unsafe-regexp': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/adjacent-overload-signatures': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// CONFIGURATION: By default, these are banned: String, Boolean, Number, Object, Symbol
'@typescript-eslint/ban-types': [
1,
{
'extendDefaults': false,
'types': {
'String': {
'message': 'Use \'string\' instead',
'fixWith': 'string'
},
'Boolean': {
'message': 'Use \'boolean\' instead',
'fixWith': 'boolean'
},
'Number': {
'message': 'Use \'number\' instead',
'fixWith': 'number'
},
'Object': {
'message': 'Use \'object\' instead, or else define a proper TypeScript type:'
},
'Symbol': {
'message': 'Use \'symbol\' instead',
'fixWith': 'symbol'
},
'Function': {
'message': 'The \'Function\' type accepts any function-like value.\nIt provides no type safety when calling the function, which can be a common source of bugs.\nIt also accepts things like class declarations, which will throw at runtime as they will not be called with \'new\'.\nIf you are expecting the function to accept certain arguments, you should explicitly define the function shape.'
}
}
}
],
// RATIONALE: Code is more readable when the type of every variable is immediately obvious.
// Even if the compiler may be able to infer a type, this inference will be unavailable
// to a person who is reviewing a GitHub diff. This rule makes writing code harder,
// but writing code is a much less important activity than reading it.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/explicit-function-return-type': [
1,
{
'allowExpressions': true,
'allowTypedFunctionExpressions': true,
'allowHigherOrderFunctions': false
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: although this is a recommended rule, it is up to dev to select coding style.
// Set to 1 (warning) or 2 (error) to enable.
'@typescript-eslint/explicit-member-accessibility': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-array-constructor': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// RATIONALE: The "any" keyword disables static type checking, the main benefit of using TypeScript.
// This rule should be suppressed only in very special cases such as JSON.stringify()
// where the type really can be anything. Even if the type is flexible, another type
// may be more appropriate such as "unknown", "{}", or "Record<k,V>".
'@typescript-eslint/no-explicit-any': 0,
// RATIONALE: The #1 rule of promises is that every promise chain must be terminated by a catch()
// handler. Thus wherever a Promise arises, the code must either append a catch handler,
// or else return the object to a caller (who assumes this responsibility). Unterminated
// promise chains are a serious issue. Besides causing errors to be silently ignored,
// they can also cause a NodeJS process to terminate unexpectedly.
'@typescript-eslint/no-floating-promises': 2,
// RATIONALE: Catches a common coding mistake.
'@typescript-eslint/no-for-in-array': 2,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-misused-new': 2,
// RATIONALE: The "namespace" keyword is not recommended for organizing code because JavaScript lacks
// a "using" statement to traverse namespaces. Nested namespaces prevent certain bundler
// optimizations. If you are declaring loose functions/variables, it's better to make them
// static members of a class, since classes support property getters and their private
// members are accessible by unit tests. Also, the exercise of choosing a meaningful
// class name tends to produce more discoverable APIs: for example, search+replacing
// the function "reverse()" is likely to return many false matches, whereas if we always
// write "Text.reverse()" is more unique. For large scale organization, it's recommended
// to decompose your code into separate NPM packages, which ensures that component
// dependencies are tracked more conscientiously.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-namespace': [
1,
{
'allowDeclarations': false,
'allowDefinitionFiles': false
}
],
// RATIONALE: Parameter properties provide a shorthand such as "constructor(public title: string)"
// that avoids the effort of declaring "title" as a field. This TypeScript feature makes
// code easier to write, but arguably sacrifices readability: In the notes for
// "@typescript-eslint/member-ordering" we pointed out that fields are central to
// a class's design, so we wouldn't want to bury them in a constructor signature
// just to save some typing.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/parameter-properties': 0,
// RATIONALE: When left in shipping code, unused variables often indicate a mistake. Dead code
// may impact performance.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-unused-vars': [
1,
{
'vars': 'all',
// Unused function arguments often indicate a mistake in JavaScript code. However in TypeScript code,
// the compiler catches most of those mistakes, and unused arguments are fairly common for type signatures
// that are overriding a base class method or implementing an interface.
'args': 'none'
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-use-before-define': [
2,
{
'functions': false,
'classes': true,
'variables': true,
'enums': true,
'typedefs': true
}
],
// Disallows require statements except in import statements.
// In other words, the use of forms such as var foo = require("foo") are banned. Instead use ES6 style imports or import foo = require("foo") imports.
'@typescript-eslint/no-var-requires': 'error',
// RATIONALE: The "module" keyword is deprecated except when describing legacy libraries.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/prefer-namespace-keyword': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: it's up to developer to decide if he wants to add type annotations
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/no-inferrable-types': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: declaration of empty interfaces may be helpful for generic types scenarios
'@typescript-eslint/no-empty-interface': 0,
// RATIONALE: This rule warns if setters are defined without getters, which is probably a mistake.
'accessor-pairs': 1,
// RATIONALE: In TypeScript, if you write x["y"] instead of x.y, it disables type checking.
'dot-notation': [
1,
{
'allowPattern': '^_'
}
],
// RATIONALE: Catches code that is likely to be incorrect
'eqeqeq': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'for-direction': 1,
// RATIONALE: Catches a common coding mistake.
'guard-for-in': 2,
// RATIONALE: If you have more than 2,000 lines in a single source file, it's probably time
// to split up your code.
'max-lines': ['warn', { max: 2000 }],
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-async-promise-executor': 2,
// RATIONALE: Deprecated language feature.
'no-caller': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-compare-neg-zero': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-cond-assign': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-constant-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-control-regex': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-debugger': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-delete-var': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-duplicate-case': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-character-class': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-pattern': 1,
// RATIONALE: Eval is a security concern and a performance concern.
'no-eval': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-ex-assign': 2,
// RATIONALE: System types are global and should not be tampered with in a scalable code base.
// If two different libraries (or two versions of the same library) both try to modify
// a type, only one of them can win. Polyfills are acceptable because they implement
// a standardized interoperable contract, but polyfills are generally coded in plain
// JavaScript.
'no-extend-native': 1,
// Disallow unnecessary labels
'no-extra-label': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-fallthrough': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-func-assign': 1,
// RATIONALE: Catches a common coding mistake.
'no-implied-eval': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-invalid-regexp': 2,
// RATIONALE: Catches a common coding mistake.
'no-label-var': 2,
// RATIONALE: Eliminates redundant code.
'no-lone-blocks': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-misleading-character-class': 2,
// RATIONALE: Catches a common coding mistake.
'no-multi-str': 2,
// RATIONALE: It's generally a bad practice to call "new Thing()" without assigning the result to
// a variable. Either it's part of an awkward expression like "(new Thing()).doSomething()",
// or else implies that the constructor is doing nontrivial computations, which is often
// a poor class design.
'no-new': 1,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-func': 2,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-object': 2,
// RATIONALE: Obsolete notation.
'no-new-wrappers': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-octal': 2,
// RATIONALE: Catches code that is likely to be incorrect
'no-octal-escape': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-regex-spaces': 2,
// RATIONALE: Catches a common coding mistake.
'no-return-assign': 2,
// RATIONALE: Security risk.
'no-script-url': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-self-assign': 2,
// RATIONALE: Catches a common coding mistake.
'no-self-compare': 2,
// RATIONALE: This avoids statements such as "while (a = next(), a && a.length);" that use
// commas to create compound expressions. In general code is more readable if each
// step is split onto a separate line. This also makes it easier to set breakpoints
// in the debugger.
'no-sequences': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-shadow-restricted-names': 2,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-sparse-arrays': 2,
// RATIONALE: Although in theory JavaScript allows any possible data type to be thrown as an exception,
// such flexibility adds pointless complexity, by requiring every catch block to test
// the type of the object that it receives. Whereas if catch blocks can always assume
// that their object implements the "Error" contract, then the code is simpler, and
// we generally get useful additional information like a call stack.
'no-throw-literal': 2,
// RATIONALE: Catches a common coding mistake.
'no-unmodified-loop-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unsafe-finally': 2,
// RATIONALE: Catches a common coding mistake.
'no-unused-expressions': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unused-labels': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-useless-catch': 1,
// RATIONALE: Avoids a potential performance problem.
'no-useless-concat': 1,
// RATIONALE: The "var" keyword is deprecated because of its confusing "hoisting" behavior.
// Always use "let" or "const" instead.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'no-var': 2,
// RATIONALE: Generally not needed in modern code.
'no-void': 1,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-with': 2,
// RATIONALE: Makes logic easier to understand, since constants always have a known value
// @typescript-eslint\eslint-plugin\dist\configs\eslint-recommended.js
'prefer-const': 1,
// RATIONALE: Catches a common coding mistake where "resolve" and "reject" are confused.
'promise/param-names': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-atomic-updates': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-yield': 1,
// "Use strict" is redundant when using the TypeScript compiler.
'strict': [
2,
'never'
],
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'use-isnan': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
// Set to 1 (warning) or 2 (error) to enable.
// Rationale to disable: !!{}
'no-extra-boolean-cast': 0,
// ====================================================================
// @microsoft/eslint-plugin-spfx
// ====================================================================
'@microsoft/spfx/import-requires-chunk-name': 1,
'@microsoft/spfx/no-require-ensure': 2,
'@microsoft/spfx/pair-react-dom-render-unmount': 1
}
},
{
// For unit tests, we can be a little bit less strict. The settings below revise the
// defaults specified in the extended configurations, as well as above.
files: [
// Test files
'*.test.ts',
'*.test.tsx',
'*.spec.ts',
'*.spec.tsx',
// Facebook convention
'**/__mocks__/*.ts',
'**/__mocks__/*.tsx',
'**/__tests__/*.ts',
'**/__tests__/*.tsx',
// Microsoft convention
'**/test/*.ts',
'**/test/*.tsx'
],
rules: {}
}
]
};

View File

@ -35,3 +35,5 @@ obj
*.cer
# .PEM Certificates
*.pem
.heft

View File

@ -0,0 +1,8 @@
{
"extends": [
"development"
],
"hints": {
"no-inline-styles": "off"
}
}

View File

@ -0,0 +1 @@
v18.17.1

View File

@ -1,5 +0,0 @@
{
"recommendations": [
"msjsdiag.debugger-for-chrome"
]
}

View File

@ -1,15 +1,11 @@
{
/**
* Install Chrome Debugger Extension for Visual Studio Code to debug your components with the
* Chrome browser: https://aka.ms/spfx-debugger-extensions
*/
"version": "0.2.0",
"configurations": [
{
"name": "Hosted workbench",
"type": "chrome",
"type": "msedge",
"request": "launch",
"url": "https://enter-your-SharePoint-site/_layouts/workbench.aspx",
"url": "https://{tenantDomain}/_layouts/workbench.aspx",
"webRoot": "${workspaceRoot}",
"sourceMaps": true,
"sourceMapPathOverrides": {

View File

@ -7,7 +7,8 @@
"**/bower_components": true,
"**/coverage": true,
"**/lib-amd": true,
"src/**/*.scss.ts": true
"src/**/*.scss.ts": true,
"**/jest-output": true
},
"typescript.tsdk": ".\\node_modules\\typescript\\lib"
}

View File

@ -1,12 +1,19 @@
{
"@microsoft/generator-sharepoint": {
"nodeVersion": "18.17.1",
"isCreatingSolution": true,
"environment": "spo",
"version": "1.13.0",
"version": "1.19.0",
"libraryName": "react-kanban-board",
"libraryId": "cccbd72b-7b89-4128-9348-0a4850ded8fd",
"packageManager": "npm",
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"componentType": "webpart"
"plusBeta": false,
"componentType": "webpart",
"sdkVersions": {
"@microsoft/teams-js": "2.12.0",
"@microsoft/microsoft-graph-client": "3.0.2"
}
}
}

View File

@ -1,19 +1,3 @@
---
page_type: sample
products:
- office-sp
languages:
- javascript
- typescript
extensions:
contentType: samples
technologies:
- SharePoint Framework
platforms:
- React
createdDate: 7/17/2019 12:00:00 AM
---
# Kanban Board
## Summary
@ -24,6 +8,10 @@ The web part uses the default columns of the SharePoint Tasks list for showing t
![picture of the web part in action](assets/kanbanofficeUI.gif)
![Kanban Board Settings: bucket Layout](assets/kanbanimg1.png)
![Kanban Board View Items](assets/kanbanimg2.png)
![Kanban Board Settings: list selection and status column order as bucket](assets/kanbanimg3.png)
## Compatibility
@ -32,8 +20,8 @@ The web part uses the default columns of the SharePoint Tasks list for showing t
| Every SPFx version is only compatible with specific version(s) of Node.js. In order to be able to build this sample, please ensure that the version of Node on your workstation matches one of the versions listed in this section. This sample will not work on a different version of Node.|
|Refer to <https://aka.ms/spfx-matrix> for more information on SPFx compatibility. |
![SPFx 1.13.0](https://img.shields.io/badge/SPFx-1.13.0-green.svg)
![Node.js v14 | v12](https://img.shields.io/badge/Node.js-v14%20%7C%20v12-green.svg)
![SPFx 1.19.0](https://img.shields.io/badge/SPFx-1.19.0-green.svg)
![Node.js v18 ](https://img.shields.io/badge/Node.js-v18-green.svg)
![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg)
![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg "SharePoint Server 2019 requires SPFx 1.4.1 or lower")
![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1")
@ -50,6 +38,7 @@ The web part uses the default columns of the SharePoint Tasks list for showing t
## Prerequisites
This web part reads the information from a Tasks list and uses the following OOB columns
* Task Name
* Assigned To
* % Complete
@ -74,6 +63,7 @@ Version|Date|Comments
1.0.1.0|April 21, 2020|Added support for Teams hosts
2.0.0.0|July 10, 2020| jqwidgets replaced with a custom Kanban Board based on Office UI Component and IE11 Support
3.0.0.0|October 29, 2021| SPFx 1.13, PnPJS v2, PnP Controls v3
4.0.0.0|Jun 1, 2024| SPFx 1.19, PnPJS v4, Node 18 (Property-ListPicker and Property-Order not used from @pnp/spfx-property-controls because of an issue )
[Read More about the implementation of this Board](./src/kanban/README.md)

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

View File

@ -6,10 +6,10 @@
"shortDescription": "This solution contains an SPFx web part which shows a Kanban board using jqxKanban ReactJS component (from JQWidgets). The web part uses the default columns of the SharePoint Tasks list for showing the board\u0027s columns and the tasks.",
"url": "https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-kanban-board",
"longDescription": [
"This solution contains an SPFx web part which shows a Kanban board using jqxKanban ReactJS component (from JQWidgets). The web part uses the default columns of the SharePoint Tasks list for showing the board\u0027s columns and the tasks."
"This solution contains an SPFx web part which shows a Kanban board. The web part uses the default columns of the SharePoint Tasks list for showing the board\u0027s columns and the tasks."
],
"creationDateTime": "2020-07-02",
"updateDateTime": "2020-07-02",
"updateDateTime": "2024-05-26",
"products": [
"SharePoint"
],
@ -20,7 +20,7 @@
},
{
"key": "SPFX-VERSION",
"value": "1.13.0"
"value": "1.19.0"
},
{
"key": "SPFX-TEAMSTAB",
@ -36,7 +36,25 @@
"type": "image",
"order": 100,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-kanban-board/assets/kanbanofficeUI.gif",
"alt": "Kanban Board Web part"
"alt": "Kanban Board Web part in action"
},
{
"type": "image",
"order": 101,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-kanban-board/assets/kanbanimg1.png",
"alt": "Kanban Board Web part configuration of a bucket"
},
{
"type": "image",
"order": 102,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-kanban-board/assets/kanbanimg2.png",
"alt": "Kanban Board Web part item View"
},
{
"type": "image",
"order": 103,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-kanban-board/assets/kanbanimg3.png",
"alt": "Kanban Board Web part task list selection and status column order as bucket"
}
],
"authors": [
@ -56,7 +74,7 @@
},
{
"gitHubAccount": "petkir",
"company": "Cubido Business Solutions GmbH",
"company": "ACP CUBIDO Digital Solutions GmbH",
"pictureUrl": "https://github.com/petkir.png",
"name": "Peter Paul Kirschner",
"twitter": "petkir_at"

View File

@ -3,7 +3,7 @@
"solution": {
"name": "react-kanban-board-client-side-solution",
"id": "cccbd72b-7b89-4128-9348-0a4850ded8fd",
"version": "3.0.0.0",
"version": "4.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
@ -12,8 +12,28 @@
"privacyUrl": "",
"termsOfUseUrl": "",
"websiteUrl": "",
"mpnId": ""
}
"mpnId": "Undefined-1.19.0"
},
"metadata": {
"shortDescription": {
"default": "react-kanban-board description"
},
"longDescription": {
"default": "react-kanban-board description"
},
"screenshotPaths": [],
"videoUrl": "",
"categories": []
},
"features": [
{
"title": "react-kanban-board KanbanBoardWebPart Feature",
"description": "The feature that activates KanbanBoardWebPart from the react-kanban-board solution.",
"id": "67cd5938-806b-4c79-b589-501f7f26998e",
"version": "4.0.0.0"
}
]
},
"paths": {
"zippedPackage": "solution/react-kanban-board.sppkg"

View File

@ -0,0 +1,3 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/core-build/sass.schema.json"
}

View File

@ -1,6 +1,6 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/core-build/serve.schema.json",
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/spfx-serve.schema.json",
"port": 4321,
"https": true,
"initialPage": "https://enter-your-SharePoint-site/_layouts/workbench.aspx"
"initialPage": "https://{tenantDomain}/_layouts/workbench.aspx"
}

View File

@ -1,9 +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.`);
var getTasks = build.rig.getTasks;
@ -15,4 +13,4 @@ build.rig.getTasks = function () {
return result;
};
build.initialize(gulp);
build.initialize(require('gulp'));

File diff suppressed because it is too large Load Diff

View File

@ -1,39 +1,46 @@
{
"name": "react-kanban-board",
"main": "lib/index.js",
"version": "3.0.0",
"version": "4.0.0",
"private": true,
"engines": "undefined",
"engines": {
"node": ">=18.17.1 <19.0.0"
},
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"@microsoft/sp-core-library": "1.13.0",
"@microsoft/sp-lodash-subset": "1.13.0",
"@microsoft/sp-office-ui-fabric-core": "1.13.0",
"@microsoft/sp-property-pane": "1.13.0",
"@microsoft/sp-webpart-base": "1.13.0",
"@pnp/sp": "2.10.0",
"@pnp/spfx-controls-react": "^3.5.0-beta.2d993b2",
"@pnp/spfx-property-controls": "^3.3.0-beta.d48002e",
"office-ui-fabric-react": "7.174.1",
"react": "16.13.1",
"react-dom": "16.13.1"
"@fluentui/react": "8.106.4",
"@microsoft/sp-adaptive-card-extension-base": "1.19.0",
"@microsoft/sp-core-library": "1.19.0",
"@microsoft/sp-lodash-subset": "1.19.0",
"@microsoft/sp-office-ui-fabric-core": "1.19.0",
"@microsoft/sp-property-pane": "1.19.0",
"@microsoft/sp-webpart-base": "1.19.0",
"@pnp/sp": "^4.1.0",
"@pnp/spfx-controls-react": "^3.18",
"@pnp/spfx-property-controls": "^3.17",
"html-react-parser": "^5.1.10",
"react": "17.0.1",
"react-dom": "17.0.1",
"tslib": "2.3.1"
},
"devDependencies": {
"@microsoft/rush-stack-compiler-3.7": "0.2.3",
"@microsoft/rush-stack-compiler-3.9": "0.4.47",
"@microsoft/sp-build-web": "1.13.0",
"@microsoft/sp-module-interfaces": "1.13.0",
"@microsoft/sp-tslint-rules": "1.13.0",
"@types/react": "16.9.51",
"@types/react-dom": "16.9.8",
"@types/webpack-env": "1.13.1",
"ajv": "~5.2.2",
"autoprefixer": "^9.8.4",
"@microsoft/eslint-config-spfx": "1.20.1",
"@microsoft/eslint-plugin-spfx": "1.20.1",
"@microsoft/rush-stack-compiler-4.7": "0.1.0",
"@microsoft/sp-build-web": "1.20.1",
"@microsoft/sp-module-interfaces": "1.20.1",
"@rushstack/eslint-config": "2.5.1",
"@types/react": "17.0.45",
"@types/react-dom": "17.0.17",
"@types/webpack-env": "1.15.2",
"ajv": "6.12.5",
"eslint": "8.7.0",
"eslint-plugin-react-hooks": "4.3.0",
"gulp": "4.0.2",
"react-html-parser": "^2.0.2"
"typescript": "4.7.4"
}
}

View File

@ -1,4 +1,4 @@
import { IPersonaProps } from "office-ui-fabric-react/lib/Persona";
import { IPersonaProps } from "@fluentui/react";
export interface IKanbanTask {
taskId: string;

View File

@ -1,3 +1,5 @@
@import '~@fluentui/react/dist/sass/References.scss';
.bucket {
width: 100%;
// border-right: 1px solid gray;

View File

@ -3,12 +3,10 @@ import styles from './KanbanBucket.module.scss';
import { IKanbanBucket } from './IKanbanBucket';
import { IKanbanTask } from './IKanbanTask';
import { IKanbanBoardTaskSettings } from './IKanbanBoardTaskSettings';
import { IKanbanBoardTaskActions } from './IKanbanBoardTaskActions';
import { ProgressIndicator } from 'office-ui-fabric-react/lib/ProgressIndicator';
import { ActionButton } from 'office-ui-fabric-react';
import KanbanTask from './KanbanTask';
import classNames from 'classnames';
import * as strings from 'KanbanBoardStrings';
import { ActionButton, ProgressIndicator } from '@fluentui/react';
export interface IKanbanBucketProps extends IKanbanBucket {
@ -19,9 +17,9 @@ export interface IKanbanBucketProps extends IKanbanBucket {
toggleCompleted?: (taskId: string) => void;
addTask?: (bucket: string) => void;
onDragStart: (event, taskId: string, bucket: string) => void;
onDragStart: (event: any, taskId: string, bucket: string) => void;
onDragEnd: (event, taskId: string, bucket: string) => void;
onDragEnd: (event: any, taskId: string, bucket: string) => void;
@ -61,15 +59,15 @@ export default class KanbanBucket extends React.Component<IKanbanBucketProps, IK
key={bucket}>
<div className={styles.headline}>
<div className={styles.headlineText}>{bucketheadline}</div>
{color && <div style={{ backgroundColor: color }} className={styles.colorindicator}></div>}
{color && <div style={{ backgroundColor: color }} className={styles.colorindicator}/>}
{showPercentageHeadline ?
(<ProgressIndicator percentComplete={percentageComplete / 100} />):
(hasOneProcessIndicator?(<div className={styles.processIndicatorHeight}></div>):(<div></div>))}
(hasOneProcessIndicator?(<div className={styles.processIndicatorHeight} />):(<div />))}
</div>
{allowAddTask && (<ActionButton
iconProps={{ iconName: 'Add' }}
allowDisabledFocus={true}
onClick={() => this.props.addTask(bucket)}
onClick={() => this.props.addTask && this.props.addTask(bucket)}
>
{strings.AddTask}
</ActionButton>)}
@ -87,7 +85,7 @@ export default class KanbanBucket extends React.Component<IKanbanBucketProps, IK
{...merge}
toggleCompleted={this.props.toggleCompleted}
isMoving={isMoving}
openDetails={this.props.openDetails}
openDetails={(taskId)=> this.props.openDetails&&this.props.openDetails(taskId)}
onDragStart={(event) => this.props.onDragStart(event, t.taskId, t.bucket)}
onDragEnd={(event) => this.props.onDragEnd(event, t.taskId, t.bucket)}
/></div>

View File

@ -0,0 +1 @@
@import '~@fluentui/react/dist/sass/References.scss';

View File

@ -3,25 +3,12 @@ import * as React from 'react';
//import styles from './KanbanBucketConfigurator.module.scss';
import * as strings from 'KanbanBoardStrings';
import { TextField, MaskedTextField } from 'office-ui-fabric-react/lib/TextField';
import { Stack, IStackProps, IStackStyles } from 'office-ui-fabric-react/lib/Stack';
import { Slider } from 'office-ui-fabric-react/lib/Slider';
import { Toggle } from 'office-ui-fabric-react/lib/Toggle';
import { cloneDeep, clone, isEqual } from '@microsoft/sp-lodash-subset';
import {
ColorPicker,
ChoiceGroup,
IChoiceGroupOption,
getColorFromString,
IColor,
IColorPickerStyles,
IColorPickerProps,
PrimaryButton,
DefaultButton,
ThemeSettingName,
} from 'office-ui-fabric-react/lib/index';
import { clone, isEqual } from '@microsoft/sp-lodash-subset';
import { IKanbanBucket } from './IKanbanBucket';
import { ColorPicker, DefaultButton, IColor, PrimaryButton, Slider, Stack, TextField, Toggle } from '@fluentui/react';
export interface IKanbanBucketConfiguratorProps {
@ -57,23 +44,10 @@ export class KanbanBucketConfigurator extends React.Component<IKanbanBucketConfi
}
public render(): React.ReactElement<IKanbanBucketConfiguratorProps> {
/*
const columnProps: Partial<IStackProps> = {
gap: 15,
styles: { root: { width: 300 } },
};*/
/*
const colorPickerStyles: Partial<IColorPickerStyles> = {
panel: { padding: 12 },
root: {
maxWidth: 352,
minWidth: 352,
},
colorRectangle: { height: 268 },
};*/
const statebucket = this.state.bucket;
if (!statebucket) {
return (<div></div>);
return (<div />);
}
return (
<Stack>
@ -84,16 +58,16 @@ export class KanbanBucketConfigurator extends React.Component<IKanbanBucketConfi
*/}
<TextField label={strings.BucketConfigHeadline} defaultValue={statebucket.bucketheadline}
onChange={(ev, value?: string) => {
const bucket = clone(this.state.bucket);
bucket.bucketheadline = value;
const bucket = this.state.bucket ? clone(this.state.bucket) : {} as IKanbanBucket;
bucket.bucketheadline = value || '';
this.setState({ bucket: bucket });
}}
/>
<Toggle label={strings.BucketConfigShowPercentage} onText={strings.BucketConfigShowPercentageShow} offText={strings.BucketConfigShowPercentageHide} inlineLabel
checked={statebucket.showPercentageHeadline}
onChange={(ev, checked) => {
const bucket = clone(this.state.bucket);
bucket.showPercentageHeadline = checked;
const bucket = this.state.bucket ? clone(this.state.bucket) : {} as IKanbanBucket;
bucket.showPercentageHeadline = checked === undefined ? true : checked;
this.setState({ bucket: bucket });
}} />
{statebucket.showPercentageHeadline && <Slider
@ -104,24 +78,22 @@ export class KanbanBucketConfigurator extends React.Component<IKanbanBucketConfi
valueFormat={(value: number) => `${value}%`}
showValue
onChange={(value: number) => {
const bucket = clone(this.state.bucket);
const bucket = this.state.bucket ? clone(this.state.bucket) : {} as IKanbanBucket;
bucket.percentageComplete = value;
this.setState({ bucket: bucket });
}}
/>}
<Toggle label={strings.BucketConfigUseColor} onText="On" offText="Off" inlineLabel
checked={this.state.useColor}
onChange={(ev, checked) => { this.setState({ useColor: checked }); }} />
onChange={(ev, checked) => { this.setState({ useColor: checked?checked:false }); }} />
{this.state.useColor && (<ColorPicker
color={statebucket.color}
// alphaSliderHidden={false}
// showPreview={true}
color={statebucket.color?statebucket.color:'white'}
onChange={(ev: any, colorObj: IColor) => {
const bucket = clone(this.state.bucket);
bucket.color = colorObj.str;
this.setState({ bucket: bucket });
if (this.state.bucket) {
const bucket = clone(this.state.bucket);
bucket.color = colorObj.str;
this.setState({ bucket: bucket });
}
}
}
/>
@ -141,21 +113,23 @@ export class KanbanBucketConfigurator extends React.Component<IKanbanBucketConfi
this.setState({
bucket: newbucket,
// showHeadline: newbucket.bucketheadline && newbucket.bucketheadline.length > 0,
useColor: newbucket.color && newbucket.color.length > 0
useColor: (!!newbucket.color && newbucket.color.length > 0)
});
}
private submitData(): void {
const newbucket: IKanbanBucket = clone(this.state.bucket);
if (!this.state.useColor) {
newbucket.color = undefined;
}
/*
if (!this.state.showHeadline) {
newbucket.color = undefined;
}
*/
if (this.props.update) {
this.props.update(this.props.index, newbucket);
if (this.state.bucket) {
const newbucket: IKanbanBucket = clone(this.state.bucket);
if (!this.state.useColor) {
newbucket.color = undefined;
}
/*
if (!this.state.showHeadline) {
newbucket.color = undefined;
}
*/
if (this.props.update) {
this.props.update(this.props.index, newbucket);
}
}
}

View File

@ -1,3 +1,5 @@
@import '~@fluentui/react/dist/sass/References.scss';
.kanbanBoard {
display: flex;
width: 100%;

View File

@ -1,6 +1,7 @@
/* eslint-disable no-throw-literal */
import * as React from 'react';
import styles from './KanbanComponent.module.scss';
import bucketstyles from './KanbanBucket.module.scss';
import * as strings from 'KanbanBoardStrings';
import { IKanbanTask, KanbanTaskMamagedPropertyType } from './IKanbanTask';
@ -11,14 +12,8 @@ import { IKanbanBucket } from './IKanbanBucket';
import KanbanBucket from './KanbanBucket';
import KanbanTaskManagedProp from './KanbanTaskManagedProp';
import { Dialog, DialogType, DialogFooter } from 'office-ui-fabric-react/lib/Dialog';
import { PrimaryButton, DefaultButton } from 'office-ui-fabric-react/lib/Button';
import { IStackStyles, Stack } from 'office-ui-fabric-react/lib/Stack';
import { clone } from '@microsoft/sp-lodash-subset';
import { CommandBar } from 'office-ui-fabric-react/lib/CommandBar';
import { TooltipHost, findIndex } from 'office-ui-fabric-react';
import { CommandBar, DefaultButton, Dialog, DialogFooter, DialogType, ICommandBarItemProps, PrimaryButton, Stack, findIndex } from '@fluentui/react';
export interface IKanbanComponentProps {
buckets: IKanbanBucket[];
@ -60,21 +55,21 @@ export class KanbanComponent extends React.Component<IKanbanComponentProps, IKan
this.state = {
openDialog: false,
leavingTaskId: null,
leavingBucket: null,
leavingTaskId: undefined,
leavingBucket: undefined,
};
this.bucketsref = [];
}
}
public render(): React.ReactElement<IKanbanComponentProps> {
const { buckets, tasks, tasksettings, taskactions, showCommandbar } = this.props;
const { buckets, tasks, tasksettings, showCommandbar } = this.props;
const { openDialog } = this.state;
const bucketwidth: number = buckets.length > 0 ? 100 / buckets.length : 100;
const { leavingBucket, leavingTaskId } = this.state;
const hasprocessIndicator = buckets.filter((b)=> b.showPercentageHeadline).length >0;
const hasprocessIndicator = buckets.filter((b) => b.showPercentageHeadline).length > 0;
return (
<div style={{ overflowX: 'auto' }}>
{showCommandbar && <CommandBar
@ -89,14 +84,14 @@ const hasprocessIndicator = buckets.filter((b)=> b.showPercentageHeadline).lengt
buckets.map((b, i) => {
const merge = { ...b, ...this.state };
return (<div
style={{
flexBasis: bucketwidth ? bucketwidth + '%' : '100%' ,
style={{
flexBasis: bucketwidth ? bucketwidth + '%' : '100%',
maxWidth: bucketwidth ? bucketwidth + '%' : '100%'
}}
className={styles.bucketwrapper}
ref={bucketContent => this.bucketsref[i] = bucketContent}
ref={(bucketContent) => { this.bucketsref[i] = bucketContent }}
key={'BucketWrapper' + b.bucket + i}
onDragOver={(event) => this.onDragOver(event, b.bucket)}
onDragLeave={(event) => this.onDragLeave(event, b.bucket)}
@ -106,7 +101,7 @@ const hasprocessIndicator = buckets.filter((b)=> b.showPercentageHeadline).lengt
key={b.bucket}
{...merge}
hasOneProcessIndicator={hasprocessIndicator}
buckettasks={tasks.filter((x) => x.bucket == b.bucket)}
buckettasks={tasks.filter((x) => x.bucket === b.bucket)}
tasksettings={tasksettings}
toggleCompleted={this.props.taskactions && this.props.taskactions.toggleCompleted ? this.props.taskactions.toggleCompleted : undefined}
@ -129,8 +124,8 @@ const hasprocessIndicator = buckets.filter((b)=> b.showPercentageHeadline).lengt
);
}
private getTaskByID(taskId: string): IKanbanTask {
const tasks = this.props.tasks.filter(t => t.taskId == this.state.openTaskId);
if (tasks.length == 1) {
const tasks = this.props.tasks.filter(t => t.taskId === this.state.openTaskId);
if (tasks.length === 1) {
return tasks[0];
}
throw "Error Taks not found by taskId";
@ -138,25 +133,20 @@ const hasprocessIndicator = buckets.filter((b)=> b.showPercentageHeadline).lengt
private renderDialog(): JSX.Element {
let renderer: (task?: IKanbanTask, bucket?: IKanbanBucket) => JSX.Element = () => (<div>Dialog Renderer Not Set</div>);
let task: IKanbanTask = undefined;
let bucket: IKanbanBucket = undefined;
let task: IKanbanTask|undefined;
let bucket: IKanbanBucket|undefined;
let dialogheadline: string = '';
switch (this.state.dialogState) {
case DialogState.Edit:
task = this.getTaskByID(this.state.openTaskId);
renderer = this.internalTaskEditRenderer.bind(this);
dialogheadline = strings.EditTaskDlgHeadline;
break;
case DialogState.New:
renderer = this.internalTaskAddRenderer.bind(this);
dialogheadline = strings.AddTaskDlgHeadline;
break;
default:
task = this.getTaskByID(this.state.openTaskId);
dialogheadline = task.title;
renderer = (this.props.renderers && this.props.renderers.taskDetail) ? this.props.renderers.taskDetail : this.internalTaskDetailRenderer.bind(this);
break;
if(this.state.dialogState=== DialogState.Edit && this.state.openTaskId !== undefined){
task = this.getTaskByID(this.state.openTaskId);
renderer = this.internalTaskEditRenderer.bind(this);
dialogheadline = strings.EditTaskDlgHeadline;
} else if(this.state.dialogState=== DialogState.New){
renderer = this.internalTaskAddRenderer.bind(this);
dialogheadline = strings.AddTaskDlgHeadline;
}else if(this.state.openTaskId !== undefined){
task = this.getTaskByID(this.state.openTaskId);
dialogheadline = task.title;
renderer = (this.props.renderers && this.props.renderers.taskDetail) ? this.props.renderers.taskDetail : this.internalTaskDetailRenderer.bind(this);
}
return (<Dialog
@ -189,20 +179,22 @@ const hasprocessIndicator = buckets.filter((b)=> b.showPercentageHeadline).lengt
}
private clickEditTask(): void {
const task = this.getTaskByID(this.state.openTaskId);
if (this.props.taskactions.taskEdit) {
if (this.state.openTaskId) {
const task = this.getTaskByID(this.state.openTaskId);
if (this.props.taskactions.taskEdit) {
this.internalCloseDialog();
this.props.taskactions.taskEdit(clone(task));
} else {
this.setState({
dialogState: DialogState.Edit,
editTask: clone(task)
});
this.internalCloseDialog();
this.props.taskactions.taskEdit(clone(task));
} else {
this.setState({
dialogState: DialogState.Edit,
editTask: clone(task)
});
}
}
}
private saveEditTask() {
if (this.props.taskactions.editTaskSaved) {
private saveEditTask(): void {
if (this.props.taskactions.editTaskSaved && this.state.editTask) {
const edittask = clone(this.state.editTask);
//check fist state and than event or in the other way
this.internalCloseDialog();
@ -211,10 +203,10 @@ const hasprocessIndicator = buckets.filter((b)=> b.showPercentageHeadline).lengt
throw "allowEdit is Set but no handler is set";
}
}
private saveAddTask() {
private saveAddTask(): void {
if (this.props.taskactions.editTaskSaved) {
const edittask = clone(this.state.editTask);
const edittask = clone(this.state.editTask) || {} as IKanbanTask;
//check fist state and than event or in the other way
this.internalCloseDialog();
this.props.taskactions.editTaskSaved(edittask);
@ -263,15 +255,15 @@ const hasprocessIndicator = buckets.filter((b)=> b.showPercentageHeadline).lengt
private internalTaskEditRenderer(task: IKanbanTask): JSX.Element {
const schema = this.props.editSchema; //TODO
// const schema = this.props.editSchema; //TODO
return (<div>Edit</div>);
}
private internalTaskAddRenderer(task?: IKanbanTask, bucket?: IKanbanBucket): JSX.Element {
const schema = this.props.editSchema; //TODO
// const schema = this.props.editSchema; //TODO
return (<div>New</div>);
}
private internalCloseDialog(ev?: React.MouseEvent<HTMLButtonElement>) {
private internalCloseDialog(ev?: React.MouseEvent<HTMLButtonElement>): void {
this.setState({
openDialog: false,
openTaskId: undefined,
@ -280,24 +272,24 @@ const hasprocessIndicator = buckets.filter((b)=> b.showPercentageHeadline).lengt
addBucket: undefined
});
}
private internalOpenDialog(taskid: string) {
private internalOpenDialog(taskid: string): void {
this.setState({
openDialog: true,
openTaskId: taskid,
dialogState: DialogState.Display
});
}
private internalAddTask(targetbucket?: string) {
let bucket: IKanbanBucket = undefined;
if (bucket) {
const buckets = this.props.buckets.filter((p) => p.bucket === targetbucket);
if (buckets.length === 1) {
bucket = clone(buckets[0]);
} else {
throw "Bucket not Found in addDialog";
private internalAddTask(targetbucket?: string): void {
let bucket: IKanbanBucket;
const buckets = this.props.buckets.filter((p) => p.bucket === targetbucket);
if (buckets.length === 1) {
bucket = clone(buckets[0]);
} else {
throw "Bucket not Found in addDialog";
}
}
if (this.props.taskactions && this.props.taskactions.taskAdd) {
this.props.taskactions.taskAdd(bucket);
} else {
@ -310,9 +302,9 @@ const hasprocessIndicator = buckets.filter((b)=> b.showPercentageHeadline).lengt
}
}
private onDragLeave(event, bucket): void {
const index = findIndex(this.props.buckets, element => element.bucket == bucket);
if (index != -1 && this.bucketsref.length > index) {
private onDragLeave(event: any, bucket: string): void {
const index = findIndex(this.props.buckets, element => element.bucket === bucket);
if (index !== -1 && this.bucketsref.length > index) {
//&& this.bucketsref[index].classList.contains(styles.dragover)) {
this.bucketsref[index].classList.remove(styles.dragover);
@ -320,17 +312,17 @@ const hasprocessIndicator = buckets.filter((b)=> b.showPercentageHeadline).lengt
}
private onDragEnd(event): void {
private onDragEnd(event: any): void {
this.dragelement = undefined;
this.setState({
leavingTaskId: null,
leavingBucket: null,
leavingTaskId: undefined,
leavingBucket: undefined,
});
}
private onDragStart(event, taskId: string, bucket: string): void {
private onDragStart(event: any, taskId: string, bucket: string): void {
console.log('onDragStart');
const taskitem = this.props.tasks.filter(p => p.taskId === taskId);
if (taskitem.length === 1) {
@ -352,12 +344,12 @@ const hasprocessIndicator = buckets.filter((b)=> b.showPercentageHeadline).lengt
}
private onDragOver(event, targetbucket: string): void {
private onDragOver(event: any, targetbucket: string): void {
event.preventDefault();
console.log('onDragOver');
if (this.dragelement.bucket !== targetbucket) {
const index = findIndex(this.props.buckets, element => element.bucket == targetbucket);
if (this.dragelement && this.dragelement?.bucket !== targetbucket) {
const index = findIndex(this.props.buckets, element => element.bucket === targetbucket);
if (index > -1 && this.bucketsref.length > index) {
//&& this.bucketsref[index].classList.contains(styles.dragover)) {
this.bucketsref[index].classList.add(styles.dragover);
@ -366,15 +358,15 @@ const hasprocessIndicator = buckets.filter((b)=> b.showPercentageHeadline).lengt
}
private onDrop(event, targetbucket: string): void {
private onDrop(event: any, targetbucket: string): void {
if (this.bucketsref && this.bucketsref.length > 0) {
this.bucketsref.forEach(x => { x.classList.remove(styles.dragover); });
}
if (this.dragelement.bucket !== targetbucket) {
if (this.dragelement && this.dragelement?.bucket !== targetbucket) {
//event.dataTransfer.getData("text");
const taskId = this.dragelement.taskId;
const source = this.props.buckets.filter(s => s.bucket == this.dragelement.bucket)[0];
const target = this.props.buckets.filter(s => s.bucket == targetbucket)[0];
const taskId = this.dragelement?.taskId;
const source = this.props.buckets.filter(s => s.bucket === this.dragelement?.bucket)[0];
const target = this.props.buckets.filter(s => s.bucket === targetbucket)[0];
if (this.props.taskactions) {
let allowMove = true;
@ -389,18 +381,18 @@ const hasprocessIndicator = buckets.filter((b)=> b.showPercentageHeadline).lengt
}
}
}
this.dragelement = null;
this.dragelement = undefined;
this.setState({
leavingTaskId: null,
leavingBucket: null,
leavingTaskId: undefined,
leavingBucket: undefined,
});
}
private getItems = () => {
private getItems = (): ICommandBarItemProps[] => {
if (this.props.allowAdd) {
return [
{
@ -417,7 +409,7 @@ const hasprocessIndicator = buckets.filter((b)=> b.showPercentageHeadline).lengt
}
private getFarItems = () => {
private getFarItems = (): ICommandBarItemProps[] => {
return [
{
key: 'info',

View File

@ -1,3 +1,4 @@
@import '~@fluentui/react/dist/sass/References.scss';
.taskcard {
padding: 5px;

View File

@ -1,18 +1,18 @@
import * as React from 'react';
import styles from './KanbanTask.module.scss';
import * as strings from 'KanbanBoardStrings';
import { IconButton } from 'office-ui-fabric-react/lib/Button';
import { IKanbanTask } from './IKanbanTask';
import { IKanbanBoardTaskSettings } from './IKanbanBoardTaskSettings';
import classNames from 'classnames';
import { Persona, PersonaSize } from 'office-ui-fabric-react';
import { IconButton, Persona, PersonaSize } from '@fluentui/react';
export interface IKanbanTaskProps extends IKanbanTask, IKanbanBoardTaskSettings {
toggleCompleted?: (taskId: string) => void;
openDetails: (taskId: string) => void;
onDragStart: (event) => void;
onDragEnd: (event) => void;
onDragStart: (event:any) => void;
onDragEnd: (event:any) => void;
isMoving: boolean;
}
@ -83,6 +83,7 @@ export default class KanbanTask extends React.Component<IKanbanTaskProps, IKanba
}
private _openDetails(): void {
console.log('openDetails');
if (this.props.openDetails) {
this.props.openDetails(this.props.taskId);
}

View File

@ -1,3 +1,5 @@
@import '~@fluentui/react/dist/sass/References.scss';
.rowcol1{
flex-basis: 30%;
}

View File

@ -4,9 +4,9 @@
import * as React from 'react';
import styles from './KanbanTaskManagedProp.module.scss';
import { IKanbanTaskManagedProps, KanbanTaskMamagedPropertyType } from './IKanbanTask';
import { Stack } from 'office-ui-fabric-react/lib/Stack';
import ReactHtmlParser from 'react-html-parser';
import { Persona, PersonaSize, IPersonaProps } from 'office-ui-fabric-react';
import { IPersonaProps, Persona, PersonaSize, Stack } from '@fluentui/react';
import HTMLReactParser from 'html-react-parser';
export interface IKanbanTaskManagedPropProps extends IKanbanTaskManagedProps { }
@ -26,7 +26,7 @@ export default class KanbanTaskManagedProp extends React.Component<IKanbanTaskMa
</Stack>
);
}
private renderValue() {
private renderValue():JSX.Element {
const { name, type, value } = this.props;
if (this.props.renderer) {
return this.props.renderer(name, value, type);
@ -40,11 +40,11 @@ export default class KanbanTaskManagedProp extends React.Component<IKanbanTaskMa
//TODO maybe Formater
break;
case KanbanTaskMamagedPropertyType.percent:
return (<span>{`${(value as any) * 100}%`} </span>);
return (value?<span>{`${(value as any) * 100}%`} </span>:<span/>);
//TODO maybe better Formater
break;
case KanbanTaskMamagedPropertyType.html:
return (<span>{ReactHtmlParser(value)}</span>);
return (value?<span>{HTMLReactParser(value)}</span>:<span/>);
break;
case KanbanTaskMamagedPropertyType.person:
@ -75,7 +75,7 @@ export default class KanbanTaskManagedProp extends React.Component<IKanbanTaskMa
return (<span>{JSON.stringify(value)}</span>);
break;
default:
throw "Unknow KanbanTaskMamagedPropertyType";
throw new Error("Unknow KanbanTaskMamagedPropertyType");
break;
}
}

View File

@ -102,8 +102,7 @@ export class MockKanban extends React.Component<IMockKanbanProps, IMockKanbanSta
);
}
private updateBucket(index: number, value: IKanbanBucket) {
debugger;
private updateBucket(index: number, value: IKanbanBucket):void {
const cstate = cloneDeep(this.state);
cstate.buckets[index] = clone(value);
this.setState(cstate);
@ -120,8 +119,8 @@ export class MockKanban extends React.Component<IMockKanbanProps, IMockKanbanSta
}
private _moved(taskId: string, targetBucket: IKanbanBucket): void {
const elementsIndex = findIndex(this.state.tasks, element => element.taskId == taskId);
let newArray = [...this.state.tasks];
const elementsIndex = findIndex(this.state.tasks, element => element.taskId === taskId);
const newArray = [...this.state.tasks];
newArray[elementsIndex].bucket = targetBucket.bucket;
this.setState({ tasks: newArray });

View File

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version, Environment, EnvironmentType } from '@microsoft/sp-core-library';
@ -8,14 +9,18 @@ import {
} from '@microsoft/sp-property-pane';
import { cloneDeep } from '@microsoft/sp-lodash-subset';
import { PropertyFieldListPicker, PropertyFieldListPickerOrderBy } from '@pnp/spfx-property-controls/lib/PropertyFieldListPicker';
import { PropertyFieldOrder } from '@pnp/spfx-property-controls/lib/PropertyFieldOrder';
//import { PropertyFieldListPicker, PropertyFieldListPickerOrderBy } from '@pnp/spfx-property-controls';
import * as strings from 'KanbanBoardWebPartStrings';
import { sp } from '@pnp/sp';
import { spfi, SPFx } from "@pnp/sp";
import PropertyPaneBucketConfigComponent from './components/PropertyPaneBucketConfig';
import KanbanBoardV2, { IKanbanBoardV2Props } from './components/KanbanBoardV2';
import { bucketOrder } from './components/bucketOrder';
import { PropertyFieldOrder } from './components/PropertyOrderField/PropertyFieldOrder';
import { mergeBucketsWithChoices } from './components/helper';
import { IKanbanBucket } from '../../kanban';
@ -23,6 +28,7 @@ import { IKanbanBucket } from '../../kanban';
import { ISPKanbanService } from './services/ISPKanbanService';
import SPKanbanService from './services/SPKanbanService';
import MockKanbanService from './services/MockKanbanService';
import { PropertyFieldListPicker, PropertyFieldListPickerOrderBy } from './components/PropertyListPicker';
export interface IKanbanBoardWebPartProps {
hideWPTitle: boolean;
@ -34,20 +40,19 @@ export interface IKanbanBoardWebPartProps {
}
export default class KanbanBoardWebPart extends BaseClientSideWebPart<IKanbanBoardWebPartProps> {
private kanbanComponent = null;
//private kanbanComponent = null;
private dataService: ISPKanbanService;
private statekey: string = Date.now().toString();
public onInit(): Promise<void> {
return super.onInit().then(_ => {
sp.setup({
spfxContext: this.context
});
if (Environment.type == EnvironmentType.Local || Environment.type == EnvironmentType.Test) {
const sp = spfi().using(SPFx(this.context));
//.using(PnPLogging(LogLevel.Warning));
if (Environment.type === EnvironmentType.Test) {
this.dataService = new MockKanbanService();
} else {
this.dataService = new SPKanbanService();
this.dataService = new SPKanbanService(sp);
}
});
@ -66,12 +71,13 @@ export default class KanbanBoardWebPart extends BaseClientSideWebPart<IKanbanBoa
statekey: this.statekey,
context: this.context,
listId: this.properties.listId,
configuredBuckets: this.properties.buckets
configuredBuckets: this.properties.buckets,
dataService: this.dataService
}
);
this.kanbanComponent = ReactDom.render(element, this.domElement);
ReactDom.render(element, this.domElement);
}
@ -105,14 +111,14 @@ export default class KanbanBoardWebPart extends BaseClientSideWebPart<IKanbanBoa
disabled: false,
onPropertyChange: this.listConfigurationChanged.bind(this),
properties: this.properties,
context: this.context,
onGetErrorMessage: null,
context: (this.context as any),
onGetErrorMessage: () => '', //TODO
deferredValidationTime: 0,
key: 'listPickerFieldId',
onListsRetrieved: (lists) => {
//TODO Check from TS Definition it should be a string but i get a number
// with Typesafe equal it fails
if (Environment.type == EnvironmentType.Test) {
if (Environment.type === EnvironmentType.Test) {
return lists;
} else {
const alists = lists.filter((l: any) => {
@ -131,14 +137,14 @@ export default class KanbanBoardWebPart extends BaseClientSideWebPart<IKanbanBoa
{
groupName: strings.propertyPaneLabelOrderBuckets,
groupFields: [
PropertyFieldOrder("buckets", {
PropertyFieldOrder("buckets", {
key: "orderedItems",
label: strings.propertyPaneLabelOrderBuckets,
items: this.properties.buckets,
properties: this.properties,
onPropertyChange: this.onPropertyPaneFieldChanged,
onRenderItem: bucketOrder,
})
})
]
}
);
@ -173,12 +179,14 @@ export default class KanbanBoardWebPart extends BaseClientSideWebPart<IKanbanBoa
};
}
private listConfigurationChanged(propertyPath: string, oldValue: any, newValue: any) {
public listConfigurationChanged(propertyPath: string, oldValue: any, newValue: any): void {
console.log('listConfigurationChanged');
this.onPropertyPaneFieldChanged(propertyPath, oldValue, newValue);
this.refreshBucket();
}
private bucketConfigurationChanged(propertyPath: string, oldValue: any, newValue: any) {
private bucketConfigurationChanged(propertyPath: string, oldValue: any, newValue: any): void {
//its an array part !!!!!
if (propertyPath.indexOf('bucket_') !== -1) {
const oribuckets: IKanbanBucket[] = cloneDeep(this.properties.buckets);
@ -192,7 +200,7 @@ export default class KanbanBoardWebPart extends BaseClientSideWebPart<IKanbanBoa
this.context.propertyPane.refresh();
this.render();
} else {
throw "propertypath is not a bucket";
throw new Error("propertypath is not a bucket");
}
}
@ -207,7 +215,8 @@ export default class KanbanBoardWebPart extends BaseClientSideWebPart<IKanbanBoa
this.properties.buckets = currentbuckets;
this.context.propertyPane.refresh();
}
);
)
.catch(error => { throw new Error('Error loading Buckets by refreshBucket') });
}
}

View File

@ -1,3 +1,5 @@
@import '~@fluentui/react/dist/sass/References.scss';
.ordercolor {
width: 10px;
height: 10px;

View File

@ -2,21 +2,20 @@ import * as React from 'react';
import * as strings from 'KanbanBoardWebPartStrings';
import { DisplayMode, Guid, Environment, EnvironmentType } from '@microsoft/sp-core-library';
import { DisplayMode } from '@microsoft/sp-core-library';
import { WebPartContext } from '@microsoft/sp-webpart-base';
import { findIndex, isEqual, cloneDeep } from '@microsoft/sp-lodash-subset';
import { Spinner } from 'office-ui-fabric-react/lib/Spinner';
import { WebPartTitle } from "@pnp/spfx-controls-react/lib/WebPartTitle";
import { Placeholder } from "@pnp/spfx-controls-react/lib/Placeholder";
import {KanbanComponent,IKanbanBucket,IKanbanTask} from '../../../kanban';
import { KanbanComponent, IKanbanBucket, IKanbanTask } from '../../../kanban';
import { mergeBucketsWithChoices } from './helper';
import { ISPKanbanService } from '../services/ISPKanbanService';
import SPKanbanService from '../services/SPKanbanService';
import MockKanbanService from '../services/MockKanbanService';
import { Spinner } from '@fluentui/react';
export interface IKanbanBoardV2Props {
hideWPTitle: boolean;
@ -27,6 +26,7 @@ export interface IKanbanBoardV2Props {
listId: string;
configuredBuckets: IKanbanBucket[]; // need mearge with current readed
statekey: string; // force refresh ;)
dataService: ISPKanbanService;
}
export interface IKanbanBoardV2State {
@ -43,7 +43,7 @@ export default class KanbanBoardV2 extends React.Component<IKanbanBoardV2Props,
private dataService: ISPKanbanService;
constructor(props: IKanbanBoardV2Props) {
super(props);
this.dataService = this.props.dataService;
this.state = {
loading: false,
isConfigured: false,
@ -52,11 +52,6 @@ export default class KanbanBoardV2 extends React.Component<IKanbanBoardV2Props,
};
}
public componentDidMount(): void {
if (Environment.type == EnvironmentType.Local || Environment.type == EnvironmentType.Test) {
this.dataService= new MockKanbanService();
} else {
this.dataService = new SPKanbanService();
}
this._getData();
}
public shouldComponentUpdate(nextProps: IKanbanBoardV2Props, nextState: IKanbanBoardV2State): boolean {
@ -68,7 +63,7 @@ export default class KanbanBoardV2 extends React.Component<IKanbanBoardV2Props,
return false;
}
public componentDidUpdate(prevProps: IKanbanBoardV2Props) {
public componentDidUpdate(prevProps: IKanbanBoardV2Props): void {
if (this.props.listId !== prevProps.listId) {
this._getData();
}
@ -122,14 +117,14 @@ export default class KanbanBoardV2 extends React.Component<IKanbanBoardV2Props,
);
}
private _onConfigure = () => {
private _onConfigure = (): void => {
this.props.context.propertyPane.open();
}
private _moved(taskId: string, targetBucket: IKanbanBucket): void {
const elementsIndex = findIndex(this.state.tasks, element => element.taskId == taskId);
let newArray = [...this.state.tasks]; // same as Clone
const elementsIndex = findIndex(this.state.tasks, element => element.taskId === taskId);
const newArray = [...this.state.tasks]; // same as Clone
newArray[elementsIndex].bucket = targetBucket.bucket;
this.dataService.updateTaskBucketMove(this.props.listId, +taskId, targetBucket.bucket)
.then(res => {
@ -144,28 +139,31 @@ export default class KanbanBoardV2 extends React.Component<IKanbanBoardV2Props,
private _getData(): void {
if (!this.props.listId || this.props.listId.length == 0) {
if (!this.props.listId || this.props.listId.length === 0) {
this.setState({ isConfigured: false, loading: false });
} else {
const listId: string = this.props.listId;
this.dataService.getBuckets(listId).then((choices) => {
this.choices = choices;
const currentbuckets: IKanbanBucket[] = mergeBucketsWithChoices(this.props.configuredBuckets, this.choices);
if (!currentbuckets) {
this.setState({ isConfigured: false, loading: false, errorMessage: 'No Buckets found' });
return;
}
this.dataService.getAllTasks(listId).then((tasks) => {
this.setState({
isConfigured: true,
loading: false,
errorMessage: undefined,
buckets: currentbuckets,
tasks: tasks
});
});
this.dataService.getBuckets(listId)
.then((choices) => {
this.choices = choices;
const currentbuckets: IKanbanBucket[] = mergeBucketsWithChoices(this.props.configuredBuckets, this.choices);
if (!currentbuckets) {
this.setState({ isConfigured: false, loading: false, errorMessage: 'No Buckets found' });
return;
}
this.dataService.getAllTasks(listId).then((tasks) => {
this.setState({
isConfigured: true,
loading: false,
errorMessage: undefined,
buckets: currentbuckets,
tasks: tasks
});
}, (reject) => { throw new Error(reject) })
.catch(error => { throw new Error('Error loading Tasks') });
});
})
.catch(error => { throw new Error('Error loading Buckets') });
this.setState({ isConfigured: true, loading: true });
}

View File

@ -0,0 +1,14 @@
.errorMessage {
font-size: 12px;
font-weight: 400;
color: #a80000;
margin: 0;
padding-top: 5px;
display: flex;
align-items: center;
}
.errorIcon {
font-size: 14px;
margin-right: 5px;
}

View File

@ -0,0 +1,27 @@
import * as React from 'react';
import styles from './FieldErrorMessage.module.scss';
import { Icon } from '@fluentui/react/lib/Icon';
export interface IFieldErrorMessageProps {
errorMessage: string;
}
/**
* Component that shows an error message when something went wront with the property control
*/
export default class FieldErrorMessage extends React.Component<IFieldErrorMessageProps> {
public render(): JSX.Element {
if (this.props.errorMessage !== 'undefined' && this.props.errorMessage !== null && this.props.errorMessage !== '') {
return (
<div aria-live="assertive">
<p className={`ms-TextField-errorMessage ${styles.errorMessage}`}>
<Icon iconName='Error' className={styles.errorIcon} />
<span data-automation-id="error-message">{this.props.errorMessage}</span>
</p>
</div>
);
} else {
return <div />;
}
}
}

View File

@ -0,0 +1,22 @@
import { IChoiceGroupOption } from '@fluentui/react/lib/ChoiceGroup';
import { IPropertyFieldListPickerPropsInternal } from './IPropertyFieldListPicker';
import { ISPLists } from './IPropertyFieldListPickerHost';
/**
* PropertyFieldListPickerHost properties interface
*/
export interface IPropertyFieldListMultiPickerHostProps extends IPropertyFieldListPickerPropsInternal {
onChange: (targetProperty?: string, newValue?: any) => void; // eslint-disable-line @typescript-eslint/no-explicit-any
}
/**
* PropertyFieldSPListMultiplePickerHost state interface
*/
export interface IPropertyFieldListMultiPickerHostState {
loadedLists: ISPLists;
results: IChoiceGroupOption[];
selectedKeys: string[];
loaded: boolean;
errorMessage?: string;
}

View File

@ -0,0 +1,152 @@
import { BaseComponentContext } from '@microsoft/sp-component-base';
import { ISPList } from './IPropertyFieldListPickerHost';
import { IPropertyPaneCustomFieldProps } from '@microsoft/sp-property-pane';
/**
* Detailed list information
*/
export interface IPropertyFieldList {
/**
* List ID
*/
id: string;
/**
* List Title
*/
title?: string;
/**
* List server relative URL
*/
url?: string;
}
/**
* Enum for specifying how the lists should be sorted
*/
export enum PropertyFieldListPickerOrderBy {
Id = 1,
Title
}
/**
* Public properties of the PropertyFieldListPicker custom field
*/
export interface IPropertyFieldListPickerProps {
/**
* Property field label displayed on top
*/
label: string;
/**
* Context of the current web part
*/
context: BaseComponentContext;
/**
* Absolute Web Url of target site (user requires permissions)
*/
webAbsoluteUrl?: string;
/**
* Initial selected list set of the control
*/
selectedList?: string | string[] | IPropertyFieldList | IPropertyFieldList[];
/**
* BaseTemplate ID(s) of the lists or libraries you want to return.
*/
baseTemplate?: number | number[];
/**
* Specify if you want to include or exclude hidden lists. By default this is true.
*/
includeHidden?: boolean;
/**
* Specify the property on which you want to order the retrieve set of lists.
*/
orderBy?: PropertyFieldListPickerOrderBy;
/**
* Defines a onPropertyChange function to raise when the selected value changed.
* Normally this function must be always defined with the 'this.onPropertyChange'
* method of the web part object.
*/
onPropertyChange(propertyPath: string, oldValue: any, newValue: any): void; // eslint-disable-line @typescript-eslint/no-explicit-any
/**
* Parent Web Part properties
*/
properties: any; // eslint-disable-line @typescript-eslint/no-explicit-any
/**
* An UNIQUE key indicates the identity of this control
*/
key?: string;
/**
* Whether the property pane field is enabled or not.
*/
disabled?: boolean;
/**
* The method is used to get the validation error message and determine whether the input value is valid or not.
*
* When it returns string:
* - If valid, it returns empty string.
* - If invalid, it returns the error message string and the text field will
* show a red border and show an error message below the text field.
*
* When it returns Promise<string>:
* - The resolved value is display as error message.
* - The rejected, the value is thrown away.
*
*/
onGetErrorMessage?: (value: string) => string | Promise<string>;
/**
* Custom Field will start to validate after users stop typing for `deferredValidationTime` milliseconds.
* Default value is 200.
*/
deferredValidationTime?: number;
/**
* Defines list titles which should be excluded from the list picker control
*/
listsToExclude?: string[];
/**
* Filter list from Odata query (takes precendents over Hidden and BaseTemplate Filters)
*/
filter?: string;
/**
* Callback that is called before the dropdown is populated
*/
onListsRetrieved?: (lists: ISPList[]) => PromiseLike<ISPList[]> | ISPList[];
/**
* Specifies if the picker returns list id, title and url as an object instead on id.
*/
includeListTitleAndUrl?: boolean;
/**
* Content type id which, if present, must be on the list
*/
contentTypeId?: string;
}
/**
* Private properties of the PropertyFieldListPicker custom field.
* We separate public & private properties to include onRender & onDispose method waited
* by the PropertyFieldCustom, witout asking to the developer to add it when he's using
* the PropertyFieldListPicker.
*
*/
export interface IPropertyFieldListPickerPropsInternal extends IPropertyFieldListPickerProps, IPropertyPaneCustomFieldProps {
label: string;
targetProperty: string;
context: BaseComponentContext;
webAbsoluteUrl?: string;
selectedList?: string | IPropertyFieldList;
baseTemplate?: number | number[];
orderBy?: PropertyFieldListPickerOrderBy;
includeHidden?: boolean;
onPropertyChange(propertyPath: string, oldValue: any, newValue: any): void; // eslint-disable-line @typescript-eslint/no-explicit-any
properties: any; // eslint-disable-line @typescript-eslint/no-explicit-any
key: string;
disabled?: boolean;
onGetErrorMessage?: (value: string | string[]) => string | Promise<string>;
deferredValidationTime?: number;
listsToExclude?: string[];
filter?: string;
onListsRetrieved?: (lists: ISPList[]) => PromiseLike<ISPList[]> | ISPList[];
}

View File

@ -0,0 +1,49 @@
import { IPropertyFieldListPickerPropsInternal } from './IPropertyFieldListPicker';
import { IDropdownOption } from '@fluentui/react/lib/Dropdown';
/**
* PropertyFieldListPickerHost properties interface
*/
export interface IPropertyFieldListPickerHostProps extends IPropertyFieldListPickerPropsInternal {
onChange: (targetProperty?: string, newValue?: any) => void; // eslint-disable-line @typescript-eslint/no-explicit-any
}
/**
* PropertyFieldListPickerHost state interface
*/
export interface IPropertyFieldListPickerHostState {
loadedLists: ISPLists;
results: IDropdownOption[];
selectedKey?: string;
errorMessage?: string;
}
/**
* Defines a collection of SharePoint lists
*/
export interface ISPLists {
value: ISPList[];
}
/**
* Defines a Content Type
*/
export interface ISPContentType{
StringId:string;
}
/**
* Defines a SharePoint list
*/
export interface ISPList {
Title: string;
Id: string;
BaseTemplate: string;
RootFolder: {
ServerRelativeUrl: string;
};
ContentTypes: Array<ISPContentType>;
}

View File

@ -0,0 +1,160 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import {
IPropertyPaneField,
PropertyPaneFieldType
} from '@microsoft/sp-property-pane';
import { BaseComponentContext } from '@microsoft/sp-component-base';
import PropertyFieldListPickerHost from './PropertyFieldListPickerHost';
import { IPropertyFieldListPickerHostProps, ISPList } from './IPropertyFieldListPickerHost';
import { PropertyFieldListPickerOrderBy, IPropertyFieldListPickerProps, IPropertyFieldListPickerPropsInternal, IPropertyFieldList } from './IPropertyFieldListPicker';
/**
* Represents a PropertyFieldListPicker object
*/
class PropertyFieldListPickerBuilder implements IPropertyPaneField<IPropertyFieldListPickerPropsInternal> {
//Properties defined by IPropertyPaneField
public type: PropertyPaneFieldType = PropertyPaneFieldType.Custom;
public targetProperty: string;
public properties: IPropertyFieldListPickerPropsInternal;
//Custom properties label: string;
private label: string;
private context: BaseComponentContext;
private webAbsoluteUrl?: string;
private selectedList: string | IPropertyFieldList|undefined;
private baseTemplate: number | number[]|undefined;
private orderBy: PropertyFieldListPickerOrderBy;
private includeHidden: boolean;
private listsToExclude: string[];
private includeListTitleAndUrl: boolean;
public onPropertyChange(propertyPath: string, oldValue: any, newValue: any): void { /* no-op; */ } // eslint-disable-line @typescript-eslint/no-explicit-any
private customProperties: any; // eslint-disable-line @typescript-eslint/no-explicit-any
private key: string;
private disabled: boolean = false;
private onGetErrorMessage: (value: string) => string | Promise<string>;
private deferredValidationTime: number = 200;
private filter: string|undefined;
private contentTypeId: string|undefined;
private onListsRetrieved?: (lists: ISPList[]) => PromiseLike<ISPList[]> | ISPList[];
/**
* Constructor method
*/
public constructor(_targetProperty: string, _properties: IPropertyFieldListPickerPropsInternal) {
this.render = this.render.bind(this);
this.targetProperty = _targetProperty;
this.properties = _properties;
this.properties.onDispose = this.dispose;
this.properties.onRender = this.render;
this.label = _properties.label;
this.context = _properties.context;
this.webAbsoluteUrl = _properties.webAbsoluteUrl;
this.selectedList = _properties.selectedList;
this.baseTemplate = _properties.baseTemplate;
this.orderBy = _properties.orderBy?_properties.orderBy:PropertyFieldListPickerOrderBy.Title;
this.includeHidden = _properties.includeHidden?_properties.includeHidden:false;
this.onPropertyChange = _properties.onPropertyChange;
this.customProperties = _properties.properties;
this.key = _properties.key;
this.onGetErrorMessage = _properties.onGetErrorMessage?_properties.onGetErrorMessage:() => '';
this.listsToExclude = _properties.listsToExclude?_properties.listsToExclude:[];
this.filter = _properties.filter;
this.onListsRetrieved = _properties.onListsRetrieved;
this.includeListTitleAndUrl = _properties.includeListTitleAndUrl?_properties.includeListTitleAndUrl:false;
this.contentTypeId=_properties.contentTypeId;
if (_properties.disabled === true) {
this.disabled = _properties.disabled;
}
if (_properties.deferredValidationTime) {
this.deferredValidationTime = _properties.deferredValidationTime;
}
}
/**
* Renders the SPListPicker field content
*/
private render(elem: HTMLElement, ctx?: any, changeCallback?: (targetProperty?: string, newValue?: any) => void): void { // eslint-disable-line @typescript-eslint/no-explicit-any
const componentProps: IPropertyFieldListPickerHostProps = {
label: this.label,
targetProperty: this.targetProperty,
context: this.context,
webAbsoluteUrl: this.webAbsoluteUrl,
baseTemplate: this.baseTemplate,
orderBy: this.orderBy,
includeHidden: this.includeHidden,
onDispose: this.dispose,
onRender: this.render,
onChange: (target,value) => ( changeCallback && changeCallback(target,value)),
onPropertyChange: this.onPropertyChange,
properties: this.customProperties,
key: this.key,
disabled: this.disabled,
onGetErrorMessage: this.onGetErrorMessage,
deferredValidationTime: this.deferredValidationTime,
listsToExclude: this.listsToExclude,
filter: this.filter,
onListsRetrieved: this.onListsRetrieved,
includeListTitleAndUrl: this.includeListTitleAndUrl,
contentTypeId:this.contentTypeId
};
// Single selector
componentProps.selectedList = this.selectedList;
const element: React.ReactElement<IPropertyFieldListPickerHostProps> = React.createElement(PropertyFieldListPickerHost, componentProps);
// Calls the REACT content generator
ReactDom.render(element, elem);
}
/**
* Disposes the current object
*/
private dispose(elem: HTMLElement): void {
ReactDom.unmountComponentAtNode(elem);
}
}
/**
* Helper method to create a SPList Picker on the PropertyPane.
* @param targetProperty - Target property the SharePoint list picker is associated to.
* @param properties - Strongly typed SPList Picker properties.
*/
export function PropertyFieldListPicker(targetProperty: string, properties: IPropertyFieldListPickerProps): IPropertyPaneField<IPropertyFieldListPickerPropsInternal> {
//Create an internal properties object from the given properties
const newProperties: IPropertyFieldListPickerPropsInternal = {
label: properties.label,
targetProperty: targetProperty,
context: properties.context,
webAbsoluteUrl: properties.webAbsoluteUrl,
selectedList: !Array.isArray(properties.selectedList) ? properties.selectedList : undefined,
baseTemplate: properties.baseTemplate,
orderBy: properties.orderBy,
includeHidden: properties.includeHidden,
onPropertyChange: properties.onPropertyChange,
properties: properties.properties,
onDispose: undefined,
onRender: (elem: HTMLElement, ctx?: any, changeCallback?: (targetProperty?: string, newValue?: any) => void): void => { /* no-op; */ }, // eslint-disable-line @typescript-eslint/no-explicit-any
key: "key"+properties.key,
disabled: properties.disabled,
onGetErrorMessage: properties.onGetErrorMessage,
deferredValidationTime: properties.deferredValidationTime,
listsToExclude: properties.listsToExclude,
filter: properties.filter,
onListsRetrieved: properties.onListsRetrieved,
includeListTitleAndUrl: properties.includeListTitleAndUrl,
contentTypeId:properties.contentTypeId
};
//Calls the PropertyFieldListPicker builder object
//This object will simulate a PropertyFieldCustom to manage his rendering process
return new PropertyFieldListPickerBuilder(targetProperty, newProperties);
}

View File

@ -0,0 +1,251 @@
import * as React from 'react';
import { Dropdown, IDropdownOption } from '@fluentui/react/lib/Dropdown';
import { Async } from '@fluentui/react/lib/Utilities';
import { Label } from '@fluentui/react/lib/Label';
import { IPropertyFieldListPickerHostProps, IPropertyFieldListPickerHostState, ISPList } from './IPropertyFieldListPickerHost';
import { IPropertyFieldList } from './IPropertyFieldListPicker';
import SPListPickerService from './SPListPickerService';
import { setPropertyValue } from '../PropertyOrderField/helper';
import FieldErrorMessage from './FieldErrorMessage';
// Empty list value, to be checked for single list selection
const EMPTY_LIST_KEY = 'NO_LIST_SELECTED';
/**
* Renders the controls for PropertyFieldListPicker component
*/
export default class PropertyFieldListPickerHost extends React.Component<IPropertyFieldListPickerHostProps, IPropertyFieldListPickerHostState> {
private latestValidateValue: string;
private async: Async;
private delayedValidate: (value: string) => void;
/**
* Constructor method
*/
constructor(props: IPropertyFieldListPickerHostProps) {
super(props);
this.state = {
loadedLists: {
value: []
},
results: [],
errorMessage: ''
};
this.async = new Async(this);
this.validate = this.validate.bind(this);
this.onChanged = this.onChanged.bind(this);
this.notifyAfterValidate = this.notifyAfterValidate.bind(this);
this.delayedValidate = this.async.debounce(this.validate, this.props.deferredValidationTime);
}
public componentDidMount(): void {
// Start retrieving the SharePoint lists
this.loadLists().then(() => { /* no-op; */ }).catch(() => { /* no-op; */ });
}
public componentDidUpdate(prevProps: IPropertyFieldListPickerHostProps, prevState: IPropertyFieldListPickerHostState): void {
if (this.props.baseTemplate !== prevProps.baseTemplate ||
this.props.webAbsoluteUrl !== prevProps.webAbsoluteUrl) {
this.loadLists().then(() => { /* no-op; */ }).catch(() => { /* no-op; */ });
}
}
/**
* Loads the list from SharePoint current web site, or target site if specified by webRelativeUrl
*/
private async loadLists(): Promise<void> {
const {
context,
selectedList
} = this.props;
const listService: SPListPickerService = new SPListPickerService(this.props, context);
const listsToExclude: string[] = this.props.listsToExclude || [];
const options = [];
let selectedListKey: string = '';
if (selectedList) {
selectedListKey = typeof selectedList === 'string' ? selectedList : selectedList.id;
}
let selectedKey: string | undefined;
const response = await listService.getLibs();
// Start mapping the list that are selected
response.value.forEach((list: ISPList) => {
if (selectedListKey === list.Id) {
selectedKey = list.Id;
}
// Make sure that the current list is NOT in the 'listsToExclude' array
if (listsToExclude.indexOf(list.Title) === -1 && listsToExclude.indexOf(list.Id) === -1) {
options.push({
key: list.Id,
text: list.Title
});
}
});
// Option to unselect the list
options.unshift({
key: EMPTY_LIST_KEY,
text: ''
});
// Update the current component state
this.setState({
loadedLists: response,
results: options,
selectedKey: selectedKey
});
}
/**
* Raises when a list has been selected
*/
private onChanged(option: IDropdownOption, index?: number): void {
const newValue: string = option.key as string;
this.delayedValidate(newValue);
}
/**
* Validates the new custom field value
*/
private validate(value: string): void {
if (this.props.onGetErrorMessage === null || this.props.onGetErrorMessage === undefined) {
this.notifyAfterValidate(value);
return;
}
if (this.latestValidateValue === value) {
return;
}
this.latestValidateValue = value;
const errResult: string | Promise<string> = this.props.onGetErrorMessage(value || '');
if (typeof errResult !== 'undefined') {
if (typeof errResult === 'string') {
if (errResult === '') {
this.notifyAfterValidate(value);
}
this.setState({
errorMessage: errResult
});
} else {
errResult.then((errorMessage: string) => {
if (!errorMessage) {
this.notifyAfterValidate(value);
}
this.setState({
errorMessage: errorMessage
});
}).catch(() => { /* no-op; */ });
}
} else {
this.notifyAfterValidate(value);
}
}
/**
* Notifies the parent Web Part of a property value change
*/
private notifyAfterValidate(newValue: string): void {
const {
onPropertyChange,
targetProperty,
selectedList,
includeListTitleAndUrl,
properties,
onChange
} = this.props;
const {
loadedLists
} = this.state;
// Check if the user wanted to unselect the list
let propValue: string | IPropertyFieldList | undefined;
if (includeListTitleAndUrl) {
if (newValue === EMPTY_LIST_KEY) {
propValue = undefined;
}
else {
const spList = loadedLists.value.filter(l => l.Id === newValue)[0];
propValue = {
id: newValue,
title: spList.Title,
url: spList.RootFolder.ServerRelativeUrl
};
}
}
else {
propValue = newValue === EMPTY_LIST_KEY ? '' : newValue;
}
// Deselect all options
const options = this.state.results.map(option => {
if (option.selected) {
option.selected = false;
}
return option;
});
// Set the current selected key
const selectedKey = newValue;
// Update the state
this.setState({
selectedKey: selectedKey,
results: options
});
if (onPropertyChange && propValue !== null) {
// Store the new property value
setPropertyValue(properties, targetProperty, propValue);
// Trigger the default onPrpertyChange event
onPropertyChange(targetProperty, selectedList, propValue);
// Trigger the apply button
if (typeof onChange !== 'undefined' && onChange !== null) {
onChange(targetProperty, propValue);
}
}
}
/**
* Called when the component will unmount
*/
public componentWillUnmount(): void {
if (typeof this.async !== 'undefined') {
this.async.dispose();
}
}
/**
* Renders the SPListpicker controls with Office UI Fabric
*/
public render(): JSX.Element {
// Renders content
return (
<div>
{this.props.label && <Label>{this.props.label}</Label>}
<Dropdown
disabled={this.props.disabled}
label=''
onChange={(ev,options) => {
this.onChanged(options as IDropdownOption);
}
}
options={this.state.results}
selectedKey={this.state.selectedKey}
/>
<FieldErrorMessage errorMessage={""+this.state.errorMessage} />
</div>
);
}
}

View File

@ -0,0 +1,118 @@
import { SPHttpClient } from '@microsoft/sp-http';
import { BaseComponentContext } from '@microsoft/sp-component-base';
import { IPropertyFieldListPickerHostProps, ISPList, ISPLists } from './IPropertyFieldListPickerHost';
import { PropertyFieldListPickerOrderBy } from './IPropertyFieldListPicker';
/**
* Service implementation to get list & list items from current SharePoint site
*/
export default class SPListPickerService {
private context: BaseComponentContext;
private props: IPropertyFieldListPickerHostProps;
/**
* Service constructor
*/
constructor(
_props: IPropertyFieldListPickerHostProps,
pageContext: BaseComponentContext
) {
this.props = _props;
this.context = pageContext;
}
/**
* Gets the collection of libs in the current SharePoint site, or target site if specified by webRelativeUrl
*/
public async getLibs(): Promise<ISPLists> {
// use the web relative url if provided, otherwise default to current SharePoint site
const webAbsoluteUrl = this.props.webAbsoluteUrl
? this.props.webAbsoluteUrl
: this.context.pageContext.web.absoluteUrl;
// If the running environment is SharePoint, request the lists REST service
let queryUrl: string;
if (this.props.contentTypeId) {
queryUrl = `${webAbsoluteUrl}/_api/lists?$select=Title,id,BaseTemplate,RootFolder/ServerRelativeUrl,ContentTypes/StringId,ContentTypes/Name&$expand=RootFolder&$expand=ContentTypes`;
} else {
queryUrl = `${webAbsoluteUrl}/_api/lists?$select=Title,id,BaseTemplate,RootFolder/ServerRelativeUrl&$expand=RootFolder`;
}
// Check if the orderBy property is provided
if (this.props.orderBy !== null) {
queryUrl += '&$orderby=';
switch (this.props.orderBy) {
case PropertyFieldListPickerOrderBy.Id:
queryUrl += 'Id';
break;
case PropertyFieldListPickerOrderBy.Title:
queryUrl += 'Title';
break;
}
}
// Adds an OData Filter to the list
if (this.props.filter) {
queryUrl += `&$filter=${encodeURIComponent(this.props.filter)}`;
}
// Check if the list have get filtered based on the list base template type
else if ((this.props.baseTemplate !== null && this.props.baseTemplate) || Array.isArray(this.props.baseTemplate)) {
if (Array.isArray(this.props.baseTemplate)) {
queryUrl += '&$filter=(';
queryUrl += this.props.baseTemplate.map(temp => `(BaseTemplate%20eq%20${temp})`).join('%20or%20');
queryUrl += ')';
} else {
queryUrl += '&$filter=BaseTemplate%20eq%20';
queryUrl += this.props.baseTemplate;
}
// Check if you also want to exclude hidden list in the list
if (this.props.includeHidden === false) {
queryUrl += '%20and%20Hidden%20eq%20false';
}
} else {
if (this.props.includeHidden === false) {
queryUrl += '&$filter=Hidden%20eq%20false';
}
}
const response = await this.context.spHttpClient.get(
queryUrl,
SPHttpClient.configurations.v1
);
let lists = (await response.json()) as ISPLists;
//remove unwanted contenttypes
if (this.props.contentTypeId) {
const testct = this.props.contentTypeId.toUpperCase();
lists.value = lists.value.filter((l) => {
for (const ct of l.ContentTypes) {
const ctid: string = ct.StringId.toUpperCase();
if (ctid.substring(0, testct.length) === testct) {
return true;
}
}
return false;
});
}
// Check if onListsRetrieved callback is defined
if (this.props.onListsRetrieved) {
//Call onListsRetrieved
const lr = this.props.onListsRetrieved(lists.value);
let output: ISPList[];
//Conditional checking to see of PromiseLike object or array
if (lr instanceof Array) {
output = lr;
} else {
output = await lr;
}
lists = {
value: output,
};
}
return lists;
}
}

View File

@ -0,0 +1,4 @@
export * from './PropertyFieldListPicker';
export * from './IPropertyFieldListPicker';
export * from './PropertyFieldListPickerHost';
export * from './IPropertyFieldListPickerHost';

View File

@ -0,0 +1,77 @@
import { IPropertyPaneCustomFieldProps } from '@microsoft/sp-property-pane';
/**
* Public properties of the PropertyFieldOrder custom field
*/
export interface IPropertyFieldOrderProps {
/**
* Property field label displayed on top
*/
label: string;
/**
* Defines an onPropertyChange function to raise when the items order changes.
* Normally this function must be defined with the 'this.onPropertyChange'
* method of the web part object.
*/
onPropertyChange(propertyPath: string, oldValue: any, newValue: any): void; // eslint-disable-line @typescript-eslint/no-explicit-any
/**
* An array of values to reorder
*/
items: Array<any>; // eslint-disable-line @typescript-eslint/no-explicit-any
/**
* The property to use for display, when undefined, the toString() method of the object is used (ignored when the onRenderItem function is specified)
*/
textProperty?: string;
/**
* When true, drag and drop reordering is disabled (defaults to false)
*/
disableDragAndDrop?: boolean;
/**
* When true, arrow buttons are not displayed (defaults to false)
*/
removeArrows?: boolean;
/**
* The maximun height for the items in px (when not set, the control expands as necessary)
*/
maxHeight?: number;
/**
* Whether the property pane field is enabled or not.
*/
disabled?: boolean;
/**
* Optional callback to provide custom rendering of the item (default is simple text based on either item or the property identified in the textProperty)
*/
onRenderItem?: (item: any, index: number) => JSX.Element; // eslint-disable-line @typescript-eslint/no-explicit-any
/**
* An UNIQUE key indicates the identity of this control
*/
key: string;
/**
* Parent Web Part properties
*/
properties: any; // eslint-disable-line @typescript-eslint/no-explicit-any
/**
* The name of the UI Fabric Font Icon to use for the move up button (defaults to ChevronUpSmall)
*/
moveUpIconName?: string;
/**
* The name of the UI Fabric Font Icon to use for the move down button (defaults to ChevronDownSmall)
*/
moveDownIconName?: string;
}
export interface IPropertyFieldOrderPropsInternal extends IPropertyFieldOrderProps, IPropertyPaneCustomFieldProps {
}

View File

@ -0,0 +1,23 @@
/**
* PropertyFieldOrderHost properties interface
*/
export interface IPropertyFieldOrderHostProps {
label: string;
disabled: boolean;
items: Array<any>; // eslint-disable-line @typescript-eslint/no-explicit-any
textProperty?: string;
moveUpIconName: string;
moveDownIconName: string;
disableDragAndDrop: boolean;
removeArrows: boolean;
maxHeight?: number;
valueChanged: (newValue: Array<any>) => void; // eslint-disable-line @typescript-eslint/no-explicit-any
onRenderItem?: (item: any, index: number) => JSX.Element; // eslint-disable-line @typescript-eslint/no-explicit-any
}
/**
* PropertyFieldOrderHost state interface
*/
export interface IPropertyFieldOrderHostState {
items: Array<any>; // eslint-disable-line @typescript-eslint/no-explicit-any
}

View File

@ -0,0 +1,94 @@
import { IPropertyPaneField, PropertyPaneFieldType } from '@microsoft/sp-property-pane';
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { IPropertyFieldOrderHostProps } from './IPropertyFieldOrderHost';
import PropertyFieldOrderHost from './PropertyFieldOrderHost';
import { IPropertyFieldOrderProps, IPropertyFieldOrderPropsInternal } from './IPropertyFieldOrder';
import { setPropertyValue } from './helper';
class PropertyFieldOrderBuilder implements IPropertyPaneField<IPropertyFieldOrderProps> {
//Properties defined by IPropertyPaneField
public type: PropertyPaneFieldType = PropertyPaneFieldType.Custom;
public targetProperty: string;
public properties: IPropertyFieldOrderPropsInternal;
private elem: HTMLElement;
private items: Array<any>; // eslint-disable-line @typescript-eslint/no-explicit-any
private changeCB?: (targetProperty?: string, newValue?: any) => void; // eslint-disable-line @typescript-eslint/no-explicit-any
public constructor(_targetProperty: string, _properties: IPropertyFieldOrderProps) {
this.targetProperty = _targetProperty;
this.properties = {
key: _properties.key,
label: _properties.label,
onPropertyChange: _properties.onPropertyChange,
disabled: _properties.disabled,
properties: _properties.properties,
items: _properties.items,
textProperty: _properties.textProperty,
moveUpIconName: _properties.moveUpIconName,
moveDownIconName: _properties.moveDownIconName,
disableDragAndDrop: _properties.disableDragAndDrop,
removeArrows: _properties.removeArrows,
maxHeight: _properties.maxHeight,
onRenderItem: _properties.onRenderItem,
onRender: this.onRender.bind(this)
};
this.items = _properties.items;
}
public render(): void {
if (!this.elem) {
return;
}
this.onRender(this.elem);
}
public onDispose(element: HTMLElement): void {
ReactDom.unmountComponentAtNode(element);
}
private onRender(elem: HTMLElement, ctx?: any, changeCallback?: (targetProperty?: string, newValue?: any) => void): void { // eslint-disable-line @typescript-eslint/no-explicit-any
if (!this.elem) {
this.elem = elem;
}
this.changeCB = changeCallback;
const element: React.ReactElement<IPropertyFieldOrderHostProps> = React.createElement(PropertyFieldOrderHost, {
label: this.properties.label,
disabled: this.properties.disabled ? this.properties.disabled : false,
items: this.items,
textProperty: this.properties.textProperty,
moveUpIconName: this.properties.moveUpIconName || 'ChevronUpSmall',
moveDownIconName: this.properties.moveDownIconName || 'ChevronDownSmall',
disableDragAndDrop: this.properties.disableDragAndDrop ? this.properties.disableDragAndDrop : false,
removeArrows: this.properties.removeArrows ? this.properties.removeArrows : false,
maxHeight: this.properties.maxHeight,
onRenderItem: this.properties.onRenderItem,
valueChanged: this.onValueChanged.bind(this)
});
ReactDom.render(element, elem);
}
private onValueChanged(newValue: Array<any>): void { // eslint-disable-line @typescript-eslint/no-explicit-any
if (this.properties.onPropertyChange && newValue !== null) {
this.properties.onPropertyChange(this.targetProperty, this.items, newValue);
this.items = newValue;
setPropertyValue(this.properties.properties, this.targetProperty, newValue);
if (typeof this.changeCB !== 'undefined' && this.changeCB !== null) {
this.changeCB(this.targetProperty, newValue);
}
}
}
}
export function PropertyFieldOrder(targetProperty: string, properties: IPropertyFieldOrderProps): IPropertyPaneField<IPropertyFieldOrderProps> {
return new PropertyFieldOrderBuilder(targetProperty, properties);
}

View File

@ -0,0 +1,65 @@
$ms-color-themePrimary: '[theme:themePrimary, default:#0078d7]';
$ms-color-neutralLight: '[theme:neutralLight, default:#eaeaea]';
$ms-color-neutralLighter: '[theme:neutralLighter, default:#f4f4f4]';
$ms-color-neutralTertiary: '[theme:neutralTertiary, default:#a6a6a6]';
$ms-color-white: '[theme:white, default:#ffffff]';
.propertyFieldOrder {
margin-bottom: 2px;
ul {
padding: 0.5px;
margin: 0;
overflow-y: auto;
}
.disabled {
li {
color: $ms-color-neutralTertiary;
}
}
li {
list-style: none;
background-color: $ms-color-white;
border: 0.5px solid;
border-color: $ms-color-neutralLight;
outline: 0.5px solid;
outline-color: $ms-color-neutralLight;
.enabled & :hover {
background-color: $ms-color-neutralLighter;
}
& > div {
padding: 3px 6px;
display: flex;
flex-direction: row;
}
}
.itemBox {
flex-grow: 1;
}
.dragEnter {
background-color: $ms-color-neutralLight;
border-top: 2px dashed;
border-top-color: $ms-color-themePrimary;
}
.dragLast {
background-color: $ms-color-neutralLight;
border-bottom: 2px dashed;
border-bottom-color: $ms-color-themePrimary;
}
.lastBox {
height: 8px;
}
}

View File

@ -0,0 +1,263 @@
import { IButtonStyles, IconButton } from '@fluentui/react/lib/Button';
//import { Selection } from '@fluentui/react/lib/DetailsList';
import { Label } from '@fluentui/react/lib/Label';
//import { DragDropHelper } from '@fluentui/react/lib/utilities/dragdrop';
//import { IDragDropContext } from '@fluentui/react/lib/utilities/dragdrop/interfaces';
import * as React from 'react';
import { IPropertyFieldOrderHostProps, IPropertyFieldOrderHostState } from './IPropertyFieldOrderHost';
import styles from './PropertyFieldOrderHost.module.scss';
import { isEqual } from '@microsoft/sp-lodash-subset';
//import { EventGroup } from '@fluentui/react/lib/Utilities'; //'@uifabric/utilities/lib/EventGroup';
export default class PropertyFieldOrderHost extends React.Component<IPropertyFieldOrderHostProps, IPropertyFieldOrderHostState> {
private _draggedItem: any; // eslint-disable-line @typescript-eslint/no-explicit-any
//private _selection: Selection;
//private _ddHelper: DragDropHelper;
private _refs: Array<HTMLElement>;
private _ddSubs: Array<any>; // eslint-disable-line @typescript-eslint/no-explicit-any
private _lastBox: HTMLDivElement;
constructor(props: IPropertyFieldOrderHostProps, state: IPropertyFieldOrderHostState) {
super(props);
// this._selection = new Selection();
/*this._ddHelper = new DragDropHelper({
selection: this._selection
});
*/
this._refs = new Array<HTMLElement>();
this._ddSubs = new Array<any>(); // eslint-disable-line @typescript-eslint/no-explicit-any
this._draggedItem = null;
this.state = {
items: []
};
}
public render(): JSX.Element {
const {
items
} = this.state;
return (
<div className={styles.propertyFieldOrder}>
{this.props.label && <Label>{this.props.label}</Label>}
<ul style={{ maxHeight: this.props.maxHeight ? this.props.maxHeight + 'px' : '100%' }} className={!this.props.disabled ? styles.enabled : styles.disabled}>
{
(items && items.length > 0) && (
items.map((value: any, index: number) => { // eslint-disable-line @typescript-eslint/no-explicit-any
return (
<li
ref={this.registerRef}
key={index}
draggable={!this.props.disableDragAndDrop && !this.props.disabled}
style={{ cursor: !this.props.disableDragAndDrop && !this.props.disabled ? 'pointer' : 'default' }}
>{this.renderItem(value, index)}</li>
);
})
)
}
{
(items && items.length > 0) && <div className={styles.lastBox} ref={(ref:HTMLDivElement):void => { this._lastBox = ref; }} />
}
</ul>
</div>
);
}
private renderItem(item: any, index: number): JSX.Element { // eslint-disable-line @typescript-eslint/no-explicit-any
return (
<div>
<div className={styles.itemBox}>
{this.renderDisplayValue(item, index)}
</div>
{!this.props.removeArrows &&
<div>{this.renderArrows(index)}</div>
}
</div>
);
}
private renderDisplayValue(item: any, index: number): JSX.Element { // eslint-disable-line @typescript-eslint/no-explicit-any
if (typeof this.props.onRenderItem === "function") {
return this.props.onRenderItem(item, index);
} else {
return (
<span>{this.props.textProperty ? item[this.props.textProperty] : item.toString()}</span>
);
}
}
private renderArrows(index: number): JSX.Element {
const arrowButtonStyles: Partial<IButtonStyles> = {
root: {
width: '14px',
height: '100%',
display: 'inline-block'
},
rootDisabled: {
backgroundColor: 'transparent'
},
icon: {
fontSize: "10px"
}
};
return (
<div>
<IconButton
disabled={this.props.disabled || index === 0}
iconProps={{ iconName: this.props.moveUpIconName }}
onClick={() => { this.onMoveUpClick(index); }}
styles={arrowButtonStyles}
/>
<IconButton
disabled={this.props.disabled || index === this.props.items.length - 1}
iconProps={{ iconName: this.props.moveDownIconName }}
onClick={() => { this.onMoveDownClick(index); }}
styles={arrowButtonStyles}
/>
</div>
);
}
public UNSAFE_componentWillMount(): void {
this.setState({
items: this.props.items || []
});
}
public componentDidMount(): void {
this.setupSubscriptions();
}
public UNSAFE_componentWillUpdate(nextProps: IPropertyFieldOrderHostProps): void {
// Check if the provided items are still the same
if (!isEqual(nextProps.items, this.state.items)) {
this.setState({
items: this.props.items || []
});
}
}
public componentDidUpdate(): void {
this.cleanupSubscriptions();
this.setupSubscriptions();
}
public componentWillUnmount(): void {
this.cleanupSubscriptions();
}
private registerRef = (ref: HTMLLIElement): void => {
this._refs.push(ref);
}
private setupSubscriptions = (): void => {
if (!this.props.disableDragAndDrop && !this.props.disabled) {
this._refs.forEach((value: HTMLElement, index: number) => {
/* this._ddSubs.push(this._ddHelper.subscribe(value, new EventGroup(value), {
eventMap: [
{
callback: (context: IDragDropContext) => {
this._draggedItem = context.data;
},
eventName: 'dragstart'
}
],
selectionIndex: index,
context: { data: this.state.items[index], index: index },
updateDropState: (isDropping: boolean, event: DragEvent) => {
if (isDropping) {
value.classList.add(styles.dragEnter);
} else {
value.classList.remove(styles.dragEnter);
}
},
canDrop: (dropContext?: IDragDropContext, dragContext?: IDragDropContext) => {
return true;
},
canDrag: (item?: any) => { // eslint-disable-line @typescript-eslint/no-explicit-any
return true;
},
onDrop: (item?: any) => { // eslint-disable-line @typescript-eslint/no-explicit-any
if (this._draggedItem) {
this.insertBeforeItem(item);
}
},
onDragEnd: () => {
this._draggedItem = null;
}
}));*/
});
//Create dropable area below list to allow items to be dragged to the bottom
if (this._refs.length && typeof this._lastBox !== "undefined") {
/*this._ddSubs.push(this._ddHelper.subscribe(this._lastBox, new EventGroup(this._lastBox), {
selectionIndex: this._refs.length,
context: { data: {}, index: this._refs.length },
updateDropState: (isDropping: boolean, event: DragEvent) => {
if (isDropping) {
this._refs[this._refs.length - 1].classList.add(styles.dragLast);
} else {
this._refs[this._refs.length - 1].classList.remove(styles.dragLast);
}
},
canDrop: (dropContext?: IDragDropContext, dragContext?: IDragDropContext) => {
return true;
},
onDrop: (item?: any, event?: DragEvent) => { // eslint-disable-line @typescript-eslint/no-explicit-any
if (this._draggedItem) {
const itemIndex: number = this.state.items.indexOf(this._draggedItem);
this.moveItemAtIndexToTargetIndex(itemIndex, this.state.items.length - 1);
}
}
}));*/
}
}
}
private cleanupSubscriptions = (): void => {
while (this._ddSubs.length) {
const sub: any = this._ddSubs.pop(); // eslint-disable-line @typescript-eslint/no-explicit-any
sub.dispose();
}
}
public insertBeforeItem = (item: any): void => { // eslint-disable-line @typescript-eslint/no-explicit-any
const itemIndex: number = this.state.items.indexOf(this._draggedItem);
let targetIndex: number = this.state.items.indexOf(item);
if (itemIndex < targetIndex) {
targetIndex -= 1;
}
this.moveItemAtIndexToTargetIndex(itemIndex, targetIndex);
}
private onMoveUpClick = (itemIndex: number): void => {
if (itemIndex > 0) {
this.moveItemAtIndexToTargetIndex(itemIndex, itemIndex - 1);
}
}
private onMoveDownClick = (itemIndex: number): void => {
if (itemIndex < this.state.items.length - 1) {
this.moveItemAtIndexToTargetIndex(itemIndex, itemIndex + 1);
}
}
private moveItemAtIndexToTargetIndex = (itemIndex: number, targetIndex: number): void => {
if (itemIndex !== targetIndex && itemIndex > -1 && targetIndex > -1 && itemIndex < this.state.items.length && targetIndex < this.state.items.length) {
const items: Array<any> = this.state.items; // eslint-disable-line @typescript-eslint/no-explicit-any
items.splice(targetIndex, 0, ...items.splice(itemIndex, 1));
this.setState({
items: items
});
this.props.valueChanged(items);
}
}
}

View File

@ -0,0 +1,12 @@
export const setPropertyValue = (properties: any, targetProperty: string, value: any): void => { // eslint-disable-line @typescript-eslint/no-explicit-any
if (!properties) {
return;
}
if (targetProperty.indexOf('.') === -1) { // simple prop
properties[targetProperty] = value;
}
else {
throw new Error('Nested properties are not supported');
// .set(properties, targetProperty, value);
}
};

Some files were not shown because too many files have changed in this diff Show More