Bin
2025-12-17 21f0498f62ada55651f4d232327e15fc47f498b1
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
import { types } from "mobx-state-tree";
 
/**
 * Validates the value against the given range.
 * By default range is from 0 to 1 including ends.
 * @param {Number} min Minimal value
 * @param {Number} max Maximal value
 */
const Range = (min = 0, max = 1) =>
  types.custom<any, number>({
    name: `Range(${min}..${max})`,
    fromSnapshot(snapshot) {
      return Number.parseFloat(snapshot);
    },
    toSnapshot(value) {
      return value.toString();
    },
    isTargetType(value) {
      const floatValue = Number.parseFloat(value);
 
      return min <= floatValue && floatValue <= max;
    },
    getValidationMessage(value) {
      if (this.isTargetType(value)) return "";
      return `Value ${value} is outside of range ${min}..${max}.`;
    },
  });
 
/**
 * Validates any string value againts CSS color rules.
 * Color value might be named, HEX, HSL(A), RGB(A).
 */
const CSSColor = types.custom<any, string>({
  name: "CSSColor",
  fromSnapshot(value) {
    return String(value);
  },
  toSnapshot(value) {
    return value.toString();
  },
  isTargetType(value) {
    const colorTester = new Option().style;
 
    colorTester.color = value;
    return colorTester.color !== "";
  },
  getValidationMessage(value) {
    if (this.isTargetType(value)) return "";
    return `Value ${value} doesn't appear to be a valid HEX color.`;
  },
});
 
export const customTypes = {
  range: Range,
  color: CSSColor,
};