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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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
import type { Ref } from 'vue'
import { computed, onMounted, ref, watch } from 'vue'
import type { ComponentTreeNode, EditStatePayload, InspectedComponentData } from '@vue/devtools-api'
import groupBy from 'lodash/groupBy'
import {
  BridgeEvents,
  BridgeSubscriptions,
  isChrome,
  openInEditor,
  searchDeepInObject,
  setStorage,
  sortByKey,
} from '@vue-devtools/shared-utils'
import { getBridge, useBridge } from '@front/features/bridge'
import type { AppRecord } from '@front/features/apps'
import { useCurrentApp, waitForAppSelect } from '@front/features/apps'
import { useRoute, useRouter } from 'vue-router'

export const rootInstances = ref<ComponentTreeNode[]>([])
export const componentsMap = ref<Record<ComponentTreeNode['id'], ComponentTreeNode>>({})
let componentsParent: Record<ComponentTreeNode['id'], ComponentTreeNode['id']> = {}
const treeFilter = ref('')
export const selectedComponentId = ref<ComponentTreeNode['id'] | null>(null)
export const selectedComponentData = ref<InspectedComponentData | null>(null)
const selectedComponentStateFilter = ref('')
export const selectedComponentPendingId = ref<ComponentTreeNode['id'] | null>(null)
let lastSelectedApp: AppRecord = null
export const lastSelectedComponentId: Record<AppRecord['id'], ComponentTreeNode['id']> = {}
export const expandedMap = ref<Record<ComponentTreeNode['id'], boolean>>({})

export function useComponentRequests() {
  const router = useRouter()

  function selectComponent(id: ComponentTreeNode['id'], replace = false) {
    if (selectedComponentId.value !== id) {
      router[replace ? 'replace' : 'push']({
        params: {
          appId: getAppIdFromComponentId(id),
          componentId: id,
        },
      })
    }
    else {
      loadComponent(id)
    }
  }

  return {
    requestComponentTree,
    selectComponent,
  }
}

export function useComponents() {
  const { onBridge, subscribe } = useBridge()
  const route = useRoute()
  const {
    requestComponentTree,
    selectComponent,
  } = useComponentRequests()
  const { currentAppId } = useCurrentApp()

  watch(treeFilter, () => {
    requestComponentTree()
  })

  watch(() => route.params.componentId, () => {
    const value = route.params.componentId as string
    if (value && getAppIdFromComponentId(value) === currentAppId.value) {
      selectedComponentId.value = value
      loadComponent(value)
    }
  }, {
    immediate: true,
  })

  function subscribeToSelectedData() {
    let unsub
    watch(selectedComponentId, (value) => {
      if (unsub) {
        unsub()
        unsub = null
      }

      if (value != null) {
        unsub = subscribe(BridgeSubscriptions.SELECTED_COMPONENT_DATA, value)
      }
    }, {
      immediate: true,
    })
  }

  // We watch for the tree data so that we can auto load the current selected component
  watch(componentsMap, () => {
    if (selectedComponentId.value && selectedComponentPendingId.value !== selectedComponentId.value && !selectedComponentData.value) {
      selectComponent(selectedComponentId.value)
    }
  }, {
    immediate: true,
    deep: true,
  })

  onBridge(BridgeEvents.TO_FRONT_APP_SELECTED, async ({ id }) => {
    await waitForAppSelect()
    requestComponentTree()
    selectedComponentData.value = null
    if (lastSelectedApp !== null) {
      selectLastComponent()
    }
    lastSelectedApp = id
  })

  // Re-select last selected component when switching back to inspector component tab
  function selectLastComponent() {
    const id = lastSelectedComponentId[currentAppId.value]
    if (id) {
      selectComponent(id, true)
    }
  }

  return {
    rootInstances: computed(() => rootInstances.value),
    treeFilter,
    selectedComponentId: computed(() => selectedComponentId.value),
    requestComponentTree,
    selectComponent,
    selectLastComponent,
    subscribeToSelectedData,
  }
}

