File size: 6,485 Bytes
4d70170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import { reactive } from 'vue'
import { getStorage, setStorage } from './storage'
import type { Bridge } from './bridge'
import { isBrowser, isMac } from './env'

// Initial state
const internalSharedData = {
  openInEditorHost: '/',
  componentNameStyle: 'class',
  theme: 'auto',
  displayDensity: 'low',
  timeFormat: 'default',
  recordVuex: true,
  cacheVuexSnapshotsEvery: 50,
  cacheVuexSnapshotsLimit: 10,
  snapshotLoading: false,
  componentEventsEnabled: true,
  performanceMonitoringEnabled: true,
  editableProps: false,
  logDetected: true,
  vuexNewBackend: false,
  vuexAutoload: false,
  vuexGroupGettersByModule: true,
  showMenuScrollTip: true,
  timelineRecording: false,
  timelineTimeGrid: true,
  timelineScreenshots: false,
  menuStepScrolling: isMac,
  pluginPermissions: {} as any,
  pluginSettings: {} as any,
  pageConfig: {} as any,
  legacyApps: false,
  trackUpdates: true,
  flashUpdates: false,
  debugInfo: false,
  isBrowser,
}

type TSharedData = typeof internalSharedData

const persisted = [
  'componentNameStyle',
  'theme',
  'displayDensity',
  'recordVuex',
  'editableProps',
  'logDetected',
  'vuexNewBackend',
  'vuexAutoload',
  'vuexGroupGettersByModule',
  'timeFormat',
  'showMenuScrollTip',
  'timelineRecording',
  'timelineTimeGrid',
  'timelineScreenshots',
  'menuStepScrolling',
  'pluginPermissions',
  'pluginSettings',
  'performanceMonitoringEnabled',
  'componentEventsEnabled',
  'trackUpdates',
  'flashUpdates',
  'debugInfo',
]

const storageVersion = '6.0.0-alpha.1'

// ---- INTERNALS ---- //

let bridge
// List of fields to persist to storage (disabled if 'false')
// This should be unique to each shared data client to prevent conflicts
let persist = false
let data

let initRetryInterval
let initRetryCount = 0

export interface SharedDataParams {
  bridge: Bridge
  persist: boolean
}

const initCbs = []

export function initSharedData(params: SharedDataParams): Promise<void> {
  return new Promise((resolve) => {
    // Mandatory params
    bridge = params.bridge
    persist = !!params.persist

    if (persist) {
      if (process.env.NODE_ENV !== 'production') {
        // eslint-disable-next-line no-console
        console.log('[shared data] Master init in progress...')
      }
      // Load persisted fields
      persisted.forEach((key) => {
        const value = getStorage(`vue-devtools-${storageVersion}:shared-data:${key}`)
        if (value !== null) {
          internalSharedData[key] = value
        }
      })
      bridge.on('shared-data:load', () => {
        // Send all fields
        Object.keys(internalSharedData).forEach((key) => {
          sendValue(key, internalSharedData[key])
        })
        bridge.send('shared-data:load-complete')
      })
      bridge.on('shared-data:init-complete', () => {
        if (process.env.NODE_ENV !== 'production') {
          // eslint-disable-next-line no-console
          console.log('[shared data] Master init complete')
        }
        clearInterval(initRetryInterval)
        resolve()
      })

      bridge.send('shared-data:master-init-waiting')
      // In case backend init is executed after frontend
      bridge.on('shared-data:minion-init-waiting', () => {
        bridge.send('shared-data:master-init-waiting')
      })

      initRetryCount = 0
      clearInterval(initRetryInterval)
      initRetryInterval = setInterval(() => {
        if (process.env.NODE_ENV !== 'production') {
          // eslint-disable-next-line no-console
          console.log('[shared data] Master init retrying...')
        }
        bridge.send('shared-data:master-init-waiting')
        initRetryCount++
        if (initRetryCount > 30) {
          clearInterval(initRetryInterval)
          console.error('[shared data] Master init failed')
        }
      }, 2000)
    }
    else {
      if (process.env.NODE_ENV !== 'production') {
        // eslint-disable-next-line no-console
        console.log('[shared data] Minion init in progress...')
      }
      bridge.on('shared-data:master-init-waiting', () => {
        if (process.env.NODE_ENV !== 'production') {
          // eslint-disable-next-line no-console
          console.log('[shared data] Minion loading data...')
        }
        // Load all persisted shared data
        bridge.send('shared-data:load')
        bridge.once('shared-data:load-complete', () => {
          if (process.env.NODE_ENV !== 'production') {
            // eslint-disable-next-line no-console
            console.log('[shared data] Minion init complete')
          }
          bridge.send('shared-data:init-complete')
          resolve()
        })
      })
      bridge.send('shared-data:minion-init-waiting')
    }

    data = reactive({ ...internalSharedData })

    // Update value from other shared data clients
    bridge.on('shared-data:set', ({ key, value }) => {
      setValue(key, value)
    })

    initCbs.forEach(cb => cb())
  })
}

export function onSharedDataInit(cb) {
  initCbs.push(cb)
  return () => {
    const index = initCbs.indexOf(cb)
    if (index !== -1) {
      initCbs.splice(index, 1)
    }
  }
}

let watchers: Partial<Record<keyof TSharedData, ((value: any, oldValue: any) => unknown)[]>> = {}

export function destroySharedData() {
  bridge.removeAllListeners('shared-data:set')
  watchers = {}
}

function setValue(key: string, value: any) {
  // Storage
  if (persist && persisted.includes(key)) {
    setStorage(`vue-devtools-${storageVersion}:shared-data:${key}`, value)
  }
  const oldValue = data[key]
  data[key] = value
  const handlers = watchers[key]
  if (handlers) {
    handlers.forEach(h => h(value, oldValue))
  }
  // Validate Proxy set trap
  return true
}

function sendValue(key: string, value: any) {
  bridge && bridge.send('shared-data:set', {
    key,
    value,
  })
}

export function watchSharedData<
  TKey extends keyof TSharedData,
>(prop: TKey, handler: (value: TSharedData[TKey], oldValue: TSharedData[TKey]) => unknown) {
  const list = watchers[prop] || (watchers[prop] = [])
  list.push(handler)
  return () => {
    const index = list.indexOf(handler)
    if (index !== -1) {
      list.splice(index, 1)
    }
  }
}

const proxy: Partial<typeof internalSharedData> = {}
Object.keys(internalSharedData).forEach((key) => {
  Object.defineProperty(proxy, key, {
    configurable: false,
    get: () => data[key],
    set: (value) => {
      sendValue(key, value)
      setValue(key, value)
    },
  })
})

export const SharedData = proxy