Skip to content

Commit

Permalink
feat: changed messages, actives, and tooltip callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
victorgarciaesgi committed Dec 11, 2024
1 parent 70a516d commit c4c4c37
Show file tree
Hide file tree
Showing 48 changed files with 174 additions and 246 deletions.
2 changes: 1 addition & 1 deletion docs/src/advanced-usage/rule-metadata.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export const strongPassword = createRule({
}
return {$valid: true};
},
message(value, { result }) {
message({ result }) {
return `Your password is ${result?.value}`;
},
});
Expand Down
4 changes: 2 additions & 2 deletions docs/src/advanced-usage/rules-operators.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ const { r$ } = useRegle(
regex: {
myError: withMessage(
and(startsWith('^'), endsWith('$')),
(value, { $params: [start, end] }) =>
({ $params: [start, end] }) =>
`Field should start with "${start}" and end with "${end}"`
),
},
Expand Down Expand Up @@ -70,7 +70,7 @@ const { r$ } = useRegle(
regex: {
myError: withMessage(
or(startsWith('^'), endsWith('$')),
(value, { $params: [start, end] }) =>
({ $params: [start, end] }) =>
`Field should start with "${start}" or end with "${end}"`
),
},
Expand Down
2 changes: 1 addition & 1 deletion docs/src/core-concepts/global-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { withMessage, minLength, required } from '@regle/rules';
const {useRegle: useCustomRegle} = defineRegleConfig({
rules: () => ({
required: withMessage(required, 'You need to provide a value'),
minLength: withMessage(minLength, (value, { $params: [count] }) => {
minLength: withMessage(minLength, ({ $params: [count] }) => {
return `Minimum length is ${count}. Current length: ${value?.length}`;
})
})
Expand Down
8 changes: 4 additions & 4 deletions docs/src/core-concepts/rules/advanced-rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,10 @@ export const requiredIf = createRule({
}
return true;
},
message(value, {$params: [condition]}) {
message({ $params: [condition] }) {
return `This field is required`,
}
active(value, { $params: [condition] }) {
active({ $params: [condition] }) {
return condition;
},
});
Expand Down Expand Up @@ -237,8 +237,8 @@ export const example = createRule({
}
return true;
},
message(value, {foo}) {
// ^?
message({foo}) {
// ^?
return 'Error example';
},
});
Expand Down
8 changes: 4 additions & 4 deletions docs/src/core-concepts/rules/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ const {r$} = useRegle({name: ''}, {
// You can also access current value and metadata with a getter function
customRule3: withMessage(
customRuleInlineWithMetaData,
(value, {foo}) => `Custom Error: ${value} ${foo}`
// ^?
({ $value, foo }) => `Custom Error: ${$value} ${foo}`
// ^?
),
}
})
Expand Down Expand Up @@ -156,8 +156,8 @@ const { r$ } = useRegle(
async (value, param) => await someAsyncCall(param),
[base]
),
(value, { $params: [param] }) => `Custom error: ${value} != ${param}`
// ^?
({ $params: [param] }) => `Custom error: ${value} != ${param}`
// ^?
),
},
}
Expand Down
4 changes: 2 additions & 2 deletions docs/src/parts/components/global-config/CustomMessages.vue
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ import { withMessage, minLength, required } from '@regle/rules';
const { useRegle: useCustomRegle } = defineRegleConfig({
rules: () => ({
required: withMessage(required, 'You need to provide a value'),
minLength: withMessage(minLength, (value, { $params: [count] }) => {
return `Minimum length is ${count}. Current length: ${value?.length}`;
minLength: withMessage(minLength, ({ $value, $params: [count] }) => {
return `Minimum length is ${count}. Current length: ${$value?.length}`;
}),
}),
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const strongPassword = createRule({
}
return { $valid: true };
},
message(value, { result }) {
message({ result }) {
return `Your password is ${result?.value.toLocaleLowerCase()}`;
},
});
Expand Down
3 changes: 1 addition & 2 deletions docs/src/parts/components/operators/OperatorAnd.vue
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ const { r$ } = useRegle(
regex: {
myError: withMessage(
and(startsWith('^'), endsWith('$')),
(value, { $params: [start, end] }) =>
`Field should start with "${start}" and end with "${end}"`
({ $params: [start, end] }) => `Field should start with "${start}" and end with "${end}"`
),
},
}
Expand Down
9 changes: 2 additions & 7 deletions docs/src/parts/components/operators/OperatorOr.vue
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
<template>
<div class="demo-container">
<div>
<input
v-model="r$.$value.regex"
:class="{ valid: r$.$fields.regex.$valid }"
placeholder="Type your regex"
/>
<input v-model="r$.$value.regex" :class="{ valid: r$.$fields.regex.$valid }" placeholder="Type your regex" />
<button type="button" @click="r$.$resetAll">Reset</button>
</div>
<ul v-if="r$.$errors.regex.length">
Expand All @@ -26,8 +22,7 @@ const { r$ } = useRegle(
regex: {
myError: withMessage(
or(startsWith('^'), endsWith('$')),
(value, { $params: [start, end] }) =>
`Field should start with "${start}" or end with "${end}"`
({ $params: [start, end] }) => `Field should start with "${start}" or end with "${end}"`
),
},
}
Expand Down
14 changes: 7 additions & 7 deletions packages/core/src/core/createRule/defineRuleProcessors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,29 +19,29 @@ export function defineRuleProcessors(
validator(value: any, ...args: any[]) {
return definition.validator(value, ...unwrapRuleParameters(args.length ? args : params));
},
message(value: any, metadata: $InternalRegleRuleMetadataConsumer) {
message(metadata: $InternalRegleRuleMetadataConsumer) {
if (typeof definition.message === 'function') {
return definition.message(value, {
return definition.message({
...metadata,
$params: unwrapRuleParameters(metadata.$params?.length ? metadata.$params : params),
$params: unwrapRuleParameters(metadata?.$params?.length ? metadata.$params : params),
});
} else {
return definition.message;
}
},
active(value: any, metadata: $InternalRegleRuleMetadataConsumer) {
active(metadata: $InternalRegleRuleMetadataConsumer) {
if (typeof definition.active === 'function') {
return definition.active(value, {
return definition.active({
...metadata,
$params: unwrapRuleParameters(metadata.$params?.length ? metadata.$params : params),
});
} else {
return definition.active ?? true;
}
},
tooltip(value: any, metadata: $InternalRegleRuleMetadataConsumer) {
tooltip(metadata: $InternalRegleRuleMetadataConsumer) {
if (typeof definition.tooltip === 'function') {
return definition.tooltip(value, {
return definition.tooltip({
...metadata,
$params: unwrapRuleParameters(metadata.$params?.length ? metadata.$params : params),
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export function createReactiveRuleStatus({
function $watch() {
scopeState = scope.run(() => {
const $defaultMetadata = computed<$InternalRegleRuleMetadataConsumer>(() => ({
$value: state.value,
$invalid: !$valid.value,
$pending: $pending.value,
$dirty: $dirty.value,
Expand All @@ -70,7 +71,7 @@ export function createReactiveRuleStatus({
const $active = computed<boolean>(() => {
if (isFormRuleDefinition(rule)) {
if (typeof rule.value.active === 'function') {
return rule.value.active(state.value, $defaultMetadata.value);
return rule.value.active($defaultMetadata.value);
} else {
return !!rule.value.active;
}
Expand All @@ -85,7 +86,7 @@ export function createReactiveRuleStatus({

if (customProcessor) {
if (typeof customProcessor === 'function') {
result = customProcessor(state.value, $defaultMetadata.value);
result = customProcessor($defaultMetadata.value);
} else {
result = customProcessor;
}
Expand All @@ -94,7 +95,7 @@ export function createReactiveRuleStatus({
const patchedKey = `_${key}_patched` as const;
if (!(customProcessor && !rule.value[patchedKey])) {
if (typeof rule.value[key] === 'function') {
result = rule.value[key](state.value, $defaultMetadata.value);
result = rule.value[key]($defaultMetadata.value);
} else {
result = rule.value[key] ?? '';
}
Expand Down
20 changes: 11 additions & 9 deletions packages/core/src/types/rules/rule.definition.type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ export interface RegleRuleDefinition<
TParams,
TAsync extends false ? TMetaData : Promise<TMetaData>
>;
message: (value: Maybe<TFilteredValue>, metadata: PossibleRegleRuleMetadataConsumer) => string | string[];
active: (value: Maybe<TFilteredValue>, metadata: PossibleRegleRuleMetadataConsumer) => boolean;
tooltip: (value: Maybe<TFilteredValue>, metadata: PossibleRegleRuleMetadataConsumer) => string | string[];
message: (metadata: PossibleRegleRuleMetadataConsumer<TFilteredValue>) => string | string[];
active: (metadata: PossibleRegleRuleMetadataConsumer<TFilteredValue>) => boolean;
tooltip: (metadata: PossibleRegleRuleMetadataConsumer<TFilteredValue>) => string | string[];
type?: string;
exec: (value: Maybe<TFilteredValue>) => TAsync extends false ? TMetaData : Promise<TMetaData>;
}
Expand Down Expand Up @@ -77,9 +77,10 @@ type DefaultMetadataProperties = Pick<ExcludeByType<RegleCommonStatus, Function>
* Will be used to consumme metadata on related helpers and rule status
*/
export type RegleRuleMetadataConsumer<
TValue extends any,
TParams extends any[] = never,
TMetadata extends RegleRuleMetadataDefinition = boolean,
> = DefaultMetadataProperties &
> = { $value: Maybe<TValue> } & DefaultMetadataProperties &
(TParams extends never
? {}
: {
Expand All @@ -94,14 +95,15 @@ export type RegleRuleMetadataConsumer<
/**
* Will be used to consumme metadata on related helpers and rule status
*/
export type PossibleRegleRuleMetadataConsumer = DefaultMetadataProperties & {
$params?: any[];
};
export type PossibleRegleRuleMetadataConsumer<TValue> = { $value: Maybe<TValue> } & DefaultMetadataProperties & {
$params?: any[];
};

/**
* @internal
*/
export type $InternalRegleRuleMetadataConsumer = DefaultMetadataProperties & {
$value: Maybe<unknown>;
$params?: any[];
[x: string]: any;
};
Expand Down Expand Up @@ -139,9 +141,9 @@ export type RegleRuleDefinitionProcessor<TValue extends any = any, TParams exten

export type RegleRuleDefinitionWithMetadataProcessor<
TValue extends any,
TMetadata extends RegleRuleMetadataConsumer<any, any>,
TMetadata extends RegleRuleMetadataConsumer<TValue, any>,
TReturn = any,
> = ((value: Maybe<TValue>, metadata: TMetadata) => TReturn) | TReturn;
> = ((metadata: TMetadata) => TReturn) | TReturn;

export type RegleCollectionRuleDefinition<
TValue = any[],
Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/types/rules/rule.init.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export type RegleInitPropertyGetter<
TReturn,
TParams extends [...any[]],
TMetadata extends RegleRuleMetadataDefinition,
> = TReturn | ((value: Maybe<TValue>, metadata: RegleRuleMetadataConsumer<TParams, TMetadata>) => TReturn);
> = TReturn | ((metadata: RegleRuleMetadataConsumer<TValue, TParams, TMetadata>) => TReturn);

/**
* @argument
Expand Down Expand Up @@ -53,9 +53,9 @@ export interface RegleRuleCore<
*/
export interface $InternalRegleRuleInit {
validator: (value: any, ...args: any[]) => RegleRuleMetadataDefinition | Promise<RegleRuleMetadataDefinition>;
message: string | string[] | ((value: any, metadata: $InternalRegleRuleMetadataConsumer) => string | string[]);
active?: boolean | ((value: any, metadata: $InternalRegleRuleMetadataConsumer) => boolean);
tooltip?: string | string[] | ((value: any, metadata: $InternalRegleRuleMetadataConsumer) => string | string[]);
message: string | string[] | ((metadata: $InternalRegleRuleMetadataConsumer) => string | string[]);
active?: boolean | ((metadata: $InternalRegleRuleMetadataConsumer) => boolean);
tooltip?: string | string[] | ((metadata: $InternalRegleRuleMetadataConsumer) => string | string[]);
type?: string;
}

Expand Down
12 changes: 3 additions & 9 deletions packages/core/src/types/rules/rule.internal.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,9 @@ export interface RegleInternalRuleDefs<
TMetadata extends RegleRuleMetadataDefinition = boolean,
> {
_validator: (value: Maybe<TValue>, ...args: TParams) => TAsync extends false ? TMetadata : Promise<TMetadata>;
_message:
| string
| string[]
| ((value: Maybe<TValue>, metadata: PossibleRegleRuleMetadataConsumer) => string | string[]);
_active?: boolean | ((value: Maybe<TValue>, metadata: PossibleRegleRuleMetadataConsumer) => boolean);
_tooltip?:
| string
| string[]
| ((value: Maybe<TValue>, metadata: PossibleRegleRuleMetadataConsumer) => string | string[]);
_message: string | string[] | ((metadata: PossibleRegleRuleMetadataConsumer<TValue>) => string | string[]);
_active?: boolean | ((metadata: PossibleRegleRuleMetadataConsumer<TValue>) => boolean);
_tooltip?: string | string[] | ((metadata: PossibleRegleRuleMetadataConsumer<TValue>) => string | string[]);
_type?: string;
_message_patched: boolean;
_tooltip_patched: boolean;
Expand Down
10 changes: 3 additions & 7 deletions packages/rules/src/helpers/and.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import type {
FormRuleDeclaration,
RegleRuleDefinition,
RegleRuleDefinitionProcessor,
} from '@regle/core';
import type { FormRuleDeclaration, RegleRuleDefinition, RegleRuleDefinitionProcessor } from '@regle/core';
import { createRule } from '@regle/core';
import type {
ExtractValueFromRules,
Expand Down Expand Up @@ -67,7 +63,7 @@ export function and<TRules extends FormRuleDeclaration<any, any>[]>(
function computeMetadata(
results: (boolean | { $valid: boolean; [x: string]: any })[]
): boolean | { $valid: boolean; [x: string]: any } {
const isAnyResultMetaData = results.some((s) => typeof s !== 'boolean');
const isAnyResultMetaData = results?.some((s) => typeof s !== 'boolean');
if (isAnyResultMetaData) {
return {
$valid: results.every((result) => {
Expand Down Expand Up @@ -109,7 +105,7 @@ export function and<TRules extends FormRuleDeclaration<any, any>[]>(

const newRule = createRule({
type: 'and',
validator: validator as any,
validator: validator,
message: 'The value does not match all of the provided validators',
});

Expand Down
2 changes: 1 addition & 1 deletion packages/rules/src/helpers/applyIf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export function applyIf<
return true;
}

function newActive(value: any, metadata: RegleRuleMetadataConsumer<any[], any>) {
function newActive(metadata: RegleRuleMetadataConsumer<any[], any>) {
const [condition] = unwrapRuleParameters<[boolean]>([_condition]);
return condition;
}
Expand Down
12 changes: 4 additions & 8 deletions packages/rules/src/helpers/not.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,14 @@ import { ruleHelpers } from './ruleHelpers';
export function not<
TValue,
TParams extends any[] = [],
TReturn extends
| RegleRuleMetadataDefinition
| Promise<RegleRuleMetadataDefinition> = RegleRuleMetadataDefinition,
TReturn extends RegleRuleMetadataDefinition | Promise<RegleRuleMetadataDefinition> = RegleRuleMetadataDefinition,
TMetadata extends RegleRuleMetadataDefinition = TReturn extends Promise<infer M> ? M : TReturn,
TAsync extends boolean = TReturn extends Promise<any> ? true : false,
>(
rule:
| RegleRuleDefinition<TValue, TParams, TAsync, TMetadata>
| InlineRuleDeclaration<TValue, TParams, TReturn>,
rule: RegleRuleDefinition<TValue, TParams, TAsync, TMetadata> | InlineRuleDeclaration<TValue, TParams, TReturn>,
message?: RegleRuleDefinitionWithMetadataProcessor<
TValue,
RegleRuleMetadataConsumer<TParams, TMetadata>,
RegleRuleMetadataConsumer<TValue, TParams, TMetadata>,
string | string[]
>
): RegleRuleDefinition<TValue, TParams, TAsync, TMetadata> {
Expand Down Expand Up @@ -61,7 +57,7 @@ export function not<

const newRule = createRule({
type: 'not',
validator: newValidator as any,
validator: newValidator,
message: (message as any) ?? 'Error',
});

Expand Down
Loading

0 comments on commit c4c4c37

Please sign in to comment.