Turn on strict mode in tsconfig.json, some helpful lints, and required cleanup where strictness necessitates it (#5195)

* Turn on strict mode in tsconfig.json

- Add route, clusterRoute, and payloadValidatedClusterRoute helper
  functions to improve types with backend routes

- Turn on the following new lints:
  - react/jsx-first-prop-new-line
  - react/jsx-wrap-multilines
  - react/jsx-one-expression-per-line
  - react/jsx-max-props-per-line
  - react/jsx-indent
  - react/jsx-indent-props

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix build

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Replace KubeObject scope strings with enum

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Revert package.json version changes

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* revert move hostedCluster(Id)

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* change some type param names to be not single letters

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* remove copy-extension-themes

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* add new make clean action

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix build to not use webpack for generating types

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix kube-object-menu.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix select.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix catalog.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* revert move fileNameMigration to index

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix ref logic error

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix log-resource-selector.test.tsx tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix dock-store.test.ts test by overriding createStorage to not touch file system

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix cluster.test.ts tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix kube=api.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fixed hotbar-store.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix kubeconfig-manager.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix cluster-role-bindings/__tests__/dialog.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix role-bindings/__tests__/dialog.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix pods.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix delete-cluster-dialog.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix daemonset.store.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix replicaset.store.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix statefulsets/dialog/dialog.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix replicasets/scale-dialog/dialog.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix deployments.store.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix deployments/scale/dialog.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix cronjob.store.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix stateful-set.api.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix deployment.api.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix api-manager.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix statefulset.store.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix job.store.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix pods.store.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix scroll-spy.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix hotbar-remove-command.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix catalog-entity-registry.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix welcome.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix verify-that-all-routes-have-route-component.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix pod-tolerations.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* better fix for previous 3 fixes, plus also select.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix kube-object-menu.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix app-paths.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix dock-tabs.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix isReactNode typing

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix sub-title.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix drawer.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix list-layout.tsx and header.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix error-boundary.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix upgrade-chart/store.ts and dock-tab.store.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix install-chart/store.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix edit-resource/store.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix create-resource/store.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix namespace-select.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix namespace-select-filter.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix crd-list.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix wrong types for extensions

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix circular dependency

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix circular dependency on catalogCategoryRegistry

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix api-kube

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix type errors, most <Select /> errors

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fixing more type errors

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* some more fixing type errors

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* convert all KubeApis to injectable with legacy global backups

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* factor out into a common file all the exports

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* convert all KubeObjectStores to injectable with legacy global backups

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix lint

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* remove unused legacy KubeApi globals

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix bad previous commit

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* more crash fixing

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* try and fix behavioural tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix sidebar-and-tab-navigation-for-core.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix sidebar-and-tab-navigation-for-extensions.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix navigation-using-application-menu.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix catalog.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Make ThemeStore non-singleton and fix navigation-to-terminal-preferences.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* extensions.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix catalog-entity-registry.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix navigation-using-application-menu.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix log-resource-selector.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix dock-tabs.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix delete-cluster-dialog.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix navigation-to-kubernetes-preferences.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix navigation-to-editor-preferences.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix navigation-to-proxy-preferences.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix navigation-using-application-menu.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix navigation-to-application-preferences.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix dock-store.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix select.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix role-bindings/__tests__/dialog.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix hotbar-remove-command.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix cluster-role-bindings/__tests__/dialog.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix navigation-to-extension-specific-preferences.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix navigation-to-telemetry-preferences.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix closing-preferences.test.tsx

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix navigation-to-editor-preferences.test.ts

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix navigation-to-proxy-preferences.test.ts

- Fix other type errors too

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* final tweaks

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Add more tsconfig files, fix bug in <Catalog>

- Make all of history, navigation injectable

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix type errors

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Convert all of kube-details-params/ and navigate/ to injectable

- This fixes a runtime error that was encountered during testing

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix runtime errors on renderer

- remove all static uses of `createPageParam` (and then removed the
  legacy global)
- Made LensRendererExtension and LensMainExtension just used
  dependencies and not the getLegacyDi
- Fixed circular dep in extension-loader

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Move registerStore calls to after injectMany

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* replace all the rest of the legacy uses of apiManager

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix stack overflow and cycles in DI

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix NamespaceSelectFilter not opening

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix WizardStep and AddNamespaceDialog

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix KubeApi's not being registered

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* cleanup WindowManager

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Proper fix for Wizard, fix NamespaceStore.subscribe

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Rewrite withTooltip to be more type correct

- Fixes mobx related "too many recursive actions" error

- Change all the uses of withTooltips to be functional components

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Add e2e test to cover kube api registration

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* cleanup internal-commands

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* remove cast in <Animate>

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix command-palette e2e test

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix type error after rebase

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix test name

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix lint

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix code to help CodeQL scanner

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* update intree extension lock files

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix build-extensions picking wrong @types/react

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix tests from rebase

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix type error

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Make KubeconfigSyncManager more injectable

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix crash in test mode for Dialog

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* make Select snapshots deterministic

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix new type error

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix kube-object.store.test.ts typing

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix merge build issues

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix snapshots after merge

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix lint after merge

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* reexport BaseKubeJsonApiObjectMetadata

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix typo in terminalSpawningPool

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* remove duplicate license header

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix typo to waitUntilDefined

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* remove iter use from getLegacyGlobalDiForExtensionApi

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* remove complex createStorage override

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* override logger with mocks only when needed for tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* remove specialized overrideStore flags for getDiForUnitTesting

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* remove unnecessary | undefined types from the exactOptionalFieldTypes experiment

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* use more descriptive name for local test mocks

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* remove unnecessary addition to 'make clean' target

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* remove oddity of KubeObjectStore.getById(undefined) being allowed

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* rename KubeObject.getDescriptor in favour of name without fundemental JS meaning

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Simplify legacyRegisterApi when working in behaviour unit tests

- Don't emit within main environment as there should be no auto
  registering there

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* change confusing variable name in ReactiveDuration

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* make visitor pattern more explicit for Entity contextMenuOpen

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* toggleDetails -> toggleKubeDetailsPane is more specific

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* remove outdated comment

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix bug where LensExtension dependencies are not set

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix tests from the revert of react 18

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix more tests from merge

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix typings with new is-compatible-extension tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* more type fixing

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Revert in-tree extension versions

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Improve name of guarding injectable for stores and apis

- New name better implies that it is just a guard state and does not do
  anything

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Add helper for <Select>.isMulti for storing in a Set<Value>

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix is-compatible-extension.test.ts types

Signed-off-by: Sebastian Malton <sebastian@malton.name>
This commit is contained in:
Sebastian Malton authored and GitHub committed 2022-05-16 07:17:57 -04:00
1 parent 381d77c633
commit dfcb7c3330
1062 files changed
+26512 -28689

No files matched your search

@@ -21,7 +21,7 @@ describe("input validation tests", () => {
];
it.each(tests)("validate %s", (input, output) => {
expect(isEmail.validate(input)).toBe(output);
expect(isEmail.validate(input, {})).toBe(output);
});
});
@@ -38,7 +38,7 @@ describe("input validation tests", () => {
];
it.each(cases)("validate %s", (input, output) => {
expect(isUrl.validate(input)).toBe(output);
expect(isUrl.validate(input, {})).toBe(output);
});
});
@@ -68,7 +68,7 @@ describe("input validation tests", () => {
];
it.each(tests)("validate %s", (input, output) => {
expect(systemName.validate(input)).toBe(output);
expect(systemName.validate(input, {})).toBe(output);
});
});
});
@@ -11,22 +11,22 @@ import { observable, makeObservable } from "mobx";
import { observer } from "mobx-react";
import logger from "../../../main/logger";
export interface DropFileInputProps extends React.DOMAttributes<any> {
export interface DropFileInputProps<T extends HTMLElement> extends React.DOMAttributes<T> {
className?: IClassName;
disabled?: boolean;
onDropFiles(files: File[], meta: DropFileMeta): void;
onDropFiles(files: File[], meta: DropFileMeta<T>): void;
}
export interface DropFileMeta<T extends HTMLElement = any> {
export interface DropFileMeta<T extends HTMLElement> {
evt: React.DragEvent<T>;
}
@observer
export class DropFileInput<T extends HTMLElement = any> extends React.Component<DropFileInputProps> {
export class DropFileInput<T extends HTMLElement> extends React.Component<DropFileInputProps<T>> {
@observable dropAreaActive = false;
dragCounter = 0; // Counter preventing firing onDragLeave() too early (https://stackoverflow.com/questions/7110353/html5-dragleave-fired-when-hovering-a-child-element)
constructor(props: DropFileInputProps) {
constructor(props: DropFileInputProps<T>) {
super(props);
makeObservable(this);
autoBind(this);
+4 -4
View File
@@ -21,7 +21,7 @@ export interface FileInputProps extends InputHTMLAttributes<any> {
}
export class FileInput extends React.Component<FileInputProps> {
protected input: HTMLInputElement;
protected input: HTMLInputElement | null = null;
protected style: React.CSSProperties = {
position: "absolute",
@@ -29,11 +29,11 @@ export class FileInput extends React.Component<FileInputProps> {
};
selectFiles = () => {
this.input.click(); // opens system dialog for selecting files
this.input?.click(); // opens system dialog for selecting files
};
protected onChange = async (evt: React.ChangeEvent<HTMLInputElement>) => {
const fileList = Array.from(evt.target.files);
const fileList = Array.from(evt.target.files ?? []);
if (!fileList.length) {
return;
@@ -49,7 +49,7 @@ export class FileInput extends React.Component<FileInputProps> {
resolve({
file,
data: reader.result,
error: reader.error ? String(reader.error) : null,
error: reader.error ? String(reader.error) : undefined,
});
};
reader.readAsText(file);
+67 -35
View File
@@ -53,7 +53,7 @@ export type InputProps = Omit<InputElementProps, "onChange" | "onSubmit"> & {
iconLeft?: IconData;
iconRight?: IconData;
contentRight?: string | React.ReactNode; // Any component of string goes after iconRight
validators?: InputValidator | InputValidator[];
validators?: InputValidator<boolean> | InputValidator<boolean>[];
blurOnEnter?: boolean;
onChange?(value: string, evt: React.ChangeEvent<InputElement>): void;
onSubmit?(value: string, evt: React.KeyboardEvent<InputElement>): void;
@@ -76,11 +76,15 @@ const defaultProps: Partial<InputProps> = {
blurOnEnter: true,
};
function isAsyncValidator(validator: InputValidator<boolean>): validator is InputValidator<true> {
return typeof validator.debounce === "number";
}
export class Input extends React.Component<InputProps, State> {
static defaultProps = defaultProps as object;
public input: InputElement | null = null;
public validators: InputValidator[] = [];
public validators: InputValidator<boolean>[] = [];
public state: State = {
focused: false,
@@ -101,13 +105,11 @@ export class Input extends React.Component<InputProps, State> {
}
setValue(value = "") {
if (value !== this.getValue()) {
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(this.input.constructor.prototype, "value").set;
nativeInputValueSetter.call(this.input, value);
const evt = new Event("input", { bubbles: true });
this.input.dispatchEvent(evt);
if (value !== this.getValue() && this.input) {
Object.getOwnPropertyDescriptor(this.input.constructor.prototype, "value")
?.set
?.call(this.input, value);
this.input.dispatchEvent(new Event("input", { bubbles: true }));
}
}
@@ -119,32 +121,34 @@ export class Input extends React.Component<InputProps, State> {
}
focus() {
this.input.focus();
this.input?.focus();
}
blur() {
this.input.blur();
this.input?.blur();
}
select() {
this.input.select();
this.input?.select();
}
private autoFitHeight() {
const { multiLine, rows, maxRows } = this.props;
const { rows, maxRows } = this.props;
const textArea = this.input;
if (!multiLine) {
if (!(textArea instanceof HTMLTextAreaElement)) {
return;
}
const textArea = this.input;
const lineHeight = parseFloat(window.getComputedStyle(textArea).lineHeight);
const rowsCount = (this.getValue().match(/\n/g) || []).length + 1;
const height = lineHeight * Math.min(Math.max(rowsCount, rows), maxRows);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const height = lineHeight * Math.min(Math.max(rowsCount, rows!), maxRows!);
textArea.style.height = `${height}px`;
}
private validationId: string;
private validationId?: string;
async validate() {
const value = this.getValue();
@@ -158,6 +162,23 @@ export class Input extends React.Component<InputProps, State> {
// stop validation check if there is an error already
break;
}
if (isAsyncValidator(validator)) {
if (!validationId) {
this.validationId = validationId = uniqueId("validation_id_");
}
asyncValidators.push(
validator.validate(value, this.props).then(
() => null, // don't consider any valid result from promise since we interested in errors only
error => this.getValidatorError(value, validator) || error,
),
);
} else {
if (!validator.validate(value, this.props)) {
errors.push(this.getValidatorError(value, validator));
}
}
const result = validator.validate(value, this.props);
if (isBoolean(result) && !result) {
@@ -188,7 +209,7 @@ export class Input extends React.Component<InputProps, State> {
}
}
this.input?.setCustomValidity(errors.length ? errors[0].toString() : "");
this.input?.setCustomValidity(errors[0]?.toString() ?? "");
}
setValidation(errors: React.ReactNode[]) {
@@ -199,24 +220,29 @@ export class Input extends React.Component<InputProps, State> {
});
}
private getValidatorError(value: string, { message }: InputValidator) {
private getValidatorError(value: string, { message }: InputValidator<boolean>) {
if (isFunction(message)) return message(value, this.props);
return message || "";
}
private setupValidators() {
this.validators = conditionalValidators
const persistentValidators = conditionalValidators
// add conditional validators if matches input props
.filter(validator => validator.condition(this.props))
// add custom validators
.concat(this.props.validators)
// debounce async validators
.map(({ debounce, ...validator }) => {
if (debounce) validator.validate = debouncePromise(validator.validate, debounce);
.filter(validator => validator.condition?.(this.props));
const selfValidators = this.props.validators ? [this.props.validators].flat() : [];
this.validators = [
...persistentValidators,
...selfValidators,
].map((validator) => {
if (isAsyncValidator(validator)) {
validator.validate = debouncePromise(validator.validate, validator.debounce);
}
return validator;
});
return validator;
});
// run validation
this.validate();
}
@@ -388,9 +414,9 @@ export class Input extends React.Component<InputProps, State> {
{errors.map((error, i) => <p key={i}>{error}</p>)}
</div>
);
// TODO: Remove side-effect to allow deterministic unit testing
const componentId = id || showErrorsAsTooltip ? getRandId({ prefix: "input_tooltip_id" }) : undefined;
const componentId = id || showErrorsAsTooltip
? getRandId({ prefix: "input_tooltip_id" })
: undefined;
let tooltipError: React.ReactNode;
if (showErrorsAsTooltip && showErrors) {
@@ -398,9 +424,10 @@ export class Input extends React.Component<InputProps, State> {
tooltipProps.className = cssNames("InputTooltipError", tooltipProps.className);
tooltipError = (
<Tooltip targetId={componentId} {...tooltipProps}>
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
<Tooltip targetId={componentId!} {...tooltipProps}>
<div className="flex gaps align-center">
<Icon material="error_outline"/>
<Icon material="error_outline" />
{errorsInfo}
</div>
</Tooltip>
@@ -412,7 +439,10 @@ export class Input extends React.Component<InputProps, State> {
{tooltipError}
<label className="input-area flex gaps align-center" id="">
{this.renderIcon(iconLeft)}
{multiLine ? <textarea {...inputProps as any} /> : <input {...inputProps as any} />}
{multiLine
? <textarea {...inputProps as never} />
: <input {...inputProps as never} />
}
{this.renderIcon(iconRight)}
{contentRight}
</label>
@@ -420,7 +450,9 @@ export class Input extends React.Component<InputProps, State> {
{!showErrorsAsTooltip && showErrors && errorsInfo}
{this.showMaxLenIndicator && (
<div className="maxLengthIndicator box right">
{this.getValue().length} / {maxLength}
{this.getValue().length}
{" / "}
{maxLength}
</div>
)}
</div>
@@ -6,27 +6,51 @@
import type { InputProps } from "./input";
import type { ReactNode } from "react";
import fse from "fs-extra";
import { TypedRegEx } from "typed-regex";
export interface InputValidator {
debounce?: number; // debounce for async validators in ms
condition?(props: InputProps): boolean; // auto-bind condition depending on input props
message?: ReactNode | ((value: string, props?: InputProps) => ReactNode | string);
validate(value: string, props?: InputProps): boolean | Promise<any>; // promise can throw error message
export class AsyncInputValidationError extends Error {}
export type InputValidator<IsAsync extends boolean> = {
/**
* Filters itself based on the input props
*/
condition?: (props: InputProps) => any;
} & (
IsAsync extends false
? {
validate: (value: string, props: InputProps) => boolean;
message: ReactNode | ((value: string, props: InputProps) => ReactNode | string);
debounce?: undefined;
}
: {
/**
* If asyncronous then the rejection message is the error message
*
* This function MUST reject with an instance of {@link AsyncInputValidationError}
*/
validate: (value: string, props: InputProps) => Promise<void>;
message?: undefined;
debounce: number;
}
);
export function inputValidator<IsAsync extends boolean = false>(validator: InputValidator<IsAsync>): InputValidator<IsAsync> {
return validator;
}
export const isRequired: InputValidator = {
export const isRequired = inputValidator({
condition: ({ required }) => required,
message: () => `This field is required`,
validate: value => !!value.trim(),
};
});
export const isEmail: InputValidator = {
export const isEmail = inputValidator({
condition: ({ type }) => type === "email",
message: () => `Wrong email format`,
validate: value => !!value.match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/),
};
});
export const isNumber: InputValidator = {
export const isNumber = inputValidator({
condition: ({ type }) => type === "number",
message: () => `Invalid number`,
validate: (value, { min, max }) => {
@@ -38,9 +62,9 @@ export const isNumber: InputValidator = {
(max != null && numVal > max)
);
},
};
});
export const isUrl: InputValidator = {
export const isUrl = inputValidator({
condition: ({ type }) => type === "url",
message: () => `Wrong url format`,
validate: value => {
@@ -50,45 +74,61 @@ export const isUrl: InputValidator = {
return false;
}
},
});
/**
* NOTE: this cast is needed because of two bugs in the typed regex package
* - https://github.com/phenax/typed-regex/issues/6
* - https://github.com/phenax/typed-regex/issues/7
*/
export const isExtensionNameInstallRegex = TypedRegEx("^(?<name>(@[-\\w]+\\/)?[-\\w]+)(@(?<version>[a-z0-9-_.]+))?$", "gi") as {
isMatch(val: string): boolean;
captures(val: string): undefined | { name: string; version?: string };
};
export const isExtensionNameInstallRegex = /^(?<name>(@[-\w]+\/)?[-\w]+)(@(?<version>[a-z0-9-_.]+))?$/gi;
export const isExtensionNameInstall: InputValidator = {
export const isExtensionNameInstall = inputValidator({
condition: ({ type }) => type === "text",
message: () => "Not an extension name with optional version",
validate: value => value.match(isExtensionNameInstallRegex) !== null,
};
validate: value => isExtensionNameInstallRegex.isMatch(value),
});
export const isPath: InputValidator = {
export const isPath = inputValidator<true>({
debounce: 100,
condition: ({ type }) => type === "text",
message: () => `This field must be a valid path`,
validate: value => value && fse.pathExistsSync(value),
};
validate: async value => {
try {
await fse.pathExists(value);
} catch {
throw new AsyncInputValidationError(`${value} is not a valid file path`);
}
},
});
export const minLength: InputValidator = {
export const minLength = inputValidator({
condition: ({ minLength }) => !!minLength,
message: (value, { minLength }) => `Minimum length is ${minLength}`,
validate: (value, { minLength }) => value.length >= minLength,
};
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
validate: (value, { minLength }) => value.length >= minLength!,
});
export const maxLength: InputValidator = {
export const maxLength = inputValidator({
condition: ({ maxLength }) => !!maxLength,
message: (value, { maxLength }) => `Maximum length is ${maxLength}`,
validate: (value, { maxLength }) => value.length <= maxLength,
};
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
validate: (value, { maxLength }) => value.length <= maxLength!,
});
const systemNameMatcher = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$/;
export const systemName: InputValidator = {
export const systemName = inputValidator({
message: () => `A System Name must be lowercase DNS labels separated by dots. DNS labels are alphanumerics and dashes enclosed by alphanumerics.`,
validate: value => !!value.match(systemNameMatcher),
};
});
export const accountId: InputValidator = {
export const accountId = inputValidator({
message: () => `Invalid account ID`,
validate: value => (isEmail.validate(value) || systemName.validate(value)),
};
validate: (value, props) => (isEmail.validate(value, props) || systemName.validate(value, props)),
});
export const conditionalValidators = [
isRequired, isEmail, isNumber, isUrl, minLength, maxLength,
@@ -9,26 +9,27 @@ import { autorun, observable, makeObservable } from "mobx";
import { disposeOnUnmount, observer } from "mobx-react";
import type { InputProps } from "./input";
import { SearchInput } from "./search-input";
import { createPageParam } from "../../navigation";
export const searchUrlParam = createPageParam({
name: "search",
defaultValue: "",
});
import type { PageParam } from "../../navigation";
import { withInjectables } from "@ogre-tools/injectable-react";
import searchUrlPageParamInjectable from "./search-url-page-param.injectable";
export interface SearchInputUrlProps extends InputProps {
compact?: boolean; // show only search-icon when not focused
}
interface Dependencies {
searchUrlParam: PageParam<string>;
}
@observer
export class SearchInputUrl extends React.Component<SearchInputUrlProps> {
class NonInjectedSearchInputUrl extends React.Component<SearchInputUrlProps & Dependencies> {
@observable inputVal = ""; // fix: use empty string on init to avoid react warnings
updateUrl = debounce((val: string) => searchUrlParam.set(val), 250);
readonly updateUrl = debounce((val: string) => this.props.searchUrlParam.set(val), 250);
componentDidMount(): void {
disposeOnUnmount(this, [
autorun(() => this.inputVal = searchUrlParam.get()),
autorun(() => this.inputVal = this.props.searchUrlParam.get()),
]);
}
@@ -44,27 +45,34 @@ export class SearchInputUrl extends React.Component<SearchInputUrlProps> {
onChange = (val: string, evt: React.ChangeEvent<any>) => {
this.setValue(val);
if (this.props.onChange) {
this.props.onChange(val, evt);
}
this.props.onChange?.(val, evt);
};
constructor(props: SearchInputUrlProps) {
constructor(props: SearchInputUrlProps & Dependencies) {
super(props);
makeObservable(this);
}
render() {
const { inputVal } = this;
const { searchUrlParam, ...searchInputProps } = this.props;
return (
<SearchInput
value={inputVal}
onChange={this.onChange}
value={this.inputVal}
onChange={(val, event) => {
this.setValue(val);
this.props.onChange?.(val, event);
}}
onClear={this.clear}
{...this.props}
{...searchInputProps}
/>
);
}
}
export const SearchInputUrl = withInjectables<Dependencies, SearchInputUrlProps>(NonInjectedSearchInputUrl, {
getProps: (di, props) => ({
...props,
searchUrlParam: di.inject(searchUrlPageParamInjectable),
}),
});
@@ -49,7 +49,7 @@ export class SearchInput extends React.Component<SearchInputProps> {
onGlobalKey(evt: KeyboardEvent) {
if (evt.key === "f" && (isMac ? evt.metaKey : evt.ctrlKey)) {
this.inputRef.current.focus();
this.inputRef.current?.focus();
}
}
@@ -66,7 +66,7 @@ export class SearchInput extends React.Component<SearchInputProps> {
if (this.props.onClear) {
this.props.onClear();
} else {
this.inputRef.current.setValue("");
this.inputRef.current?.setValue("");
}
}
@@ -75,7 +75,13 @@ export class SearchInput extends React.Component<SearchInputProps> {
let rightIcon = <Icon small material="search"/>;
if (showClearIcon && value) {
rightIcon = <Icon small material="close" onClick={this.clear}/>;
rightIcon = (
<Icon
small
material="close"
onClick={this.clear}
/>
);
}
return (
@@ -0,0 +1,20 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import createPageParamInjectable from "../../navigation/create-page-param.injectable";
const searchUrlPageParamInjectable = getInjectable({
id: "search-url-page-param",
instantiate: (di) => {
const createPageParam = di.inject(createPageParamInjectable);
return createPageParam({
name: "search",
defaultValue: "",
});
},
});
export default searchUrlPageParamInjectable;
@@ -4,17 +4,21 @@
*/
import { getInjectable } from "@ogre-tools/injectable";
import hotbarStoreInjectable from "../../../../common/hotbar-store.injectable";
import type { InputValidator } from "../input_validators";
import hotbarStoreInjectable from "../../../../common/hotbars/store.injectable";
import { inputValidator } from "../input_validators";
const uniqueHotbarNameInjectable = getInjectable({
id: "unique-hotbar-name",
instantiate: di => ({
condition: ({ required }) => required,
message: () => "Hotbar with this name already exists",
validate: value => !di.inject(hotbarStoreInjectable).getByName(value),
} as InputValidator),
instantiate: di => {
const store = di.inject(hotbarStoreInjectable);
return inputValidator({
condition: ({ required }) => required,
message: () => "Hotbar with this name already exists",
validate: value => !store.findByName(value),
});
},
});
export default uniqueHotbarNameInjectable;