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

Document and cleanup of utility functions #1442

Merged
merged 3 commits into from
Dec 13, 2022
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
3 changes: 2 additions & 1 deletion packages/toolpad-app/src/toolpad/AppEditor/BindingEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import {
JsExpressionAction,
} from '@mui/toolpad-core';
import { TabContext, TabList } from '@mui/lab';
import { Maybe, WithControlledProp, GlobalScopeMeta } from '../../utils/types';
import { Maybe, WithControlledProp } from '../../utils/types';
import { JsExpressionEditor } from './PageEditor/JsExpressionEditor';
import JsonView from '../../components/JsonView';
import { tryFormatExpression } from '../../utils/prettier';
Expand All @@ -44,6 +44,7 @@ import * as appDom from '../../appDom';
import { usePageEditorState } from './PageEditor/PageEditorProvider';
import GlobalScopeExplorer from './GlobalScopeExplorer';
import TabPanel from '../../components/TabPanel';
import { GlobalScopeMeta } from '../../types';

interface BindingEditorContext {
label: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Typography, Divider, Box, SxProps } from '@mui/material';
import * as React from 'react';
import ObjectInspector from '../../components/ObjectInspector';
import { GlobalScopeMeta } from '../../utils/types';
import { GlobalScopeMeta } from '../../types';

