@builder.io/sdk-react-native 0.0.1-57 → 0.0.1-58

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.
@@ -1,84 +0,0 @@
1
- import * as React from "react";
2
- import { View, StyleSheet, Image, Text } from "react-native";
3
-
4
- interface CustomFont {
5
- family?: string;
6
- kind?: string;
7
- fileUrl?: string;
8
- files?: {
9
- [key: string]: string;
10
- };
11
- }
12
- interface Props {
13
- cssCode?: string;
14
- customFonts?: CustomFont[];
15
- }
16
-
17
- import RenderInlinedStyles from "../../render-inlined-styles.lite";
18
-
19
- export default function RenderContentStyles(props: Props) {
20
- function getCssFromFont(font) {
21
- // TODO: compute what font sizes are used and only load those.......
22
- const family =
23
- font.family +
24
- (font.kind && !font.kind.includes("#") ? ", " + font.kind : "");
25
- const name = family.split(",")[0];
26
- const url = font.fileUrl ?? font?.files?.regular;
27
- let str = "";
28
-
29
- if (url && family && name) {
30
- str += `
31
- @font-face {
32
- font-family: "${family}";
33
- src: local("${name}"), url('${url}') format('woff2');
34
- font-display: fallback;
35
- font-weight: 400;
36
- }
37
- `.trim();
38
- }
39
-
40
- if (font.files) {
41
- for (const weight in font.files) {
42
- const isNumber = String(Number(weight)) === weight;
43
-
44
- if (!isNumber) {
45
- continue;
46
- } // TODO: maybe limit number loaded
47
-
48
- const weightUrl = font.files[weight];
49
-
50
- if (weightUrl && weightUrl !== url) {
51
- str += `
52
- @font-face {
53
- font-family: "${family}";
54
- src: url('${weightUrl}') format('woff2');
55
- font-display: fallback;
56
- font-weight: ${weight};
57
- }
58
- `.trim();
59
- }
60
- }
61
- }
62
-
63
- return str;
64
- }
65
-
66
- function getFontCss({ customFonts }) {
67
- // TODO: flag for this
68
- // if (!builder.allowCustomFonts) {
69
- // return '';
70
- // }
71
- // TODO: separate internal data from external
72
- return customFonts?.map((font) => getCssFromFont(font))?.join(" ") || "";
73
- }
74
-
75
- function injectedStyles() {
76
- return `
77
- ${props.cssCode || ""}
78
- ${getFontCss({
79
- customFonts: props.customFonts,
80
- })}`;
81
- }
82
-
83
- return <RenderInlinedStyles styles={injectedStyles()} />;
84
- }
@@ -1,310 +0,0 @@
1
- import * as React from "react";
2
- import { View, StyleSheet, Image, Text } from "react-native";
3
- import { useState, useContext, useEffect } from "react";
4
-
5
- export type RenderContentProps = {
6
- content?: BuilderContent;
7
- model?: string;
8
- data?: {
9
- [key: string]: any;
10
- };
11
- context?: {
12
- [key: string]: any;
13
- };
14
- apiKey: string;
15
- customComponents?: RegisteredComponent[];
16
- };
17
- interface BuilderComponentStateChange {
18
- state: {
19
- [key: string]: any;
20
- };
21
- ref: {
22
- name?: string;
23
- props?: {
24
- builderBlock?: {
25
- id?: string;
26
- };
27
- };
28
- };
29
- }
30
-
31
- import { getDefaultRegisteredComponents } from "../../constants/builder-registered-components.js";
32
- import { TARGET } from "../../constants/target.js";
33
- import BuilderContext from "../../context/builder.context";
34
- import { evaluate } from "../../functions/evaluate.js";
35
- import {
36
- convertSearchParamsToQueryObject,
37
- getBuilderSearchParams,
38
- } from "../../functions/get-builder-search-params/index.js";
39
- import { getContent } from "../../functions/get-content/index.js";
40
- import { getFetch } from "../../functions/get-fetch.js";
41
- import { isBrowser } from "../../functions/is-browser.js";
42
- import { isEditing } from "../../functions/is-editing.js";
43
- import { isPreviewing } from "../../functions/is-previewing.js";
44
- import { previewingModelName } from "../../functions/previewing-model-name.js";
45
- import {
46
- components,
47
- createRegisterComponentMessage,
48
- } from "../../functions/register-component.js";
49
- import { track } from "../../functions/track.js";
50
- import RenderBlocks from "../render-blocks.lite";
51
- import RenderContentStyles from "./components/render-styles.lite";
52
-
53
- export default function RenderContent(props: RenderContentProps) {
54
- function useContent() {
55
- const mergedContent = {
56
- ...props.content,
57
- ...overrideContent,
58
- data: { ...props.content?.data, ...props.data, ...overrideContent?.data },
59
- };
60
- return mergedContent;
61
- }
62
-
63
- const [overrideContent, setOverrideContent] = useState(() => null);
64
-
65
- const [update, setUpdate] = useState(() => 0);
66
-
67
- const [overrideState, setOverrideState] = useState(() => ({}));
68
-
69
- function contentState() {
70
- return { ...props.content?.data?.state, ...props.data, ...overrideState };
71
- }
72
-
73
- function context() {
74
- return {};
75
- }
76
-
77
- function allRegisteredComponents() {
78
- const allComponentsArray = [
79
- ...getDefaultRegisteredComponents(), // While this `components` object is deprecated, we must maintain support for it.
80
- // Since users are able to override our default components, we need to make sure that we do not break such
81
- // existing usage.
82
- // This is why we spread `components` after the default Builder.io components, but before the `props.customComponents`,
83
- // which is the new standard way of providing custom components, and must therefore take precedence.
84
- ...components,
85
- ...(props.customComponents || []),
86
- ];
87
- const allComponents = allComponentsArray.reduce(
88
- (acc, curr) => ({ ...acc, [curr.name]: curr }),
89
- {}
90
- );
91
- return allComponents;
92
- }
93
-
94
- function processMessage(event) {
95
- const { data } = event;
96
-
97
- if (data) {
98
- switch (data.type) {
99
- case "builder.contentUpdate": {
100
- const messageContent = data.data;
101
- const key =
102
- messageContent.key ||
103
- messageContent.alias ||
104
- messageContent.entry ||
105
- messageContent.modelName;
106
- const contentData = messageContent.data;
107
-
108
- if (key === props.model) {
109
- setOverrideContent(contentData);
110
- }
111
-
112
- break;
113
- }
114
-
115
- case "builder.patchUpdates": {
116
- // TODO
117
- break;
118
- }
119
- }
120
- }
121
- }
122
-
123
- function evaluateJsCode() {
124
- // run any dynamic JS code attached to content
125
- const jsCode = useContent?.()?.data?.jsCode;
126
-
127
- if (jsCode) {
128
- evaluate({
129
- code: jsCode,
130
- context: context(),
131
- state: contentState(),
132
- });
133
- }
134
- }
135
-
136
- function httpReqsData() {
137
- return {};
138
- }
139
-
140
- function evalExpression(expression) {
141
- return expression.replace(/{{([^}]+)}}/g, (_match, group) =>
142
- evaluate({
143
- code: group,
144
- context: context(),
145
- state: contentState(),
146
- })
147
- );
148
- }
149
-
150
- function handleRequest({ url, key }) {
151
- const fetchAndSetState = async () => {
152
- const fetch = await getFetch();
153
- const response = await fetch(url);
154
- const json = await response.json();
155
- const newOverrideState = { ...overrideState, [key]: json };
156
- setOverrideState(newOverrideState);
157
- };
158
-
159
- fetchAndSetState();
160
- }
161
-
162
- function runHttpRequests() {
163
- const requests = useContent?.()?.data?.httpRequests ?? {};
164
- Object.entries(requests).forEach(([key, url]) => {
165
- if (url && (!httpReqsData()[key] || isEditing())) {
166
- const evaluatedUrl = evalExpression(url);
167
- handleRequest({
168
- url: evaluatedUrl,
169
- key,
170
- });
171
- }
172
- });
173
- }
174
-
175
- function emitStateUpdate() {
176
- if (isEditing()) {
177
- window.dispatchEvent(
178
- new CustomEvent("builder:component:stateChange", {
179
- detail: {
180
- state: contentState(),
181
- ref: {
182
- name: props.model,
183
- },
184
- },
185
- })
186
- );
187
- }
188
- }
189
-
190
- useEffect(() => {
191
- if (isBrowser()) {
192
- if (isEditing()) {
193
- Object.values(allRegisteredComponents()).forEach(
194
- (registeredComponent) => {
195
- const message = createRegisterComponentMessage(registeredComponent);
196
- window.parent?.postMessage(message, "*");
197
- }
198
- );
199
- window.addEventListener("message", processMessage);
200
- window.addEventListener(
201
- "builder:component:stateChangeListenerActivated",
202
- emitStateUpdate
203
- );
204
- }
205
-
206
- if (useContent()) {
207
- track("impression", {
208
- contentId: useContent().id,
209
- });
210
- } // override normal content in preview mode
211
-
212
- if (isPreviewing()) {
213
- if (props.model && previewingModelName() === props.model) {
214
- const currentUrl = new URL(location.href);
215
- const previewApiKey = currentUrl.searchParams.get("apiKey");
216
-
217
- if (previewApiKey) {
218
- getContent({
219
- model: props.model,
220
- apiKey: previewApiKey,
221
- options: getBuilderSearchParams(
222
- convertSearchParamsToQueryObject(currentUrl.searchParams)
223
- ),
224
- }).then((content) => {
225
- if (content) {
226
- setOverrideContent(content);
227
- }
228
- });
229
- }
230
- }
231
- }
232
-
233
- evaluateJsCode();
234
- runHttpRequests();
235
- emitStateUpdate();
236
- }
237
- }, []);
238
-
239
- useEffect(() => {
240
- evaluateJsCode();
241
- }, [useContent?.()?.data?.jsCode]);
242
- useEffect(() => {
243
- runHttpRequests();
244
- }, [useContent?.()?.data?.httpRequests]);
245
- useEffect(() => {
246
- emitStateUpdate();
247
- }, [contentState()]);
248
-
249
- useEffect(() => {
250
- return () => {
251
- if (isBrowser()) {
252
- window.removeEventListener("message", processMessage);
253
- window.removeEventListener(
254
- "builder:component:stateChangeListenerActivated",
255
- emitStateUpdate
256
- );
257
- }
258
- };
259
- }, []);
260
-
261
- return (
262
- <BuilderContext.Provider
263
- value={{
264
- get content() {
265
- return useContent();
266
- },
267
-
268
- get state() {
269
- return contentState();
270
- },
271
-
272
- get context() {
273
- return context();
274
- },
275
-
276
- get apiKey() {
277
- return props.apiKey;
278
- },
279
-
280
- get registeredComponents() {
281
- return allRegisteredComponents();
282
- },
283
- }}
284
- >
285
- {useContent() ? (
286
- <>
287
- <View
288
- onClick={(event) =>
289
- track("click", {
290
- contentId: useContent().id,
291
- })
292
- }
293
- data-builder-content-id={useContent?.()?.id}
294
- >
295
- {(useContent?.()?.data?.cssCode ||
296
- useContent?.()?.data?.customFonts?.length) &&
297
- TARGET !== "reactNative" ? (
298
- <RenderContentStyles
299
- cssCode={useContent().data.cssCode}
300
- customFonts={useContent().data.customFonts}
301
- />
302
- ) : null}
303
-
304
- <RenderBlocks blocks={useContent?.()?.data?.blocks} />
305
- </View>
306
- </>
307
- ) : null}
308
- </BuilderContext.Provider>
309
- );
310
- }
@@ -1,36 +0,0 @@
1
- import * as React from "react";
2
- import { View, StyleSheet, Image, Text } from "react-native";
3
-
4
- interface Props {
5
- styles: string;
6
- }
7
-
8
- import { TARGET } from "../constants/target.js";
9
-
10
- export default function RenderInlinedStyles(props: Props) {
11
- function injectedStyleScript() {
12
- return `<${tagName()}>${props.styles}</${tagName()}>`;
13
- }
14
-
15
- function tagName() {
16
- // NOTE: we have to obfusctate the name of the tag due to a limitation in the svelte-preprocessor plugin.
17
- // https://github.com/sveltejs/vite-plugin-svelte/issues/315#issuecomment-1109000027
18
- return "sty" + "le";
19
- }
20
-
21
- const TagNameRef = tagName();
22
-
23
- return (
24
- <>
25
- {TARGET === "svelte" ? (
26
- <>
27
- <View dangerouslySetInnerHTML={{ __html: injectedStyleScript() }} />
28
- </>
29
- ) : (
30
- <TagNameRef>
31
- <Text>{props.styles}</Text>
32
- </TagNameRef>
33
- )}
34
- </>
35
- );
36
- }