File size: 2,026 Bytes
dc06ee7
 
 
 
 
 
 
376f172
dc06ee7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
376f172
 
dc06ee7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Faker, en, faker as fak } from '@faker-js/faker'
import Graph, { UndirectedGraph } from 'graphology'
import erdosRenyi from 'graphology-generators/random/erdos-renyi'
import { useCallback, useEffect, useState } from 'react'
import seedrandom from 'seedrandom'
import { randomColor } from '@/lib/utils'
import * as Constants from '@/lib/constants'
import { useGraphStore } from '@/stores/graph'

export type NodeType = {
  x: number
  y: number
  label: string
  size: number
  color: string
  highlighted?: boolean
}
export type EdgeType = { label: string }

/**
 * The goal of this file is to seed random generators if the query params 'seed' is present.
 */
const useRandomGraph = () => {
  const [faker, setFaker] = useState<Faker>(fak)

  useEffect(() => {
    // Globally seed the Math.random
    const params = new URLSearchParams(document.location.search)
    const seed = params.get('seed') // is the string "Jonathan"
    if (seed) {
      seedrandom(seed, { global: true })
      // seed faker with the random function
      const f = new Faker({ locale: en })
      f.seed(Math.random())
      setFaker(f)
    }
  }, [])

  const randomGraph = useCallback(() => {
    useGraphStore.getState().reset()

    // Create the graph
    const graph = erdosRenyi(UndirectedGraph, { order: 100, probability: 0.1 })
    graph.nodes().forEach((node: string) => {
      graph.mergeNodeAttributes(node, {
        label: faker.person.fullName(),
        size: faker.number.int({ min: Constants.minNodeSize, max: Constants.maxNodeSize }),
        color: randomColor(),
        x: Math.random(),
        y: Math.random(),
        // for node-border
        borderColor: randomColor(),
        borderSize: faker.number.float({ min: 0, max: 1, multipleOf: 0.1 }),
        // for node-image
        pictoColor: randomColor(),
        image: faker.image.urlLoremFlickr()
      })
    })
    return graph as Graph<NodeType, EdgeType>
  }, [faker])

  return { faker, randomColor, randomGraph }
}

export default useRandomGraph