From 3a63b73b88487744dd8f0a0e0d3bb68625175c7d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?"J.=20Rene=CC=81e=20Beach"?= <splendidnoise@gmail.com>
Date: Fri, 1 Feb 2013 16:46:25 -0500
Subject: [PATCH] Issue #1880606 by jessebeach: Introduce a configuration UI 
 for theme-based breakpoints
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Signed-off-by: J. Renée Beach <splendidnoise@gmail.com>
---
 core/modules/layout/config/layout.devices.yml |   21 +
 core/modules/layout/css/layout.base.css       |  134 ++++++
 core/modules/layout/css/layout.theme.css      |   23 +
 core/modules/layout/images/handle.png         |    4 +
 core/modules/layout/images/ruler.png          |    3 +
 core/modules/layout/js/layout.js              |  603 +++++++++++++++++++++++++
 core/modules/layout/layout.module             |  128 ++++++
 7 files changed, 916 insertions(+)
 create mode 100644 core/modules/layout/config/layout.devices.yml
 create mode 100644 core/modules/layout/css/layout.base.css
 create mode 100644 core/modules/layout/css/layout.theme.css
 create mode 100644 core/modules/layout/images/handle.png
 create mode 100644 core/modules/layout/images/ruler.png
 create mode 100644 core/modules/layout/js/layout.js

