-
Notifications
You must be signed in to change notification settings - Fork 0
/
Utils.ts
291 lines (262 loc) · 9.15 KB
/
Utils.ts
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Core
*/
import { LegacyRef, MutableRefObject, RefCallback, useCallback, useEffect, useRef, useState } from "react";
import { Primitives, PrimitiveValue, PropertyDescription, PropertyRecord, PropertyValueFormat } from "@itwin/appui-abstract";
import { IPropertyValueRenderer, PropertyValueRendererManager } from "@itwin/components-react";
import { assert, Guid, GuidString, IDisposable } from "@itwin/core-bentley";
import { TranslationOptions } from "@itwin/core-common";
import { Descriptor, Field, LabelCompositeValue, LabelDefinition, parseCombinedFieldNames, Ruleset, Value } from "@itwin/presentation-common";
import { Presentation } from "@itwin/presentation-frontend";
import { InstanceKeyValueRenderer } from "../properties/InstanceKeyValueRenderer";
const localizationNamespaceName = "PresentationComponents";
/**
* Registers 'PresentationComponents' localization namespace and returns callback
* to unregister it.
* @internal
*/
export const initializeLocalization = async () => {
await Presentation.localization.registerNamespace(localizationNamespaceName);
return () => Presentation.localization.unregisterNamespace(localizationNamespaceName); // eslint-disable-line @itwin/no-internal
};
/**
* Registers custom property value renderers and returns cleanup callback that unregisters them.
* @internal
*/
export const initializePropertyValueRenderers = async () => {
const customRenderers: Array<{ name: string; renderer: IPropertyValueRenderer }> = [{ name: "SelectableInstance", renderer: new InstanceKeyValueRenderer() }];
for (const { name, renderer } of customRenderers) {
PropertyValueRendererManager.defaultManager.registerRenderer(name, renderer);
}
return () => {
for (const { name } of customRenderers) {
PropertyValueRendererManager.defaultManager.unregisterRenderer(name);
}
};
};
/**
* Translate a string with the specified id from `PresentationComponents`
* localization namespace. The `stringId` should not contain namespace - it's
* prepended automatically.
*
* @internal
*/
export const translate = (stringId: string, options?: TranslationOptions): string => {
stringId = `${localizationNamespaceName}:${stringId}`;
return Presentation.localization.getLocalizedString(stringId, options);
};
/**
* Creates a display name for the supplied component
* @internal
*/
export const getDisplayName = <P>(component: React.ComponentType<P>): string => {
if (component.displayName) {
return component.displayName;
}
if (component.name) {
return component.name;
}
return "Component";
};
/**
* Finds a field given the name of property record created from that field.
* @internal
*/
export const findField = (descriptor: Descriptor, recordPropertyName: string): Field | undefined => {
let fieldsSource: { getFieldByName: (name: string) => Field | undefined } | undefined = descriptor;
const fieldNames = parseCombinedFieldNames(recordPropertyName);
while (fieldsSource && fieldNames.length) {
const field: Field | undefined = fieldsSource.getFieldByName(fieldNames.shift()!);
fieldsSource = field && field.isNestedContentField() ? field : undefined;
if (!fieldNames.length) {
return field;
}
}
return undefined;
};
/**
* Creates property record for label using label definition.
* @internal
*/
export const createLabelRecord = (label: LabelDefinition, name: string): PropertyRecord => {
const value: PrimitiveValue = {
displayValue: label.displayValue,
value: createPrimitiveLabelValue(label),
valueFormat: PropertyValueFormat.Primitive,
};
const property: PropertyDescription = {
displayLabel: "Label",
typename: label.typeName,
name,
};
return new PropertyRecord(value, property);
};
const createPrimitiveLabelValue = (label: LabelDefinition) => {
return LabelDefinition.isCompositeDefinition(label) ? createPrimitiveCompositeValue(label.rawValue) : label.rawValue;
};
const createPrimitiveCompositeValue = (compositeValue: LabelCompositeValue): Primitives.Composite => {
return {
separator: compositeValue.separator,
parts: compositeValue.values.map((part) => ({
displayValue: part.displayValue,
typeName: part.typeName,
rawValue: createPrimitiveLabelValue(part),
})),
};
};
/** @internal */
export type RulesetOrId = Ruleset | string;
/**
* Returns ruleset id from `RulesetOrId`.
* @internal
*/
export function getRulesetId(ruleset: RulesetOrId) {
return typeof ruleset === "string" ? ruleset : ruleset.id;
}
/**
* A helper to track ongoing async tasks. Usage:
* ```
* await using(tracker.trackAsyncTask(), async (_r) => {
* await doSomethingAsync();
* });
* ```
*
* Can be used with `waitForPendingAsyncs` in test helpers to wait for all
* async tasks to complete.
*
* @internal
*/
export class AsyncTasksTracker {
private _asyncsInProgress = new Set<GuidString>();
public get pendingAsyncs() {
return this._asyncsInProgress;
}
public trackAsyncTask(): IDisposable {
const id = Guid.createValue();
this._asyncsInProgress.add(id);
return {
dispose: () => this._asyncsInProgress.delete(id),
};
}
}
/** @internal */
export function useResizeObserver<T extends HTMLElement>() {
const observer = useRef<ResizeObserver>();
const [{ width, height }, setSize] = useState<{ width?: number; height?: number }>({});
const ref = useCallback((element: T | null) => {
observer.current?.disconnect();
if (element) {
observer.current = new ResizeObserver(
/* istanbul ignore next */
(entries) => {
window.requestAnimationFrame(() => {
assert(entries.length === 1);
setSize(entries[0].contentRect);
});
},
);
observer.current.observe(element);
}
}, []);
return {
ref,
width,
height,
};
}
/** @internal */
export function useMergedRefs<T>(...refs: Array<MutableRefObject<T | null> | LegacyRef<T>>): RefCallback<T> {
return useCallback(
(instance: T | null) => {
refs.forEach((ref) => {
// istanbul ignore else
if (typeof ref === "function") {
ref(instance);
} else if (ref) {
(ref as MutableRefObject<T | null>).current = instance;
}
});
},
[...refs], // eslint-disable-line react-hooks/exhaustive-deps
);
}
/**
* A hook that helps components throw errors in React's render loop so they can be captured by React error
* boundaries.
*
* Usage: simply call the returned function with an error and it will be re-thrown in React render loop.
*
* @internal
*/
export function useErrorState() {
const [_, setError] = useState(undefined);
const setErrorState = useCallback((e: unknown) => {
setError(() => {
throw e instanceof Error ? e : /* istanbul ignore next */ new Error();
});
}, []);
return setErrorState;
}
/**
* A hook that rerenders component after some time.
* @param delayMilliseconds - milliseconds to delay. Default is 250.
* @internal
*/
export function useDelay(delayMilliseconds: number = 250) {
const [passed, setPassed] = useState(false);
useEffect(() => {
const timeout = setTimeout(() => {
setPassed(true);
}, delayMilliseconds);
return () => {
clearTimeout(timeout);
};
}, [delayMilliseconds]);
return passed;
}
export interface UniqueValue {
displayValue: string;
groupedRawValues: Value[];
}
/**
* Function for serializing `UniqueValue`.
* Returns an object, which consists of `displayValues` and `groupedRawValues`.
*/
export function serializeUniqueValues(values: UniqueValue[]): { displayValues: string; groupedRawValues: string } {
const displayValues: string[] = [];
const groupedRawValues: {
[key: string]: Value[];
} = {};
values.forEach((item) => {
displayValues.push(item.displayValue);
groupedRawValues[item.displayValue] = [...item.groupedRawValues];
});
return { displayValues: JSON.stringify(displayValues), groupedRawValues: JSON.stringify(groupedRawValues) };
}
/**
* Function for deserializing `displayValues` and `groupedRawValues`.
* Returns an array of `UniqueValue` or undefined if parsing fails.
*/
export function deserializeUniqueValues(serializedDisplayValues: string, serializedGroupedRawValues: string): UniqueValue[] | undefined {
const tryParseJSON = (value: string) => {
try {
return JSON.parse(value);
} catch {
return false;
}
};
const displayValues = tryParseJSON(serializedDisplayValues);
const groupedRawValues = tryParseJSON(serializedGroupedRawValues);
if (!displayValues || !groupedRawValues || !Array.isArray(displayValues) || Object.keys(groupedRawValues).length !== displayValues.length) {
return undefined;
}
const uniqueValues: UniqueValue[] = [];
for (const displayValue of displayValues) {
uniqueValues.push({ displayValue, groupedRawValues: groupedRawValues[displayValue] });
}
return uniqueValues;
}