react-scope-value-store.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import { ScopeValueStore } from '../../../../../types/ide/scope-value-store'
  2. import _ from 'lodash'
  3. import customLocalStorage from '../../../infrastructure/local-storage'
  4. import { debugConsole } from '@/utils/debugging'
  5. const NOT_FOUND = Symbol('not found')
  6. type Watcher<T> = {
  7. removed: boolean
  8. callback: (value: T) => void
  9. }
  10. // A value that has been set
  11. type ScopeValueStoreValue<T = any> = {
  12. value?: T
  13. watchers: Watcher<T>[]
  14. }
  15. type WatcherUpdate<T = any> = {
  16. path: string
  17. value: T
  18. watchers: Watcher<T>[]
  19. }
  20. type NonExistentValue = {
  21. value: undefined
  22. }
  23. type AllowedNonExistentPath = {
  24. path: string
  25. deep: boolean
  26. }
  27. type Persister = {
  28. localStorageKey: string
  29. toPersisted?: (value: unknown) => unknown
  30. }
  31. function isObject(value: unknown): value is object {
  32. return (
  33. value !== null &&
  34. typeof value === 'object' &&
  35. !('length' in value && typeof value.length === 'number' && value.length > 0)
  36. )
  37. }
  38. function ancestorPaths(path: string) {
  39. const ancestors: string[] = []
  40. let currentPath = path
  41. let lastPathSeparatorPos: number
  42. while ((lastPathSeparatorPos = currentPath.lastIndexOf('.')) !== -1) {
  43. currentPath = currentPath.slice(0, lastPathSeparatorPos)
  44. ancestors.push(currentPath)
  45. }
  46. return ancestors
  47. }
  48. // Store scope values in a simple map
  49. export class ReactScopeValueStore implements ScopeValueStore {
  50. private readonly items = new Map<string, ScopeValueStoreValue>()
  51. private readonly persisters: Map<string, Persister> = new Map()
  52. private watcherUpdates = new Map<string, WatcherUpdate>()
  53. private watcherUpdateTimer: number | null = null
  54. private allowedNonExistentPaths: AllowedNonExistentPath[] = []
  55. private nonExistentPathAllowed(path: string) {
  56. return this.allowedNonExistentPaths.some(allowedPath => {
  57. return (
  58. allowedPath.path === path ||
  59. (allowedPath.deep && path.startsWith(allowedPath.path + '.'))
  60. )
  61. })
  62. }
  63. // Create an item for a path. Attempt to get a value for the item from its
  64. // ancestors, if there are any.
  65. private findInAncestors(path: string): ScopeValueStoreValue {
  66. // Populate value from the nested property ancestors, if possible
  67. for (const ancestorPath of ancestorPaths(path)) {
  68. const ancestorItem = this.items.get(ancestorPath)
  69. if (
  70. ancestorItem &&
  71. 'value' in ancestorItem &&
  72. isObject(ancestorItem.value)
  73. ) {
  74. const pathRelativeToAncestor = path.slice(ancestorPath.length + 1)
  75. const ancestorValue = _.get(ancestorItem.value, pathRelativeToAncestor)
  76. if (ancestorValue !== NOT_FOUND) {
  77. return { value: ancestorValue, watchers: [] }
  78. }
  79. }
  80. }
  81. return { watchers: [] }
  82. }
  83. private getItem<T>(path: string): ScopeValueStoreValue<T> | NonExistentValue {
  84. const item = this.items.get(path) || this.findInAncestors(path)
  85. if (!('value' in item)) {
  86. if (this.nonExistentPathAllowed(path)) {
  87. debugConsole.log(
  88. `No value found for key '${path}'. This is allowed because the path is in allowedNonExistentPaths`
  89. )
  90. return { value: undefined }
  91. } else {
  92. throw new Error(`No value found for key '${path}'`)
  93. }
  94. }
  95. return item
  96. }
  97. private reassembleObjectValue(path: string, value: Record<string, any>) {
  98. const newValue: Record<string, any> = { ...value }
  99. const pathPrefix = path + '.'
  100. for (const [key, item] of this.items.entries()) {
  101. if (key.startsWith(pathPrefix)) {
  102. const propName = key.slice(pathPrefix.length)
  103. if (propName.indexOf('.') === -1 && 'value' in item) {
  104. newValue[propName] = item.value
  105. }
  106. }
  107. }
  108. return newValue
  109. }
  110. flushUpdates() {
  111. if (this.watcherUpdateTimer) {
  112. window.clearTimeout(this.watcherUpdateTimer)
  113. this.watcherUpdateTimer = null
  114. }
  115. // Clone watcherUpdates in case a watcher creates new watcherUpdates
  116. const watcherUpdates = [...this.watcherUpdates.values()]
  117. this.watcherUpdates = new Map()
  118. for (const { value, watchers } of watcherUpdates) {
  119. for (const watcher of watchers) {
  120. if (!watcher.removed) {
  121. watcher.callback.call(null, value)
  122. }
  123. }
  124. }
  125. }
  126. private scheduleWatcherUpdate<T>(
  127. path: string,
  128. value: T,
  129. watchers: Watcher<T>[]
  130. ) {
  131. // Make a copy of the watchers so that any watcher added before this update
  132. // runs is not triggered
  133. const update: WatcherUpdate = {
  134. value,
  135. path,
  136. watchers: [...watchers],
  137. }
  138. this.watcherUpdates.set(path, update)
  139. if (!this.watcherUpdateTimer) {
  140. this.watcherUpdateTimer = window.setTimeout(() => {
  141. this.watcherUpdateTimer = null
  142. this.flushUpdates()
  143. }, 0)
  144. }
  145. }
  146. get<T>(path: string) {
  147. return this.getItem<T>(path).value
  148. }
  149. private setValue<T>(path: string, value: T): void {
  150. debugConsole.log('setValue', path, value)
  151. let item = this.items.get(path)
  152. if (item === undefined) {
  153. item = { value, watchers: [] }
  154. this.items.set(path, item)
  155. } else if (!('value' in item)) {
  156. item = { ...item, value }
  157. this.items.set(path, item)
  158. } else if (item.value === value) {
  159. // Don't update and trigger watchers if the value hasn't changed
  160. return
  161. } else {
  162. item.value = value
  163. }
  164. this.scheduleWatcherUpdate<T>(path, value, item.watchers)
  165. // Persist to local storage, if configured to do so
  166. const persister = this.persisters.get(path)
  167. if (persister) {
  168. customLocalStorage.setItem(
  169. persister.localStorageKey,
  170. persister.toPersisted?.(value) || value
  171. )
  172. }
  173. }
  174. private setValueAndDescendants<T>(path: string, value: T): void {
  175. this.setValue(path, value)
  176. // Set nested values non-recursively, only updating existing items
  177. if (isObject(value)) {
  178. const pathPrefix = path + '.'
  179. for (const [nestedPath, existingItem] of this.items.entries()) {
  180. if (nestedPath.startsWith(pathPrefix)) {
  181. const newValue = _.get(
  182. value,
  183. nestedPath.slice(pathPrefix.length),
  184. NOT_FOUND
  185. )
  186. // Only update a nested value if it has changed
  187. if (
  188. newValue !== NOT_FOUND &&
  189. (!('value' in existingItem) || newValue !== existingItem.value)
  190. ) {
  191. this.setValue(nestedPath, newValue)
  192. }
  193. }
  194. }
  195. // Delete nested items corresponding to properties that do not exist in
  196. // the new object
  197. const pathsToDelete: string[] = []
  198. const newPropNames = new Set(Object.keys(value))
  199. for (const path of this.items.keys()) {
  200. if (path.startsWith(pathPrefix)) {
  201. const propName = path.slice(pathPrefix.length).split('.', 1)[0]
  202. if (!newPropNames.has(propName)) {
  203. pathsToDelete.push(path)
  204. }
  205. }
  206. }
  207. for (const path of pathsToDelete) {
  208. this.items.delete(path)
  209. }
  210. }
  211. }
  212. set(path: string, value: unknown): void {
  213. this.setValueAndDescendants(path, value)
  214. // Reassemble ancestors. For example, if the path is x.y.z, x.y and x have
  215. // now changed too and must be updated
  216. for (const ancestorPath of ancestorPaths(path)) {
  217. const ancestorItem = this.items.get(ancestorPath)
  218. if (ancestorItem && 'value' in ancestorItem) {
  219. ancestorItem.value = this.reassembleObjectValue(
  220. ancestorPath,
  221. ancestorItem.value
  222. )
  223. this.scheduleWatcherUpdate(
  224. ancestorPath,
  225. ancestorItem.value,
  226. ancestorItem.watchers
  227. )
  228. }
  229. }
  230. }
  231. // Watch for changes in a scope value. The value does not need to exist yet.
  232. // Watchers are batched and called asynchronously to avoid chained state
  233. // watcherUpdates, which result in warnings from React (see
  234. // https://github.com/facebook/react/issues/18178)
  235. watch<T>(path: string, callback: Watcher<T>['callback']): () => void {
  236. let item = this.items.get(path)
  237. if (!item) {
  238. item = this.findInAncestors(path)
  239. this.items.set(path, item)
  240. }
  241. const watchers = item.watchers
  242. const watcher = { removed: false, callback }
  243. item.watchers.push(watcher)
  244. // Schedule watcher immediately. This is to work around the fact that there
  245. // is a delay between getting an initial value and adding a watcher in
  246. // useScopeValue, during which the value could change without being
  247. // observed
  248. if ('value' in item) {
  249. // add this watcher to any existing watchers scheduled for this path
  250. const { watchers } = this.watcherUpdates.get(path) ?? { watchers: [] }
  251. this.scheduleWatcherUpdate<T>(path, item.value, [...watchers, watcher])
  252. }
  253. return () => {
  254. // Add a flag to the watcher so that it can be ignored if the watcher is
  255. // removed in the interval between observing a change and being called
  256. watcher.removed = true
  257. _.pull(watchers, watcher)
  258. }
  259. }
  260. persisted<Value, PersistedValue>(
  261. path: string,
  262. fallbackValue: Value,
  263. localStorageKey: string,
  264. converter?: {
  265. toPersisted: (value: Value) => PersistedValue
  266. fromPersisted: (persisted: PersistedValue) => Value
  267. }
  268. ) {
  269. const persistedValue = customLocalStorage.getItem(
  270. localStorageKey
  271. ) as PersistedValue | null
  272. let value: Value = fallbackValue
  273. if (persistedValue !== null) {
  274. value = converter
  275. ? converter.fromPersisted(persistedValue)
  276. : (persistedValue as Value)
  277. }
  278. this.set(path, value)
  279. // Don't persist the value until set() is called
  280. this.persisters.set(path, {
  281. localStorageKey,
  282. toPersisted: converter?.toPersisted as Persister['toPersisted'],
  283. })
  284. }
  285. allowNonExistentPath(path: string, deep = false) {
  286. this.allowedNonExistentPaths.push({ path, deep })
  287. }
  288. // For debugging
  289. dump() {
  290. const entries = []
  291. for (const [path, item] of this.items.entries()) {
  292. entries.push({
  293. path,
  294. value: 'value' in item ? item.value : '[not set]',
  295. watcherCount: item.watchers.length,
  296. })
  297. }
  298. return entries
  299. }
  300. }