« get me outta code hell

DisplayElement.js « ui - tui-lib - Pure Node.js library for making visual command-line programs (ala vim, ncdu)
about summary refs log tree commit diff
path: root/ui/DisplayElement.js
blob: b27772e45877b4b039019120ddef4b7f00bafbfc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
const EventEmitter = require('events')
const exception = require('../util/exception')

module.exports = class DisplayElement extends EventEmitter {
  // A general class that handles dealing with screen coordinates, the tree
  // of elements, and other common stuff.
  //
  // This element doesn't handle any real rendering; just layouts. Placing
  // characters at specific positions should be implemented in subclasses.
  //
  // It's a subclass of EventEmitter, so you can make your own events within
  // the logic of your subclass.

  constructor() {
    super()

    this[DisplayElement.drawValues] = {}
    this[DisplayElement.lastDrawValues] = {}
    this[DisplayElement.scheduledDraw] = false

    this.children = []
    this.parent = null

    this.visible = true

    this.x = 0
    this.y = 0
    this.w = 0
    this.h = 0

    this.hPadding = 0
    this.vPadding = 0

    // Note! This only applies to the parent, not the children. Useful for
    // when you want an element to cover the whole screen but allow mouse
    // events to pass through.
    this.clickThrough = false
  }

  drawTo(writable) {
    // Writes text to a "writable" - an object that has a "write" method.
    // Custom rendering should be handled as an override of this method in
    // subclasses of DisplayElement.
  }

  renderTo(writable) {
    // Like drawTo, but only calls drawTo if the element is visible. Use this
    // with your root element, not drawTo.

    if (this.visible) {
      this.drawTo(writable)
      this.drawChildrenTo(writable)
      this.didRenderTo(writable)
    }
  }

  didRenderTo(writable) {
    // Called immediately after rendering this element AND all of its
    // children. If you need to do something when that happens, override this
    // method in your subclass.
    //
    // It's fine to draw more things to the writable here - just keep in mind
    // that it'll be drawn over this element and its children, but not any
    // elements drawn in the future.
  }

  fixLayout() {
    // Adjusts the layout of children in this element. If your subclass has
    // any children in it, you should override this method.
  }

  fixAllLayout() {
    // Runs fixLayout on this as well as all children.

    this.fixLayout()
    for (const child of this.children) {
      child.fixAllLayout()
    }
  }

  drawChildrenTo(writable) {
    // Draws all of the children to a writable.

    for (const child of this.children) {
      child.renderTo(writable)
    }
  }

  getDep(key) {
    return this[DisplayElement.drawValues][key]
  }

  setDep(key, value) {
    const oldValue = this[DisplayElement.drawValues][key]
    if (value !== this[DisplayElement.drawValues][key]) {
      this[DisplayElement.drawValues][key] = value
      this.scheduleDraw()
      // Grumble: technically it's possible for a root element to not be an
      // actual Root. While we don't check for this case most of the time (even
      // though we ought to), we do here because it's not unlikely for draw
      // dependency values to be changed before the element is actually added
      // to a Root element.
      if (this.root.scheduleRender) {
        this.root.scheduleRender()
      }
    }
    return value
  }

  scheduleDrawWithoutPropertyChange() {
    // Utility function for when you need to schedule a draw without updating
    // any particular draw-dependency property on the element. Works by setting
    // an otherwise unused dep to a unique object. (We can't use a symbol here,
    // because then Object.entries doesn't notice it.)
    this.setDep('drawWithoutProperty', Math.random())
  }

  scheduleDraw() {
    this[DisplayElement.scheduledDraw] = true
  }

  unscheduleDraw() {
    this[DisplayElement.scheduledDraw] = false
  }

  hasScheduledDraw() {
    if (this[DisplayElement.scheduledDraw]) {
      for (const [ key, value ] of Object.entries(this[DisplayElement.drawValues])) {
        if (value !== this[DisplayElement.lastDrawValues][key]) {
          return true
        }
      }
    }
    return false
  }

  updateLastDrawValues() {
    Object.assign(this[DisplayElement.lastDrawValues], this[DisplayElement.drawValues])
  }

  eachDescendant(fn) {
    // Run a function on this element, all of its children, all of their
    // children, etc.
    fn(this)
    for (const child of this.children) {
      child.eachDescendant(fn)
    }
  }

  addChild(child, afterIndex = this.children.length, {fixLayout = true} = {}) {
    // TODO Don't let a direct ancestor of this be added as a child. Don't
    // let itself be one of its childs either!

    if (child === this) {
      throw exception(
        'EINVALIDHIERARCHY', 'An element cannot be a child of itself')
    }

    child.parent = this

    if (afterIndex === this.children.length) {
      this.children.push(child)
    } else {
      this.children.splice(afterIndex, 0, child)
    }

    if (fixLayout) {
      child.fixLayout()
    }
  }

  removeChild(child, {fixLayout = true} = {}) {
    // Removes the given child element from the children list of this
    // element. It won't be rendered in the future. If the given element
    // isn't a direct child of this element, nothing will happen.

    if (child.parent !== this) {
      return
    }

    child.parent = null
    this.children.splice(this.children.indexOf(child), 1)

    if (fixLayout) {
      this.fixLayout()
    }
  }

  centerInParent() {
    // Utility function to center this element in its parent. Must be called
    // only when it has a parent. Set the width and height of the element
    // before centering it!

    if (this.parent === null) {
      throw new Error('Cannot center in parent when parent is null')
    }

    this.x = Math.round((this.parent.contentW - this.w) / 2)
    this.y = Math.round((this.parent.contentH - this.h) / 2)
  }

  fillParent() {
    // Utility function to fill this element in its parent. Must be called
    // only when it has a parent.

    if (this.parent === null) {
      throw new Error('Cannot fill parent when parent is null')
    }

    this.x = 0
    this.y = 0
    this.w = this.parent.contentW
    this.h = this.parent.contentH
  }

  fitToParent() {
    // Utility function to position this element so that it stays within its
    // parent's bounds. Must be called only when it has a parent.
    //
    // This function is useful when (and only when) the right or bottom edge
    // of this element may be past the right or bottom edge of its parent.
    // In such a case, the element will first be moved left or up by the
    // distance that its edge exceeds that of its parent, so that its edge is
    // no longer past the parent's. Then, if the left or top edge of the
    // element is less than zero, i.e. outside the parent, it is set to zero
    // and the element's width or height is adjusted so that it does not go
    // past the bounds of the parent.

    if (this.x + this.w > this.parent.right) {
      const offendExtent = (this.x + this.w) - this.parent.contentW
      this.x -= offendExtent
      if (this.x < 0) {
        const offstartExtent = 0 - this.x
        this.w -= offstartExtent
        this.x = 0
      }
    }

    if (this.y + this.h > this.parent.bottom) {
      const offendExtent = (this.y + this.h) - this.parent.contentH
      this.y -= offendExtent
      if (this.y < 0) {
        const offstartExtent = 0 - this.y
        this.h -= offstartExtent
        this.y = 0
      }
    }
  }

  get root() {
    let el = this
    while (el.parent) {
      el = el.parent
    }
    return el
  }

  get directAncestors() {
    const ancestors = []
    let el = this
    while (el.parent) {
      el = el.parent
      ancestors.push(el)
    }
    return ancestors
  }

  getElementAt(x, y) {
    // Gets the topmost element at the provided absolute coordinate.
    // Note that elements which are not visible or have the clickThrough
    // property set to true are not considered.

    const children = this.children.slice()

    // Start searching the last- (top-) rendered children first.
    children.reverse()

    for (const el of children) {
      if (!el.visible || el.clickThrough) {
        continue
      }

      const el2 = el.getElementAt(x, y)
      if (el2) {
        return el2
      }

      const { absX, absY, w, h } = el
      if (absX <= x && absX + w > x) {
        if (absY <= y && absY + h > y) {
          return el
        }
      }
    }
    return null
  }

  get x() { return this.getDep('x') }
  set x(v) { return this.setDep('x', v) }
  get y() { return this.getDep('y') }
  set y(v) { return this.setDep('y', v) }
  get hPadding() { return this.getDep('hPadding') }
  set hPadding(v) { return this.setDep('hPadding', v) }
  get vPadding() { return this.getDep('vPadding') }
  set vPadding(v) { return this.setDep('vPadding', v) }
  get visible() { return this.getDep('visible') }
  set visible(v) { return this.setDep('visible', v) }

  get absX() {
    if (this.parent) {
      return this.parent.contentX + this.x
    } else {
      return this.x
    }
  }

  get absY() {
    if (this.parent) {
      return this.parent.contentY + this.y
    } else {
      return this.y
    }
  }

  // Where contents should be positioned.
  get contentX() { return this.absX + this.hPadding }
  get contentY() { return this.absY + this.vPadding }
  get contentW() { return this.w - this.hPadding * 2 }
  get contentH() { return this.h - this.vPadding * 2 }

  get left()   { return this.x }
  get right()  { return this.x + this.w }
  get top()    { return this.y }
  get bottom() { return this.y + this.h }

  get absLeft()   { return this.absX }
  get absRight()  { return this.absX + this.w - 1 }
  get absTop()    { return this.absY }
  get absBottom() { return this.absY + this.h - 1 }
}

module.exports.drawValues = Symbol('drawValues')
module.exports.lastDrawValues = Symbol('lastDrawValues')
module.exports.scheduledDraw = Symbol('scheduledDraw')