| 1 |
/* ************************************************************************ */ |
| 2 |
/* */ |
| 3 |
/* This file is part of Frama-C. */ |
| 4 |
/* */ |
| 5 |
/* Copyright (C) 2007-2022 */ |
| 6 |
/* CEA (Commissariat à l'énergie atomique et aux énergies */ |
| 7 |
/* alternatives) */ |
| 8 |
/* */ |
| 9 |
/* you can redistribute it and/or modify it under the terms of the GNU */ |
| 10 |
/* Lesser General Public License as published by the Free Software */ |
| 11 |
/* Foundation, version 2.1. */ |
| 12 |
/* */ |
| 13 |
/* It is distributed in the hope that it will be useful, */ |
| 14 |
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */ |
| 15 |
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ |
| 16 |
/* GNU Lesser General Public License for more details. */ |
| 17 |
/* */ |
| 18 |
/* See the GNU Lesser General Public License version 2.1 */ |
| 19 |
/* for more details (enclosed in the file licenses/LGPLv2.1). */ |
| 20 |
/* */ |
| 21 |
/* ************************************************************************ */ |
| 22 |
|
| 23 |
/* eslint-disable @typescript-eslint/explicit-function-return-type */ |
| 24 |
/* eslint-disable @typescript-eslint/no-explicit-any */ |
| 25 |
|
| 26 |
/** |
| 27 |
Dome Application (Renderer Process) |
| 28 |
|
| 29 |
This modules manages your main application window |
| 30 |
and its interaction with the main process. |
| 31 |
|
| 32 |
Example: |
| 33 |
|
| 34 |
* ```ts |
| 35 |
* // File 'src/renderer/index.js': |
| 36 |
* import Application from './Application.js' ; |
| 37 |
* Dome.setContent( Application ); |
| 38 |
* ``` |
| 39 |
|
| 40 |
@packageDocumentation |
| 41 |
@module dome |
| 42 |
*/ |
| 43 |
|
| 44 |
import _ from 'lodash'; |
| 45 |
import React from 'react'; |
| 46 |
import ReactDOM from 'react-dom'; |
| 47 |
import { AppContainer } from 'react-hot-loader'; |
| 48 |
import { ipcRenderer } from 'electron'; |
| 49 |
import SYS, * as System from 'dome/system'; |
| 50 |
import * as Json from 'dome/data/json'; |
| 51 |
import * as Settings from 'dome/data/settings'; |
| 52 |
import './dark.css'; |
| 53 |
import './light.css'; |
| 54 |
import './style.css'; |
| 55 |
import { State } from './data/states'; |
| 56 |
|
| 57 |
// -------------------------------------------------------------------------- |
| 58 |
// --- Context |
| 59 |
// -------------------------------------------------------------------------- |
| 60 |
|
| 61 |
// main window focus |
| 62 |
let windowFocus = true; |
| 63 |
|
| 64 |
function setContextAppNode() { |
| 65 |
const node = document.getElementById('app'); |
| 66 |
if (node) { |
| 67 |
node.className = |
| 68 |
`dome-container dome-platform-${System.platform |
| 69 |
}${windowFocus ? ' dome-window-active' : ' dome-window-inactive'}`; |
| 70 |
} |
| 71 |
return node; |
| 72 |
} |
| 73 |
|
| 74 |
// -------------------------------------------------------------------------- |
| 75 |
// --- Helpers |
| 76 |
// -------------------------------------------------------------------------- |
| 77 |
|
| 78 |
/** Configured to be `'true'` when in development mode. */ |
| 79 |
export const { DEVEL } = System; |
| 80 |
|
| 81 |
export type PlatformKind = 'linux' | 'macos' | 'windows'; |
| 82 |
|
| 83 |
/** System platform. */ |
| 84 |
export const platform: PlatformKind = (System.platform as PlatformKind); |
| 85 |
|
| 86 |
// -------------------------------------------------------------------------- |
| 87 |
// --- User's Directories |
| 88 |
// -------------------------------------------------------------------------- |
| 89 |
|
| 90 |
let loadedPaths = false; |
| 91 |
const remoteAppPaths: { [index: string]: string } = {}; |
| 92 |
|
| 93 |
function getPath(k: string): string { |
| 94 |
if (!loadedPaths) { |
| 95 |
loadedPaths = true; |
| 96 |
Object.assign(remoteAppPaths, ipcRenderer.sendSync('dome.app.paths')); |
| 97 |
} |
| 98 |
return remoteAppPaths[k]; |
| 99 |
} |
| 100 |
|
| 101 |
/** Returns user's home directory. */ |
| 102 |
export function getHome() { return getPath('home'); } |
| 103 |
|
| 104 |
/** Returns user's desktop directory. */ |
| 105 |
export function getDesktop() { return getPath('desktop'); } |
| 106 |
|
| 107 |
/** Returns user's documents directory. */ |
| 108 |
export function getDocuments() { return getPath('documents'); } |
| 109 |
|
| 110 |
/** Returns user's downloads directory. */ |
| 111 |
export function getDownloads() { return getPath('downloads'); } |
| 112 |
|
| 113 |
/** Returns temporary directory. */ |
| 114 |
export function getTempDir() { return getPath('temp'); } |
| 115 |
|
| 116 |
/** Working directory (Application Window). */ |
| 117 |
export function getWorkingDir() { return System.getWorkingDir(); } |
| 118 |
|
| 119 |
/** Current process ID.. */ |
| 120 |
export function getPID() { return System.getPID(); } |
| 121 |
|
| 122 |
// -------------------------------------------------------------------------- |
| 123 |
// --- Application Emitter |
| 124 |
// -------------------------------------------------------------------------- |
| 125 |
|
| 126 |
/** Typed Dome Event. |
| 127 |
|
| 128 |
To register an event with no argument, simply use `new Event('myEvent')`. |
| 129 |
*/ |
| 130 |
export class Event<A = void> { |
| 131 |
|
| 132 |
private name: string; |
| 133 |
|
| 134 |
constructor(name: string) { |
| 135 |
this.name = name; |
| 136 |
this.emit = this.emit.bind(this); |
| 137 |
} |
| 138 |
|
| 139 |
on(callback: (arg: A) => void) { |
| 140 |
System.emitter.on(this.name, callback); |
| 141 |
} |
| 142 |
|
| 143 |
off(callback: (arg: A) => void) { |
| 144 |
System.emitter.off(this.name, callback); |
| 145 |
} |
| 146 |
|
| 147 |
/** |
| 148 |
Notify all listeners with the provided argument. |
| 149 |
This methods is bound to the event, so you may use `myEvent.emit` |
| 150 |
as a callback function, instead of eg. `(arg) => myEvent.emit(arg)`. |
| 151 |
*/ |
| 152 |
emit(arg: A) { |
| 153 |
System.emitter.emit(this.name, arg); |
| 154 |
} |
| 155 |
|
| 156 |
/** |
| 157 |
Number of currenty registered listeners. |
| 158 |
*/ |
| 159 |
listenerCount() { |
| 160 |
return System.emitter.listenerCount(this.name); |
| 161 |
} |
| 162 |
|
| 163 |
} |
| 164 |
|
| 165 |
/** Custom React Hook on event. */ |
| 166 |
export function useEvent<A>( |
| 167 |
evt: undefined | null | Event<A>, |
| 168 |
callback: (arg: A) => void, |
| 169 |
) { |
| 170 |
return React.useEffect(() => { |
| 171 |
if (evt) { |
| 172 |
evt.on(callback); |
| 173 |
return () => evt.off(callback); |
| 174 |
} |
| 175 |
return undefined; |
| 176 |
}, [evt, callback]); |
| 177 |
} |
| 178 |
|
| 179 |
// -------------------------------------------------------------------------- |
| 180 |
// --- Application Events |
| 181 |
// -------------------------------------------------------------------------- |
| 182 |
|
| 183 |
/** |
| 184 |
Dome update event. |
| 185 |
It is emitted when a general re-rendering is required, typically when |
| 186 |
the window frame is resized. |
| 187 |
You can use it for your own components as an easy-to-use global |
| 188 |
re-render event. |
| 189 |
*/ |
| 190 |
export const update = new Event('dome.update'); |
| 191 |
|
| 192 |
/** |
| 193 |
Dome reload event. |
| 194 |
It is emitted when the entire window is reloaded. |
| 195 |
*/ |
| 196 |
export const reload = new Event('dome.reload'); |
| 197 |
ipcRenderer.on('dome.ipc.reload', () => reload.emit()); |
| 198 |
|
| 199 |
/** |
| 200 |
Dome « Find » event. Trigered by [Cmd+F] and [Edit > Find] menu. |
| 201 |
*/ |
| 202 |
export const find = new Event('dome.find'); |
| 203 |
ipcRenderer.on('dome.ipc.find', () => find.emit()); |
| 204 |
|
| 205 |
/** Command-line arguments event handler. */ |
| 206 |
export function onCommand( |
| 207 |
job: (argv: string[], workingDir: string) => void, |
| 208 |
) { |
| 209 |
System.emitter.on('dome.command', job); |
| 210 |
} |
| 211 |
|
| 212 |
ipcRenderer.on('dome.ipc.command', (_event, argv, wdir) => { |
| 213 |
SYS.setCommandLine(argv, wdir); |
| 214 |
System.emitter.emit('dome.command', argv, wdir); |
| 215 |
}); |
| 216 |
|
| 217 |
/** Window Settings event. |
| 218 |
Emitted when window settings are reset or restored. */ |
| 219 |
export const windowSettings = new Event(Settings.window); |
| 220 |
|
| 221 |
/** Global Settings event. |
| 222 |
Emiited when global settings are updated. */ |
| 223 |
export const globalSettings = new Event(Settings.global); |
| 224 |
|
| 225 |
// -------------------------------------------------------------------------- |
| 226 |
// --- Closing |
| 227 |
// -------------------------------------------------------------------------- |
| 228 |
|
| 229 |
ipcRenderer.on('dome.ipc.closing', System.doExit); |
| 230 |
|
| 231 |
/** Register a callback to be executed when the window is closing. */ |
| 232 |
export function atExit(callback: () => void) { |
| 233 |
System.atExit(callback); |
| 234 |
} |
| 235 |
|
| 236 |
// -------------------------------------------------------------------------- |
| 237 |
// --- Focus Management |
| 238 |
// -------------------------------------------------------------------------- |
| 239 |
|
| 240 |
/** Window focus event. */ |
| 241 |
export const focus = new Event<boolean>('dome.focus'); |
| 242 |
|
| 243 |
/** Current focus state of the main window. See also [[useWindowFocus]]. */ |
| 244 |
export function isFocused() { return windowFocus; } |
| 245 |
|
| 246 |
ipcRenderer.on('dome.ipc.focus', (_sender, value) => { |
| 247 |
windowFocus = value; |
| 248 |
setContextAppNode(); |
| 249 |
focus.emit(value); |
| 250 |
}); |
| 251 |
|
| 252 |
/** Return the current window focus. See [[isFocused]]. */ |
| 253 |
export function useWindowFocus(): boolean { |
| 254 |
useUpdate(focus); |
| 255 |
return windowFocus; |
| 256 |
} |
| 257 |
|
| 258 |
// -------------------------------------------------------------------------- |
| 259 |
// --- Web Navigation |
| 260 |
// -------------------------------------------------------------------------- |
| 261 |
|
| 262 |
/** |
| 263 |
DOM href events for internal URLs. |
| 264 |
|
| 265 |
This event is emitted whenever some `<a href/>` DOM element |
| 266 |
is clicked with an internal link. External links will be automatically |
| 267 |
opened with the user's default Web navigator. |
| 268 |
*/ |
| 269 |
export const navigate = new Event<string>('dome.href'); |
| 270 |
|
| 271 |
ipcRenderer.on( |
| 272 |
'dome.ipc.href', |
| 273 |
(_sender, href) => navigate.emit(href), |
| 274 |
); |
| 275 |
|
| 276 |
// -------------------------------------------------------------------------- |
| 277 |
// --- Window Management |
| 278 |
// -------------------------------------------------------------------------- |
| 279 |
|
| 280 |
export function isApplicationWindow() { |
| 281 |
return process.argv.includes(SYS.WINDOW_APPLICATION_ARGV); |
| 282 |
} |
| 283 |
|
| 284 |
export function isPreferencesWindow() { |
| 285 |
return process.argv.includes(SYS.WINDOW_PREFERENCES_ARGV); |
| 286 |
} |
| 287 |
|
| 288 |
// -------------------------------------------------------------------------- |
| 289 |
// --- Window Title |
| 290 |
// -------------------------------------------------------------------------- |
| 291 |
|
| 292 |
/** Sets the modified status of the window-frame flag. |
| 293 |
User feedback is platform dependent. */ |
| 294 |
export function setModified(modified = false) { |
| 295 |
ipcRenderer.send('dome.ipc.window.modified', modified); |
| 296 |
} |
| 297 |
|
| 298 |
/** Sets the window-frame title. */ |
| 299 |
export function setTitle(title: string) { |
| 300 |
ipcRenderer.send('dome.ipc.window.title', title); |
| 301 |
} |
| 302 |
|
| 303 |
// -------------------------------------------------------------------------- |
| 304 |
// --- Window Container |
| 305 |
// -------------------------------------------------------------------------- |
| 306 |
|
| 307 |
function setContainer( |
| 308 |
Component: React.FunctionComponent | React.ComponentClass, |
| 309 |
) { |
| 310 |
Settings.synchronize(); |
| 311 |
const appNode = setContextAppNode(); |
| 312 |
const contents = <AppContainer><Component /></AppContainer>; |
| 313 |
ReactDOM.render(contents, appNode); |
| 314 |
} |
| 315 |
|
| 316 |
// -------------------------------------------------------------------------- |
| 317 |
// --- Main Content |
| 318 |
// -------------------------------------------------------------------------- |
| 319 |
|
| 320 |
/** |
| 321 |
Defines the user's main window content. |
| 322 |
|
| 323 |
Binds the component to the main window. A `<Component/>` instance is |
| 324 |
generated and rendered in the `#app` window element. Its class name is set to |
| 325 |
`dome-platform-<platform>` with the `<platform>` set to the `Dome.platform` |
| 326 |
value. This class name can be used as a CSS selector for platform-dependent |
| 327 |
styling. |
| 328 |
|
| 329 |
@param Component - to be rendered in the main window |
| 330 |
*/ |
| 331 |
export function setApplicationWindow( |
| 332 |
Component: React.FunctionComponent | React.ComponentClass, |
| 333 |
) { |
| 334 |
if (isApplicationWindow()) setContainer(Component); |
| 335 |
} |
| 336 |
|
| 337 |
// -------------------------------------------------------------------------- |
| 338 |
// --- Settings Window |
| 339 |
// -------------------------------------------------------------------------- |
| 340 |
|
| 341 |
/** |
| 342 |
Defines the user's preferences window content. |
| 343 |
|
| 344 |
A `<Component/>` instance is generated and rendered in the `#app` window |
| 345 |
element. Its class name is set to `dome-platform-<platform>` with the |
| 346 |
`<platform>` set to the `Dome.platform` value. This class name can be used as |
| 347 |
a CSS selector for platform-dependent styling. |
| 348 |
|
| 349 |
@param Component - to be rendered in the preferences window |
| 350 |
*/ |
| 351 |
export function setPreferencesWindow( |
| 352 |
Component: React.FunctionComponent | React.ComponentClass, |
| 353 |
) { |
| 354 |
if (isPreferencesWindow()) setContainer(Component); |
| 355 |
} |
| 356 |
|
| 357 |
// -------------------------------------------------------------------------- |
| 358 |
// --- MenuBar Management |
| 359 |
// -------------------------------------------------------------------------- |
| 360 |
|
| 361 |
type callback = () => void; |
| 362 |
const customItemCallbacks = new Map<string, callback>(); |
| 363 |
|
| 364 |
/** |
| 365 |
Create a new custom menu in the menu bar. |
| 366 |
|
| 367 |
|
| 368 |
This function shall be called statically, although calls from _secondary_ |
| 369 |
windows would be ignored. It is also possible to call this function from the |
| 370 |
main process. |
| 371 |
|
| 372 |
It is also possible to call this function from the main process. |
| 373 |
|
| 374 |
@param label - the menu title (shall be unique) |
| 375 |
*/ |
| 376 |
export function addMenu(label: string) { |
| 377 |
ipcRenderer.send('dome.ipc.menu.addmenu', label); |
| 378 |
} |
| 379 |
|
| 380 |
export type MenuName = 'File' | 'Edit' | 'View' | string; |
| 381 |
export type MenuItemType = 'normal' | 'separator' | 'checkbox' | 'radio'; |
| 382 |
|
| 383 |
export interface MenuItemProps { |
| 384 |
/** The label of the menu to insert the item in. */ |
| 385 |
menu: MenuName; |
| 386 |
/** The menu item identifier. Shall be unique in the _entire_ menu bar. */ |
| 387 |
id: string; |
| 388 |
/** Default is `'normal'`. */ |
| 389 |
type: MenuItemType; |
| 390 |
/** Item label. Only optional for separators. */ |
| 391 |
label?: string; |
| 392 |
/** Item is visible or not (default is `true`). */ |
| 393 |
visible?: boolean; |
| 394 |
/** Enabled item (default is `true`). */ |
| 395 |
enabled?: boolean; |
| 396 |
/** Item status for radio and checkbox. Default is `false`. */ |
| 397 |
checked?: boolean; |
| 398 |
/** Keyboard shortcut. */ |
| 399 |
key?: string; |
| 400 |
/** Callback. */ |
| 401 |
onClick?: () => void; |
| 402 |
} |
| 403 |
|
| 404 |
/** Inserts a new custom item in a menu. |
| 405 |
|
| 406 |
The menu can be modified later with [[setMenuItem]]. |
| 407 |
|
| 408 |
When clicked, the menu-item will also trigger a `'dome.menu.clicked'(id)` |
| 409 |
event on all application windows. The item callback, if any, is invoked only |
| 410 |
in the process that specify it. |
| 411 |
|
| 412 |
Key short cuts shall be specified with the following codes: - `"Cmd+<Key>"` |
| 413 |
for command (MacOS) or control (Linux) key - `"Alt+<Key>"` for command+option |
| 414 |
(MacOS) or alt (Linux) key - `"Meta+<Key>"` for command+shift (MacOS) or |
| 415 |
control+alt (Linux) key |
| 416 |
|
| 417 |
This function shall be called statically, although calls from _secondary_ |
| 418 |
windows would be ignored. It is also possible to call this function from the |
| 419 |
main process. |
| 420 |
*/ |
| 421 |
export function addMenuItem(props: MenuItemProps) { |
| 422 |
if (!props.id && props.type !== 'separator') { |
| 423 |
// eslint-disable-next-line no-console |
| 424 |
console.error('[Dome] Missing menu-item identifier', props); |
| 425 |
return; |
| 426 |
} |
| 427 |
const { onClick, ...options } = props; |
| 428 |
if (onClick) customItemCallbacks.set(props.id, onClick); |
| 429 |
ipcRenderer.send('dome.ipc.menu.addmenuitem', options); |
| 430 |
} |
| 431 |
|
| 432 |
export interface MenuItemOptions { |
| 433 |
id: string; |
| 434 |
label?: string; |
| 435 |
visible?: boolean; |
| 436 |
enabled?: boolean; |
| 437 |
checked?: boolean; |
| 438 |
onClick?: null | (() => void); |
| 439 |
} |
| 440 |
|
| 441 |
/** |
| 442 |
Update properties of an existing menu-item. |
| 443 |
|
| 444 |
If an `onClick` callback is specified, it will _replace_ the previous one. |
| 445 |
You shall specify `null` to remove the previously registered callback |
| 446 |
(`undefined` callback is ignored). |
| 447 |
|
| 448 |
It is also possible to call this function from the main process. |
| 449 |
*/ |
| 450 |
export function setMenuItem(options: MenuItemOptions) { |
| 451 |
const { onClick, ...updates } = options; |
| 452 |
if (onClick === null) { |
| 453 |
customItemCallbacks.delete(options.id); |
| 454 |
} else if (onClick !== undefined) { |
| 455 |
customItemCallbacks.set(options.id, onClick); |
| 456 |
} |
| 457 |
ipcRenderer.send('dome.ipc.menu.setmenuitem', updates); |
| 458 |
} |
| 459 |
|
| 460 |
ipcRenderer.on('dome.ipc.menu.clicked', (_sender, id: string) => { |
| 461 |
const callback = customItemCallbacks.get(id); |
| 462 |
if (callback) callback(); |
| 463 |
}); |
| 464 |
|
| 465 |
// -------------------------------------------------------------------------- |
| 466 |
// --- Context Menus |
| 467 |
// -------------------------------------------------------------------------- |
| 468 |
|
| 469 |
export interface PopupMenuItemProps { |
| 470 |
/** Item label. */ |
| 471 |
label: string; |
| 472 |
/** Optional menu identifier. */ |
| 473 |
id?: string; |
| 474 |
/** Displayed item, default is `true`. */ |
| 475 |
display?: boolean; |
| 476 |
/** Enabled item, default is `true`. */ |
| 477 |
enabled?: boolean; |
| 478 |
/** Checked item, default is `false`. */ |
| 479 |
checked?: boolean; |
| 480 |
/** Item selection callback. */ |
| 481 |
onClick?: (() => void); |
| 482 |
} |
| 483 |
|
| 484 |
export type PopupMenuItem = PopupMenuItemProps | 'separator'; |
| 485 |
|
| 486 |
/** |
| 487 |
Popup a contextual menu. |
| 488 |
|
| 489 |
Items can be separated by inserting a `'separator'` constant string in the |
| 490 |
array. Item identifier and label default to each others. Alternatively, an |
| 491 |
item can be specified by a single string that will be used for both its label |
| 492 |
and identifier. Undefined or null items are allowed (and skipped). |
| 493 |
|
| 494 |
The menu is displayed at the current mouse location. The callback is called |
| 495 |
with the selected item identifier or label. If the menu popup is canceled by |
| 496 |
the user, the callback is called with `undefined`. |
| 497 |
|
| 498 |
Example: |
| 499 |
|
| 500 |
* ```ts |
| 501 |
* let myPopup = (_evt) => Dome.popupMenu([ …items… ],(id) => … ); |
| 502 |
* <div onRightClick={myPopup}>...</div> |
| 503 |
* ``` |
| 504 |
|
| 505 |
*/ |
| 506 |
export function popupMenu( |
| 507 |
items: PopupMenuItem[], |
| 508 |
callback?: (item: string | undefined) => void, |
| 509 |
) { |
| 510 |
const ipcItems = items.map((item) => { |
| 511 |
if (!item) return undefined; |
| 512 |
if (item === 'separator') return item; |
| 513 |
return { |
| 514 |
label: item.label, |
| 515 |
id: item.id, |
| 516 |
display: !!(item.display ?? true), |
| 517 |
enabled: !!(item.enabled ?? true), |
| 518 |
checked: !!(item.checked ?? false), |
| 519 |
}; |
| 520 |
}); |
| 521 |
ipcRenderer.invoke('dome.popup', ipcItems).then((index: number) => { |
| 522 |
const item = items[index]; |
| 523 |
if (item && item !== 'separator') { |
| 524 |
const { id, label, onClick } = item; |
| 525 |
if (onClick) onClick(); |
| 526 |
if (callback) callback(id || label); |
| 527 |
} else { |
| 528 |
if (callback) callback(undefined); |
| 529 |
} |
| 530 |
}); |
| 531 |
} |
| 532 |
|
| 533 |
// -------------------------------------------------------------------------- |
| 534 |
// --- React Hooks |
| 535 |
// -------------------------------------------------------------------------- |
| 536 |
|
| 537 |
/** |
| 538 |
Hook to re-render on demand (Custom React Hook). |
| 539 |
Returns a callback to trigger a render on demand. |
| 540 |
*/ |
| 541 |
export function useForceUpdate() { |
| 542 |
const [tac, onTic] = React.useState(false); |
| 543 |
return () => onTic(!tac); |
| 544 |
} |
| 545 |
|
| 546 |
/** |
| 547 |
Hook to re-render on Dome events (Custom React Hook). |
| 548 |
@param events - event names, defaults to a single `'dome.update'`. |
| 549 |
*/ |
| 550 |
export function useUpdate(...events: Event<any>[]) { |
| 551 |
const fn = useForceUpdate(); |
| 552 |
React.useEffect(() => { |
| 553 |
const theEvents = events ? events.slice() : [update]; |
| 554 |
theEvents.forEach((evt) => evt.on(fn)); |
| 555 |
return () => theEvents.forEach((evt) => evt.off(fn)); |
| 556 |
}); |
| 557 |
} |
| 558 |
|
| 559 |
/** |
| 560 |
Hook to re-render when a Promise returns. |
| 561 |
The promise will be typically created by using `React.useMemo()`. |
| 562 |
The hook returns three informations: |
| 563 |
- result: the promise result if it succeeds, undefined otherwise; |
| 564 |
- error: the promise error if it fails, undefined otherwise; |
| 565 |
- loading: the promise status, true if the promise is still running. |
| 566 |
*/ |
| 567 |
export function usePromise<T>(job: Promise<T>) { |
| 568 |
const [result, setResult] = React.useState<T | undefined>(); |
| 569 |
const [error, setError] = React.useState<Error | undefined>(); |
| 570 |
const [loading, setLoading] = React.useState(true); |
| 571 |
React.useEffect(() => { |
| 572 |
let cancel = false; |
| 573 |
const doCancel = () => { if (!cancel) setLoading(false); return cancel; }; |
| 574 |
const onResult = (x: T) => { if (!doCancel()) setResult(x); }; |
| 575 |
const onError = (e: Error) => { if (!doCancel()) setError(e); }; |
| 576 |
job.then(onResult, onError); |
| 577 |
return () => { cancel = true; }; |
| 578 |
}, [job]); |
| 579 |
return { result, error, loading }; |
| 580 |
} |
| 581 |
|
| 582 |
/* Internal type alias */ |
| 583 |
type Serialize<A> = (a: A) => string; |
| 584 |
|
| 585 |
/** |
| 586 |
Hook to add a cache system to a function, allowing to reuse previous results. |
| 587 |
As the equality used in JS maps does not allow to effectively implement a |
| 588 |
cache for complex type, a serialization function can be procured. |
| 589 |
The hook returns the cached version of the function. |
| 590 |
*/ |
| 591 |
export function useCache<K, V>(r: (k: K) => V, s?: Serialize<K>): (k: K) => V { |
| 592 |
const { current: cache } = React.useRef(new Map<string, V>()); |
| 593 |
const serialize = React.useMemo(() => s ? s : (k: K) => `${k}`, [s]); |
| 594 |
const get = React.useCallback((k: K): V => { |
| 595 |
const id = serialize(k); |
| 596 |
if (cache.has(id)) |
| 597 |
return cache.get(id) as V; |
| 598 |
const v = r(k); |
| 599 |
cache.set(id, v); |
| 600 |
return v; |
| 601 |
}, [cache, r, serialize]); |
| 602 |
return get; |
| 603 |
} |
| 604 |
|
| 605 |
// -------------------------------------------------------------------------- |
| 606 |
// --- Timer Hooks |
| 607 |
// -------------------------------------------------------------------------- |
| 608 |
|
| 609 |
interface Clock { |
| 610 |
timer?: NodeJS.Timeout; |
| 611 |
pending: number; // Number of listeners |
| 612 |
time: number; // Ellapsed time since firts pending |
| 613 |
event: string; // Tic events |
| 614 |
period: number; // Period |
| 615 |
} |
| 616 |
|
| 617 |
// Collection of clocks indexed by period |
| 618 |
const CLOCKS = new Map<number, Clock>(); |
| 619 |
|
| 620 |
const CLOCKEVENT = (period: number) => `dome.clock.${period}`; |
| 621 |
|
| 622 |
const TIC_CLOCK = (clk: Clock) => () => { |
| 623 |
if (0 < clk.pending) { |
| 624 |
clk.time += clk.period; |
| 625 |
System.emitter.emit(clk.event, clk.time); |
| 626 |
} else { |
| 627 |
if (clk.timer) clearInterval(clk.timer); |
| 628 |
CLOCKS.delete(clk.period); |
| 629 |
} |
| 630 |
}; |
| 631 |
|
| 632 |
const INC_CLOCK = (period: number) => { |
| 633 |
let clk = CLOCKS.get(period); |
| 634 |
if (!clk) { |
| 635 |
const event = CLOCKEVENT(period); |
| 636 |
const time = (new Date()).getTime(); |
| 637 |
clk = { pending: 0, time, period, event }; |
| 638 |
clk.timer = setInterval(TIC_CLOCK(clk), period); |
| 639 |
CLOCKS.set(period, clk); |
| 640 |
} |
| 641 |
clk.pending++; |
| 642 |
return clk.event; |
| 643 |
}; |
| 644 |
|
| 645 |
const DEC_CLOCK = (period: number) => { |
| 646 |
const clk = CLOCKS.get(period); |
| 647 |
if (clk) clk.pending--; |
| 648 |
}; |
| 649 |
|
| 650 |
export interface Timer { |
| 651 |
/** Starts the timer, if not yet. */ |
| 652 |
start(): void; |
| 653 |
/** Stops the timer. Can be restarted after. */ |
| 654 |
stop(): void; |
| 655 |
/** Elapsed time (in milliseconds). */ |
| 656 |
time: number; |
| 657 |
/** Running timer. */ |
| 658 |
running: boolean; |
| 659 |
} |
| 660 |
|
| 661 |
/** |
| 662 |
Synchronized start & stop timer (Custom React Hook). |
| 663 |
|
| 664 |
Create a local timer, synchronized on a global clock, that can be started |
| 665 |
and stopped on demand during the life cycle of the component. |
| 666 |
|
| 667 |
Each timer has its individual start & stop state. However, |
| 668 |
all timers with the same period _are_ synchronized with each others. |
| 669 |
|
| 670 |
@param period - timer interval, in milliseconds (ms) |
| 671 |
@param initStart - whether to initially start the timer (default is `false`) |
| 672 |
|
| 673 |
*/ |
| 674 |
export function useClock(period: number, initStart: boolean): Timer { |
| 675 |
const started = React.useRef(0); |
| 676 |
const [time, setTime] = React.useState(0); |
| 677 |
const [running, setRunning] = React.useState(initStart); |
| 678 |
const start = React.useCallback(() => setRunning(false), []); |
| 679 |
const stop = React.useCallback(() => { |
| 680 |
setRunning(false); |
| 681 |
setTime(0); |
| 682 |
started.current = 0; |
| 683 |
}, []); |
| 684 |
React.useEffect(() => { |
| 685 |
if (running) { |
| 686 |
const event = INC_CLOCK(period); |
| 687 |
const callback = (t: number) => { |
| 688 |
if (!started.current) started.current = t; |
| 689 |
else setTime(t - started.current); |
| 690 |
}; |
| 691 |
System.emitter.on(event, callback); |
| 692 |
return () => { |
| 693 |
System.emitter.off(event, callback); |
| 694 |
DEC_CLOCK(period); |
| 695 |
}; |
| 696 |
} return undefined; |
| 697 |
}, [period, running]); |
| 698 |
return { time, running, start, stop }; |
| 699 |
} |
| 700 |
|
| 701 |
// -------------------------------------------------------------------------- |
| 702 |
// --- Settings Hookds |
| 703 |
// -------------------------------------------------------------------------- |
| 704 |
|
| 705 |
/** |
| 706 |
Bool window settings helper. Default is `false` unless specified. |
| 707 |
*/ |
| 708 |
export function useBoolSettings( |
| 709 |
key: string | undefined, |
| 710 |
defaultValue = false, |
| 711 |
) { |
| 712 |
return Settings.useWindowSettings( |
| 713 |
key, Json.jBoolean, defaultValue, |
| 714 |
); |
| 715 |
} |
| 716 |
|
| 717 |
/** |
| 718 |
Bool window settings helper with a flip callback. |
| 719 |
*/ |
| 720 |
export function useFlipSettings( |
| 721 |
key: string | undefined, |
| 722 |
defaultValue = false, |
| 723 |
): [boolean, () => void] { |
| 724 |
const [state, setState] = Settings.useWindowSettings( |
| 725 |
key, Json.jBoolean, defaultValue, |
| 726 |
); |
| 727 |
return [state, () => setState(!state)]; |
| 728 |
} |
| 729 |
|
| 730 |
/** Number window settings helper. Default is `0` unless specified. */ |
| 731 |
export function useNumberSettings( |
| 732 |
key: string | undefined, |
| 733 |
defaultValue = 0, |
| 734 |
): State<number> { |
| 735 |
return Settings.useWindowSettings( |
| 736 |
key, Json.jNumber, defaultValue, |
| 737 |
); |
| 738 |
} |
| 739 |
|
| 740 |
/** String window settings. Default is `''` unless specified). */ |
| 741 |
export function useStringSettings(key: string | undefined, defaultValue = '') { |
| 742 |
return Settings.useWindowSettings( |
| 743 |
key, Json.jString, defaultValue, |
| 744 |
); |
| 745 |
} |
| 746 |
|
| 747 |
/** Optional string window settings. Default is `undefined`. */ |
| 748 |
export function useStringOptSettings(key: string | undefined) { |
| 749 |
return Settings.useWindowSettings( |
| 750 |
key, Json.jString, undefined, |
| 751 |
); |
| 752 |
} |
| 753 |
|
| 754 |
/** Direct shortcut to [[dome/data/settings.useWindowSettings]]. */ |
| 755 |
export const { useWindowSettings } = Settings; |
| 756 |
|
| 757 |
/** |
| 758 |
Utility shortcut to [[dome/data/settings.useGlobalSettings]] |
| 759 |
with global settings class created on-the-fly. |
| 760 |
*/ |
| 761 |
export function useGlobalSettings<A extends Json.json>( |
| 762 |
globalKey: string, |
| 763 |
decoder: Json.Loose<A>, |
| 764 |
defaultValue: A, |
| 765 |
) { |
| 766 |
// Object creation is cheaper than useMemo... |
| 767 |
const G = new Settings.GlobalSettings( |
| 768 |
globalKey, decoder, Json.identity, defaultValue, |
| 769 |
); |
| 770 |
return Settings.useGlobalSettings(G); |
| 771 |
} |
| 772 |
|
| 773 |
// -------------------------------------------------------------------------- |
| 774 |
// --- Pretty Printing (Browser Console) |
| 775 |
// -------------------------------------------------------------------------- |
| 776 |
|
| 777 |
export class Debug { |
| 778 |
moduleName: string; |
| 779 |
constructor(moduleName: string) { |
| 780 |
this.moduleName = moduleName; |
| 781 |
} |
| 782 |
|
| 783 |
/* eslint-disable no-console */ |
| 784 |
|
| 785 |
log(...args: any) { |
| 786 |
if (DEVEL) console.log(`[${this.moduleName}]`, ...args); |
| 787 |
} |
| 788 |
|
| 789 |
warn(...args: any) { |
| 790 |
if (DEVEL) console.warn(`[${this.moduleName}]`, ...args); |
| 791 |
} |
| 792 |
|
| 793 |
error(...args: any) { |
| 794 |
if (DEVEL) console.error(`[${this.moduleName}]`, ...args); |
| 795 |
} |
| 796 |
|
| 797 |
/* eslint-enable */ |
| 798 |
} |
| 799 |
|
| 800 |
// -------------------------------------------------------------------------- |