@react-native-gpui/svg 0.0.0-stage → 15.15.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,8 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@react-native-gpui/svg` are listed here. Each version's section becomes the notes of its GitHub release.
4
+
5
+ ## 15.15.0-alpha.0 - 2026-11-01
6
+
7
+ - First release, for `react-native-svg` 15.15.x.
8
+ - Renders SVG elements with the desktop renderer.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Streetwriters
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,23 @@
1
- # Temporary Holding Version
1
+ # @react-native-gpui/svg
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Desktop support for [`react-native-svg`](https://github.com/software-mansion/react-native-svg): SVG elements drawn by the desktop renderer.
4
+
5
+ Part of [react-native-gpui](https://github.com/streetwriters/react-native-gpui), React Native for macOS, Windows and Linux.
6
+
7
+ ## Install
8
+
9
+ Install it next to `react-native-svg`:
10
+
11
+ ```sh
12
+ npm install react-native-svg@15.15.x @react-native-gpui/svg
13
+ ```
14
+
15
+ Keep using `react-native-svg` as you do on iOS and Android; its JavaScript API is unchanged. Autolinking builds the desktop side when the app is built.
16
+
17
+ ## Documentation
18
+
19
+ [Supported libraries](https://streetwriters.github.io/react-native-gpui/docs/supported-libraries)
20
+
21
+ ## License
22
+
23
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,8 @@
1
+ # SVG shared Fabric props/shadow-node descriptors are supplied by RN Codegen
2
+ # and react-native-svg's published common C++ shadow-node headers.
3
+ set(_svg_codegen_dir "${RN_GPUI_PROJECT_ROOT}/desktop/autolink/codegen/rnsvg")
4
+ set_property(GLOBAL APPEND PROPERTY RN_GPUI_PACKAGE_MODULE_SOURCES
5
+ "${CMAKE_CURRENT_LIST_DIR}/cpp/GpuiSvgModule.cpp")
6
+ set_property(GLOBAL APPEND PROPERTY RN_GPUI_PACKAGE_MODULE_INSTALLERS svg)
7
+ set_property(GLOBAL APPEND PROPERTY RN_GPUI_PACKAGE_MODULE_INCLUDE_DIRS
8
+ "${_svg_codegen_dir}")
@@ -0,0 +1,10 @@
1
+ [package]
2
+ name = "rn-gpui-svg"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+
6
+ [dependencies]
7
+ react-native-gpui = { version = "0.1" }
8
+ rn-gpui-sys = { version = "0.1" }
9
+ gpui = { version = "0.2" }
10
+ serde_json = "1"
@@ -0,0 +1,38 @@
1
+ //! Puts the C++ runtime's shared libraries on this crate's test binary rpath.
2
+ //!
3
+ //! `rn-gpui-svg`'s tests build gpui trees, which link `libjsi.dylib` and the rest
4
+ //! of the Node-API runtime. Core's `build.rs` emits
5
+ //! `cargo:rustc-link-arg=-Wl,-rpath,<dir>` for its own binary — the app — and that
6
+ //! flag is not inherited by a dependency's test binary, so the test process
7
+ //! aborted in dyld with `Library not loaded: @rpath/libjsi.dylib` before running a
8
+ //! single test.
9
+ //!
10
+ //! Core exports the directories it was given as `DEP_RN_GPUI_CORE_RPATHS`, which
11
+ //! is the same variable core's own `build.rs` reads. Re-emitting it here scopes
12
+ //! the flag to this crate's test binary, since `cargo:rustc-link-arg` without a
13
+ //! target suffix applies to the crate's own targets and not to the app that
14
+ //! depends on it.
15
+
16
+ fn main() {
17
+ println!("cargo:rerun-if-env-changed=DEP_RN_GPUI_CORE_RPATHS");
18
+ println!("cargo:rerun-if-changed=build.rs");
19
+
20
+ let Ok(dirs) = std::env::var("DEP_RN_GPUI_CORE_RPATHS") else {
21
+ return;
22
+ };
23
+ let dirs = dirs
24
+ .split('|')
25
+ .filter(|dir| !dir.is_empty())
26
+ .collect::<Vec<_>>();
27
+ if dirs.is_empty() {
28
+ return;
29
+ }
30
+ // MSVC and MinGW have no rpath, and the flag is rejected outright; Windows
31
+ // finds the DLLs through PATH, which the test runner already arranges.
32
+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
33
+ return;
34
+ }
35
+ for dir in dirs {
36
+ println!("cargo:rustc-link-arg=-Wl,-rpath,{dir}");
37
+ }
38
+ }
@@ -0,0 +1,141 @@
1
+ #include "GpuiModules.h"
2
+ #include "MountBatchBuilder.h"
3
+
4
+ #include <react/renderer/components/rnsvg/Props.h>
5
+
6
+ #include <folly/json.h>
7
+ #include <string>
8
+ #include <vector>
9
+
10
+ namespace rngpui {
11
+ using namespace facebook::react;
12
+
13
+ namespace {
14
+ constexpr const char* kSvgComponents[] = {
15
+ "RNSVGSvgView",
16
+ "RNSVGCircle",
17
+ "RNSVGEllipse",
18
+ "RNSVGLine",
19
+ "RNSVGPath",
20
+ "RNSVGRect",
21
+ "RNSVGGroup",
22
+ "RNSVGDefs",
23
+ "RNSVGClipPath",
24
+ "RNSVGLinearGradient",
25
+ "RNSVGRadialGradient",
26
+ "RNSVGText",
27
+ "RNSVGTSpan",
28
+ };
29
+
30
+ template <typename T>
31
+ folly::dynamic svgJsonValue(const T& value) {
32
+ return value;
33
+ }
34
+
35
+ folly::dynamic svgJsonValue(const Float& value) {
36
+ return value;
37
+ }
38
+ folly::dynamic svgJsonValue(const SharedColor& value) {
39
+ return value ? folly::dynamic(argb(value)) : folly::dynamic(nullptr);
40
+ }
41
+ folly::dynamic svgJsonValue(const std::vector<std::string>& values) {
42
+ folly::dynamic result = folly::dynamic::array();
43
+ for (const auto& value : values)
44
+ result.push_back(value);
45
+ return result;
46
+ }
47
+ folly::dynamic svgJsonValue(const std::vector<Float>& values) {
48
+ folly::dynamic result = folly::dynamic::array();
49
+ for (auto value : values)
50
+ result.push_back(value);
51
+ return result;
52
+ }
53
+
54
+ template <typename T>
55
+ folly::dynamic svgPropsJson(const T& props) {
56
+ folly::dynamic result = folly::dynamic::object();
57
+ #define RN_GPUI_COPY_SVG_PROP(name) \
58
+ if constexpr (requires { props.name; }) \
59
+ result[#name] = svgJsonValue(props.name)
60
+ RN_GPUI_COPY_SVG_PROP(name);
61
+ RN_GPUI_COPY_SVG_PROP(d);
62
+ RN_GPUI_COPY_SVG_PROP(x);
63
+ RN_GPUI_COPY_SVG_PROP(y);
64
+ RN_GPUI_COPY_SVG_PROP(x1);
65
+ RN_GPUI_COPY_SVG_PROP(y1);
66
+ RN_GPUI_COPY_SVG_PROP(x2);
67
+ RN_GPUI_COPY_SVG_PROP(y2);
68
+ RN_GPUI_COPY_SVG_PROP(cx);
69
+ RN_GPUI_COPY_SVG_PROP(cy);
70
+ RN_GPUI_COPY_SVG_PROP(r);
71
+ RN_GPUI_COPY_SVG_PROP(rx);
72
+ RN_GPUI_COPY_SVG_PROP(ry);
73
+ RN_GPUI_COPY_SVG_PROP(width);
74
+ RN_GPUI_COPY_SVG_PROP(height);
75
+ RN_GPUI_COPY_SVG_PROP(vbWidth);
76
+ RN_GPUI_COPY_SVG_PROP(vbHeight);
77
+ RN_GPUI_COPY_SVG_PROP(minX);
78
+ RN_GPUI_COPY_SVG_PROP(minY);
79
+ RN_GPUI_COPY_SVG_PROP(align);
80
+ RN_GPUI_COPY_SVG_PROP(meetOrSlice);
81
+ RN_GPUI_COPY_SVG_PROP(opacity);
82
+ RN_GPUI_COPY_SVG_PROP(color);
83
+ RN_GPUI_COPY_SVG_PROP(propList);
84
+ RN_GPUI_COPY_SVG_PROP(fill);
85
+ RN_GPUI_COPY_SVG_PROP(fillOpacity);
86
+ RN_GPUI_COPY_SVG_PROP(fillRule);
87
+ RN_GPUI_COPY_SVG_PROP(stroke);
88
+ RN_GPUI_COPY_SVG_PROP(strokeOpacity);
89
+ RN_GPUI_COPY_SVG_PROP(strokeWidth);
90
+ RN_GPUI_COPY_SVG_PROP(strokeLinecap);
91
+ RN_GPUI_COPY_SVG_PROP(strokeLinejoin);
92
+ RN_GPUI_COPY_SVG_PROP(strokeDasharray);
93
+ RN_GPUI_COPY_SVG_PROP(strokeDashoffset);
94
+ RN_GPUI_COPY_SVG_PROP(strokeMiterlimit);
95
+ RN_GPUI_COPY_SVG_PROP(matrix);
96
+ RN_GPUI_COPY_SVG_PROP(mask);
97
+ RN_GPUI_COPY_SVG_PROP(clipPath);
98
+ RN_GPUI_COPY_SVG_PROP(offset);
99
+ RN_GPUI_COPY_SVG_PROP(stopColor);
100
+ RN_GPUI_COPY_SVG_PROP(stopOpacity);
101
+ #undef RN_GPUI_COPY_SVG_PROP
102
+ return result;
103
+ }
104
+
105
+ folly::dynamic svgPropsJson(const std::string& component, const Props& props) {
106
+ #define RN_GPUI_SVG_PROPS(tag, type) \
107
+ if (component == tag) { \
108
+ if (auto typed = dynamic_cast<const type*>(&props)) \
109
+ return svgPropsJson(*typed); \
110
+ }
111
+ RN_GPUI_SVG_PROPS("RNSVGSvgView", RNSVGSvgViewProps)
112
+ RN_GPUI_SVG_PROPS("RNSVGCircle", RNSVGCircleProps)
113
+ RN_GPUI_SVG_PROPS("RNSVGEllipse", RNSVGEllipseProps)
114
+ RN_GPUI_SVG_PROPS("RNSVGLine", RNSVGLineProps)
115
+ RN_GPUI_SVG_PROPS("RNSVGPath", RNSVGPathProps)
116
+ RN_GPUI_SVG_PROPS("RNSVGRect", RNSVGRectProps)
117
+ RN_GPUI_SVG_PROPS("RNSVGGroup", RNSVGGroupProps)
118
+ RN_GPUI_SVG_PROPS("RNSVGDefs", RNSVGDefsProps)
119
+ RN_GPUI_SVG_PROPS("RNSVGClipPath", RNSVGClipPathProps)
120
+ RN_GPUI_SVG_PROPS("RNSVGLinearGradient", RNSVGLinearGradientProps)
121
+ RN_GPUI_SVG_PROPS("RNSVGRadialGradient", RNSVGRadialGradientProps)
122
+ RN_GPUI_SVG_PROPS("RNSVGText", RNSVGTextProps)
123
+ RN_GPUI_SVG_PROPS("RNSVGTSpan", RNSVGTSpanProps)
124
+ #undef RN_GPUI_SVG_PROPS
125
+ return folly::dynamic::object();
126
+ }
127
+
128
+ } // namespace
129
+
130
+ void rn_gpui_install_svg_module() {
131
+ for (const char* component : kSvgComponents) {
132
+ registerComponentProps(
133
+ component, [](const std::string& name, const ShadowView& view) {
134
+ if (!view.props)
135
+ return std::string("{}");
136
+ return folly::toJson(svgPropsJson(name, *view.props));
137
+ });
138
+ }
139
+ }
140
+
141
+ } // namespace rngpui
@@ -0,0 +1,465 @@
1
+ use gpui::{div, prelude::*, px, AnyElement, App, Window};
2
+ use react_native_gpui::extensions::{
3
+ register_component_renderer, ComponentNode, ComponentRenderer,
4
+ };
5
+ use rn_gpui_sys::ffi::RectF;
6
+ use std::collections::HashMap;
7
+ use std::hash::{Hash, Hasher};
8
+ use std::sync::{Arc, Mutex, OnceLock, Weak};
9
+
10
+ const COMPONENTS: &[&str] = &[
11
+ "RNSVGSvgView",
12
+ "RNSVGCircle",
13
+ "RNSVGEllipse",
14
+ "RNSVGLine",
15
+ "RNSVGPath",
16
+ "RNSVGRect",
17
+ "RNSVGGroup",
18
+ "RNSVGDefs",
19
+ "RNSVGClipPath",
20
+ "RNSVGLinearGradient",
21
+ "RNSVGRadialGradient",
22
+ "RNSVGText",
23
+ "RNSVGTSpan",
24
+ "RNSVGMask",
25
+ "RNSVGSymbol",
26
+ "RNSVGPattern",
27
+ "RNSVGMarker",
28
+ "RNSVGTextPath",
29
+ "RNSVGUse",
30
+ ];
31
+
32
+ struct SvgRenderer;
33
+
34
+ impl ComponentRenderer for SvgRenderer {
35
+ fn render(
36
+ &self,
37
+ node: &ComponentNode,
38
+ window: &mut Window,
39
+ cx: &mut App,
40
+ ) -> Option<AnyElement> {
41
+ if node.component != "RNSVGSvgView" {
42
+ return Some(div().into_any_element());
43
+ }
44
+ // The frame is in unscaled coordinates and this element is painted
45
+ // scaled, exactly as `ComponentRenderer::render` documents, so the box
46
+ // has to be scaled the same way core scales the element it would have
47
+ // built. `size_full()` sized the image to its parent instead: the
48
+ // document is rasterized at the window's scale factor, and an image
49
+ // carries no intrinsic size, so every SVG stretched to fill whatever
50
+ // surrounded it and painted over the text below it.
51
+ let frame = node.frame;
52
+ let (scale_x, scale_y) = node.scale;
53
+ let width = frame.w * scale_x;
54
+ let height = frame.h * scale_y;
55
+ let document = svg_document(node, frame, cx);
56
+ let scale = window.scale_factor();
57
+ let image = cached_svg_image(document, frame.w, frame.h, scale);
58
+ Some(
59
+ gpui::img(image)
60
+ .w(px(width))
61
+ .h(px(height))
62
+ .into_any_element(),
63
+ )
64
+ }
65
+ }
66
+
67
+ pub fn rn_gpui_register() {
68
+ for component in COMPONENTS {
69
+ register_component_renderer(*component, Arc::new(SvgRenderer));
70
+ }
71
+ }
72
+
73
+ fn svg_document(node: &ComponentNode, frame: RectF, cx: &App) -> String {
74
+ let props = &node.props;
75
+ let mut attributes = format!(
76
+ "xmlns=\"http://www.w3.org/2000/svg\" width=\"{}\" height=\"{}\"",
77
+ svg_number(frame.w),
78
+ svg_number(frame.h)
79
+ );
80
+ for (name, attribute) in [
81
+ ("color", "color"),
82
+ ("fill", "fill"),
83
+ ("stroke", "stroke"),
84
+ ("strokeWidth", "stroke-width"),
85
+ ("fillOpacity", "fill-opacity"),
86
+ ("strokeOpacity", "stroke-opacity"),
87
+ ("opacity", "opacity"),
88
+ ] {
89
+ if let Some(value) = props.get(name).filter(|value| !value.is_null()) {
90
+ if let Some(value) = svg_value(value) {
91
+ attributes.push_str(&format!(" {attribute}=\"{}\"", svg_escape(&value)));
92
+ }
93
+ }
94
+ }
95
+ if let Some(cap) = props
96
+ .get("strokeLinecap")
97
+ .and_then(serde_json::Value::as_i64)
98
+ {
99
+ let cap = ["butt", "round", "square"]
100
+ .get(cap as usize)
101
+ .copied()
102
+ .unwrap_or("butt");
103
+ attributes.push_str(&format!(" stroke-linecap=\"{cap}\""));
104
+ }
105
+ if let Some(join) = props
106
+ .get("strokeLinejoin")
107
+ .and_then(serde_json::Value::as_i64)
108
+ {
109
+ let join = ["miter", "round", "bevel"]
110
+ .get(join as usize)
111
+ .copied()
112
+ .unwrap_or("miter");
113
+ attributes.push_str(&format!(" stroke-linejoin=\"{join}\""));
114
+ }
115
+ if let (Some(width), Some(height)) = (
116
+ props.get("vbWidth").and_then(serde_json::Value::as_f64),
117
+ props.get("vbHeight").and_then(serde_json::Value::as_f64),
118
+ ) {
119
+ if width > 0.0 && height > 0.0 {
120
+ let min_x = props
121
+ .get("minX")
122
+ .and_then(serde_json::Value::as_f64)
123
+ .unwrap_or(0.0);
124
+ let min_y = props
125
+ .get("minY")
126
+ .and_then(serde_json::Value::as_f64)
127
+ .unwrap_or(0.0);
128
+ attributes.push_str(&format!(
129
+ " viewBox=\"{} {} {} {}\"",
130
+ svg_number(min_x as f32),
131
+ svg_number(min_y as f32),
132
+ svg_number(width as f32),
133
+ svg_number(height as f32)
134
+ ));
135
+ if let Some(align) = props.get("align").and_then(serde_json::Value::as_str) {
136
+ let mode = match props
137
+ .get("meetOrSlice")
138
+ .and_then(serde_json::Value::as_i64)
139
+ .unwrap_or(0)
140
+ {
141
+ 1 => "slice",
142
+ 2 => "none",
143
+ _ => "meet",
144
+ };
145
+ attributes.push_str(&format!(
146
+ " preserveAspectRatio=\"{} {}\"",
147
+ svg_escape(align),
148
+ mode
149
+ ));
150
+ }
151
+ }
152
+ }
153
+ let mut document = format!("<svg {attributes}>");
154
+ for child in &node.children {
155
+ svg_node(child, cx, &mut document);
156
+ }
157
+ document.push_str("</svg>");
158
+ document
159
+ }
160
+
161
+ fn svg_node(node: &ComponentNode, cx: &App, output: &mut String) {
162
+ let props = &node.props;
163
+ let element = match node.component.as_str() {
164
+ "RNSVGCircle" => "circle",
165
+ "RNSVGEllipse" => "ellipse",
166
+ "RNSVGLine" => "line",
167
+ "RNSVGPath" => "path",
168
+ "RNSVGRect" => "rect",
169
+ "RNSVGGroup" => "g",
170
+ "RNSVGDefs" => "defs",
171
+ "RNSVGClipPath" => "clipPath",
172
+ "RNSVGLinearGradient" => "linearGradient",
173
+ "RNSVGRadialGradient" => "radialGradient",
174
+ "RNSVGMask" => "mask",
175
+ "RNSVGSymbol" => "symbol",
176
+ "RNSVGPattern" => "pattern",
177
+ "RNSVGMarker" => "marker",
178
+ "RNSVGText" => "text",
179
+ "RNSVGTSpan" => "tspan",
180
+ "RNSVGTextPath" => "textPath",
181
+ "RNSVGUse" => "use",
182
+ _ => "",
183
+ };
184
+ if element.is_empty() {
185
+ for child in &node.children {
186
+ svg_node(child, cx, output);
187
+ }
188
+ return;
189
+ }
190
+ let mut attributes = String::new();
191
+ for name in [
192
+ "id",
193
+ "name",
194
+ "href",
195
+ "d",
196
+ "x",
197
+ "y",
198
+ "x1",
199
+ "y1",
200
+ "x2",
201
+ "y2",
202
+ "cx",
203
+ "cy",
204
+ "r",
205
+ "rx",
206
+ "ry",
207
+ "width",
208
+ "height",
209
+ "color",
210
+ "fill",
211
+ "stroke",
212
+ "strokeWidth",
213
+ "fillOpacity",
214
+ "strokeOpacity",
215
+ "strokeDasharray",
216
+ "strokeDashoffset",
217
+ "strokeMiterlimit",
218
+ "opacity",
219
+ "fontSize",
220
+ "fontWeight",
221
+ "fontFamily",
222
+ "textLength",
223
+ "dominantBaseline",
224
+ "offset",
225
+ "stopColor",
226
+ "stopOpacity",
227
+ ] {
228
+ if !svg_property_is_set(props, name) {
229
+ continue;
230
+ }
231
+ if let Some(value) = props.get(name) {
232
+ let attribute = match name {
233
+ "strokeWidth" => "stroke-width",
234
+ "fillOpacity" => "fill-opacity",
235
+ "strokeOpacity" => "stroke-opacity",
236
+ "strokeDasharray" => "stroke-dasharray",
237
+ "strokeDashoffset" => "stroke-dashoffset",
238
+ "strokeMiterlimit" => "stroke-miterlimit",
239
+ "fontSize" => "font-size",
240
+ "fontWeight" => "font-weight",
241
+ "fontFamily" => "font-family",
242
+ "dominantBaseline" => "dominant-baseline",
243
+ "stopColor" => "stop-color",
244
+ "stopOpacity" => "stop-opacity",
245
+ other => other,
246
+ };
247
+ let value = if value.is_null() && matches!(name, "fill" | "stroke") {
248
+ Some("none".to_owned())
249
+ } else {
250
+ svg_value(value)
251
+ };
252
+ if let Some(value) = value {
253
+ attributes.push_str(&format!(" {attribute}=\"{}\"", svg_escape(&value)));
254
+ }
255
+ }
256
+ }
257
+ if let Some(rule) = props
258
+ .get("fillRule")
259
+ .filter(|_| svg_property_is_set(props, "fillRule"))
260
+ .and_then(serde_json::Value::as_i64)
261
+ {
262
+ attributes.push_str(&format!(
263
+ " fill-rule=\"{}\"",
264
+ if rule == 0 { "evenodd" } else { "nonzero" }
265
+ ));
266
+ }
267
+ if let Some(cap) = props
268
+ .get("strokeLinecap")
269
+ .filter(|_| svg_property_is_set(props, "strokeLinecap"))
270
+ .and_then(serde_json::Value::as_i64)
271
+ {
272
+ let cap = ["butt", "round", "square"]
273
+ .get(cap as usize)
274
+ .copied()
275
+ .unwrap_or("butt");
276
+ attributes.push_str(&format!(" stroke-linecap=\"{cap}\""));
277
+ }
278
+ if let Some(join) = props
279
+ .get("strokeLinejoin")
280
+ .filter(|_| svg_property_is_set(props, "strokeLinejoin"))
281
+ .and_then(serde_json::Value::as_i64)
282
+ {
283
+ let join = ["miter", "round", "bevel"]
284
+ .get(join as usize)
285
+ .copied()
286
+ .unwrap_or("miter");
287
+ attributes.push_str(&format!(" stroke-linejoin=\"{join}\""));
288
+ }
289
+ if let Some(matrix) = props.get("matrix").and_then(serde_json::Value::as_array) {
290
+ if matrix.len() >= 16 {
291
+ let values = [0, 1, 4, 5, 12, 13].map(|index| matrix[index].as_f64().unwrap_or(0.0));
292
+ attributes.push_str(&format!(
293
+ " transform=\"matrix({} {} {} {} {} {})\"",
294
+ values[0], values[1], values[2], values[3], values[4], values[5]
295
+ ));
296
+ }
297
+ }
298
+ output.push('<');
299
+ output.push_str(element);
300
+ output.push_str(&attributes);
301
+ output.push('>');
302
+ for child in &node.children {
303
+ svg_node(child, cx, output);
304
+ }
305
+ output.push_str("</");
306
+ output.push_str(element);
307
+ output.push('>');
308
+ }
309
+
310
+ fn svg_property_is_set(props: &serde_json::Value, name: &str) -> bool {
311
+ if !matches!(
312
+ name,
313
+ "fill"
314
+ | "fillOpacity"
315
+ | "fillRule"
316
+ | "stroke"
317
+ | "strokeWidth"
318
+ | "strokeOpacity"
319
+ | "strokeLinecap"
320
+ | "strokeLinejoin"
321
+ | "strokeDasharray"
322
+ | "strokeDashoffset"
323
+ | "strokeMiterlimit"
324
+ ) {
325
+ return true;
326
+ }
327
+ props
328
+ .get("propList")
329
+ .and_then(serde_json::Value::as_array)
330
+ .is_none_or(|properties| {
331
+ properties
332
+ .iter()
333
+ .any(|property| property.as_str() == Some(name))
334
+ })
335
+ }
336
+
337
+ fn svg_value(value: &serde_json::Value) -> Option<String> {
338
+ match value.get("type").and_then(serde_json::Value::as_i64) {
339
+ Some(1) => {
340
+ return value
341
+ .get("brushRef")
342
+ .and_then(serde_json::Value::as_str)
343
+ .map(|id| format!("url(#{id})"))
344
+ }
345
+ Some(2) => return Some("currentColor".to_owned()),
346
+ Some(3) => return Some("context-fill".to_owned()),
347
+ Some(4) => return Some("context-stroke".to_owned()),
348
+ _ => {}
349
+ }
350
+
351
+ if let Some(number) = value.as_f64() {
352
+ if number < 0.0 && number.fract() == 0.0 {
353
+ return Some(format!("#{:06x}", (number as i64 as u32) & 0x00ff_ffff));
354
+ }
355
+ if (0x0100_0000..=0xffff_ffff).contains(&(number as u64)) {
356
+ let argb = number as u32;
357
+ return Some(format!(
358
+ "rgba({}, {}, {}, {})",
359
+ (argb >> 16) & 0xff,
360
+ (argb >> 8) & 0xff,
361
+ argb & 0xff,
362
+ ((argb >> 24) & 0xff) as f32 / 255.0
363
+ ));
364
+ }
365
+ return Some(svg_number(number as f32));
366
+ }
367
+ if let Some(value) = value.as_str() {
368
+ return Some(value.to_owned());
369
+ }
370
+ if let Some(value) = value.as_array() {
371
+ return Some(
372
+ value
373
+ .iter()
374
+ .filter_map(svg_value)
375
+ .collect::<Vec<_>>()
376
+ .join(" "),
377
+ );
378
+ }
379
+ value
380
+ .get("payload")
381
+ .and_then(svg_value)
382
+ .or_else(|| value.get("value").and_then(svg_value))
383
+ }
384
+
385
+ fn svg_escape(value: &str) -> String {
386
+ value
387
+ .replace('&', "&amp;")
388
+ .replace('"', "&quot;")
389
+ .replace('<', "&lt;")
390
+ .replace('>', "&gt;")
391
+ }
392
+
393
+ fn svg_number(value: f32) -> String {
394
+ if value.fract() == 0.0 {
395
+ format!("{value:.0}")
396
+ } else {
397
+ value.to_string()
398
+ }
399
+ }
400
+
401
+ fn cached_svg_image(
402
+ document: String,
403
+ width: f32,
404
+ height: f32,
405
+ scale: f32,
406
+ ) -> std::sync::Arc<gpui::Image> {
407
+ type SvgCache = HashMap<(u64, u32, u32, u32), Weak<gpui::Image>>;
408
+ static CACHE: OnceLock<Mutex<SvgCache>> = OnceLock::new();
409
+ let mut hasher = std::collections::hash_map::DefaultHasher::new();
410
+ document.hash(&mut hasher);
411
+ let key = (
412
+ hasher.finish(),
413
+ width.to_bits(),
414
+ height.to_bits(),
415
+ scale.to_bits(),
416
+ );
417
+ let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
418
+ let mut cache = cache
419
+ .lock()
420
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
421
+ if let Some(image) = cache.get(&key).and_then(Weak::upgrade) {
422
+ return image;
423
+ }
424
+ let image = std::sync::Arc::new(gpui::Image::from_bytes(
425
+ gpui::ImageFormat::Svg,
426
+ document.into_bytes(),
427
+ ));
428
+ cache.insert(key, std::sync::Arc::downgrade(&image));
429
+ if cache.len() > 512 {
430
+ cache.retain(|_, image| image.strong_count() > 0);
431
+ }
432
+ image
433
+ }
434
+
435
+ #[cfg(test)]
436
+ mod svg_paint_tests {
437
+ use super::{svg_property_is_set, svg_value};
438
+ use serde_json::json;
439
+
440
+ #[test]
441
+ fn brushes_keep_current_color_and_reference_semantics() {
442
+ assert_eq!(
443
+ svg_value(&json!({"type": 2})).as_deref(),
444
+ Some("currentColor")
445
+ );
446
+ assert_eq!(
447
+ svg_value(&json!({"type": 1, "brushRef": "gradient"})).as_deref(),
448
+ Some("url(#gradient)")
449
+ );
450
+ assert_eq!(
451
+ svg_value(&json!({"type": 0, "payload": 0xff64d2ff_u32})).as_deref(),
452
+ Some("rgba(100, 210, 255, 1)")
453
+ );
454
+ }
455
+
456
+ #[test]
457
+ fn default_black_fill_does_not_override_inherited_none() {
458
+ let child = json!({"fill": {"type": 0, "payload": 0xff000000_u32}, "strokeLinecap": 0, "propList": []});
459
+ assert!(!svg_property_is_set(&child, "fill"));
460
+ assert!(!svg_property_is_set(&child, "strokeLinecap"));
461
+ let group = json!({"fill": null, "stroke": {"type": 2}, "propList": ["fill", "stroke"]});
462
+ assert!(svg_property_is_set(&group, "fill"));
463
+ assert!(svg_property_is_set(&group, "stroke"));
464
+ }
465
+ }
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@react-native-gpui/svg",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "15.15.0-alpha.0",
4
+ "description": "GPUI Fabric renderer adapter for react-native-svg",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/streetwriters/react-native-gpui.git",
9
+ "directory": "modules/svg"
10
+ },
11
+ "homepage": "https://streetwriters.github.io/react-native-gpui/",
12
+ "bugs": {
13
+ "url": "https://github.com/streetwriters/react-native-gpui/issues"
14
+ },
15
+ "files": [
16
+ "desktop",
17
+ "react-native.config.js",
18
+ "CHANGELOG.md",
19
+ "!**/*.test.js",
20
+ "!**/*.test.mjs",
21
+ "!**/*.test.ts",
22
+ "!**/*.test.cjs"
23
+ ],
24
+ "peerDependencies": {
25
+ "react-native": "0.87.x",
26
+ "react-native-svg": "15.15.x"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public",
30
+ "tag": "latest"
31
+ }
32
+ }
@@ -0,0 +1,51 @@
1
+ module.exports = {
2
+ dependency: {
3
+ platforms: {
4
+ desktop: {
5
+ cmake: 'desktop',
6
+ crate: 'rn-gpui-svg',
7
+ componentCodegenPackage: 'react-native-svg',
8
+ componentSourcePackage: 'react-native-svg',
9
+ componentDescriptors: [
10
+ 'RNSVGCircleComponentDescriptor',
11
+ 'RNSVGClipPathComponentDescriptor',
12
+ 'RNSVGDefsComponentDescriptor',
13
+ 'RNSVGFeBlendComponentDescriptor',
14
+ 'RNSVGFeColorMatrixComponentDescriptor',
15
+ 'RNSVGFeCompositeComponentDescriptor',
16
+ 'RNSVGFeFloodComponentDescriptor',
17
+ 'RNSVGFeGaussianBlurComponentDescriptor',
18
+ 'RNSVGFeMergeComponentDescriptor',
19
+ 'RNSVGFeOffsetComponentDescriptor',
20
+ 'RNSVGFilterComponentDescriptor',
21
+ 'RNSVGEllipseComponentDescriptor',
22
+ 'RNSVGForeignObjectComponentDescriptor',
23
+ 'RNSVGGroupComponentDescriptor',
24
+ 'RNSVGLinearGradientComponentDescriptor',
25
+ 'RNSVGLineComponentDescriptor',
26
+ 'RNSVGMarkerComponentDescriptor',
27
+ 'RNSVGMaskComponentDescriptor',
28
+ 'RNSVGPathComponentDescriptor',
29
+ 'RNSVGPatternComponentDescriptor',
30
+ 'RNSVGRadialGradientComponentDescriptor',
31
+ 'RNSVGRectComponentDescriptor',
32
+ 'RNSVGSymbolComponentDescriptor',
33
+ 'RNSVGTextComponentDescriptor',
34
+ 'RNSVGTextPathComponentDescriptor',
35
+ 'RNSVGTSpanComponentDescriptor',
36
+ 'RNSVGUseComponentDescriptor',
37
+ 'RNSVGSvgViewComponentDescriptor',
38
+ ],
39
+ componentHeaders: [
40
+ 'react/renderer/components/rnsvg/ComponentDescriptors.h',
41
+ 'react/renderer/components/rnsvg/RNSVGComponentDescriptors.h',
42
+ ],
43
+ componentIncludeDirs: ['common/cpp'],
44
+ componentSources: [
45
+ 'common/cpp/react/renderer/components/rnsvg/RNSVGShadowNodes.cpp',
46
+ 'common/cpp/react/renderer/components/rnsvg/RNSVGLayoutableShadowNode.cpp',
47
+ ],
48
+ },
49
+ },
50
+ },
51
+ };