MDL-59758 js: auto_rows module easier to use
authorDamyon Wiese <damyon@moodle.com>
Fri, 8 Sep 2017 06:51:31 +0000 (14:51 +0800)
committerDamyon Wiese <damyon@moodle.com>
Tue, 7 Nov 2017 02:36:13 +0000 (10:36 +0800)
Allow passing the direct text area, or a container.
Trigger change events on the text area, not the container.
Properly handle starting with rows > 1

lib/amd/build/auto_rows.min.js
lib/amd/src/auto_rows.js

index 30ec60f..c95209b 100644 (file)
Binary files a/lib/amd/build/auto_rows.min.js and b/lib/amd/build/auto_rows.min.js differ
index 1532ad2..2c04a47 100644 (file)
@@ -42,6 +42,7 @@ define(['jquery'], function($) {
      */
     var calculateRows = function(element) {
         var currentRows = element.attr('rows');
+        var minRows = element.data('min-rows');
         var maxRows = element.attr('data-max-rows');
 
         var height = element.height();
@@ -58,13 +59,38 @@ define(['jquery'], function($) {
         // based on the row attribute.
         element.css('height', '');
 
-        if (maxRows && rows >= maxRows) {
+        if (rows < minRows) {
+            return minRows;
+        } else if (maxRows && rows >= maxRows) {
             return maxRows;
         } else {
             return rows;
         }
     };
 
+    /**
+     * Listener for change events to trigger resizing of the element.
+     *
+     * @method changeListener
+     * @param {Event} e The triggered event.
+     * @private
+     */
+    var changeListener = function(root, e) {
+        var element = $(e.target);
+        var minRows = element.data('min-rows');
+        var currentRows = element.attr('rows');
+
+        if (typeof minRows === "undefined") {
+            element.data('min-rows', currentRows);
+        }
+        var rows = calculateRows(element);
+
+        if (rows != currentRows) {
+            element.attr('rows', rows);
+            element.trigger(EVENTS.ROW_CHANGE);
+        }
+    };
+
     /**
      * Add the event listeners for all text areas within the given element.
      *
@@ -73,16 +99,11 @@ define(['jquery'], function($) {
      * @public
      */
     var init = function(root) {
-        $(root).on('input propertychange', SELECTORS.ELEMENT, function(e) {
-            var element = $(e.target);
-            var currentRows = element.attr('rows');
-            var rows = calculateRows(element);
-
-            if (rows != currentRows) {
-                element.attr('rows', rows);
-                $(root).trigger(EVENTS.ROW_CHANGE);
-            }
-        });
+        if ($(root).data('auto-rows')) {
+            $(root).on('input propertychange', changeListener.bind(this, root));
+        } else {
+            $(root).on('input propertychange', SELECTORS.ELEMENT, changeListener.bind(this, root));
+        }
     };
 
     return /** @module core/auto_rows */ {