@weaverse/react 0.1.7 → 0.1.8

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/src/core.ts DELETED
@@ -1,274 +0,0 @@
1
- // TODO: Implement Weaverse SDK class
2
- import fetch from 'isomorphic-unfetch'
3
- import {isBrowser} from './utils'
4
-
5
-
6
- export interface ProjectDataItemType {
7
- type: string
8
- name: string
9
- id: string | number
10
- }
11
-
12
- export interface ProjectDataType {
13
- items: ProjectDataItemType[]
14
- }
15
-
16
- // const isSheetAccessible = (sheet: CSSStyleSheet) => {
17
- // if (sheet.href && !sheet.href.startsWith(location.origin)) {
18
- // return false
19
- // }
20
- //
21
- // try {
22
- // sheet.cssRules
23
- // return true
24
- // } catch (e) {
25
- // return false
26
- // }
27
- // }
28
-
29
- // export class WeaverseStyle {
30
- // public styleSheets: StyleSheetList
31
- // public document: Document
32
- //
33
- // constructor(root: Document) {
34
- // this.document = root
35
- // this.styleSheets = this.document.styleSheets
36
- // }
37
- //
38
- // // Create styleSheet instance that work both on client and server side
39
- // createSheet = (root?: Document) => {
40
- // let sheetInstance: any = null
41
- //
42
- // const reset = () => {
43
- // const sheets = Object(root).styleSheets || []
44
- // // iterate all stylesheets until a hydratable stylesheet is found
45
- // for (const sheet of sheets) {
46
- // if (!isSheetAccessible(sheet)) continue
47
- //
48
- // for (let index = 0, rules = sheet.cssRules; rules[index]; ++index) {
49
- // // /** @type {CSSStyleRule} Possible indicator rule. */
50
- // const check = Object(rules[index])
51
- // if (check.selectorText && check.selectorText.includes('@media')) {
52
- // if (!sheetInstance) sheetInstance = {sheet, reset, rules: sheet.cssRules}
53
- // break
54
- // }
55
- //
56
- // }
57
- //
58
- // // if a hydratable stylesheet is found, stop looking
59
- // if (sheetInstance) break
60
- // }
61
- // // if no hydratable stylesheet is found
62
- // if (!sheetInstance) {
63
- // const createCSSMediaRule = (sourceCssText: string) => {
64
- // let rule: any = {
65
- // cssRules: [],
66
- // insertRule(cssText: string, index: number) {
67
- // this.cssRules.splice(index, 0, createCSSMediaRule(cssText))
68
- // },
69
- // get cssText() {
70
- // return sourceCssText === '@media{}' ? `@media{${[].map.call(this.cssRules, (cssRule: any) => cssRule.cssText).join('')}}` : sourceCssText
71
- // }
72
- // }
73
- // return rule
74
- // }
75
- //
76
- // sheetInstance = {
77
- // sheet: root ? (root.head || root).appendChild(root.createElement('style')).sheet : createCSSMediaRule(''),
78
- // rules: {},
79
- // reset,
80
- // toString() {
81
- // const {cssRules} = sheetInstance.sheet
82
- // return [].map
83
- // .call(cssRules, (cssMediaRule: CSSMediaRule, cssRuleIndex) => {
84
- // const {cssText} = cssMediaRule
85
- //
86
- // let lastRuleCssText = ''
87
- // if (cssRules[cssRuleIndex - 1]) {
88
- // if (!cssMediaRule.cssRules.length) return ''
89
- //
90
- // for (const name in sheetInstance.rules) {
91
- // if (sheetInstance.rules[name].group === cssMediaRule) {
92
- // return `--sxs{--sxs:${[...sheetInstance.rules[name].cache].join(' ')}}${cssText}`
93
- // }
94
- // }
95
- //
96
- // return cssMediaRule.cssRules.length ? `${lastRuleCssText}${cssText}` : ''
97
- // }
98
- //
99
- // return cssText
100
- // })
101
- // .join('')
102
- // }
103
- // }
104
- // }
105
- // }
106
- //
107
- // }
108
- //
109
- // }
110
-
111
- export type WeaverseType = {
112
- [key: string]: any
113
- appUrl?: string,
114
- projectKey?: string,
115
- projectData?: ProjectDataType
116
- }
117
-
118
- export class Weaverse {
119
- elementInstances = new Map<string, any>()
120
- itemInstances = new Map<string | number, WeaverseItemStore>()
121
- appUrl: string = process.env.NODE_ENV === 'development' ? 'http://localhost:3000' : 'https://weaverse.io'
122
- projectKey: string = ''
123
- projectData: ProjectDataType = {
124
- items: []
125
- }
126
- listeners: Set<any> = new Set()
127
- isEditor = false
128
- currentFrameSubscription: any
129
-
130
- constructor({appUrl, projectKey, projectData}: WeaverseType = {}) {
131
- this.appUrl = appUrl || this.appUrl
132
- this.projectKey = projectKey || this.projectKey
133
- projectData && (this.projectData = projectData)
134
- this.init()
135
- }
136
-
137
- registerElement(name: string, element: any) {
138
- this.elementInstances.set(name, element)
139
- }
140
-
141
- init() {
142
- this.subscribeMessageEvent()
143
- }
144
-
145
- subscribe(fn: any) {
146
- this.listeners.add(fn)
147
- }
148
-
149
- unsubscribe(fn: any) {
150
- this.listeners.delete(fn)
151
- }
152
-
153
- triggerUpdate() {
154
- this.listeners.forEach(fn => fn())
155
- this.triggerEditorUpdate()
156
- }
157
-
158
- fetchProjectData() {
159
- return fetch(this.appUrl + `/api/public/${this.projectKey}`).then(r => r.json())
160
- }
161
-
162
- updateProjectData() {
163
- if (this.projectKey) {
164
- this.fetchProjectData().then(data => {
165
- if (data) {
166
- this.projectData = data
167
- this.initItemData()
168
- this.triggerUpdate()
169
- }
170
- }).catch(err => {
171
- console.error(err)
172
- })
173
- }
174
- }
175
-
176
- subscribeMessageEvent() {
177
- if (typeof this.currentFrameSubscription === 'function') {
178
- this.currentFrameSubscription()
179
- }
180
- isBrowser && window.addEventListener('message', this.handleMessageEvent)
181
- this.currentFrameSubscription = () => {
182
- isBrowser && window.removeEventListener('message', this.handleMessageEvent)
183
- }
184
- return this.currentFrameSubscription
185
- }
186
-
187
- triggerEditorUpdate(type = 'weaverse.workspace.init') {
188
- if (this.isEditor) {
189
- window.top?.postMessage({
190
- type, payload: {
191
- projectKey: this.projectKey,
192
- projectData: this.projectData
193
- }
194
- }, '*')
195
- }
196
- }
197
-
198
- handleMessageEvent = (e: MessageEvent) => {
199
- if (e.data?.type?.startsWith('weaverse.')) {
200
- let type = e.data.type
201
- switch (type) {
202
- case 'weaverse.editor.ready':
203
- this.isEditor = true
204
- break
205
- case 'weaverse.editor.update':
206
- let {payload} = e.data
207
- let {itemId, background} = payload
208
- let instance = this.itemInstances.get(itemId)
209
- if (instance) {
210
- instance.setData({
211
- style: {
212
- background
213
- }
214
- })
215
- }
216
- }
217
- }
218
- }
219
-
220
- initItemData() {
221
- let data = this.projectData
222
- if (data.items) {
223
- data.items.forEach(item => {
224
- let itemStore = this.itemInstances.get(item.id) || new WeaverseItemStore(item, this)
225
- this.itemInstances.set(item.id, itemStore)
226
- })
227
- }
228
- }
229
- }
230
-
231
- export class WeaverseItemStore {
232
- data: any = {}
233
- listeners: Set<any> = new Set()
234
- Component: any
235
-
236
- constructor(itemData: any = {}, weaverse: Weaverse) {
237
- this.data = itemData
238
- let {type} = itemData
239
- if (type) {
240
- this.Component = weaverse.elementInstances.get(type)
241
- }
242
- }
243
-
244
- setData = (data: any) => {
245
- this.data = Object.assign(this.data, data)
246
- this.triggerUpdate()
247
- }
248
-
249
- subscribe = (fn: any) => {
250
- this.listeners.add(fn)
251
- }
252
-
253
- unsubscribe = (fn: any) => {
254
- this.listeners.delete(fn)
255
- }
256
-
257
- triggerUpdate = () => {
258
- this.listeners.forEach(fn => {
259
- return fn(this.data)
260
- })
261
- }
262
-
263
-
264
-
265
- // addItem(item: any) {
266
- // this.items.push(item)
267
- // this.triggerUpdate()
268
- // }
269
- //
270
- // removeItem(item: any) {
271
- // this.items = this.items.filter(i => i !== item)
272
- // this.triggerUpdate()
273
- // }
274
- }
@@ -1,12 +0,0 @@
1
- import React from 'react'
2
-
3
- export const BaseElement = ({tag = 'div', children, ...props}: any) => {
4
- return React.createElement(tag, {
5
- ...props
6
- }, children)
7
- }
8
-
9
- BaseElement.configs = {
10
- type: 'base'
11
- }
12
- export default BaseElement
@@ -1,22 +0,0 @@
1
- import * as React from 'react'
2
-
3
- export const Button = (props: any) => {
4
- let [count, setCount] = React.useState(0)
5
- return <button {...props} onClick={() => setCount(count + 1)}>Test Button {count}</button>
6
- }
7
-
8
- Button.defaultProps = {
9
- style: {
10
- backgroundColor: 'green',
11
- borderRadius: '9999px',
12
- fontSize: '13px',
13
- padding: '10px 15px'
14
- },
15
- type: 'button',
16
- tag: 'button'
17
- }
18
- Button.configs = {
19
- type: 'button'
20
- }
21
-
22
- export default Button
@@ -1,8 +0,0 @@
1
- import Button from './button'
2
- import BaseElement from './base'
3
-
4
- const elements = {
5
- Button,
6
- BaseElement
7
- }
8
- export default elements
package/src/index.tsx DELETED
@@ -1,78 +0,0 @@
1
- import * as React from 'react'
2
- import {useEffect} from 'react'
3
- import {Weaverse, WeaverseType} from './core'
4
- import Elements from './elements'
5
-
6
- let stitches = require('@stitches/core')
7
-
8
- const createRootContext = (configs: WeaverseType) => {
9
- const rootContext = new Weaverse(configs)
10
- Object.keys(Elements).forEach(key => {
11
- // @ts-ignore
12
- Elements[key]?.configs?.type && rootContext.registerElement(Elements[key].configs.type, Elements[key])
13
- })
14
-
15
- return rootContext
16
- }
17
-
18
- const WeaverseRoot = ({context, defaultData}: { context: Weaverse, defaultData: any }) => {
19
- let [, setData] = React.useState<any>(context.projectData)
20
- useEffect(() => {
21
- let handleUpdate = () => {
22
- setData(context.projectData)
23
- }
24
- context.subscribe(handleUpdate)
25
- context.updateProjectData()
26
-
27
- return () => {
28
- context.unsubscribe(handleUpdate)
29
- }
30
- }, [])
31
- if (!context.projectData?.items?.length && defaultData) {
32
- context.projectData = defaultData
33
- context.initItemData()
34
- }
35
- return <RenderItem itemId={0} context={context}/>
36
- }
37
-
38
-
39
- const Item = ({itemInstance, elementInstances, context}: any) => {
40
- let [data, setData] = React.useState<any>(itemInstance.data)
41
- let {id, type, childIds, ...rest} = data
42
-
43
- useEffect(() => {
44
- let handleUpdate = (update: any) => {
45
- setData({...update})
46
- }
47
- itemInstance.subscribe(handleUpdate)
48
- return () => {
49
- itemInstance.unsubscribe(handleUpdate)
50
- }
51
- }, [])
52
- let Component = elementInstances.get(type)
53
- if (Component) {
54
- return <Component key={id} data-wv-id={id} {...rest}>
55
- {Array.isArray(childIds)
56
- && childIds.map(childId =>
57
- <RenderItem
58
- key={childId}
59
- itemId={childId}
60
- context={context}
61
- />
62
- )}
63
- </Component>
64
- }
65
- return null
66
- }
67
-
68
-
69
- const RenderItem = ({itemId, context}: { itemId: number, context: any }): any => {
70
- let {itemInstances, elementInstances} = context
71
- let itemInstance = itemInstances.get(itemId)
72
- if (itemInstance) {
73
- return <Item itemInstance={itemInstance} elementInstances={elementInstances} context={context}/>
74
- }
75
- return <></>
76
- }
77
-
78
- export {createRootContext, WeaverseRoot}
package/src/types.d.ts DELETED
@@ -1,13 +0,0 @@
1
- import {ReactChild} from 'react'
2
-
3
- export interface HWSDKConfig {
4
- initialData?: any
5
- token?: string
6
- projectId?: string
7
- hydrate?: boolean
8
- apiUrl?: string
9
- }
10
-
11
- export interface HWProps extends HWSDKConfig {
12
- children?: ReactChild;
13
- }
@@ -1,3 +0,0 @@
1
- export const isReactNative = typeof navigator === 'object' && navigator.product === 'ReactNative'
2
- export const isBrowser = typeof window !== 'undefined' && !isReactNative
3
- export const isIframe = isBrowser && window.top !== window.self
@@ -1,23 +0,0 @@
1
- const toAlphabeticChar = (/** @type {number} */ code) => String.fromCharCode(code + (code > 25 ? 39 : 97))
2
-
3
- const toAlphabeticName = (/** @type {number} */ code) => {
4
- let name = ''
5
- let x
6
-
7
- for (x = Math.abs(code); x > 52; x = (x / 52) | 0) name = toAlphabeticChar(x % 52) + name
8
-
9
- return toAlphabeticChar(x % 52) + name
10
- }
11
-
12
- const toPhash = (/** @type {number} */ h, /** @type {string} */ x) => {
13
- let i = x.length
14
- while (i) h = (h * 33) ^ x.charCodeAt(--i)
15
- return h
16
- }
17
-
18
- export const toHash = (/** @type {object} */ value) => toAlphabeticName(
19
- toPhash(
20
- 5381,
21
- JSON.stringify(value)
22
- ) >>> 0
23
- )