export function useComponent(instance: Ref<ComponentTreeNode>) {
  const { selectComponent, requestComponentTree } = useComponentRequests()
  const { subscribe } = useBridge()

  const isExpanded = computed(() => isComponentOpen(instance.value.id))
  const isExpandedUndefined = computed(() => expandedMap.value[instance.value.id] == null)

  function toggleExpand(recursively = false, value?, child?) {
    const treeNode = child || instance.value
    if (!treeNode.hasChildren) {
      return
    }
    const isOpen = value === undefined ? !isExpanded.value : value
    setComponentOpen(treeNode.id, isOpen)
    if (isComponentOpen(treeNode.id)) {
      requestComponentTree(treeNode.id, recursively)
    }
    else {
      // stop expanding all treenode
      treeNode.autoOpen = false
    }
    if (recursively) {
      treeNode.children.forEach((child) => {
        toggleExpand(recursively, value, child)
      })
    }
  }

  const isSelected = computed(() => selectedComponentId.value === instance.value.id)

  function select(id = instance.value.id) {
    selectComponent(id)
  }

  function subscribeToComponentTree() {
    let unsub
    watch(() => instance.value.id, (value) => {
      if (unsub) {
        unsub()
        unsub = null
      }

      if (value != null) {
        unsub = subscribe(BridgeSubscriptions.COMPONENT_TREE, value)
      }
    }, {
      immediate: true,
    })
  }

  onMounted(() => {
    if (instance.value.autoOpen) {
      toggleExpand(true, true)
    }
    else if (isExpanded.value) {
      requestComponentTree(instance.value.id)
    }
  })

  return {
    isExpanded,
    isExpandedUndefined,
    isComponentOpen,
    toggleExpand,
    isSelected,
    select,
    subscribeToComponentTree,
  }
}

export function setComponentOpen(id: ComponentTreeNode['id'], isOpen: boolean) {
  expandedMap.value[id] = isOpen
}

export function isComponentOpen(id: ComponentTreeNode['id']) {
  return !!expandedMap.value[id]
}

export function useSelectedComponent() {
  const data = computed(() => selectedComponentData.value)
  const state = computed(() => selectedComponentData.value
    ? groupBy(sortByKey(selectedComponentData.value.state.filter((el) => {
      try {
        return searchDeepInObject({
          [el.key]: el.value,
        }, selectedComponentStateFilter.value)
      }
      catch (e) {
        return {
          [el.key]: e,
        }
      }
    })), 'type')
    : ({}))

  const fileIsPath = computed(() => data.value?.file && /[/\\]/.test(data.value.file))

  function inspectDOM() {
    if (!data.value) {
      return
    }
    if (isChrome) {
      getBridge().send(BridgeEvents.TO_BACK_COMPONENT_INSPECT_DOM, { instanceId: data.value.id })
    }
    else {
      // eslint-disable-next-line no-alert
      window.alert('DOM inspection is not supported in this shell.')
    }
  }

  function openFile() {
    if (!data.value) {
      return
    }
    openInEditor(data.value.file)
  }

  const { bridge } = useBridge()

  function editState(dotPath: string, payload: EditStatePayload, type?: string) {
    bridge.send(BridgeEvents.TO_BACK_COMPONENT_EDIT_STATE, {
      instanceId: data.value?.id,
      dotPath,
      type,
      ...payload,
    })
  }

  function scrollToComponent() {
    bridge.send(BridgeEvents.TO_BACK_COMPONENT_SCROLL_TO, {
      instanceId: data.value?.id,
    })
  }

  return {
    data,
    state,
    stateFilter: selectedComponentStateFilter,
    inspectDOM,
    fileIsPath,
    openFile,
    editState,
    scrollToComponent,
    selectedComponentId,
  }
}

export const updateTrackingEvents = ref<Record<string, ComponentUpdateTrackingEvent>>({})
export const updateTrackingLimit = ref(Date.now() + 5_000)

export function resetComponents() {
  rootInstances.value = []
  componentsMap.value = {}
  componentsParent = {}
  updateTrackingEvents.value = {}
  updateTrackingLimit.value = Date.now() + 5_000
}

export const requestedComponentTree = new Set()

let requestComponentTreeRetryDelay = 500

