use-scope.tsx 931 B

123456789101112131415161718192021222324252627282930
  1. import { merge } from 'lodash'
  2. import { useLayoutEffect, useRef } from 'react'
  3. /**
  4. * Merge properties with the scope object, for use in Storybook stories
  5. */
  6. export const useScope = (scope: Record<string, unknown>) => {
  7. const scopeRef = useRef<typeof scope | null>(null)
  8. if (scopeRef.current === null) {
  9. scopeRef.current = scope
  10. }
  11. useLayoutEffect(() => {
  12. if (scopeRef.current) {
  13. for (const [path, value] of Object.entries(scopeRef.current)) {
  14. let existingValue: typeof value | undefined
  15. try {
  16. existingValue = window.overleaf.unstable.store.get(path)
  17. } catch {
  18. // allowed not to exist
  19. }
  20. if (typeof existingValue === 'object' && typeof value === 'object') {
  21. window.overleaf.unstable.store.set(path, merge(existingValue, value))
  22. } else {
  23. window.overleaf.unstable.store.set(path, value)
  24. }
  25. }
  26. }
  27. }, [])
  28. }