export interface GlobalScopeExplorerProps {
value?: Record<string, unknown>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { Stack, SxProps } from '@mui/material';
import * as React from 'react';
import { BindableAttrValue, PropValueType, LiveBinding } from '@mui/toolpad-core';
import { BindingEditor } from '../BindingEditor';
import { WithControlledProp, GlobalScopeMeta } from '../../../utils/types';
import { WithControlledProp } from '../../../utils/types';
import { GlobalScopeMeta } from '../../../types';
import { getDefaultControl } from '../../propertyControls';

function renderDefaultControl(params: RenderControlParams<any>) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import * as React from 'react';
import jsonToTs from 'json-to-ts';
import { Skeleton, styled, SxProps } from '@mui/material';
import { WithControlledProp, GlobalScopeMeta } from '../../../utils/types';
import { WithControlledProp } from '../../../utils/types';
import { GlobalScopeMeta } from '../../../types';
import lazyComponent from '../../../utils/lazyComponent';
import { hasOwnProperty } from '../../../utils/collections';
import ElementContext from '../ElementContext';
Expand Down
3 changes: 2 additions & 1 deletion packages/toolpad-app/src/toolpadDataSources/rest/client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
ConnectionEditorProps,
ExecFetchFn,
QueryEditorProps,
GlobalScopeMeta,
} from '../../types';
import {
FetchPrivateQuery,
Expand All @@ -41,7 +42,7 @@ import {
useEvaluateLiveBindingEntries,
} from '../../toolpad/AppEditor/useEvaluateLiveBinding';
import MapEntriesEditor from '../../components/MapEntriesEditor';
import { Maybe, GlobalScopeMeta } from '../../utils/types';
import { Maybe } from '../../utils/types';
import AuthenticationEditor from './AuthenticationEditor';
import { isSaveDisabled, validation } from '../../utils/forms';
import * as appDom from '../../appDom';
Expand Down
8 changes: 8 additions & 0 deletions packages/toolpad-app/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,3 +193,11 @@ export interface RuntimeState {
appId: string;
modules: Record<string, CompiledModule>;
}

export interface MetaField {
description?: string;
deprecated?: boolean | string;
tsType?: string;
value?: any;
}
export type GlobalScopeMeta = Record<string, MetaField>;
52 changes: 0 additions & 52 deletions packages/toolpad-app/src/utils/bindings.ts

This file was deleted.

19 changes: 18 additions & 1 deletion packages/toolpad-app/src/utils/collections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,21 @@ type Require<T, K extends keyof T> = T & { [P in K]-?: T[P] };

type Ensure<U, K extends PropertyKey> = K extends keyof U ? Require<U, K> : U & Record<K, unknown>;

/**
* Type aware version of Object.protoype.hasOwnProperty.
* See https://fettblog.eu/typescript-hasownproperty/
*/
export function hasOwnProperty<X extends {}, Y extends PropertyKey>(
obj: X,
prop: Y,
): obj is Ensure<X, Y> {
return obj.hasOwnProperty(prop);
}

/**
* Maps `obj` to a new object. The `mapper` function receices an entry array of jey and value and
* is allowed to manipulate both. It can also return `null` to omit a property from the result.
*/
export function mapProperties<P, L extends PropertyKey, U>(
obj: P,
mapper: <K extends PropertiesOf<P>>(old: [K, P[K]]) => [L, U] | null,
Expand All @@ -31,20 +39,29 @@ export function mapProperties<U, V>(
);
}

/**
Copy link
Member

@apedroferreira apedroferreira Dec 12, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't hurt to have these descriptions, but i feel like a few (not all) of these utilities are almost self-explanatory and don't really need comments? So maybe we don't need to enforce that every utility method always has comments (it's fine to keep them now though), and it's ok to rely on self-explanatory method names?

Also have we decided definitively if we want to maintain our own utilities or rely on an external library (just for the typical stuff that for example lodash already does)? I'm fine with either (maybe slightly more in favor of using a library), but we should just find a consensus I guess.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also have we decided definitively if we want to maintain our own utilities or rely on an external library (just for the typical stuff that for example lodash already does)? I'm fine with either (maybe slightly more in favor of using a library), but we should just find a consensus I guess.

We will just keep making informed decisions based on the use-case at hand, the available options, our experience, the maintenance cost required, etc... and not fall in the trap of taking on dogmas around this. Making the decision of using a library that does 85% of what you need may as well be detrimental to your overall codebase if the other 15% turn into a maintenance hell. Almost all of functions that are in the utils are there because of shortcomings in available options.

* Maps an objects' property keys. The result is a new object with the mapped keys, but the same values.
*/
export function mapKeys<U>(
obj: Record<string, U>,
mapper: (old: string) => string,
): Record<string, U> {
return mapProperties(obj, ([key, value]) => [mapper(key), value]);
}

/**
* Maps an objects' property values. The result is a new object with the same keys, but mapped values.
*/
export function mapValues<P, V>(
obj: P,
mapper: (old: P[PropertiesOf<P>], key: PropertiesOf<P>) => V,
): Record<PropertiesOf<P>, V> {
return mapProperties(obj, ([key, value]) => [key, mapper(value, key)]);
}

/**
* Filters an objects' property values. Similar to `array.filter` but for objects. The result is a new
* object with all the properties removed for which `filter` returned `false`.
*/
export function filterValues<P>(obj: P, filter: (old: P[keyof P]) => boolean): Partial<P>;
export function filterValues<U>(
obj: Record<string, U>,
Expand Down
5 changes: 5 additions & 0 deletions packages/toolpad-app/src/utils/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,9 @@ const crypto =
(invariant(!!global.crypto, 'Remove the crypto polyfill'), require('crypto'))
: global.crypto;

/**
* Isomorphic version of web `crypto`.
* In anticipation of `globalThis.crypto` becoming stable in Node.js.
* See https://nodejs.org/api/globals.html#crypto_1
*/
export default crypto;
14 changes: 14 additions & 0 deletions packages/toolpad-app/src/utils/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,20 @@ export function serializeError(error: Error): SerializedError {
return { message, name, stack };
}

/**
* Creates a javascript `Error` from an unkown value if it's not already an error.
* Does a best effort at inferring a message. Intended to be used typically in `catch`
* blocks, as there is no way to enforce only `Error` objects being thrown.
*
* ```
* try {
* // ...
* } catch (rawError) {
* const error = errorFrom(rawError);
* console.assert(error instancof Error);
* }
* ```
*/
export function errorFrom(maybeError: unknown): Error {
if (maybeError instanceof Error) {
return maybeError;
Expand Down
4 changes: 4 additions & 0 deletions packages/toolpad-app/src/utils/evalExpression.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
let iframe: HTMLIFrameElement;

/**
* Evaluates a javascript expression with global scope in an iframe.
*/
export default function evalExpression(code: string, globalScope: Record<string, unknown>) {
// TODO: investigate https://www.npmjs.com/package/ses
if (!iframe) {
Expand Down
4 changes: 2 additions & 2 deletions packages/toolpad-app/src/utils/fields.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const SINGLE_ACTION_INPUT_TYPES = ['checkbox', 'radio', 'range', 'color'];

export const hasFieldFocus = (documentTarget = document) => {
export function hasFieldFocus(documentTarget = document): boolean {
const activeElement = documentTarget.activeElement as HTMLElement | HTMLInputElement;

if (!activeElement) {
Expand All @@ -15,4 +15,4 @@ export const hasFieldFocus = (documentTarget = document) => {
const focusedContentEditable = contentEditable === 'true';

return focusedInput || focusedTextarea || focusedContentEditable;
};
}
6 changes: 6 additions & 0 deletions packages/toolpad-app/src/utils/forms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ function errorMessage(error: FieldError) {
}
}

/**
* Translates `react-hook-form` `formState` into error/helpText properties for UI components.
*/
export function validation<T extends FieldValues>(
formState: FormState<T>,
field: keyof T,
Expand All @@ -24,6 +27,9 @@ export function validation<T extends FieldValues>(
};
}

/**
* Reads `react-hook-form` `formState` and checks whether the state can and needs to be saved.
*/
export function isSaveDisabled<T extends FieldValues>(formState: FormState<T>): boolean {
// Always destructure formState to trigger underlying react-hook-form Proxy object
const { isValid, isDirty } = formState;
Expand Down
3 changes: 3 additions & 0 deletions packages/toolpad-app/src/utils/fs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import * as fs from 'fs/promises';

/**
* Like `fs.readFile`, but for JSON files specifically. Will throw on malformed JSON.
*/
export async function readJsonFile(path: string): Promise<any> {
const content = await fs.readFile(path, { encoding: 'utf-8' });
return JSON.parse(content);
Expand Down
31 changes: 25 additions & 6 deletions packages/toolpad-app/src/utils/geometry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,16 @@ export interface Rectangle {
height: number;
}

/**
* Calculates the Euclidian distance between two points
*/
export function distanceToPoint(x1: number, y1: number, x2: number, y2: number): number {
return Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
}

/**
* Calculates the shortest Euclidian distance from a point to a rectangle. Returns `0` if the
* point falss within the rectangle.
*/
export function distanceToRect(rect: Rectangle, x: number, y: number) {
const left = rect.x;
const top = rect.y;
Expand Down Expand Up @@ -43,8 +49,11 @@ export function distanceToRect(rect: Rectangle, x: number, y: number) {
return 0;
}

// All credit goes to https://stackoverflow.com/a/6853926/419436
// I was too lazy to figure out the math
/**
* Calculates the shortes Euclidian distance from a point to a line segment.
* All credit goes to https://stackoverflow.com/a/6853926/419436
* I was too lazy to figure out the math
*/
export function distanceToLine(
x1: number,
y1: number,
Expand Down Expand Up @@ -85,6 +94,9 @@ export function distanceToLine(
return Math.sqrt(dx * dx + dy * dy);
}

/**
* Translates a `Rectangle` into CSS properties for absolutely positioned elements.
*/
export function absolutePositionCss({ x, y, width, height }: Rectangle): React.CSSProperties {
return { left: x, top: y, width, height };
}
Expand All @@ -101,7 +113,9 @@ export function isReverseFlow(flowDirection: FlowDirection): boolean {
return flowDirection === 'row-reverse' || flowDirection === 'column-reverse';
}

// Returns the bounding client rect of an element against another element.
/**
* Returns the bounding client rect of an element relative to its container.
*/
export function getRelativeBoundingRect(containerElm: Element, childElm: Element): Rectangle {
const containerRect = containerElm.getBoundingClientRect();
const childRect = childElm.getBoundingClientRect();
Expand All @@ -114,8 +128,10 @@ export function getRelativeBoundingRect(containerElm: Element, childElm: Element
};
}

// Returns the bounding box of an element against another element.
// Considers the box model to return the full dimensions, including padding/border/margin.
/**
* Returns the bounding box of an element against another element.
* Considers the box model to return the full dimensions, including padding/border/margin.
*/
export function getRelativeOuterRect(containerElm: Element, childElm: Element): Rectangle {
const { x, y, width, height } = getRelativeBoundingRect(containerElm, childElm);
const styles = window.getComputedStyle(childElm);
Expand All @@ -140,6 +156,9 @@ export function getRelativeOuterRect(containerElm: Element, childElm: Element):
};
}

/**
* Checks whether a point falls within a reactangle
*/
export function rectContainsPoint(rect: Rectangle, x: number, y: number): boolean {
return rect.x <= x && rect.x + rect.width >= x && rect.y <= y && rect.y + rect.height >= y;
}
Expand Down
6 changes: 6 additions & 0 deletions packages/toolpad-app/src/utils/har.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { Har } from 'har-format';

/**
* Initializes an empty HAR object.
*/
export function createHarLog(): Har {
return {
log: {
Expand All @@ -21,6 +24,9 @@ function oldestFirst(a: WithStartedDateTime, b: WithStartedDateTime): number {
return new Date(a.startedDateTime).valueOf() - new Date(b.startedDateTime).valueOf();
}

/**
* Merge two HAR files into a new one.
*/
export function mergeHar(target: Har, ...src: Har[]): Har {
for (const har of src) {
if (har.log.pages) {
Expand Down
Loading