« get me outta code hell

New fitToParent function - 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
diff options
context:
space:
mode:
authorFlorrie <towerofnix@gmail.com>2018-07-25 13:17:24 -0300
committerFlorrie <towerofnix@gmail.com>2018-07-25 13:17:24 -0300
commit07a667058b9f1ae12e07222b3058d0e2500dd3dc (patch)
tree046c01fac3e50b9a70a3f3899e162b133ffec73c /ui
parentc36c19ced2e8f9824744d0543b6d97d64606d953 (diff)
New fitToParent function
Diffstat (limited to 'ui')
-rw-r--r--ui/DisplayElement.js34
1 files changed, 34 insertions, 0 deletions
diff --git a/ui/DisplayElement.js b/ui/DisplayElement.js
index 1ba9852..66d29aa 100644
--- a/ui/DisplayElement.js
+++ b/ui/DisplayElement.js
@@ -132,6 +132,40 @@ module.exports = class DisplayElement extends EventEmitter {
     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) {