Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PeoplePicker] Context optimization #1764

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 23 additions & 10 deletions docs/documentation/docs/controls/PeoplePicker.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,26 @@ This control renders a People picker field which can be used to select one or mo

![Selected people](../assets/Peoplepicker-multiplechoices.png)


## How to use this control in your solutions

- Check that you installed the `@pnp/spfx-controls-react` dependency. Check out the [getting started](../../#getting-started) page for more information about installing the dependency.
- Import the following modules to your component:

```typescript
import { PeoplePicker, PrincipalType } from "@pnp/spfx-controls-react/lib/PeoplePicker";
import { IPeoplePickerContext, PeoplePicker, PrincipalType } from "@pnp/spfx-controls-react/lib/PeoplePicker";
```

- Use the `PeoplePicker` control in your code as follows:

```typescript
const peoplePickerContext: IPeoplePickerContext = {
absoluteUrl: this.props.context.pageContext.web.absoluteUrl,
msGraphClientFactory: this.props.context.msGraphClientFactory,
spHttpClient: this.props.context.spHttpClient
};

<PeoplePicker
context={this.props.context}
context={peoplePickerContext}
titleText="People Picker"
personSelectionLimit={3}
groupName={"Team Site Owners"} // Leave this blank in case you want to filter from all users
Expand Down Expand Up @@ -59,7 +64,7 @@ The People picker control can be configured with the following properties:

| Property | Type | Required | Description | Default |
| ---- | ---- | ---- | ---- | ---- |
| context | BaseComponentContext | yes | Context of the current web part. | |
| context | IPeoplePickerContext | yes | Context of the component, based on the SPFx context ([*BaseComponentContext*](https://learn.microsoft.com/javascript/api/sp-component-base/basecomponentcontext?view=sp-typescript-latest)). | |
| titleText | string | no | Text to be displayed on the control | |
| groupName | string | no | Group from which users are fetched. Leave it blank if need to filter all users. When both groupName and groupId specified groupName takes precedence. | _none_ |
| groupId | number \| string \| (string\|number)[] | no | Group from which users are fetched. Leave it blank if need to filter all users. When both groupId and groupName specified groupName takes precedence. If string is specified, Microsoft 365 Group is used. If array is used, fetch results from multiple groups | _none_ |
Expand All @@ -82,8 +87,8 @@ The People picker control can be configured with the following properties:
| allowUnvalidated | boolean | no | When true, allow email addresses that have not been validated to be entered, effectively allowing any user. | false |
| suggestionsLimit | number | no | Maximum number of suggestions to show in the full suggestion list. | 5 |
| resolveDelay | number | no | Add delay to resolve and search users | 200 |
| placeholder | string | no | Short text hint to display in empty picker |
| styles | Partial<IBasePickerStyles> | no | Styles to apply on control |
| placeholder | string | no | Short text hint to display in empty picker | |
| styles | Partial<IBasePickerStyles> | no | Styles to apply on control | |
| searchTextLimit | number | no | Specifies the minimum character count needed to begin retrieving search results. | 2 |

Enum `PrincipalType`
Expand All @@ -97,13 +102,21 @@ The `PrincipalType` enum can be used to specify the types of information you wan
| SecurityGroup | 4 |
| SharePointGroup | 8 |

Interface `IPeoplePickerContext`

## MSGraph Permissions required
Provides mandatory properties to search users on the tenant

This control requires the following scopes if groupId is of type String:
| Value | Type | Description |
| ---- | ---- | ---- |
| absoluteUrl | string | Current `SPWeb` absolute URL. |
| msGraphClientFactory | MSGraphClientFactory | Instance of MSGraphClientFactory used for querying Microsoft Graph REST API. |
| spHttpClient | SPHttpClient | Instance of SPHttpClient used for querying SharePoint REST API. |

at least : GroupMember.Read.All, Directory.Read.All
## MSGraph Permissions required

This control requires at least one the following scopes if `groupId` is of type `string`:

![](https://telemetry.sharepointpnp.com/sp-dev-fx-controls-react/wiki/controls/PeoplePicker)
- *GroupMember.Read.All* + *User.ReadBasic.All*
- *Directory.Read.All*

![](https://telemetry.sharepointpnp.com/sp-dev-fx-controls-react/wiki/controls/PeoplePicker)
2 changes: 1 addition & 1 deletion src/common/telemetry/version.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const version: string = "3.18.0";
export const version: string = "3.18.0";
12 changes: 9 additions & 3 deletions src/controls/dynamicForm/dynamicField/DynamicField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { DateTimePicker } from '../../dateTimePicker/DateTimePicker';
import { FilePicker, IFilePickerResult } from '../../filePicker';
import { ListItemPicker } from '../../listItemPicker';
import { LocationPicker } from '../../locationPicker';
import { PeoplePicker, PrincipalType } from '../../peoplepicker';
import { IPeoplePickerContext, PeoplePicker, PrincipalType } from '../../peoplepicker';
import { RichText } from '../../richText';
import { IPickerTerms, TaxonomyPicker } from '../../taxonomyPicker';
import styles from '../DynamicForm.module.scss';
Expand Down Expand Up @@ -93,6 +93,12 @@ export class DynamicField extends React.Component<IDynamicFieldProps, IDynamicFi
placeholder: placeholder
};

const peoplePickerContext: IPeoplePickerContext = {
absoluteUrl: context.pageContext.web.absoluteUrl,
msGraphClientFactory: context.msGraphClientFactory,
spHttpClient: context.spHttpClient
};

// const defaultValue = fieldDefaultValue;

const labelEl = <label className={(required) ? styles.fieldRequired + ' ' + styles.fieldLabel : styles.fieldLabel}>{label}</label>;
Expand Down Expand Up @@ -377,7 +383,7 @@ export class DynamicField extends React.Component<IDynamicFieldProps, IDynamicFi
placeholder={placeholder}
defaultSelectedUsers={userValue}
peoplePickerCntrlclassName={styles.fieldDisplay}
context={context}
context={peoplePickerContext}
personSelectionLimit={1}
showtooltip={false}
showHiddenInUI={false}
Expand All @@ -401,7 +407,7 @@ export class DynamicField extends React.Component<IDynamicFieldProps, IDynamicFi
placeholder={placeholder}
defaultSelectedUsers={valueToDisplay !== undefined ? valueToDisplay : defaultValue}
peoplePickerCntrlclassName={styles.fieldDisplay}
context={context}
context={peoplePickerContext}
personSelectionLimit={30}
showtooltip={false}
showHiddenInUI={false}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import * as strings from 'ControlStrings';
import { CustomCollectionFieldType, ICustomCollectionField } from '../ICustomCollectionField';
import { Dropdown, IDropdownOption } from '@fluentui/react/lib/components/Dropdown';
import { ComboBox, IComboBoxOption } from '@fluentui/react/lib/components/ComboBox';
import { PeoplePicker, PrincipalType } from "../../peoplepicker";
import { IPeoplePickerContext, PeoplePicker, PrincipalType } from "../../peoplepicker";
import { Callout, DirectionalHint } from '@fluentui/react/lib/components/Callout';
import { CollectionIconField } from '../collectionIconField';
import { clone, findIndex, sortBy } from '@microsoft/sp-lodash-subset';
Expand Down Expand Up @@ -467,6 +467,11 @@ export class CollectionDataItem extends React.Component<ICollectionDataItemProps
private renderField(field: ICustomCollectionField, item: any): JSX.Element { // eslint-disable-line @typescript-eslint/no-explicit-any
const disableFieldOnEdit: boolean = field.disableEdit && !!this.props.fUpdateItem;
const _selectedComboBoxKeys: string[] = [];
const peoplePickerContext: IPeoplePickerContext = {
absoluteUrl: this.props.context.pageContext.web.absoluteUrl,
spHttpClient: this.props.context.spHttpClient,
msGraphClientFactory: this.props.context.msGraphClientFactory
};
let _selectedComboBoxKey: string = null;
let _comboBoxOptions: IComboBoxOption[] = null;
let _selectedUsers: string[] = null;
Expand Down Expand Up @@ -580,7 +585,7 @@ export class CollectionDataItem extends React.Component<ICollectionDataItemProps

return <PeoplePicker
peoplePickerCntrlclassName={styles.peoplePicker}
context={this.props.context}
context={peoplePickerContext}
personSelectionLimit={typeof field.maximumUsers === "number" ? field.maximumUsers : typeof field.multiSelect === "boolean" && field.multiSelect === false ? 1 : 99}
principalTypes={[PrincipalType.User]}
ensureUser={true}
Expand Down
16 changes: 2 additions & 14 deletions src/controls/peoplepicker/IPeoplePicker.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { BaseComponentContext } from '@microsoft/sp-component-base';
import { IBasePickerStyles } from "@fluentui/react";
import { DirectionalHint } from "@fluentui/react/lib/common/DirectionalHint";
import { IPersonaProps } from "@fluentui/react/lib/components/Persona/Persona.types";
import { PrincipalType } from ".";
import { IPeoplePickerContext, PrincipalType } from ".";

/**
* Used to display a placeholder in case of no or temporary content. Button is optional.
Expand All @@ -12,7 +11,7 @@ export interface IPeoplePickerProps {
/**
* Context of the component
*/
context: BaseComponentContext;
context: IPeoplePickerContext;
/**
* Text of the Control
*/
Expand Down Expand Up @@ -139,17 +138,6 @@ export interface IPeoplePickerProps {
resultFilter?: (result: IPersonaProps[]) => IPersonaProps[];
}

export interface IPeoplePickerState {
mostRecentlyUsedPersons?: IPersonaProps[];
errorMessage?: string;
internalErrorMessage?: string;
resolveDelay?: number;

selectedPersons?: IPersonaProps[];
peoplePersonaMenu?: IPersonaProps[];
delayResults?: boolean;
}

export interface IPeoplePickerUserItem {
/**
* LoginName or Id of the principal in the site.
Expand Down
19 changes: 19 additions & 0 deletions src/controls/peoplepicker/IPeoplePickerContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { MSGraphClientFactory, SPHttpClient } from "@microsoft/sp-http";

/**
* Context for the PeoplePicker control
*/
export interface IPeoplePickerContext {
/**
* Current `SPWeb` absolute URL.
*/
absoluteUrl: string;
/**
* Instance of MSGraphClientFactory used for querying Microsoft Graph REST API.
*/
msGraphClientFactory: MSGraphClientFactory;
/**
* Instance of SPHttpClient used for querying SharePoint REST API.
*/
spHttpClient: SPHttpClient;
}
13 changes: 12 additions & 1 deletion src/controls/peoplepicker/PeoplePickerComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import * as React from 'react';
import * as telemetry from '../../common/telemetry';
import styles from './PeoplePickerComponent.module.scss';
import SPPeopleSearchService from "../../services/PeopleSearchService";
import { IPeoplePickerProps, IPeoplePickerState } from './IPeoplePicker';
import { IPeoplePickerProps } from './IPeoplePicker';
import { TooltipHost } from '@fluentui/react/lib/Tooltip';
import { DirectionalHint } from '@fluentui/react/lib/Callout';
import { NormalPeoplePicker } from '@fluentui/react/lib/components/pickers/PeoplePicker/PeoplePicker';
Expand All @@ -14,6 +14,17 @@ import FieldErrorMessage from '../errorMessage/ErrorMessage';
import isEqual from 'lodash/isEqual';
import uniqBy from 'lodash/uniqBy';

interface IPeoplePickerState {
mostRecentlyUsedPersons?: IPersonaProps[];
errorMessage?: string;
internalErrorMessage?: string;
resolveDelay?: number;

selectedPersons?: IPersonaProps[];
peoplePersonaMenu?: IPersonaProps[];
delayResults?: boolean;
}

/**
* PeoplePicker component
*/
Expand Down
1 change: 1 addition & 0 deletions src/controls/peoplepicker/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './IPeoplePicker';
export * from './IPeoplePickerContext';
export * from './PeoplePickerComponent';
export * from './PrincipalType';
21 changes: 12 additions & 9 deletions src/services/PeopleSearchService.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { BaseComponentContext } from '@microsoft/sp-component-base';
import { ISPHttpClientOptions, SPHttpClient } from '@microsoft/sp-http';
import { findIndex } from "@microsoft/sp-lodash-subset";
import { sp } from '@pnp/sp';
Expand All @@ -7,7 +6,7 @@ import "@pnp/sp/sputilities";
import "@pnp/sp/webs";
import { Web } from "@pnp/sp/webs";
import { IUserInfo } from "../controls/peoplepicker/IUsers";
import { IPeoplePickerUserItem, PrincipalType } from "../PeoplePicker";
import { IPeoplePickerContext, IPeoplePickerUserItem, PrincipalType } from "../PeoplePicker";

/**
* Service implementation to search people in SharePoint
Expand All @@ -19,12 +18,16 @@ export default class SPPeopleSearchService {
/**
* Service constructor
*/
constructor(private context: BaseComponentContext) {
constructor(private context: IPeoplePickerContext) {
this.cachedPersonas = {};
this.cachedLocalUsers = {};
this.cachedLocalUsers[this.context.pageContext.web.absoluteUrl] = [];
this.cachedLocalUsers[context.absoluteUrl] = [];
// Setup PnPjs
sp.setup({ pageContext: this.context.pageContext });
sp.setup({ pageContext: {
web: {
absoluteUrl: context.absoluteUrl
}
}});
}

/**
Expand All @@ -33,7 +36,7 @@ export default class SPPeopleSearchService {
* @param value
*/
public generateUserPhotoLink(value: string): string {
return `${this.context.pageContext.web.absoluteUrl}/_layouts/15/userphoto.aspx?accountname=${encodeURIComponent(value)}&size=M`;
return `${this.context.absoluteUrl}/_layouts/15/userphoto.aspx?accountname=${encodeURIComponent(value)}&size=M`;
}

/**
Expand Down Expand Up @@ -109,7 +112,7 @@ export default class SPPeopleSearchService {
private async searchTenant(siteUrl: string, query: string, maximumSuggestions: number, principalTypes: PrincipalType[], ensureUser: boolean, allowUnvalidated: boolean, groupId: number | string): Promise<IPeoplePickerUserItem[]> {
try {
// If the running env is SharePoint, loads from the peoplepicker web service
const userRequestUrl: string = `${siteUrl || this.context.pageContext.web.absoluteUrl}/_api/SP.UI.ApplicationPages.ClientPeoplePickerWebServiceInterface.clientPeoplePickerSearchUser`;
const userRequestUrl: string = `${siteUrl || this.context.absoluteUrl}/_api/SP.UI.ApplicationPages.ClientPeoplePickerWebServiceInterface.clientPeoplePickerSearchUser`;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const searchBody: any = {
queryParams: {
Expand Down Expand Up @@ -143,7 +146,7 @@ export default class SPPeopleSearchService {

// Get user loginName from user email
const _users = [];
const batch = Web(this.context.pageContext.web.absoluteUrl).createBatch();
const batch = Web(this.context.absoluteUrl).createBatch();
for (const value of graphUserResponse.value) {
sp.web.inBatch(batch).ensureUser(value.userPrincipalName).then(u => _users.push(u.data)).catch(() => {
// no-op
Expand Down Expand Up @@ -203,7 +206,7 @@ export default class SPPeopleSearchService {
for (const value of values) {
// Only ensure the user if it is not a SharePoint group
if (!value.EntityData || (value.EntityData && typeof value.EntityData.SPGroupID === "undefined" && value.EntityData.PrincipalType !== "UNVALIDATED_EMAIL_ADDRESS")) {
const id = await this.ensureUser(value.Key, siteUrl || this.context.pageContext.web.absoluteUrl);
const id = await this.ensureUser(value.Key, siteUrl || this.context.absoluteUrl);
value.LoginName = value.Key;
value.Key = id;
}
Expand Down
Loading