plugins: HFS.watchState

Massimo Melina committed May 25, 2023 at 16:14 UTC 233057b731ee8a27728d2cb27f8a56ce40b2305c
2 files changed +15 -3
dev-plugins.md
+7 -2
@@ -150,12 +150,16 @@ The HFS objects contains many properties:
150 - `reloadList`
151 - `logout`
152 - `state` [object with many values in it](https://github.com/rejetto/hfs/blob/main/frontend/src/state.ts)
153 +- `watchState: (key: string, callback)=>function`
154 + - watch the `key` property of the state object above
155 + - `callback(newValue)` will be called at each change
156 + - use returned callback to stop watching
157 - `React` whole React object, as for `require('react')` (JSX syntax is not supported here)
158 - `h` shortcut for React.createElement
159 - `t` [translator function](https://github.com/rejetto/hfs/blob/main/frontend/src/i18n.ts)
160 - `_` [lodash library](https://lodash.com/docs/)
157 -- `Icon` component for icons. Properties:
158 - - `name: string` refer to file `icons.ts` for names, but you can also enter an emoji instead.
161 +- `Icon: ReactComponent` Properties:
162 + - `name: string` refer to file `icons.ts` for names, but you can also enter an emoji instead.
163
164 The following properties are accessible only immediately at top-level; don't call it later in a callback.
165 - `getPluginConfig()` returns object of all config keys that are declared frontend-accessible by this plugin.
@@ -271,6 +275,7 @@ HFS will scan through them in inverted alphabetical order searching for a compat
275 - 8.2 (v0.46.0)
276 - entry.getNext, getPrevious, getNextFiltered, getPreviousFiltered, getDefaultIcon
277 - platform-dependent distribution
278 + - HFS.watchState
279 - 8.1 (v0.45.0) should have been 0.44.0 but forgot to update number
280 - full URL support for frontend_js and frontend_css
281 - custom.html
frontend/src/misc.ts
+8 -1
@@ -12,6 +12,8 @@ import _ from 'lodash'
12 import { apiCall, setDefaultApiCallOptions } from '@hfs/shared/api'
13 import { reloadList } from './useFetchList'
14 import { logout } from './login'
15 +import { subscribeKey } from 'valtio/utils'
16 +import { uploadState } from './upload'
17 export * from '@hfs/shared'
18
19 export const ERRORS: Record<number, string> = {
@@ -58,7 +60,12 @@ export function hfsEvent(name: string, params?:Dict) {
60 return output
61 }
62
61 -const tools = { h, React, state, t, _, dialogLib, apiCall, reloadList, logout, Icon, hIcon }
63 +const tools = { h, React, state, t, _, dialogLib, apiCall, reloadList, logout, Icon, hIcon,
64 + watchState(k: string, cb: (v: any) => void) {
65 + const up = k.split('upload.')[1]
66 + return subscribeKey(up ? uploadState : state as any, up || k, cb, true)
67 + }
68 +}
69 Object.assign((window as any).HFS ||= {}, {
70 ...tools,
71 onEvent(name: string, cb: (params:any, tools: any, output:any) => any) {