use-scope.tsx 766 B

1234567891011121314151617181920212223242526
  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. window.overleaf.unstable.store.set(path, merge(existingValue, value))
  21. }
  22. }
  23. }, [])
  24. }