UNPKG

2 kBJavaScriptView Raw
1/**
2 * React Blessed ID Operations
3 * ============================
4 *
5 * Cache register for blessed nodes stored by ID.
6 */
7import {debounce} from 'lodash';
8
9/**
10 * The blessed nodes internal index;
11 */
12const blessedNodes = {};
13
14/**
15 * Backend for blessed ID operations.
16 *
17 * @constructor ReactBlessedIDOperations
18 */
19class ReactBlessedIDOperations {
20 constructor() {
21 this.screen = null;
22 }
23
24 /**
25 * Set the current screen.
26 *
27 * @param {BlessedScreen} screen - The screen to attach.
28 * @return {ReactBlessedIDOperations} - Returns itself.
29 */
30 setScreen(screen) {
31 this.screen = screen;
32
33 // Creating a debounced version of the render method so we won't render
34 // multiple time per frame, in vain.
35 screen.debouncedRender = debounce(() => screen.render(), 0);
36
37 return this;
38 }
39
40 /**
41 * Add a new node to the index.
42 *
43 * @param {string} ID - The node's id.
44 * @param {BlessedNode} node - The node itself.
45 * @return {ReactBlessedIDOperations} - Returns itself.
46 */
47 add(ID, node) {
48 blessedNodes[ID] = node;
49 return this;
50 }
51
52 /**
53 * Get a node from the index.
54 *
55 * @param {string} ID - The node's id.
56 * @return {BlessedNode} - The node.
57 */
58 get(ID) {
59 return blessedNodes[ID];
60 }
61
62 /**
63 * Get the parent of a node from the index.
64 *
65 * @param {string} ID - The node's id.
66 * @return {BlessedScreen|BlessedNode} - The node.
67 */
68 getParent(ID) {
69
70 // If the node is root, we return the screen itself
71 if (ID.match(/\./g).length === 1)
72 return this.screen;
73
74 const parentID = ID.split('.').slice(0, -1).join('.');
75 return this.get(parentID);
76 }
77
78 /**
79 * Drop a node from the index.
80 *
81 * @param {string} ID - The node's id.
82 * @return {ReactBlessedIDOperations} - Returns itself.
83 */
84 drop(ID) {
85 delete blessedNodes[ID];
86 return this;
87 }
88}
89
90export default new ReactBlessedIDOperations();