|
| 1 | +import { devtoolsPluginBuffer } from '../../ctx/plugin' |
| 2 | +import { PluginDescriptor } from '../../types' |
| 3 | +import { DevToolsV6PluginAPIHookKeys, devtoolsContext, getInspector } from '../../ctx' |
| 4 | + |
| 5 | +function _getSettings(settings: PluginDescriptor['settings']) { |
| 6 | + const _settings = {} |
| 7 | + Object.keys(settings!).forEach((key) => { |
| 8 | + _settings[key] = settings![key].defaultValue |
| 9 | + }) |
| 10 | + |
| 11 | + return _settings |
| 12 | +} |
| 13 | + |
| 14 | +function getPluginLocalKey(pluginId: string) { |
| 15 | + return `__VUE_DEVTOOLS_NEXT_PLUGIN_SETTINGS__${pluginId}__` |
| 16 | +} |
| 17 | + |
| 18 | +export function getPluginSettingsOptions(pluginId: string) { |
| 19 | + const descriptor = getInspector(pluginId)?.descriptor |
| 20 | + const item = devtoolsPluginBuffer.find(item => item[0].id === descriptor?.id)?.[0] ?? null |
| 21 | + return item?.settings ?? null |
| 22 | +} |
| 23 | + |
| 24 | +export function getPluginSettings(pluginId: string, fallbackValue?: PluginDescriptor['settings']) { |
| 25 | + const localKey = getPluginLocalKey(pluginId) |
| 26 | + if (localKey) { |
| 27 | + const localSettings = localStorage.getItem(localKey) |
| 28 | + if (localSettings) { |
| 29 | + return JSON.parse(localSettings) |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + if (pluginId) { |
| 34 | + const item = devtoolsPluginBuffer.find(item => item[0].id === pluginId)?.[0] ?? null |
| 35 | + return _getSettings(item?.settings ?? {}) |
| 36 | + } |
| 37 | + return _getSettings(fallbackValue) |
| 38 | +} |
| 39 | + |
| 40 | +export function initPluginSettings(pluginId: string, settings: PluginDescriptor['settings']) { |
| 41 | + const localKey = getPluginLocalKey(pluginId) |
| 42 | + const localSettings = localStorage.getItem(localKey) |
| 43 | + if (!localSettings) { |
| 44 | + localStorage.setItem(localKey, JSON.stringify(_getSettings(settings))) |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +export function setPluginSettings(pluginId: string, key: string, value: string) { |
| 49 | + const localKey = getPluginLocalKey(pluginId) |
| 50 | + const localSettings = localStorage.getItem(localKey)! |
| 51 | + const parsedLocalSettings = JSON.parse(localSettings || '{}') |
| 52 | + const updated = { |
| 53 | + ...parsedLocalSettings, |
| 54 | + [key]: value, |
| 55 | + } |
| 56 | + localStorage.setItem(localKey, JSON.stringify(updated)) |
| 57 | + |
| 58 | + // @ts-expect-error hookable |
| 59 | + devtoolsContext.hooks.callHookWith((callbacks) => { |
| 60 | + callbacks.forEach(cb => cb({ |
| 61 | + pluginId, |
| 62 | + key, |
| 63 | + oldValue: parsedLocalSettings[key], |
| 64 | + newValue: value, |
| 65 | + settings: updated, |
| 66 | + })) |
| 67 | + }, DevToolsV6PluginAPIHookKeys.SET_PLUGIN_SETTINGS) |
| 68 | +} |
0 commit comments