This repository has been archived by the owner on Sep 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
css-error.ts
70 lines (62 loc) · 2.06 KB
/
css-error.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
import { translateAfter } from '@proc7ts/fun-events';
import { arrayOfElements, isArrayOfElements } from '@proc7ts/primitives';
import { InputAspects__NS } from '../../aspects';
import { InValidation } from '../../validation';
import { InCssClasses } from './css-classes.aspect';
/**
* Builds a source of error marker CSS classes.
*
* Applies error marker class(es) when the given error message codes present in
* {@link InValidation.Result validation result}.
*
* @category Style
* @param mark - Error mark. Specifies CSS class(es) to apply when requested error present.
* A class with `has-error` name in {@link InputAspects__NS input aspects namespace} is used by default.
* @param when - {@link InValidation.Message Validation message} code(s) to expect.
* {@link InValidation.Result.ok Any} error matches by default.
*
* @returns A source of CSS class names to apply.
*/
export function inCssError({
mark,
when,
}: {
mark?: InCssClasses.Spec | readonly InCssClasses.Spec[] | undefined;
when?: string | readonly string[] | undefined;
} = {}): InCssClasses.Source {
let hasError: (errors: InValidation.Result) => boolean;
if (!when) {
hasError = defaultInCssHasError;
} else if (isArrayOfElements(when)) {
hasError = when.length ? errors => when.every(code => errors.has(code)) : defaultInCssHasError;
} else {
hasError = errors => errors.has(when);
}
return control => control
.aspect(InValidation)
.read.do(
translateAfter((send, errors) => hasError(errors) ? send(...inCssErrorMarks(mark)) : send()),
);
}
/**
* @internal
*/
function defaultInCssHasError(errors: InValidation.Result): boolean {
return !errors.ok;
}
/**
* @internal
*/
const defaultInCssErrorMarks: readonly InCssClasses.Spec[] = [['has-error', InputAspects__NS]];
/**
* @internal
*/
function inCssErrorMarks(
mark?: InCssClasses.Spec | readonly InCssClasses.Spec[],
): readonly InCssClasses.Spec[] {
if (!mark) {
return defaultInCssErrorMarks;
}
const marks = arrayOfElements(mark);
return marks.length ? marks : defaultInCssErrorMarks;
}