react-scope-value-store.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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: 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]
  117. this.watcherUpdates = []
  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.push(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. let item = this.items.get(path)
  151. if (item === undefined) {
  152. item = { value, watchers: [] }
  153. this.items.set(path, item)
  154. } else if (!('value' in item)) {
  155. item = { ...item, value }
  156. this.items.set(path, item)
  157. } else if (item.value === value) {
  158. // Don't update and trigger watchers if the value hasn't changed
  159. return
  160. } else {
  161. item.value = value
  162. }
  163. this.scheduleWatcherUpdate<T>(path, value, item.watchers)
  164. // Persist to local storage, if configured to do so
  165. const persister = this.persisters.get(path)
  166. if (persister) {
  167. customLocalStorage.setItem(
  168. persister.localStorageKey,
  169. persister.toPersisted?.(value) || value
  170. )
  171. }
  172. }
  173. private setValueAndDescendants<T>(path: string, value: T): void {
  174. this.setValue(path, value)
  175. // Set nested values non-recursively, only updating existing items
  176. if (isObject(value)) {
  177. const pathPrefix = path + '.'
  178. for (const [nestedPath, existingItem] of this.items.entries()) {
  179. if (nestedPath.startsWith(pathPrefix)) {
  180. const newValue = _.get(
  181. value,
  182. nestedPath.slice(pathPrefix.length),
  183. NOT_FOUND
  184. )
  185. // Only update a nested value if it has changed
  186. if (
  187. newValue !== NOT_FOUND &&
  188. (!('value' in existingItem) || newValue !== existingItem.value)
  189. ) {
  190. this.setValue(nestedPath, newValue)
  191. }
  192. }
  193. }
  194. // Delete nested items corresponding to properties that do not exist in
  195. // the new object
  196. const pathsToDelete: string[] = []
  197. const newPropNames = new Set(Object.keys(value))
  198. for (const path of this.items.keys()) {
  199. if (path.startsWith(pathPrefix)) {
  200. const propName = path.slice(pathPrefix.length).split('.', 1)[0]
  201. if (!newPropNames.has(propName)) {
  202. pathsToDelete.push(path)
  203. }
  204. }
  205. }
  206. for (const path of pathsToDelete) {
  207. this.items.delete(path)
  208. }
  209. }
  210. }
  211. set(path: string, value: unknown): void {
  212. this.setValueAndDescendants(path, value)
  213. // Reassemble ancestors. For example, if the path is x.y.z, x.y and x have
  214. // now changed too and must be updated
  215. for (const ancestorPath of ancestorPaths(path)) {
  216. const ancestorItem = this.items.get(ancestorPath)
  217. if (ancestorItem && 'value' in ancestorItem) {
  218. ancestorItem.value = this.reassembleObjectValue(
  219. ancestorPath,
  220. ancestorItem.value
  221. )
  222. this.scheduleWatcherUpdate(
  223. ancestorPath,
  224. ancestorItem.value,
  225. ancestorItem.watchers
  226. )
  227. }
  228. }
  229. }
  230. // Watch for changes in a scope value. The value does not need to exist yet.
  231. // Watchers are batched and called asynchronously to avoid chained state
  232. // watcherUpdates, which result in warnings from React (see
  233. // https://github.com/facebook/react/issues/18178)
  234. watch<T>(path: string, callback: Watcher<T>['callback']): () => void {
  235. let item = this.items.get(path)
  236. if (!item) {
  237. item = this.findInAncestors(path)
  238. this.items.set(path, item)
  239. }
  240. const watchers = item.watchers
  241. const watcher = { removed: false, callback }
  242. item.watchers.push(watcher)
  243. // Schedule watcher immediately. This is to work around the fact that there
  244. // is a delay between getting an initial value and adding a watcher in
  245. // useScopeValue, during which the value could change without being
  246. // observed
  247. if ('value' in item) {
  248. this.scheduleWatcherUpdate<T>(path, item.value, [watcher])
  249. }
  250. return () => {
  251. // Add a flag to the watcher so that it can be ignored if the watcher is
  252. // removed in the interval between observing a change and being called
  253. watcher.removed = true
  254. _.pull(watchers, watcher)
  255. }
  256. }
  257. persisted<Value, PersistedValue>(
  258. path: string,
  259. fallbackValue: Value,
  260. localStorageKey: string,
  261. converter?: {
  262. toPersisted: (value: Value) => PersistedValue
  263. fromPersisted: (persisted: PersistedValue) => Value
  264. }
  265. ) {
  266. const persistedValue = customLocalStorage.getItem(
  267. localStorageKey
  268. ) as PersistedValue | null
  269. let value: Value = fallbackValue
  270. if (persistedValue !== null) {
  271. value = converter
  272. ? converter.fromPersisted(persistedValue)
  273. : (persistedValue as Value)
  274. }
  275. this.set(path, value)
  276. // Don't persist the value until set() is called
  277. this.persisters.set(path, {
  278. localStorageKey,
  279. toPersisted: converter?.toPersisted as Persister['toPersisted'],
  280. })
  281. }
  282. allowNonExistentPath(path: string, deep = false) {
  283. this.allowedNonExistentPaths.push({ path, deep })
  284. }
  285. // For debugging
  286. dump() {
  287. const entries = []
  288. for (const [path, item] of this.items.entries()) {
  289. entries.push({
  290. path,
  291. value: 'value' in item ? item.value : '[not set]',
  292. watcherCount: item.watchers.length,
  293. })
  294. }
  295. return entries
  296. }
  297. }