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

New control ModernTaxonomyPicker #1014

Merged
merged 19 commits into from
Oct 2, 2021
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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
74 changes: 74 additions & 0 deletions docs/documentation/docs/controls/ModernTaxonomyPicker.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Modern Taxonomy Picker

This control allows you to select one or more Terms from a TermSet via its TermSet ID. You can also configure the control to select the child terms from a specific term in the TermSet by setting the anchorTermId. This is the modern version of the taxonomy picker that uses the REST API and makes use of some load on demand features which makes it well suited for large term sets.

!!! note "Disclaimer"
Since this control is meant to look as and work in the same way as the out-of-the-box control it lacks some of the features from the legacy ```TaxonomyPicker``` control. If you need some of those features please continue using the legacy version.

**Empty term picker**

![Empty term picker](../assets/modernTaxonomyPicker-empty.png)

**Selecting terms**

![Selecting terms](../assets/modernTaxonomyPicker-tree-selection.png)

**Selected terms in picker**

![Selected terms in the input](../assets/modernTaxonomyPicker-selected-terms.png)

**Term picker: Auto Complete**

![Selected terms in the input](../assets/modernTaxonomyPicker-input-autocomplete.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 { ModernTaxonomyPicker } from "@pnp/spfx-controls-react/lib/ModernTaxonomyPicker";
```

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

```TypeScript
<ModernTaxonomyPicker allowMultipleSelections={true}
termSetId="f233d4b7-68fb-41ef-8b58-2af0bafc0d38"
panelTitle="Select Term"
label="Taxonomy Picker"
context={this.props.context}
onChange={this.onTaxPickerChange} />
```

- With the `onChange` property you can capture the event of when the terms in the picker has changed:

```typescript
private onTaxPickerChange(terms : ITermInfo[]) {
console.log("Terms", terms);
}
```

## Implementation

The ModernTaxonomyPicker control can be configured with the following properties:

| Property | Type | Required | Description |
| ---- | ---- | ---- | ---- |
| panelTitle | string | yes | TermSet Picker Panel title. |
| label | string | yes | Text displayed above the Taxonomy Picker. |
| disabled | boolean | no | Specify if the control should be disabled. Default value is false. |
| context | BaseComponentContext | yes | Context of the current web part or extension. |
| initialValues | ITermInfo[] | no | Defines the terms selected by default. ITermInfo comes from PnP/PnPjs and can be imported with <br/>```import { ITermInfo } from '@pnp/sp/taxonomy';``` |
| allowMultipleSelections | boolean | no | Defines if the user can select only one or multiple terms. Default value is false. |
| termSetId | string | yes | The Id of the TermSet that you would like the Taxonomy Picker to select terms from. |
| onChange | function | no | Captures the event of when the terms in the picker has changed. |
| anchorTermId | string | no | Set the id of a child term in the TermSet to be able to select terms from that level and below. |
| placeHolder | string | no | Short text hint to display in picker. |
| required | boolean | no | Specifies if to display an asterisk near the label. Default value is false. |
| customPanelWidth | number | no | Custom panel width in pixels. |
| termPickerProps | IModernTermPickerProps | no | Custom properties for the term picker (More info: [IBasePickerProps interface](https://developer.microsoft.com/en-us/fluentui#/controls/web/pickers#IBasePickerProps)). |
| themeVariant | IReadonlyTheme | no | The current loaded SharePoint theme/section background (More info: [Supporting section backgrounds](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/guidance/supporting-section-backgrounds)). |

![](https://telemetry.sharepointpnp.com/sp-dev-fx-controls-react/wiki/controls/TaxonomyPicker)
1 change: 1 addition & 0 deletions docs/documentation/docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ The following controls are currently available:
- [LivePersona](./controls/LivePersona) (Live Persona control)
- [LocationPicker](./controls/LocationPicker) (Location Picker control)
- [Map](./controls/Map) (renders a map in a web part)
- [ModernTaxonomyPicker](./controls/ModernTaxonomyPicker) (Modern Taxonomy Picker)
- [MyTeams](./controls/MyTeams) (My Teams)
- [PeoplePicker](./controls/PeoplePicker) (People Picker)
- [Placeholder](./controls/Placeholder) (shows an initial placeholder if the web part has to be configured)
Expand Down
1 change: 1 addition & 0 deletions docs/documentation/mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ nav:
- LivePersona: 'controls/LivePersona.md'
- LocationPicker: 'controls/LocationPicker.md'
- Map: 'controls/Map.md'
- ModernTaxonomyPicker: 'controls/ModernTaxonomyPicker.md'
- MyTeams: 'controls/MyTeams.md'
- Pagination: 'controls/Pagination.md'
- PeoplePicker: 'controls/PeoplePicker.md'
Expand Down
1 change: 1 addition & 0 deletions src/ModernTaxonomyPicker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './controls/modernTaxonomyPicker';
25 changes: 25 additions & 0 deletions src/controls/modernTaxonomyPicker/ModernTaxonomyPicker.module.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
.modernTaxonomyPicker {

.termField {
align-items: center;
border-spacing: 0;
display: flex;
width: 100%;

.termFieldInput {
flex-grow: 1;
}

.termFieldButton {
text-align: center;
width: 42px;
}

input[type="text"] {
cursor: pointer;
opacity: 0.8;
width: 100%;
}
}

}
280 changes: 280 additions & 0 deletions src/controls/modernTaxonomyPicker/ModernTaxonomyPicker.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,280 @@
import * as React from 'react';
import { BaseComponentContext } from '@microsoft/sp-component-base';
import { Guid } from '@microsoft/sp-core-library';
import { IIconProps } from 'office-ui-fabric-react/lib/components/Icon';
import { PrimaryButton,
DefaultButton,
IconButton,
IButtonStyles
} from 'office-ui-fabric-react/lib/Button';
import { Label } from 'office-ui-fabric-react/lib/Label';
import { Panel,
PanelType
} from 'office-ui-fabric-react/lib/Panel';
import { IBasePickerStyleProps,
IBasePickerStyles,
ISuggestionItemProps
} from 'office-ui-fabric-react/lib/Pickers';
import { IStackTokens,
Stack
} from 'office-ui-fabric-react/lib/Stack';
import { IStyleFunctionOrObject } from 'office-ui-fabric-react/lib/Utilities';
import { sp } from '@pnp/sp';
import { SPTaxonomyService } from '../../services/SPTaxonomyService';
import { TaxonomyPanelContents } from './taxonomyPanelContents';
import styles from './ModernTaxonomyPicker.module.scss';
import * as strings from 'ControlStrings';
import { TooltipHost } from '@microsoft/office-ui-fabric-react-bundle';
import { useId } from '@uifabric/react-hooks';
import { ITooltipHostStyles } from 'office-ui-fabric-react';
import { ITermInfo,
ITermSetInfo,
ITermStoreInfo
} from '@pnp/sp/taxonomy';
import { TermItemSuggestion } from './termItem/TermItemSuggestion';
import { ModernTermPicker } from './modernTermPicker/ModernTermPicker';
import { IModernTermPickerProps, ITermItemProps } from './modernTermPicker/ModernTermPicker.types';
import { TermItem } from './termItem/TermItem';
import { IReadonlyTheme } from "@microsoft/sp-component-base";
import { isUndefined } from 'lodash';

export type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;

export interface IModernTaxonomyPickerProps {
allowMultipleSelections?: boolean;
termSetId: string;
anchorTermId?: string;
panelTitle: string;
label: string;
context: BaseComponentContext;
initialValues?: ITermInfo[];
disabled?: boolean;
required?: boolean;
onChange?: (newValue?: ITermInfo[]) => void;
onRenderItem?: (itemProps: ITermItemProps) => JSX.Element;
onRenderSuggestionsItem?: (term: ITermInfo, itemProps: ISuggestionItemProps<ITermInfo>) => JSX.Element;
placeHolder?: string;
customPanelWidth?: number;
themeVariant?: IReadonlyTheme;
termPickerProps?: Optional<IModernTermPickerProps, 'onResolveSuggestions'>;
}

export function ModernTaxonomyPicker(props: IModernTaxonomyPickerProps) {
const [taxonomyService] = React.useState(() => new SPTaxonomyService(props.context));
const [panelIsOpen, setPanelIsOpen] = React.useState(false);
const [selectedOptions, setSelectedOptions] = React.useState<ITermInfo[]>([]);
const [selectedPanelOptions, setSelectedPanelOptions] = React.useState<ITermInfo[]>([]);
const [currentTermStoreInfo, setCurrentTermStoreInfo] = React.useState<ITermStoreInfo>();
const [currentTermSetInfo, setCurrentTermSetInfo] = React.useState<ITermSetInfo>();
const [currentAnchorTermInfo, setCurrentAnchorTermInfo] = React.useState<ITermInfo>();
const [currentLanguageTag, setCurrentLanguageTag] = React.useState<string>("");

React.useEffect(() => {
sp.setup(props.context);
taxonomyService.getTermStoreInfo()
.then((termStoreInfo) => {
setCurrentTermStoreInfo(termStoreInfo);
setCurrentLanguageTag(props.context.pageContext.cultureInfo.currentUICultureName !== '' ?
props.context.pageContext.cultureInfo.currentUICultureName :
currentTermStoreInfo.defaultLanguageTag);
setSelectedOptions(Object.prototype.toString.call(props.initialValues) === '[object Array]' ?
props.initialValues.map(term => { return { ...term, languageTag: currentLanguageTag, termStoreInfo: currentTermStoreInfo } as ITermInfo;}) :
[]);
});
taxonomyService.getTermSetInfo(Guid.parse(props.termSetId))
.then((termSetInfo) => {
setCurrentTermSetInfo(termSetInfo);
});
if (props.anchorTermId && props.anchorTermId !== Guid.empty.toString()) {
taxonomyService.getTermById(Guid.parse(props.termSetId), props.anchorTermId ? Guid.parse(props.anchorTermId) : Guid.empty)
.then((anchorTermInfo) => {
setCurrentAnchorTermInfo(anchorTermInfo);
});
}
}, []);

React.useEffect(() => {
if (props.onChange) {
props.onChange(selectedOptions);
}
}, [selectedOptions]);

function onOpenPanel(): void {
if (props.disabled === true) {
return;
}
setSelectedPanelOptions(selectedOptions);
setPanelIsOpen(true);
}

function onClosePanel(): void {
setSelectedPanelOptions([]);
setPanelIsOpen(false);
}

function onApply(): void {
setSelectedOptions([...selectedPanelOptions]);
onClosePanel();
}

async function onResolveSuggestions(filter: string, selectedItems?: ITermInfo[]): Promise<ITermInfo[]> {
if (filter === '') {
return [];
}
const filteredTerms = await taxonomyService.searchTerm(Guid.parse(props.termSetId), filter, currentLanguageTag, props.anchorTermId ? Guid.parse(props.anchorTermId) : Guid.empty);
const filteredTermsWithoutSelectedItems = filteredTerms.filter((term) => {
if (!selectedItems || selectedItems.length === 0) {
return true;
}
return selectedItems.every((item) => item.id !== term.id);
});
const filteredTermsAndAvailable = filteredTermsWithoutSelectedItems.filter((term) => term.isAvailableForTagging.filter((t) => t.setId === props.termSetId)[0].isAvailable);
return filteredTermsAndAvailable;
}

async function onLoadParentLabel(termId: Guid): Promise<string> {
const termInfo = await taxonomyService.getTermById(Guid.parse(props.termSetId), termId);
if (termInfo.parent) {
let labelsWithMatchingLanguageTag = termInfo.parent.labels.filter((termLabel) => (termLabel.languageTag === currentLanguageTag));
if (labelsWithMatchingLanguageTag.length === 0) {
labelsWithMatchingLanguageTag = termInfo.parent.labels.filter((termLabel) => (termLabel.languageTag === currentTermStoreInfo.defaultLanguageTag));
}
return labelsWithMatchingLanguageTag[0]?.name;
}
else {
let termSetNames = currentTermSetInfo.localizedNames.filter((name) => name.languageTag === currentLanguageTag);
if (termSetNames.length === 0) {
termSetNames = currentTermSetInfo.localizedNames.filter((name) => name.languageTag === currentTermStoreInfo.defaultLanguageTag);
}
return termSetNames[0].name;
}
}

function onRenderSuggestionsItem(term: ITermInfo, itemProps: ISuggestionItemProps<ITermInfo>): JSX.Element {
return (
<TermItemSuggestion
onLoadParentLabel={onLoadParentLabel}
term={term}
termStoreInfo={currentTermStoreInfo}
languageTag={currentLanguageTag}
{...itemProps}
/>
);
}

function onRenderItem(itemProps: ITermItemProps): JSX.Element {
let labels = itemProps.item.labels.filter((name) => name.languageTag === currentLanguageTag && name.isDefault);
if (labels.length === 0) {
labels = itemProps.item.labels.filter((name) => name.languageTag === currentTermStoreInfo.defaultLanguageTag && name.isDefault);
}

return labels.length > 0 ? (
<TermItem languageTag={currentLanguageTag} termStoreInfo={currentTermStoreInfo} {...itemProps}>{labels[0].name}</TermItem>
) : null;
}

function getTextFromItem(termInfo: ITermInfo): string {
let labelsWithMatchingLanguageTag = termInfo.labels.filter((termLabel) => (termLabel.languageTag === currentLanguageTag));
if (labelsWithMatchingLanguageTag.length === 0) {
labelsWithMatchingLanguageTag = termInfo.labels.filter((termLabel) => (termLabel.languageTag === currentTermStoreInfo.defaultLanguageTag));
}
return labelsWithMatchingLanguageTag[0]?.name;
}

const calloutProps = { gapSpace: 0 };
const tooltipId = useId('tooltip');
const hostStyles: Partial<ITooltipHostStyles> = { root: { display: 'inline-block' } };
const addTermButtonStyles: IButtonStyles = {rootHovered: {backgroundColor: "inherit"}, rootPressed: {backgroundColor: "inherit"}};
const termPickerStyles: IStyleFunctionOrObject<IBasePickerStyleProps, IBasePickerStyles> = { input: {minheight: 34}, text: {minheight: 34} };

return (
<div className={styles.modernTaxonomyPicker}>
{props.label && <Label required={props.required}>{props.label}</Label>}
<div className={styles.termField}>
<div className={styles.termFieldInput}>
<ModernTermPicker
{...props.termPickerProps}
removeButtonAriaLabel={strings.ModernTaxonomyPickerRemoveButtonText}
onResolveSuggestions={props.termPickerProps?.onResolveSuggestions ?? onResolveSuggestions}
itemLimit={props.allowMultipleSelections ? undefined : 1}
selectedItems={selectedOptions}
disabled={props.disabled}
styles={props.termPickerProps?.styles ?? termPickerStyles}
onChange={(itms?: ITermInfo[]) => {
setSelectedOptions(itms || []);
setSelectedPanelOptions(itms || []);
}}
getTextFromItem={getTextFromItem}
pickerSuggestionsProps={props.termPickerProps?.pickerSuggestionsProps ?? {noResultsFoundText: strings.ModernTaxonomyPickerNoResultsFound}}
inputProps={props.termPickerProps?.inputProps ?? {
'aria-label': props.placeHolder || strings.ModernTaxonomyPickerDefaultPlaceHolder,
placeholder: props.placeHolder || strings.ModernTaxonomyPickerDefaultPlaceHolder
}}
onRenderSuggestionsItem={props.onRenderSuggestionsItem ?? onRenderSuggestionsItem}
onRenderItem={props.onRenderItem ?? onRenderItem}
themeVariant={props.themeVariant}
/>
</div>
<div className={styles.termFieldButton}>
<TooltipHost
content={strings.ModernTaxonomyPickerAddTagButtonTooltip}
id={tooltipId}
calloutProps={calloutProps}
styles={hostStyles}
>
<IconButton disabled={props.disabled} styles={addTermButtonStyles} iconProps={{ iconName: 'Tag' } as IIconProps} onClick={onOpenPanel} aria-describedby={tooltipId} />
</TooltipHost>
</div>
</div>

<Panel
isOpen={panelIsOpen}
hasCloseButton={true}
closeButtonAriaLabel={strings.ModernTaxonomyPickerPanelCloseButtonText}
onDismiss={onClosePanel}
isLightDismiss={true}
type={props.customPanelWidth ? PanelType.custom : PanelType.medium}
customWidth={props.customPanelWidth ? `${props.customPanelWidth}px` : undefined}
headerText={props.panelTitle}
onRenderFooterContent={() => {
const horizontalGapStackTokens: IStackTokens = {
childrenGap: 10,
};
return (
<Stack horizontal disableShrink tokens={horizontalGapStackTokens}>
<PrimaryButton text={strings.ModernTaxonomyPickerApplyButtonText} value="Apply" onClick={onApply} />
<DefaultButton text={strings.ModernTaxonomyPickerCancelButtonText} value="Cancel" onClick={onClosePanel} />
</Stack>
);
}}>

{
props.termSetId && (
<div key={props.termSetId} >
<TaxonomyPanelContents
allowMultipleSelections={props.allowMultipleSelections}
onResolveSuggestions={props.termPickerProps?.onResolveSuggestions ?? onResolveSuggestions}
onLoadMoreData={taxonomyService.getTerms}
anchorTermInfo={currentAnchorTermInfo}
termSetInfo={currentTermSetInfo}
termStoreInfo={currentTermStoreInfo}
context={props.context}
termSetId={Guid.parse(props.termSetId)}
pageSize={50}
selectedPanelOptions={selectedPanelOptions}
setSelectedPanelOptions={setSelectedPanelOptions}
placeHolder={props.placeHolder || strings.ModernTaxonomyPickerDefaultPlaceHolder}
onRenderSuggestionsItem={props.onRenderSuggestionsItem ?? onRenderSuggestionsItem}
onRenderItem={props.onRenderItem ?? onRenderItem}
getTextFromItem={getTextFromItem}
languageTag={currentLanguageTag}
themeVariant={props.themeVariant}
termPickerProps={props.termPickerProps}
/>
</div>
)
}
</Panel>
</div >
);
}
Loading