diff --git a/core/modules/layout/config/layout.devices.yml b/core/modules/layout/config/layout.devices.yml
new file mode 100644
index 0000000..da246a4
--- /dev/null
+++ b/core/modules/layout/config/layout.devices.yml
@@ -0,0 +1,21 @@
+devices:
+  iphone:
+    label: iPhone
+    dimensions:
+      width: 320
+      height: 480
+  android:
+    label: Android
+    dimensions:
+      width: 540
+      height: 960
+  ipad:
+    label: iPad
+    dimensions:
+      width: 768
+      height: 1024
+  desktop:
+    label: desktop
+    dimensions:
+      width: 1366
+      height: 768
diff --git a/core/modules/layout/css/layout.base.css b/core/modules/layout/css/layout.base.css
new file mode 100644
index 0000000..97c2197
--- /dev/null
+++ b/core/modules/layout/css/layout.base.css
@@ -0,0 +1,134 @@
+#layout-previewer-container {
+  box-shadow: 0 0 10px 0 black;
+  display: none;
+  height: 100%;
+  left: -200%;
+  position: absolute;
+  width: 100%;
+  z-index: 1500;
+}
+#layout-previewer-container.active {
+  display: block;
+  left: 0;
+}
+.layout-modal-background {
+  background-color: black;
+  background-color: rgba(0,0,0,0.92);
+  bottom: 0;
+  height: 100%;
+  left: 0;
+  position: fixed;
+  right: 0;
+  top: 3em;
+  width: 100%;
+  z-index: 1;
+}
+.layout-slider-background {
+  background-color: white;
+  border: 1px solid white;
+  height: 2em;
+  position: absolute;
+  top: 1px;
+  width: 100%;
+  z-index: 2;
+}
+#layout-bp-view {
+  background-color: rgba(150,150,150,0.6667);
+  height: 2em;
+  position: absolute;
+  top: 2px;
+  width: 100%;
+  z-index: 5;
+}
+.layout-bp {
+  height: 2em;
+  position: absolute;
+  left: auto;
+  top: 0;
+  width: 100%;
+}
+.layout-bp div {
+  box-sizing: border-box;
+  height: 2em;
+  margin: 0 auto;
+  width: 100%;
+}
+.layout-bp-min {
+  background-color: rgba(255,255,255,0.75);
+  border-color: white;
+  border-style: solid;
+  border-width: 0 1px;
+  position: relative;
+}
+.layout-bp .label {
+  box-sizing: border-box;
+  display: block;
+  font-size: 0.7em;
+  height: 1em;
+  left: -100%;
+  line-height: 1;
+  padding-right: 6px;
+  position: absolute;
+  text-align: right;
+  top: 0;
+  white-space: nowrap;
+  width: 100%;
+}
+#frame-slider {
+  z-index: 50;
+}
+#frame-slider.ui-slider-horizontal .ui-slider-handle {
+  border: 0;
+  border-left: 1px solid #b0b0b0;
+  border-radius: 0;
+  height: 100%;
+  margin-left: 0;
+  top: 0;
+}
+#frame-slider.ui-slider-horizontal .ui-slider-handle + .ui-slider-handle {
+  border-left: 0 none;
+  border-right: 1px solid #b0b0b0;
+  margin-left: -1.2em;
+}
+#layout-previewer-container iframe {
+  height: 100%;
+  position: relative;
+  width: 100%;
+  z-index: 25;
+}
+#layout-previewer-controls {
+  position: absolute;
+  top: 1em;
+  z-index: 100;
+}
+#layout-size-input {
+  float: left;
+  font-size: 0.75em;
+}
+#layout-size-input * {
+  -moz-box-sizing: border-box;
+  -webkit-box-sizing: border-box;
+  box-sizing: border-box;
+  display: inline-block;
+  float: left;
+}
+#layout-size-input .label {
+}
+#layout-size-input input {
+  padding: 0;
+  width: 10em;
+}
+#layout-size-input .unit {
+}
+#layout-devices-list {
+  display: block;
+  float: left;
+}
+/* Override Toolbar styling */
+.layout-preview-frame #toolbar-administration {
+  display: none !important;
+}
+body.toolbar-tray-open.layout-preview-frame {
+  margin-left: 0 !important;
+  margin-right: 0 !important;
+}
diff --git a/core/modules/layout/css/layout.theme.css b/core/modules/layout/css/layout.theme.css
new file mode 100644
index 0000000..10016f9
--- /dev/null
+++ b/core/modules/layout/css/layout.theme.css
@@ -0,0 +1,23 @@
+#frame-slider {
+  background-attachment: scroll;
+  background-color: transparent;
+  background-image: url("../images/ruler.png");
+  background-position: center bottom;
+  background-repeat: repeat-x;
+  border-color: #ccc;
+  border-style: solid;
+  border-radius: 0;
+  border-width: 1px 0 0;
+  height: 2em;
+}
+#frame-slider .ui-slider-range {
+  background: none;
+  background-color: rgba(90,90,90,0.2);
+}
+#frame-slider.ui-slider-horizontal .ui-slider-handle {
+  background-attachment: scroll;
+  background-color: transparent;
+  background-image: url("../images/handle.png");
+  background-position: center 1px;
+  background-repeat: no-repeat;
+}
diff --git a/core/modules/layout/images/handle.png b/core/modules/layout/images/handle.png
new file mode 100644
index 0000000..656b884
--- /dev/null
+++ b/core/modules/layout/images/handle.png
@@ -0,0 +1,4 @@
+PNG
+
+   IHDR         &(ۙ   tEXtSoftware Adobe ImageReadyqe<  IDATxڤ9Aa?@B !$8	82bZ$q_fke[\AS~˛/@z"hEI'ėXFov.1"2(=ܻ/9LX_USB.uXsA{VX`˅xc0Еdl6q8D"i< k^)8뽿%&x5#0#LN'%r9jQy8G;>a.K1R9L:|Bp'vz"F-|Hv4ᕛTnQXr;C9VT.-# GܨT*r@Q^Fd9sR)lZV(ك	nZ4>H=n^KaPW)UFWCRD?wFȃS:(pjRkUV.JCb^+5Ul60ը&()n*{T/iZLcͩGĮ:ő
+e>:T-{*zVmи=l|!&JIJcTŭ^lTnRT. >]C`ci(et 2(M^L͕ɒ{R@ҤAcӎwG1:$? *M=b    IENDB`
\ No newline at end of file
diff --git a/core/modules/layout/images/ruler.png b/core/modules/layout/images/ruler.png
new file mode 100644
index 0000000..a600619
--- /dev/null
+++ b/core/modules/layout/images/ruler.png
@@ -0,0 +1,3 @@
+PNG
+
+   IHDR   Z      )#yM   tEXtSoftware Adobe ImageReadyqe<   CIDATxױ   AuXWXTB®NfF _thC;"]  V    IENDB`
\ No newline at end of file
diff --git a/core/modules/layout/js/layout.js b/core/modules/layout/js/layout.js
new file mode 100644
index 0000000..3c5c5ba
--- /dev/null
+++ b/core/modules/layout/js/layout.js
@@ -0,0 +1,603 @@
+(function (Drupal, $) {
+
+  Drupal.layout = Drupal.layout || {};
+
+  var size; // The width of the preview container.
+  var handles = []; // The values of the jQuery UI Slider handles.
+  var leftOffset; // The left value of the iframe containing the previewed page.
+  var $frame; // The iframe that contains the previewed page.
+  var iframeDocument; // The document of the iframe that contains the preview.
+  var $slider; // The jQuery UI Slider widget that adjusts the iframed preview.
+  var $container; // The container of the page preview component.
+  var $sizeInput; // The input element that display the width of the preview.
+  var breakpoints = {}; // A list of breakpoints, keyed by configuration string.
+  var $breakpointView; // The container of the breakpoint views.
+  var devices = {};
+  var $deviceSelectorView; // A select element of pre-configured device sizes.
+
+  Drupal.behaviors.layout = {
+    attach: function (context, settings) {
+      var $body = $(window.top.document.body).once('layout-preview');
+
+      if ($body.length) {
+        // Set up the trigger link.
+        $('#layout-previewer').on('click.layout', toggleLayoutPreview);
+      }
+      // Remove administrative elements in the document inside the iframe.
+      if (window.top !== window.self) {
+        window.self.document.body.className += ' layout-preview-frame';
+      }
+    }
+  };
+
+  /**
+   * Toggles the layout preview component on or off.
+   *
+   * When first toggled on, the layout preview component is built. All
+   * subsequent toggles hide or show the build component.
+   *
+   * @param Object Event
+   *   - jQuery Event object.
+   */
+  var toggleLayoutPreview = function (event) {
+    event.preventDefault();
+    // Build the previewer if it doesn't exist.
+    if (!$container) {
+      // Initialize the handle positions.
+      handles = (handles.length) ? handles : [0, document.documentElement.clientWidth];
+      buildPreviewer();
+      // Size is the width of the iframe.
+      updateDimensions({width: (size || window.top.document.documentElement.clientWidth)});
+    }
+    $container.toggleClass('active');
+  };
+
+  /**
+   * Assembles a layout previewer.
+   */
+  var buildPreviewer = function () {
+    $(window.top.document.body).once('layout-preview-container', function (index, element) {
+      $container = $(Drupal.theme('layoutContainer'))
+        .appendTo(window.top.document.body);
+      $frame = $(Drupal.theme('layoutFrame'))
+        .css({
+          'width': size
+        })
+        .appendTo($container);
+      // Slider.
+      $slider = $(Drupal.theme('layoutSlider'))
+        .slider({
+          'animate': 'fast',
+          'range': true,
+          'max': document.documentElement.clientWidth,
+          'min': 0,
+          'values': handles,
+          'slide': handleSlide
+        })
+        .prependTo($container);
+
+      // Load the breakpoints for the current theme.
+      if ('breakpoints' in Drupal.settings.layout.routes) {
+        $.ajax(Drupal.settings.layout.routes.breakpoints)
+          .success(breakpointsCallback);
+      }
+      // Attach controls
+      $container.append(Drupal.theme('layoutControls'));
+      // Load the preconfigured device settings.
+      if ('devices' in Drupal.settings.layout.routes) {
+        $.ajax(Drupal.settings.layout.routes.devices)
+          .success(devicesCallback);
+      }
+      // Width label.
+      $sizeInput = $(Drupal.theme('layoutSizeInput'))
+        .appendTo($container.find('#layout-previewer-controls'));
+      // Displace the top of the container.
+      $container
+        .css({
+          top: getDisplacement('top'),
+        })
+        .attr('data-offset-top', getDisplacement('top'));
+      // The contentDocument property is not supported in IE until IE8.
+      iframeDocument = $frame[0].contentDocument || $frame[0].contentWindow.document;
+
+      $(window.top).on('resize.layout', handleWindowResize);
+      $sizeInput.on('keypress.layout', {pattern: /^[0-9\.]$/, callback: handleSizeInputChange}, keyManager);
+      $container.on('sizeUpdate.layout', refreshPreviewSizing);
+
+      // Trigger a resize to kick off some initial placements.
+      $(window.top).triggerHandler('resize.layout');
+
+      // Load the current page URI into the preview iframe.
+      // @todo, are there any security implications to loading a page like this?
+      iframeDocument.location.href = Drupal.settings.basePath + Drupal.settings.currentPath;
+    });
+  };
+
+  /**
+   * Responds to a jQuery UI Slider slide event.
+   *
+   * @param Object Event
+   *   - jQuery Event object.
+   *
+   * @param Object ui
+   *   - jQuery Slider widget state information resulting from a slide event.
+   */
+  var handleSlide = function (event, ui) {
+    // Layout will control the placement of the handles.
+    event.preventDefault();
+    var delta = 0;
+    var vals = [];
+    var handle, split, width;
+    // Get the delta of the original value of the handles and the new value.
+    for (var i = ui.values.length - 1; i >= 0; i--) {
+      // Get the original handle value.
+      var handle = handles[i];
+      // The new handle value.
+      var value = ui.values[i];
+      // If the original and the new values are not equal, adjust the handles.
+      if (handle !== value) {
+        var max = $slider.slider('option', 'max');
+        var otherHandle = (i === 0) ? 1 : 0;
+        vals[i] = value;
+        // The value of the other handle is the inverse of the percentage of the
+        // active handle.
+        vals[otherHandle] = max * (1 - (value / max));
+        // Get the updated width of the viewport.
+        width = Math.abs(vals[i] - vals[otherHandle]);
+        // Update the dimension variables in the closure.
+        updateDimensions({width: width});
+        // Only one handle moves at a time, so if a handle-move was processed,
+        // then break;
+        break;
+      }
+    }
+  };
+
+  /**
+   * Responds to keypress events from the frame size input.
+   *
+   * @param Object Event
+   *   - jQuery Event object.
+   */
+  var handleSizeInputChange = function (event) {
+    var newSize;
+    if (event.isDefaultPrevented()) {
+      return false;
+    }
+    if (event.key) {
+      newSize = $sizeInput.find('input').val();
+      // If the key is a '.' and the value already contains one then
+      // prevent default.
+      if (event.key == '.' && newSize.indexOf('.') > -1) {
+        event.preventDefault();
+      }
+    }
+    // Process the press of the enter key.
+    if (event.keyCode === 13) {
+      var newSize = parseFloat($sizeInput.find('input').val());
+      if (newSize > 0) {
+        // Update the dimensions variables in the closure.
+        updateDimensions({width: newSize}, 250);
+      }
+    }
+  };
+
+  /**
+   * Updates the dimension variables of the previewer components.
+   *
+   * @param Array values
+   *   - An array that contains the position values of the handles of the jQuery
+   *   UI slider.
+   *
+   * @param max
+   *   - The maximum width of the previewer. Often this is just the width of the
+   *   client.
+   *
+   * @param speed
+   *   - A number representing time in milliseconds or a jQuery speed keyword.
+   *   Determines the speed at which animations between changes dimension values
+   *   should take place. Defaults to zero.
+   */
+  var updateDimensions = function (dimensions, speed) {
+    var width = dimensions.width || NaN;
+    var height = dimensions.height || NaN;
+    // Calculate the handle placements.
+    var max = $slider.slider('option', 'max');
+    var values = [];
+    var gutterPercent = (1 - (width / max)) / 2;
+    values[0] = gutterPercent * max;
+    values[1] = (gutterPercent * max) + width;
+    // Store the new values of the handles.
+    handles = [values[0], values[1]];
+    // Set the new size of the frame.
+    size = Math.round((max * ((values[1] - values[0]) / max)) * 10) / 10;
+    // Set the left offset of the frame.
+    leftOffset = max * (values[0] / max);
+    // Trigger a dimension change.
+    $container.trigger('sizeUpdate.layout', speed);
+  };
+
+  /**
+   * Responds to window resize events.
+   *
+   * @param Object Event
+   *   - jQuery Event object.
+   */
+  var handleWindowResize = function (event) {
+    var doc = this.document.documentElement;
+    var docWidth = doc.clientWidth;
+    var framePercent = size / docWidth;
+    var gutterPercent = (1 - framePercent) / 2;
+    // Adjust the parameters of the slider.
+    $slider
+      // The new max of the slider is the width of the document.
+      .slider('option', 'max', docWidth)
+      // Update the position values of the slider handles.
+      .slider('values', [(gutterPercent * docWidth), ((gutterPercent + framePercent) * docWidth)]);
+    // If the window has been reduced below the width of the frame, reduce the
+    // width of the frame.
+    updateDimensions({width: ((docWidth < size) ? docWidth : size)});
+    // Adjust the parameters of the frame.
+    $frame.css({
+      'left': gutterPercent * docWidth,
+      'width': size
+    });
+    // Adjust the position of the size input.
+    var inputPercent = $sizeInput.width() / docWidth;
+    gutterPercent = (1 - inputPercent) / 2;
+    $container.find('#layout-previewer-controls').css({
+      'left': gutterPercent * docWidth
+    });
+    // Update the size input value.
+    $sizeInput.find('input').val(size);
+  };
+
+  /**
+   * Renders breakpoint configuration to an HTML view.
+   *
+   * @param Object data
+   *   - Breakpoint configuration data. The keys of the object correspond to the
+   *   keys of theme-configured breakpoints. The value of each key is a string
+   *   that represents a media query.
+   *
+   * @param String textStatus
+   *   - The status of the AJAX request.
+   *
+   * @param Object jqXHR
+   *   - A jQuery XMLHttpRequest object.
+   */
+  var breakpointsCallback = function (data, textStatus, jqXHR) {
+    $breakpointView = $(Drupal.theme('layoutBreakpointView'));
+    var $item, options;
+    for (var bp in data) {
+      if (data.hasOwnProperty(bp)) {
+        breakpoints[bp] = parseMediaQuery(data[bp]);
+        // Append a representation of each breakpoint to the frame slider.
+        if (breakpoints[bp].hasquery) {
+          options = breakpoints[bp];
+          options.id = 'layout-bp-' + bp.replace(/\./g, '-');
+          options.label = bp;
+          $item = $(Drupal.theme('layoutBreakpointItemView', options));
+          $breakpointView.prepend($item);
+        }
+      }
+    }
+    if ($breakpointView.children().length) {
+      // @todo, These breakpoints should be sorted by minw eventually. For now
+      // we assume they are listed from small to largest.
+      $container.append($breakpointView);
+    }
+  };
+
+  /**
+   * Renders device configuration to an HTML view.
+   *
+   * @param Object data
+   *   - Device configuration data. The keys of the object correspond to the
+   *   names of devices.
+   *
+   * @param String textStatus
+   *   - The status of the AJAX request.
+   *
+   * @param Object jqXHR
+   *   - A jQuery XMLHttpRequest object.
+   */
+  var devicesCallback = function (data, textStatus, jqXHR) {
+    var deviceName, deviceInfo, identifier, options;
+    // Build the select element.
+    $deviceSelectorView = $(Drupal.theme('deviceSelector'));
+    // Create a select box in the UI for selecting a pre-configured device.
+    for (deviceName in data) {
+      if (data.hasOwnProperty(deviceName)) {
+        deviceInfo = data[deviceName];
+        // Clean the device name
+        identifier = 'layout-device-' + deviceName.replace(/\s/g, '-');
+        // Save the device data.
+        devices[identifier] = deviceInfo;
+        // Build the options.
+        options = {
+          'label': deviceInfo.label,
+          'value': identifier
+        }
+        // Create a select item.
+        $deviceSelectorView.append($(Drupal.theme('deviceSelectorItem', options)));
+      }
+    }
+    if ($deviceSelectorView.length > 0) {
+      // Prepend a 'no device' option.
+      $deviceSelectorView.prepend($(Drupal.theme('deviceSelectorItem', {
+        'label': Drupal.t('No device selected'),
+        'value': ''
+      })));
+    // Append the selector to the preview container.
+    $container
+      .find('#layout-previewer-controls')
+      .append($deviceSelectorView)
+      .on('change', '#layout-devices-list', loadDeviceViewConfig);
+    }
+  };
+
+  /**
+   *
+   */
+  function loadDeviceViewConfig (event) {
+    var info, width;
+    var value = $(event.target).val();
+    if (value && value in devices) {
+      info = devices[value];
+      var width = info.dimensions.width;
+      updateDimensions({width: width}, 250);
+    }
+  }
+
+  /**
+   * Redraws the layout preview component based on the stored dimensions.
+   *
+   * @param Object event
+   *   - A jQuery event object.
+   *
+   * @param Number/String speed
+   *   - A number representing time in milliseconds or a jQuery speed keyword.
+   *   Determines the speed at which animations between changes dimension values
+   *   should take place. Defaults to zero.
+   */
+  var refreshPreviewSizing = function (event, speed) {
+    speed = speed || 0;
+    // Adjust the frame.
+    $slider.slider('option', 'values', [handles[0], handles[1]]);
+    $frame.animate({
+      left: leftOffset,
+      width: size
+    }, speed);
+    // Update the size input value.
+    $sizeInput.find('input').val(size);
+  };
+
+  /**
+   * Get the total displacement of given region.
+   *
+   * @param String region
+   *   Region name. Either "top" or "bottom".
+   *
+   * @return
+   *   The total displacement of given region in pixels.
+   */
+  var getDisplacement = function (region) {
+    var displacement = 0;
+    var lastDisplaced = $('[data-offset-' + region + ']');
+    if (lastDisplaced.length) {
+      displacement = parseInt(lastDisplaced.attr('data-offset-' + region));
+    }
+    return displacement;
+  };
+
+  $.extend(Drupal.theme, {
+    /**
+     * Returns the preview container element.
+     */
+    layoutContainer: function () {
+      return '<div id="layout-previewer-container"><div class="layout-slider-background"></div><div class="layout-modal-background"></div></div>';
+    },
+
+    /**
+     * Returns an overlay iframe element.
+     */
+    layoutFrame: function (url) {
+      return '<iframe id="layout-previewer" frameborder="0" scrolling="auto" allowtransparency="true"></iframe>';
+    },
+
+    /**
+     * Returns the HTML for the jQuery UI Slider attachment.
+     */
+    layoutSlider: function () {
+      return '<div id="frame-slider"></div>';
+    },
+
+    /**
+     *
+     */
+    layoutControls: function () {
+      return '<div id="layout-previewer-controls" />';
+    },
+
+    /**
+     * Returns the input element for changing the preview width.
+     */
+    layoutSizeInput: function () {
+      return '<div id="layout-size-input"><span class="label">' + Drupal.t('Width') + '</span><input name="layout_width" type="text" /><span class="unit">px</span></div>';
+    },
+
+    /**
+     * Returns the wrapper for breakpoint item views.
+     */
+    layoutBreakpointView: function () {
+      return '<div id="layout-bp-view"></div>'
+    },
+
+    /**
+     * Returns individual breakpoint configuration views.
+     */
+    layoutBreakpointItemView: function (options) {
+      var markup = '';
+      options = options || {};
+
+      markup += '<div id="' + (options.id || '')  + '" class="layout-bp">';
+      markup += '<div class="layout-bp-max" style="width:' + ((options.maxw) ? options.maxw : ((options.minw) ? options.minw : 'auto')) + ';">';
+      markup += '<div class="layout-bp-min" style="width:' + ((options.minw) ? options.minw : 'auto') + ';"><span class="label">' + options.label  + '</span></div>';
+      markup += '</div>';
+      markup += '</div>';
+
+      return markup;
+    },
+
+    /**
+     * Returns a select list of preconfigured device dimensions.
+     */
+    deviceSelector: function () {
+      return '<select id="layout-devices-list"></select>';
+    },
+
+    /**
+     * Returns an option item for the device selector.
+     */
+    deviceSelectorItem: function (options) {
+      return '<option value="' + options.value +'">' + options.label + '</option>';
+    }
+  });
+
+  /**
+   * Handles key input.
+   *
+   * Fires a callback function with either return the key that was pressed in
+   * the event.key property, or, if the key is a control key or does not match
+   * a supplied pattern, then null as the event.key value.
+   *
+   * @param Regex event.data.pattern
+   *   - A regular expression that filters allowed key input. Only keys matching
+   *   the expression will be returned. All other keys return null.
+   *
+   * @param Function event.data.callback
+   *   - A callback function to be invoked after a key is processed. Any
+   *   variadic parameters supplied to keyManager are passed through as well.
+   *
+   * @param Array event.data.controls
+   *   - An Array of char codes that should be ignored as control keys.
+   */
+  var keyManager = function (event) {
+    event.data = event.data || {};
+    var pattern = event.data.pattern || undefined;
+    var callback = event.data.callback || undefined;
+    var controls = event.data.controls || [
+      8, // Delete.
+      13, // Enter.
+      37, // Left.
+      38, // Up.
+      39, // Right.
+      40 // Down.
+    ];
+    // Get the key from its keyCode.
+    var key = mapKeyToChar(event.shiftKey, event.keyCode);
+    // Prevent default if:
+    // (1) mapKeyToChar did not produce a key and the key is not a control key.
+    // (2) mapKeyToChar produced a key and the pattern does not match.
+    if ((!key && $.inArray(event.keyCode, controls) === -1) ||
+        (key && (pattern && typeof pattern === 'object' && 'exec' in pattern && !pattern.exec(key)))) {
+      event.preventDefault();
+    }
+    // Provide the key as the mapped character in the event object.
+    event.key = (key) ? key : null;
+    // The callback function should check for isDefaultPrevented() to know if
+    // the keyManager validated this key.
+    if (callback && typeof callback === 'function') {
+      callback.apply(this, arguments);
+    }
+  }
+
+  /**
+   * Maps keyCode to Strings, taking the shift key state into account.
+   *
+   * @param Boolean isShifted
+   *   - A Boolean representing if the shift key was pressed (true) or not
+   *   (false)
+   *
+   * @param Number keyCode
+   *   - The numeric code of the key that was pressed.
+   *
+   * @return String
+   *   - A single character corresponding to the keyCode or null if no
+   *   correspondence is found.
+   */
+  var mapKeyToChar = function (isShifted, keyCode) {
+    if (keyCode === 27
+      || keyCode === 8
+      || keyCode === 9
+      || keyCode === 20
+      || keyCode === 16
+      || keyCode === 17
+      || keyCode === 91
+      || keyCode === 13
+      || keyCode === 92
+      || keyCode === 18) {
+      return false;
+    }
+    if (typeof isShifted != "boolean" || typeof keyCode != "number") {
+      return false;
+    }
+    var charMap = [];
+    charMap[192] = "~";
+    charMap[49] = "!";
+    charMap[50] = "@";
+    charMap[51] = "#";
+    charMap[52] = "$";
+    charMap[53] = "%";
+    charMap[54] = "^";
+    charMap[55] = "&";
+    charMap[56] = "*";
+    charMap[57] = "(";
+    charMap[48] = ")";
+    charMap[109] = "_";
+    charMap[107] = "+";
+    charMap[219] = "{";
+    charMap[221] = "}";
+    charMap[220] = "|";
+    charMap[59] = ":";
+    charMap[222] = "\"";
+    charMap[188] = "<";
+    charMap[190] = ">";
+    charMap[191] = "?";
+    charMap[32] = " ";
+    var character = "";
+    if (isShifted) {
+      if (keyCode >= 65 && keyCode <= 90) {
+        character = String.fromCharCode(keyCode);
+      }
+      else {
+        character = charMap[keyCode];
+      }
+    }
+    else {
+      if (keyCode >= 65 && keyCode <= 90) {
+        character = String.fromCharCode(keyCode).toLowerCase();
+      }
+      else {
+        character = String.fromCharCode(keyCode);
+      }
+    }
+    return character;
+  }
+
+  /**
+   * Parses a String representing a media query into usable values.
+   *
+   * @param String mq
+   *   - A String representing a media query e.g. 'all and (min-width: 800px)'
+   */
+  var parseMediaQuery = function (mq) {
+    return {
+      media : mq.split("(")[0].match(/(only\s+)?([a-zA-Z]+)\s?/) && RegExp.$2 || "all",
+      hasquery: mq.indexOf("(") > -1,
+      minw  : mq.match(/\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/) && parseFloat(RegExp.$1) + (RegExp.$2 || ""),
+      maxw  : mq.match(/\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/) && parseFloat(RegExp.$1) + (RegExp.$2 || "")
+    }
+  }
+}(Drupal, jQuery));
diff --git a/core/modules/layout/layout.module b/core/modules/layout/layout.module
index c6ed7ae..93a3a36 100644
--- a/core/modules/layout/layout.module
+++ b/core/modules/layout/layout.module
@@ -5,6 +5,8 @@
  * Manages page layouts for content presentation.
  */
 
+use Symfony\Component\HttpFoundation\JsonResponse;
+
 /**
  * Implements hook_menu().
  */
@@ -25,6 +27,20 @@ function layout_menu() {
     'access arguments' => array(4),
     'file' => 'layout.admin.inc',
   );
+  // Fetch breakpoints for a theme.
+  $items['layout/breakpoints'] = array(
+    'page callback' => 'layout_retrieve_theme_breakpoints_jsonp',
+    'access callback' => 'user_access',
+    'access arguments' => array('administer layouts'),
+    'type' => MENU_CALLBACK,
+  );
+  // Fetch device listing.
+  $items['layout/devices'] = array(
+    'page callback' => 'layout_retrieve_device_info_jsonp',
+    'access callback' => 'user_access',
+    'access arguments' => array('administer layouts'),
+    'type' => MENU_CALLBACK,
+  );
   return $items;
 }
 
@@ -80,3 +96,115 @@ function layout_theme($existing, $type, $theme, $path) {
   }
   return $items;
 }
+
+/**
+ * Page callback: Returns the breakpoints of the current active theme.
+ *
+ * @see layout_menu().
+ */
+function layout_retrieve_device_info_jsonp() {
+  $devices = config('layout.devices')->get('devices');
+
+  $response = new JsonResponse($devices);
+  return $response;
+}
+
+/**
+ * Page callback: Returns the breakpoints of the current active theme.
+ *
+ * @see layout_menu().
+ */
+function layout_retrieve_theme_breakpoints_jsonp() {
+  global $theme_key;
+
+  // Get the configured breakpoint to switch from vertical to horizontal
+  // toolbar presentation.
+  $media_queries = array();
+  $breakpoints = entity_load('breakpoint_group', 'theme.' . $theme_key . '.' . $theme_key);
+  if (!empty($breakpoints)) {
+    $media_queries = array_map(
+      function($object) {
+        return $object->mediaQuery;
+      },
+      $breakpoints->breakpoints
+    );
+  }
+
+  $response = new JsonResponse($media_queries);
+  return $response;
+}
+
+/**
+ * Implements hook_toolbar().
+ */
+function layout_toolbar() {
+  $items = array();
+
+  $items['layout_preview'] = array(
+    'tab' => array(
+      '#type' => 'link',
+      '#title' => t('Layout preview'),
+      '#href' => '',
+      '#html' => TRUE,
+      '#options' => array(
+        'attributes' => array(
+          'title' => t('Preview page layout'),
+          'id' => 'layout-previewer',
+        ),
+      ),
+    ),
+    '#attached' => array(
+      'library' => array(
+        array('layout', 'layout.previewer'),
+      ),
+    ),
+    '#weight' => 200,
+  );
+
+  return $items;
+}
+
+/**
+ * Implements hook_library().
+ */
+function layout_library_info() {
+  $libraries = array();
+  $path = drupal_get_path('module', 'layout');
+  $options = array(
+    'scope' => 'footer',
+    'attributes' => array('defer' => TRUE),
+  );
+
+  $libraries['layout.previewer'] = array(
+    'title' => 'Preview layouts',
+    'website' => 'http://drupal.org/project/layout',
+    'version' => VERSION,
+    'css' => array(
+      $path . '/css/layout.base.css',
+      $path . '/css/layout.theme.css',
+    ),
+    'js' => array(
+      // Core.
+      $path . '/js/layout.js' => $options,
+      array(
+        'data' => array(
+          'layout' => array(
+            'routes' => array(
+              'breakpoints' => 'layout/breakpoints',
+              'devices' => 'layout/devices',
+            ),
+          ),
+        ),
+        'type' => 'setting',
+      ),
+    ),
+    'dependencies' => array(
+      array('system', 'jquery'),
+      array('system', 'drupal.ajax'),
+      array('system', 'drupalSettings'),
+      array('system', 'jquery.ui.slider'),
+    ),
+  );
+
+  return $libraries;
+}
-- 
1.7.10.4

