UNPKG

2.21 kBtext/x-cView Raw
1/**
2 * Copyright (c) Facebook, Inc. and its affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8#pragma once
9
10#include <folly/Optional.h>
11#include <folly/dynamic.h>
12#include <react/core/RawProps.h>
13#include <react/graphics/Color.h>
14#include <react/graphics/Geometry.h>
15#include <react/graphics/conversions.h>
16
17namespace facebook {
18namespace react {
19
20template <typename T>
21void fromRawValue(const RawValue &rawValue, T &result) {
22 result = (T)rawValue;
23}
24
25template <typename T>
26void fromRawValue(const RawValue &rawValue, std::vector<T> &result) {
27 if (rawValue.hasType<std::vector<RawValue>>()) {
28 auto items = (std::vector<RawValue>)rawValue;
29 auto length = items.size();
30 result.clear();
31 result.reserve(length);
32 for (int i = 0; i < length; i++) {
33 T itemResult;
34 fromRawValue(items.at(i), itemResult);
35 result.push_back(itemResult);
36 }
37 return;
38 }
39
40 // The case where `value` is not an array.
41 result.clear();
42 result.reserve(1);
43 T itemResult;
44 fromRawValue(rawValue, itemResult);
45 result.push_back(itemResult);
46}
47
48template <typename T>
49T convertRawProp(
50 const RawProps &rawProps,
51 const std::string &name,
52 const T &sourceValue,
53 const T &defaultValue = T()) {
54 const auto rawValue = rawProps.at(name);
55
56 if (!rawValue) {
57 return sourceValue;
58 }
59
60 // Special case: `null` always means `the prop was removed, use default
61 // value`.
62 if (!rawValue->hasValue()) {
63 return defaultValue;
64 }
65
66 T result;
67 fromRawValue(*rawValue, result);
68 return result;
69}
70
71template <typename T>
72static folly::Optional<T> convertRawProp(
73 const RawProps &rawProps,
74 const std::string &name,
75 const folly::Optional<T> &sourceValue,
76 const folly::Optional<T> &defaultValue = {}) {
77 const auto rawValue = rawProps.at(name);
78
79 if (!rawValue) {
80 return sourceValue;
81 }
82
83 // Special case: `null` always means `the prop was removed, use default
84 // value`.
85 if (!rawValue->hasValue()) {
86 return defaultValue;
87 }
88
89 T result;
90 fromRawValue(*rawValue, result);
91 return folly::Optional<T>{result};
92}
93
94} // namespace react
95} // namespace facebook