/
Pivot.base.tsx
320 lines (271 loc) · 9.92 KB
/
Pivot.base.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import * as React from 'react';
import { BaseComponent, KeyCodes, getId, getNativeProps, divProperties, classNamesFunction, warn } from '../../Utilities';
import { CommandButton } from '../../Button';
import { IPivotProps, IPivotStyleProps, IPivotStyles } from './Pivot.types';
import { IPivotItemProps } from './PivotItem.types';
import { FocusZone, FocusZoneDirection } from '../../FocusZone';
import { PivotItem } from './PivotItem';
import { PivotLinkFormat } from './Pivot.types';
import { PivotLinkSize } from './Pivot.types';
import { Icon } from '../../Icon';
const getClassNames = classNamesFunction<IPivotStyleProps, IPivotStyles>();
export interface IPivotState {
selectedKey: string | undefined;
}
type PivotLinkCollection = {
links: IPivotItemProps[];
keyToIndexMapping: { [key: string]: number };
keyToTabIdMapping: { [key: string]: string };
};
/**
* Usage:
*
* <Pivot>
* <PivotItem headerText="Foo">
* <Label>Pivot #1</Label>
* </PivotItem>
* <PivotItem headerText="Bar">
* <Label>Pivot #2</Label>
* </PivotItem>
* <PivotItem headerText="Bas">
* <Label>Pivot #3</Label>
* </PivotItem>
* </Pivot>
*/
export class PivotBase extends BaseComponent<IPivotProps, IPivotState> {
private _pivotId: string;
private _focusZone = React.createRef<FocusZone>();
private _classNames: { [key in keyof IPivotStyles]: string };
constructor(props: IPivotProps) {
super(props);
this._warnDeprecations({
initialSelectedKey: 'defaultSelectedKey',
initialSelectedIndex: 'defaultSelectedIndex'
});
this._pivotId = getId('Pivot');
const links: IPivotItemProps[] = this._getPivotLinks(props).links;
const { defaultSelectedKey = props.initialSelectedKey, defaultSelectedIndex = props.initialSelectedIndex } = props;
let selectedKey: string | undefined;
if (defaultSelectedKey) {
selectedKey = defaultSelectedKey;
} else if (typeof defaultSelectedIndex === 'number') {
selectedKey = links[defaultSelectedIndex].itemKey!;
} else if (links.length) {
selectedKey = links[0].itemKey!;
}
this.state = {
selectedKey
};
}
/**
* Sets focus to the first pivot tab.
*/
public focus(): void {
if (this._focusZone.current) {
this._focusZone.current.focus();
}
}
public render(): JSX.Element {
const linkCollection = this._getPivotLinks(this.props);
const selectedKey = this._getSelectedKey(linkCollection);
const divProps = getNativeProps<React.HTMLAttributes<HTMLDivElement>>(this.props, divProperties);
this._classNames = this._getClassNames(this.props);
return (
<div role="tablist" {...divProps}>
{this._renderPivotLinks(linkCollection, selectedKey)}
{selectedKey && this._renderPivotItem(linkCollection, selectedKey)}
</div>
);
}
private _getSelectedKey(linkCollection: PivotLinkCollection) {
const { selectedKey: propsSelectedKey } = this.props;
if (this._isKeyValid(linkCollection, propsSelectedKey) || propsSelectedKey === null) {
return propsSelectedKey;
}
const { selectedKey: stateSelectedKey } = this.state;
if (this._isKeyValid(linkCollection, stateSelectedKey)) {
return stateSelectedKey;
}
if (linkCollection.links.length) {
return linkCollection.links[0].itemKey;
}
return undefined;
}
/**
* Renders the set of links to route between pivots
*/
private _renderPivotLinks(linkCollection: PivotLinkCollection, selectedKey: string | null | undefined): JSX.Element {
const items = linkCollection.links.map(l => this._renderPivotLink(linkCollection, l, selectedKey));
return (
<FocusZone componentRef={this._focusZone} direction={FocusZoneDirection.horizontal}>
<div className={this._classNames.root}>{items}</div>
</FocusZone>
);
}
private _renderPivotLink = (
linkCollection: PivotLinkCollection,
link: IPivotItemProps,
selectedKey: string | null | undefined
): JSX.Element => {
const { itemKey, headerButtonProps } = link;
const tabId = linkCollection.keyToTabIdMapping[itemKey!];
const { onRenderItemLink } = link;
let linkContent: JSX.Element | null;
const isSelected: boolean = selectedKey === itemKey;
if (onRenderItemLink) {
linkContent = onRenderItemLink(link, this._renderLinkContent);
} else {
linkContent = this._renderLinkContent(link);
}
let contentString = link.headerText || '';
contentString += link.itemCount ? ' (' + link.itemCount + ')' : '';
// Adding space supplementary for icon
contentString += link.itemIcon ? ' xx' : '';
return (
<CommandButton
{...headerButtonProps}
id={tabId}
key={itemKey}
className={isSelected ? this._classNames.linkIsSelected : this._classNames.link}
onClick={this._onLinkClick.bind(this, itemKey)}
onKeyPress={this._onKeyPress.bind(this, itemKey)}
ariaLabel={link.ariaLabel}
role="tab"
aria-selected={isSelected}
name={link.headerText}
keytipProps={link.keytipProps}
data-content={contentString}
>
{linkContent}
</CommandButton>
);
};
private _renderLinkContent = (link: IPivotItemProps): JSX.Element => {
const { itemCount, itemIcon, headerText } = link;
const classNames = this._classNames;
return (
<span className={classNames.linkContent}>
{itemIcon !== undefined && (
<span className={classNames.icon}>
<Icon iconName={itemIcon} />
</span>
)}
{headerText !== undefined && <span className={classNames.text}> {link.headerText}</span>}
{itemCount !== undefined && <span className={classNames.count}> ({itemCount})</span>}
</span>
);
};
/**
* Renders the current Pivot Item
*/
private _renderPivotItem(linkCollection: PivotLinkCollection, itemKey: string | undefined): JSX.Element | null {
if (this.props.headersOnly || !itemKey) {
return null;
}
const index = linkCollection.keyToIndexMapping[itemKey];
const selectedTabId = linkCollection.keyToTabIdMapping[itemKey];
return (
<div role="tabpanel" aria-labelledby={selectedTabId} className={this._classNames.itemContainer}>
{React.Children.toArray(this.props.children)[index]}
</div>
);
}
/**
* Gets the set of PivotLinks as array of IPivotItemProps
* The set of Links is determined by child components of type PivotItem
*/
private _getPivotLinks(props: IPivotProps): PivotLinkCollection {
const result: PivotLinkCollection = {
links: [],
keyToIndexMapping: {},
keyToTabIdMapping: {}
};
React.Children.map(React.Children.toArray(props.children), (child: React.ReactChild, index: number) => {
if (_isPivotItem(child)) {
const pivotItem = child;
const { linkText, ...pivotItemProps } = pivotItem.props;
const itemKey = pivotItem.props.itemKey || index.toString();
result.links.push({
// Use linkText (deprecated) if headerText is not provided
headerText: linkText,
...pivotItemProps,
itemKey: itemKey
});
result.keyToIndexMapping[itemKey] = index;
result.keyToTabIdMapping[itemKey] = this._getTabId(itemKey, index);
} else {
warn('The children of a Pivot component must be of type PivotItem to be rendered.');
}
});
return result;
}
/**
* Generates the Id for the tab button.
*/
private _getTabId(itemKey: string, index: number): string {
if (this.props.getTabId) {
return this.props.getTabId(itemKey, index);
}
return this._pivotId + `-Tab${index}`;
}
/**
* whether the key exists in the pivot items.
*/
private _isKeyValid(linkCollection: PivotLinkCollection, itemKey: string | null | undefined): boolean {
return itemKey !== undefined && itemKey !== null && linkCollection.keyToIndexMapping[itemKey] !== undefined;
}
/**
* Handles the onClick event on PivotLinks
*/
private _onLinkClick(itemKey: string, ev: React.MouseEvent<HTMLElement>): void {
ev.preventDefault();
this._updateSelectedItem(itemKey, ev);
}
/**
* Handle the onKeyPress eventon the PivotLinks
*/
private _onKeyPress(itemKey: string, ev: React.KeyboardEvent<HTMLElement>): void {
if (ev.which === KeyCodes.enter) {
ev.preventDefault();
this._updateSelectedItem(itemKey);
}
}
/**
* Updates the state with the new selected index
*/
private _updateSelectedItem(itemKey: string, ev?: React.MouseEvent<HTMLElement>): void {
this.setState({
selectedKey: itemKey
});
const linkCollection = this._getPivotLinks(this.props);
if (this.props.onLinkClick && linkCollection.keyToIndexMapping[itemKey] >= 0) {
const index = linkCollection.keyToIndexMapping[itemKey];
// React.Element<any> cannot directly convert to PivotItem.
const item = React.Children.toArray(this.props.children)[index];
if (_isPivotItem(item)) {
this.props.onLinkClick(item, ev);
}
}
}
private _getClassNames(props: IPivotProps): { [key in keyof IPivotStyles]: string } {
const { theme } = props;
const rootIsLarge: boolean = props.linkSize === PivotLinkSize.large;
const rootIsTabs: boolean = props.linkFormat === PivotLinkFormat.tabs;
return getClassNames(props.styles!, {
theme: theme!,
rootIsLarge,
rootIsTabs
});
}
}
function _isPivotItem(item: React.ReactNode): item is PivotItem {
// In theory, we should be able to just check item.type === PivotItem.
// However, under certain unclear circumstances (see https://github.com/OfficeDev/office-ui-fabric-react/issues/10785),
// the object identity is different despite the function implementation being the same.
return (
!!item &&
typeof item === 'object' &&
!!(item as React.ReactElement).type &&
((item as React.ReactElement).type as React.ComponentType).name === PivotItem.name
);
}