export async function requestComponentTree(instanceId: ComponentTreeNode['id'] | null = null, recursively = false) {
  if (!instanceId) {
    instanceId = '_root'
  }

  if (requestedComponentTree.has(instanceId)) {
    return
  }
  requestedComponentTree.add(instanceId)

  await waitForAppSelect()

  _sendTreeRequest(instanceId, recursively)
  _queueRetryTree(instanceId, recursively)
}

function _sendTreeRequest(instanceId: ComponentTreeNode['id'], recursively = false) {
  getBridge().send(BridgeEvents.TO_BACK_COMPONENT_TREE, {
    instanceId,
    filter: treeFilter.value,
    recursively,
  })
}

function _queueRetryTree(instanceId: ComponentTreeNode['id'], recursively = false) {
  setTimeout(() => _retryRequestComponentTree(instanceId, recursively), requestComponentTreeRetryDelay)
  requestComponentTreeRetryDelay *= 1.5
}

function _retryRequestComponentTree(instanceId: ComponentTreeNode['id'], recursively = false) {
  if (rootInstances.value.length) {
    requestComponentTreeRetryDelay = 500
    return
  }
  _sendTreeRequest(instanceId, recursively)
  _queueRetryTree(instanceId, recursively)
}

export function ensureComponentsMapData(data: ComponentTreeNode) {
  let component = componentsMap.value[data.id]
  if (!component) {
    component = addToComponentsMap(data)
  }
  else {
    component = updateComponentsMapData(data)
  }
  return component
}

function ensureComponentsMapChildren(id: string, children: ComponentTreeNode[]) {
  const result = children.map(child => ensureComponentsMapData(child))
  for (const child of children) {
    componentsParent[child.id] = id
  }
  return result
}

function updateComponentsMapData(data: ComponentTreeNode) {
  const component = componentsMap.value[data.id]
  for (const key in data) {
    if (key === 'children') {
      if (!data.hasChildren || data.children.length) {
        const children = ensureComponentsMapChildren(component.id, data.children)
        component[key] = children
      }
    }
    else {
      component[key] = data[key]
    }
  }
  return component
}

function addToComponentsMap(data: ComponentTreeNode) {
  if (!data.hasChildren || data.children.length) {
    data.children = ensureComponentsMapChildren(data.id, data.children)
  }
  componentsMap.value[data.id] = data
  return data
}

export async function loadComponent(id: ComponentTreeNode['id']) {
  if (!id || selectedComponentPendingId.value === id) {
    return
  }
  lastSelectedComponentId[getAppIdFromComponentId(id)] = id
  setStorage('lastSelectedComponentId', lastSelectedComponentId)
  selectedComponentPendingId.value = id
  await waitForAppSelect()
  getBridge().send(BridgeEvents.TO_BACK_COMPONENT_SELECTED_DATA, id)
}

export function sortChildren(children: ComponentTreeNode[]) {
  return children.slice().sort((a, b) => {
    if (a.inactive && !b.inactive) {
      return 1
    }
    else if (!a.inactive && b.inactive) {
      return -1
    }
    const order = compareIndexLists(a.domOrder ?? [], b.domOrder ?? [])
    if (order === 0) {
      return a.id.localeCompare(b.id)
    }
    else {
      return order
    }
  })
}

function compareIndexLists(a: number[], b: number[]): number {
  if (!a.length || !b.length) {
    return 0
  }
  else if (a[0] === b[0]) {
    return compareIndexLists(a.slice(1), b.slice(1))
  }
  else {
    return a[0] - b[0]
  }
}

export function getAppIdFromComponentId(id: string) {
  const index = id.indexOf(':')
  const appId = id.substring(0, index)
  return appId
}

export interface ComponentUpdateTrackingEvent {
  instanceId: string
  time: number
  count: number
}

export function addUpdateTrackingEvent(instanceId: string, time: number) {
  const event = updateTrackingEvents.value[instanceId]
  if (event) {
    event.count++
    event.time = time
  }
  else {
    updateTrackingEvents.value[instanceId] = {
      instanceId,
      time,
      count: 1,
    }
  }
}