The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
import { isFunction, isNonEmptyString, isNumber } from '@sniptt/guards';
import React from 'react';
import { type CaretPreservingElement } from '@/host/caret/types/CaretPreservingElement';
import { type SetEditableFocused } from '@/host/caret/types/SetEditableFocused';
import { recordNativeEdit } from '@/host/caret/utils/recordNativeEdit';
import { type ElementRefCallback } from '@/host/elements/types/ElementRefCallback';
const resolveInitialValue = (candidate: unknown): string | undefined => {
if (isNonEmptyString(candidate)) {
return candidate;
}
if (isNumber(candidate)) {
return String(candidate);
}
return undefined;
};
type CreateCaretPreservingElementParams = {
htmlTag: 'input' | 'textarea';
reactBindableProps: Record<string, unknown>;
hostEnforcedProps: Record<string, unknown>;
setEditableFocused: SetEditableFocused | null;
caretPreservingElementRef: ElementRefCallback;
};
export const createCaretPreservingElement = ({
htmlTag,
reactBindableProps,
hostEnforcedProps,
setEditableFocused,
caretPreservingElementRef,
}: CreateCaretPreservingElementParams) => {
const {
value,
defaultValue,
onFocus: forwardedOnFocus,
onBlur: forwardedOnBlur,
onInput: forwardedOnInput,
...rest
} = reactBindableProps;
const initialValue =
resolveInitialValue(defaultValue) ?? resolveInitialValue(value);
const handleFocus = (event: React.FocusEvent<CaretPreservingElement>) => {
setEditableFocused?.(true);
if (isFunction(forwardedOnFocus)) {
forwardedOnFocus(event);
}
};
const handleBlur = (event: React.FocusEvent<CaretPreservingElement>) => {
setEditableFocused?.(false);
if (isFunction(forwardedOnBlur)) {
forwardedOnBlur(event);
}
};
const handleInput = (event: React.FormEvent<CaretPreservingElement>) => {
recordNativeEdit(event.currentTarget);
if (isFunction(forwardedOnInput)) {
forwardedOnInput(event);
}
};
return React.createElement(htmlTag, {
...rest,
...hostEnforcedProps,
defaultValue: initialValue,
onFocus: handleFocus,
onBlur: handleBlur,
onInput: handleInput,
ref: caretPreservingElementRef,
});
};