-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
ApiReferencesTable.tsx
371 lines (335 loc) · 12.4 KB
/
ApiReferencesTable.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import * as React from 'react';
import { mergeStyles, getTheme } from 'office-ui-fabric-react/lib/Styling';
import {
DetailsList,
DetailsRow,
IDetailsRowProps,
IDetailsRowStyles,
DetailsListLayoutMode,
IColumn,
ColumnActionsMode
} from 'office-ui-fabric-react/lib/DetailsList';
import { Link } from 'office-ui-fabric-react/lib/Link';
import { SelectionMode } from 'office-ui-fabric-react/lib/Selection';
import { Stack } from 'office-ui-fabric-react/lib/Stack';
import { Text, ITextStyles } from 'office-ui-fabric-react/lib/Text';
import { ILinkToken } from 'office-ui-fabric-react/lib/common/DocPage.types';
import { useConst } from '@uifabric/react-hooks';
import { IApiInterfaceProperty, IApiEnumProperty, IMethod, IApiReferencesTableProps } from './ApiReferencesTableSet.types';
import { Markdown } from '../Markdown/index';
import { codeFontFamily } from '../CodeSnippet/CodeSnippet.styles';
import { titleCase } from '../../utilities/string';
// TODO: remove
export { IApiReferencesTableProps };
export type IApiReferencesTableState = {};
/** @internal */
type IApiDetailsListProps = (IApiEnumDetailsListProps | IApiPropertyDetailsListProps | IApiMethodDetailsListProps) & {
tokenResolver: IApiReferencesTableProps['tokenResolver'];
};
/** Do not use directly */
interface IApiEnumDetailsListProps {
itemKind: 'enum';
items: IApiEnumProperty[];
}
/** Do not use directly */
interface IApiPropertyDetailsListProps {
itemKind: 'property';
items: IApiInterfaceProperty[];
}
/** Do not use directly */
interface IApiMethodDetailsListProps {
itemKind: 'method';
items: IMethod[];
}
/** @internal */
export const gapTokens = {
xsmall: { childrenGap: 2.5 },
small: { childrenGap: 8 },
medium: { childrenGap: 16 },
large: { childrenGap: 48 }
};
const DEPRECATED_COLOR = '#FFF1CC';
const deprecatedTextStyles: Partial<ITextStyles> = {
root: {
backgroundColor: DEPRECATED_COLOR,
padding: 10,
borderRadius: 2
}
};
const theme = getTheme();
const rootClass = mergeStyles({
selectors: {
// Switch code blocks to a nicer font family and smaller size (monospace fonts tend to be large)
code: { fontFamily: codeFontFamily, fontSize: '11px' }
}
});
export class ApiReferencesTable extends React.Component<IApiReferencesTableProps, IApiReferencesTableState> {
public static defaultProps: Partial<IApiReferencesTableProps> = {
title: 'Properties'
};
private _isEnum: boolean;
private _isClass: boolean;
private _isTypeAlias: boolean;
constructor(props: IApiReferencesTableProps) {
super(props);
const { renderAs } = props;
this._isEnum = !!(renderAs === 'enum' || props.renderAsEnum);
this._isClass = !!(renderAs === 'class' || props.renderAsClass);
this._isTypeAlias = !!(renderAs === 'typeAlias' || props.renderAsTypeAlias);
}
public render(): JSX.Element | null {
const { extendsTokens, deprecated, deprecatedMessage, tokenResolver, properties, methods } = this.props;
const hasProperties = properties.length > 0;
const hasMethods = methods && methods.length > 0;
const hasExtendsTokens = extendsTokens && extendsTokens.length > 0;
const description =
(this.props.description || '').trim() ||
// If this is an empty table with no description, add something basic to make clear that
// the empty heading is intentional
(!this._isTypeAlias && !hasProperties && !hasMethods ? '(No properties)' : undefined);
return (
<Stack className={rootClass} tokens={gapTokens.medium}>
<Stack tokens={gapTokens.small}>
{this._renderTitle()}
{deprecated && _renderDeprecatedMessage(deprecatedMessage)}
{(description || hasExtendsTokens) && (
<Stack tokens={gapTokens.xsmall}>
{description && <Markdown>{description}</Markdown>}
{hasExtendsTokens && <Text variant="small">Extends {_renderLinkTokens(tokenResolver, extendsTokens!)}</Text>}
</Stack>
)}
</Stack>
{(hasMethods || hasProperties) && this._renderTables()}
</Stack>
);
}
private _renderTables(): JSX.Element | undefined {
const { properties, methods, tokenResolver } = this.props;
if (this._isClass) {
// Render class members and methods tables
return (
<Stack tokens={gapTokens.medium}>
{properties.length > 0 && (
<Stack tokens={gapTokens.small}>
<Text variant={'medium'}>Members</Text>
<ApiDetailsList itemKind="property" items={properties as IApiInterfaceProperty[]} tokenResolver={tokenResolver} />
</Stack>
)}
{methods && methods.length > 0 && (
<Stack tokens={gapTokens.small}>
<Text variant={'medium'}>Methods</Text>
<ApiDetailsList itemKind="method" items={methods!} tokenResolver={tokenResolver} />
</Stack>
)}
</Stack>
);
}
// Render enum or interface property tables
// (the calling method already verified that at least one property is defined)
return this._isEnum ? (
<ApiDetailsList itemKind="enum" items={properties as IApiEnumProperty[]} tokenResolver={tokenResolver} />
) : (
<ApiDetailsList itemKind="property" items={properties as IApiInterfaceProperty[]} tokenResolver={tokenResolver} />
);
}
private _renderTitle(): JSX.Element | undefined {
const { title, name } = this.props;
return title ? (
<Text variant="xLarge" as="h3" styles={{ root: { marginTop: 0 } }} id={name}>
{title}
</Text>
) : (
undefined
);
}
}
/**
* Memoized DetailsList wrapper handling scenarios specific to API reference tables.
*/
const ApiDetailsList: React.FunctionComponent<IApiDetailsListProps> = React.memo(props => {
// Alphabetize the items and add a key to each one.
const { itemKind, items } = props;
const processedItems: IApiEnumProperty[] | IApiInterfaceProperty[] | IMethod[] = useConst(() => {
if (itemKind === 'enum') {
return (items as IApiEnumProperty[])
.sort((a, b) => (a.value < b.value ? -1 : a.value > b.value ? 1 : 0))
.map(item => ({ ...item, key: item.name }));
}
return (items as IApiInterfaceProperty[] | IMethod[])
.sort((a, b) => {
// Ensure anything required comes first if handling props.
if (itemKind === 'property' && !!a.required !== !!b.required) {
return a.required ? -1 : 1;
}
// Ensure the constructor is first if handling methods.
if (itemKind === 'method' && a.name === 'constructor') {
return -1;
}
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
})
.map(item => ({ ...item, key: item.name }));
});
const columns = useConst(() => _getColumns(props));
return (
<DetailsList
items={processedItems}
columns={columns}
selectionMode={SelectionMode.none}
layoutMode={DetailsListLayoutMode.justified}
onRenderRow={_onRenderRow}
onShouldVirtualize={_returnFalse}
/>
);
});
const _returnFalse = () => false;
const rowStyles: Partial<IDetailsRowStyles> = {
root: {
color: theme.semanticColors.bodyText,
selectors: {
':hover': {
background: 'none',
color: theme.semanticColors.bodyText
}
}
},
isMultiline: { wordBreak: 'break-word' }
};
function _onRenderRow(props: IDetailsRowProps) {
return <DetailsRow {...props} styles={rowStyles} />;
}
/** Field names used in the API list (used in generating columns and renderers) */
type ApiListFieldName = 'name' | 'value' | 'type' | 'defaultValue' | 'description' | 'signature';
/** Map from field name to min and max widths (used in generating columns) */
const columnWidths: { [K in ApiListFieldName]: [number, number] } = {
name: [150, 250],
value: [100, 200],
type: [130, 150],
defaultValue: [130, 150],
description: [300, 400],
signature: [200, 300]
};
/** Map from item kind to list of column names (used in generating columns) */
const columnNames: { [K in IApiDetailsListProps['itemKind']]: ApiListFieldName[] } = {
enum: ['name', 'value', 'description'],
method: ['name', 'signature', 'description'],
property: ['name', 'type', 'defaultValue', 'description']
};
function _getColumns(props: IApiDetailsListProps): IColumn[] {
const { itemKind, tokenResolver } = props;
return columnNames[itemKind].map(
(fieldName: ApiListFieldName): IColumn => {
const [minWidth, maxWidth] = columnWidths[fieldName];
return {
name: fieldName === 'defaultValue' ? 'Default value' : titleCase(fieldName),
fieldName,
key: fieldName,
minWidth,
maxWidth,
isCollapsible: false,
isResizable: true,
isMultiline: fieldName !== 'name' && fieldName !== 'value',
isRowHeader: fieldName === 'name',
columnActionsMode: ColumnActionsMode.disabled,
onRender: (item: IApiInterfaceProperty | IApiEnumProperty | IMethod) => {
if (fieldName === 'type' || fieldName === 'signature') {
const typeTokens = (item as IMethod | IApiInterfaceProperty).typeTokens;
if (typeTokens && typeTokens.length > 0) {
return <Text variant="small">{_renderLinkTokens(tokenResolver, typeTokens)}</Text>;
}
return undefined;
}
return _renderCell(item, fieldName);
}
};
}
);
}
function _renderCell(
item: IApiInterfaceProperty | IApiEnumProperty | IMethod,
property: 'name' | 'description' | 'defaultValue' | 'value'
) {
let text = (item as any)[property] || ''; // tslint:disable-line:no-any
// Format property names and defaults as code for easier reading
if (property !== 'description' && text.indexOf('`') === -1) {
text = '`' + text + '`';
}
// For description only, render a message if the property is deprecated.
if (property === 'description') {
return _referencesTableCell(text, { deprecated: item.deprecated, deprecatedMessage: item.deprecatedMessage });
}
if (property === 'name' && (item as IApiInterfaceProperty).required) {
return _referencesTableCell(text, { required: true });
}
return _referencesTableCell(text);
}
function _referencesTableCell(text: string, options: Pick<IApiInterfaceProperty, 'deprecated' | 'deprecatedMessage' | 'required'> = {}) {
const { deprecated, deprecatedMessage, required } = options;
return (
<>
{deprecated && _renderDeprecatedMessage(deprecatedMessage)}
<Text block variant="small" style={{ marginTop: deprecated ? '1em' : undefined }}>
{_extractCodeBlocks(text)}
{required && <em> (required)</em>}
</Text>
</>
);
}
function _renderDeprecatedMessage(deprecatedMessage?: string) {
deprecatedMessage = (deprecatedMessage || '').trim();
if (deprecatedMessage) {
// Ensure the messsage is formatted as a sentence
deprecatedMessage = deprecatedMessage[0].toUpperCase() + deprecatedMessage.slice(1);
if (deprecatedMessage.slice(-1)[0] !== '.') {
deprecatedMessage += '.';
}
}
return (
<Text block variant="small" styles={deprecatedTextStyles}>
Warning: this API is now obsolete. {deprecatedMessage && _extractCodeBlocks(deprecatedMessage)}
</Text>
);
}
/**
* Convert from a list of tokens to a list of actual links and code segments.
*/
function _renderLinkTokens(tokenResolver: IApiReferencesTableProps['tokenResolver'], linkTokens: ILinkToken[]): React.ReactNode[] {
return linkTokens.map((token: ILinkToken, index: number) => {
if (token.text) {
const key = token.text + index;
if (token.linkedPage && token.linkedPageGroup) {
return (
<Link key={key} {...tokenResolver(token as Required<ILinkToken>)}>
<code>{token.text}</code>
</Link>
);
}
return <code key={key}>{token.text}</code>;
}
return undefined;
});
}
/**
* Loops through text and places code blocks in code elements
*/
function _extractCodeBlocks(text: string): React.ReactNode[] {
// Unescape some characters
text = (text || '').replace(/\\([@<>{}])/g, '$1');
const result: React.ReactNode[] = [];
let index = 0;
let inCodeBlock = false;
while (index < text.length) {
let sectionEnd = text.indexOf('`', index);
if (sectionEnd === -1) {
sectionEnd = text.length;
}
const sectionContent = text.substring(index, sectionEnd);
if (inCodeBlock) {
result.push(<code key={index}>{sectionContent}</code>);
} else {
result.push(sectionContent);
}
inCodeBlock = !inCodeBlock;
index = sectionEnd + 1;
}
return result;
}