Commit 31b73898 authored by Gábor Hojtsy's avatar Gábor Hojtsy
Browse files

#157752 by quicksketch: extend AHAH functionality to most types of form...

#157752 by quicksketch: extend AHAH functionality to most types of form elements, without writing JavaScript. Also AHAH enable the blocks admin page.
parent 5fc06cec
......@@ -1575,7 +1575,7 @@ function expand_radios($element) {
/**
* Add AHAH information about a form element to the page to communicate with
* javascript. If #ahah_path is set on an element, this additional javascript is
* javascript. If #ahah[path] is set on an element, this additional javascript is
* added to the page header to attach the AHAH behaviors. See ahah.js for more
* information.
*
......@@ -1590,24 +1590,43 @@ function expand_radios($element) {
function form_expand_ahah($element) {
static $js_added = array();
// Add a reasonable default event handler if none specified.
if (isset($element['#ahah']['path']) && !isset($element['#ahah']['event'])) {
switch ($element['#type']) {
case 'submit':
case 'button':
case 'image_button':
$element['#ahah']['event'] = 'click';
break;
case 'password':
case 'textfield':
case 'textarea':
$element['#ahah']['event'] = 'blur';
break;
case 'radio':
case 'checkbox':
case 'select':
$element['#ahah']['event'] = 'change';
break;
}
}
// Adding the same javascript settings twice will cause a recursion error,
// we avoid the problem by checking if the javascript has already been added.
if (!isset($js_added[$element['#id']]) && isset($element['#ahah_event']) && isset($element['#ahah_path'])) {
if (isset($element['#ahah']['path']) && isset($element['#ahah']['event']) && !isset($js_added[$element['#id']])) {
drupal_add_js('misc/jquery.form.js');
drupal_add_js('misc/ahah.js');
drupal_add_js('misc/progress.js');
$ahah_binding = array(
'id' => $element['#id'],
'uri' => url($element['#ahah_path']),
'event' => $element['#ahah_event'],
'effect' => empty($element['#ahah_effect']) ? 'none' : $element['#ahah_effect'],
'method' => empty($element['#ahah_method']) ? 'replace' : $element['#ahah_method'],
'url' => url($element['#ahah']['path']),
'event' => $element['#ahah']['event'],
'wrapper' => empty($element['#ahah']['wrapper']) ? NULL : $element['#ahah']['wrapper'],
'selector' => empty($element['#ahah']['selector']) ? '#'. $element['#id'] : $element['#ahah']['selector'],
'effect' => empty($element['#ahah']['effect']) ? 'none' : $element['#ahah']['effect'],
'method' => empty($element['#ahah']['method']) ? 'replace' : $element['#ahah']['method'],
);
if (!empty($element['#ahah_wrapper'])) {
$ahah_binding['wrapper'] = $element['#ahah_wrapper'];
}
drupal_add_js(array('ahah' => array($element['#id'] => $ahah_binding)), 'setting');
$js_added[$element['#id']] = TRUE;
......
......@@ -7,8 +7,8 @@
* page. The request returns a small chunk of HTML, which is then directly
* injected into the page.
*
* Drupal uses this file to enhance form elements with #ahah_path and
* #ahah_wrapper properties. If set, this file will automatically be included
* Drupal uses this file to enhance form elements with #ahah[path] and
* #ahah[wrapper] properties. If set, this file will automatically be included
* to provide AHAH capabilities.
*/
......@@ -18,8 +18,13 @@
Drupal.behaviors.ahah = function(context) {
for (var base in Drupal.settings.ahah) {
if (!$('#'+ base + '.ahah-processed').size()) {
var element = Drupal.settings.ahah[base];
var ahah = new Drupal.ahah(base, element);
var element_settings = Drupal.settings.ahah[base];
$(element_settings.selector).each(function() {
element_settings.element = this;
var ahah = new Drupal.ahah(base, element_settings);
});
$('#'+ base).addClass('ahah-processed');
}
}
......@@ -28,95 +33,148 @@ Drupal.behaviors.ahah = function(context) {
/**
* AHAH object.
*/
Drupal.ahah = function(base, element) {
Drupal.ahah = function(base, element_settings) {
// Set the properties for this object.
this.id = '#' + base;
this.event = element.event;
this.uri = element.uri;
this.wrapper = '#'+ element.wrapper;
this.effect = element.effect;
this.method = element.method;
this.element = element_settings.element;
this.selector = element_settings.selector;
this.event = element_settings.event;
this.url = element_settings.url;
this.wrapper = '#'+ element_settings.wrapper;
this.effect = element_settings.effect;
this.method = element_settings.method;
if (this.effect == 'none') {
this.showEffect = 'show';
this.hideEffect = 'hide';
this.showSpeed = '';
}
else if (this.effect == 'fade') {
this.showEffect = 'fadeIn';
this.hideEffect = 'fadeOut';
this.showSpeed = 'slow';
}
else {
this.showEffect = this.effect + 'Toggle';
this.hideEffect = this.effect + 'Toggle';
this.showSpeed = 'slow';
}
Drupal.redirectFormButton(this.uri, $(this.id).get(0), this);
// Record the form action and target, needed for iFrame file uploads.
var form = $(this.element).parents('form');
this.form_action = form.attr('action');
this.form_target = form.attr('target');
this.form_encattr = form.attr('encattr');
// Set the options for the ajaxSubmit function.
// The 'this' variable will not persist inside of the options object.
var ahah = this;
var options = {
url: ahah.url,
beforeSubmit: function(form_values, element_settings, options) {
return ahah.beforeSubmit(form_values, element_settings, options);
},
success: function(response, status) {
// Sanity check for browser support (object expected).
// When using iFrame uploads, responses must be returned as a string.
if (typeof(response) == 'string') {
response = Drupal.parseJson(response);
}
return ahah.success(response, status);
},
complete: function(response, status) {
if (status == 'error') {
return ahah.error(response.responseText);
}
},
dataType: 'json',
type: 'POST'
};
// Bind the ajaxSubmit function to the element event.
$(element_settings.element).bind(element_settings.event, function() {
$(element_settings.element).parents('form').ajaxSubmit(options);
return false;
});
};
/**
* Handler for the form redirection submission.
*/
Drupal.ahah.prototype.onsubmit = function () {
Drupal.ahah.prototype.beforeSubmit = function (form_values, element, options) {
// Insert progressbar and stretch to take the same space.
this.progress = new Drupal.progressBar('ahah_progress');
this.progress.setProgress(-1, Drupal.t('Please wait...'));
var wrapper = $(this.wrapper);
var button = $(this.id);
var progress_element = $(this.progress.element);
progress_element.css('float', 'left').css({
display: 'none',
width: '10em',
margin: '0 0 0 20px'
});
button.css('float', 'left').attr('disabled', true).after(progress_element);
if (progress_element[this.showEffect]) {
progress_element[this.showEffect]();
}
var progress_element = $(this.progress.element).addClass('ahah-progress');
$(this.element).addClass('progress-disabled').attr('disabled', true).after(progress_element);
};
/**
* Handler for the form redirection completion.
*/
Drupal.ahah.prototype.oncomplete = function (data) {
Drupal.ahah.prototype.success = function (response, status) {
var wrapper = $(this.wrapper);
var button = $(this.id);
var form = $(this.element).parents('form');
var progress_element = $(this.progress.element);
var new_content = $('<div>' + data + '</div>');
// Manually insert HTML into the jQuery object, using $() directly crashes
// Safari with long string lengths. http://dev.jquery.com/ticket/1152
var new_content = $('<div></div>').html(response.data);
Drupal.freezeHeight();
// Restore the previous action and target to the form.
form.attr('action', this.form_action);
this.form_target ? form.attr('target', this.form_target) : form.removeAttr('target');
this.form_encattr ? form.attr('target', this.form_encattr) : form.removeAttr('encattr');
// Remove the progress element.
progress_element.remove();
$(this.element).removeClass('progess-disabled').attr('disabled', false);
// Hide the new content before adding to page.
new_content.hide();
if (this.showEffect != 'show') {
new_content.hide();
}
// Add the form and re-attach behavior.
// Add the new content to the page.
Drupal.freezeHeight();
if (this.method == 'replace') {
wrapper.empty().append(new_content);
}
else if (wrapper[this.method]) {
else {
wrapper[this.method](new_content);
}
if (new_content[this.showEffect]) {
new_content[this.showEffect]();
// Determine what effect use and what content will receive the effect, then
// show the new content. For browser compatibility, Safari is excluded from
// using effects on table rows.
if ($('.ahah-new-content', new_content).size() > 0 && !($.browser.safari && $("tr.ahah-new-content", new_content).size() > 0)) {
$('.ahah-new-content', new_content).hide();
new_content.show();
$(".ahah-new-content", new_content)[this.showEffect](this.showSpeed);
}
else if (this.showEffect != 'show') {
new_content[this.showEffect](this.showSpeed);
}
// Attach all javascript behaviors to the new content, if it was successfully
// added to the page, this if statement allows #ahah[wrapper] to be optional.
if (new_content.parents('html').length > 0) {
Drupal.attachBehaviors(new_content);
}
button.css('float', 'none').attr('disabled', false);
Drupal.attachBehaviors(new_content);
Drupal.unfreezeHeight();
};
/**
* Handler for the form redirection error.
*/
Drupal.ahah.prototype.onerror = function (error) {
Drupal.ahah.prototype.error = function (error) {
alert(Drupal.t('An error occurred:\n\n@error', { '@error': error }));
// Resore the previous action and target to the form.
element.parent('form').attr( { action: this.form_action, target: this.form_target} );
// Remove progressbar.
$(this.progress.element).remove();
this.progress = null;
// Undo hide.
$(this.wrapper).show();
// Re-enable the element.
$(this.id).css('float', 'none').attr('disabled', false);
$(this.element).removeClass('progess-disabled').attr('disabled', false);
};
......@@ -181,103 +181,15 @@ Drupal.theme = function(func) {
};
/**
* Redirects a button's form submission to a hidden iframe and displays the result
* in a given wrapper. The iframe should contain a call to
* window.parent.iframeHandler() after submission.
*/
Drupal.redirectFormButton = function (uri, button, handler) {
// Trap the button
button.onmouseover = button.onfocus = function() {
button.onclick = function() {
// Create target iframe
Drupal.deleteIframe();
Drupal.createIframe();
// Prepare variables for use in anonymous function.
var button = this;
var action = button.form.action;
var target = button.form.target;
// Redirect form submission to iframe
this.form.action = uri;
this.form.target = 'redirect-target';
this.form.submit();
handler.onsubmit();
// Set iframe handler for later
window.iframeHandler = function () {
var iframe = $('#redirect-target').get(0);
// Restore form submission
button.form.action = action;
button.form.target = target;
// Get response from iframe body
try {
response = (iframe.contentWindow || iframe.contentDocument || iframe).document.body.innerHTML;
// Firefox 1.0.x hack: Remove (corrupted) control characters
response = response.replace(/[\f\n\r\t]/g, ' ');
if (window.opera) {
// Opera-hack: it returns innerHTML sanitized.
response = response.replace(/&quot;/g, '"');
}
}
catch (e) {
response = null;
}
response = eval('('+ response +');');
// Check response code
if (!response || response.status == 0) {
handler.onerror(response.data || Drupal.t('Error parsing response'));
return;
}
handler.oncomplete(response.data);
return true;
};
return true;
};
};
button.onmouseout = button.onblur = function() {
button.onclick = null;
};
};
/**
* Create an invisible iframe for form submissions.
* Parse a JSON response.
*
* The result is either the JSON object, or an object with 'status' 0 and 'data' an error message.
*/
Drupal.createIframe = function () {
if ($('#redirect-holder').size()) {
return;
Drupal.parseJson = function (data) {
if ((data.substring(0, 1) != '{') && (data.substring(0, 1) != '[')) {
return { status: 0, data: data.length ? data : Drupal.t('Unspecified error') };
}
// Note: some browsers require the literal name/id attributes on the tag,
// some want them set through JS. We do both.
window.iframeHandler = function () {};
var div = document.createElement('div');
div.id = 'redirect-holder';
$(div).html('<iframe name="redirect-target" id="redirect-target" class="redirect" onload="window.iframeHandler();"></iframe>');
var iframe = div.firstChild;
$(iframe)
.attr({
name: 'redirect-target',
id: 'redirect-target'
})
.css({
position: 'absolute',
height: '1px',
width: '1px',
visibility: 'hidden'
});
$('body').append(div);
};
/**
* Delete the invisible iframe
*/
Drupal.deleteIframe = function () {
$('#redirect-holder').remove();
return eval('(' + data + ');');
};
/**
......
......@@ -4,3 +4,12 @@
padding-left: inherit;
padding-right: 1.5em;
}
#blocks select {
margin-left: 18px;
}
#blocks select.progress-disabled {
margin-left: 0px;
}
#blocks .progress .bar {
float: right;
}
......@@ -6,63 +6,105 @@
* Admin page callbacks for the block module.
*/
/**
* Menu callback for admin/build/block.
*/
function block_admin_display($theme = NULL) {
global $custom_theme;
// If non-default theme configuration has been selected, set the custom theme.
$custom_theme = isset($theme) ? $theme : variable_get('theme_default', 'garland');
// Fetch and sort blocks
$blocks = _block_rehash();
usort($blocks, '_block_compare');
return drupal_get_form('block_admin_display_form', $blocks, $theme);
}
/**
* Generate main block administration form.
*/
function block_admin_display(&$form_state, $theme = NULL) {
function block_admin_display_form(&$form_state, $blocks, $theme = NULL) {
global $theme_key, $custom_theme;
// Add CSS
drupal_add_css(drupal_get_path('module', 'block') .'/block.css', 'module', 'all', FALSE);
// If non-default theme configuration has been selected, set the custom theme.
if ($theme) {
$custom_theme = $theme;
}
else {
$custom_theme = variable_get('theme_default', 'garland');
}
$custom_theme = isset($theme) ? $theme : variable_get('theme_default', 'garland');
init_theme();
// Fetch and sort blocks
$blocks = _block_rehash();
usort($blocks, '_block_compare');
$throttle = module_exists('throttle');
$block_regions = array(BLOCK_REGION_NONE => '<'. t('none') .'>') + system_region_list($theme_key);
// Build form tree
$form['#action'] = arg(3) ? url('admin/build/block/list/'. $theme_key) : url('admin/build/block');
$form['#tree'] = TRUE;
$form = array(
'#action' => arg(3) ? url('admin/build/block/list/'. $theme_key) : url('admin/build/block'),
'#tree' => TRUE,
'#cache' => TRUE,
'#prefix' => '<div id="block-admin-display-form-wrapper">',
'#suffix' => '</div>',
);
foreach ($blocks as $i => $block) {
$form[$i]['module'] = array('#type' => 'value', '#value' => $block['module']);
$form[$i]['delta'] = array('#type' => 'value', '#value' => $block['delta']);
$form[$i]['info'] = array('#value' => check_plain($block['info']));
$form[$i]['theme'] = array('#type' => 'hidden', '#value' => $theme_key);
$form[$i]['weight'] = array('#type' => 'weight', '#default_value' => $block['weight']);
$form[$i]['region'] = array('#type' => 'select',
$key = $block['module'] .'_'. $block['delta'];
$form[$key]['module'] = array(
'#type' => 'value',
'#value' => $block['module'],
);
$form[$key]['delta'] = array(
'#type' => 'value',
'#value' => $block['delta'],
);
$form[$key]['info'] = array(
'#value' => check_plain($block['info'])
);
$form[$key]['theme'] = array(
'#type' => 'hidden',
'#value' => $theme_key
);
$form[$key]['weight'] = array(
'#type' => 'weight',
'#default_value' => $block['weight'],
);
$form[$key]['region'] = array(
'#type' => 'select',
'#default_value' => $block['status'] ? (isset($block['region']) ? $block['region'] : system_default_region($theme_key)) : BLOCK_REGION_NONE,
'#options' => $block_regions,
);
if ($throttle) {
$form[$i]['throttle'] = array('#type' => 'checkbox', '#default_value' => isset($block['throttle']) ? $block['throttle'] : FALSE);
$form[$key]['throttle'] = array('#type' => 'checkbox', '#default_value' => isset($block['throttle']) ? $block['throttle'] : FALSE);
}
$form[$i]['configure'] = array('#value' => l(t('configure'), 'admin/build/block/configure/'. $block['module'] .'/'. $block['delta']));
$form[$key]['configure'] = array('#value' => l(t('configure'), 'admin/build/block/configure/'. $block['module'] .'/'. $block['delta']));
if ($block['module'] == 'block') {
$form[$i]['delete'] = array('#value' => l(t('delete'), 'admin/build/block/delete/'. $block['delta']));
$form[$key]['delete'] = array('#value' => l(t('delete'), 'admin/build/block/delete/'. $block['delta']));
}
}
$form['submit'] = array('#type' => 'submit', '#value' => t('Save blocks'));
// Attach the AHAH events to the submit button. Set the AHAH selector to every
// select element in the form. The AHAH event could be attached to every select
// element individually, but using the selector is more efficient, especially
// on a page where hundreds of AHAH enabled elements may be present.
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save blocks'),
'#ahah' => array(
'path' => 'admin/build/block/list/js/'. $theme_key,
'selector' => '#block-admin-display-form-wrapper select',
'wrapper' => 'block-admin-display-form-wrapper',
'event' => 'change',
'effect' => 'fade',
),
);
return $form;
}
/**
* Process main block administration form submission.
*/
function block_admin_display_submit($form, &$form_state) {
function block_admin_display_form_submit($form, &$form_state) {
foreach ($form_state['values'] as $block) {
$block['status'] = $block['region'] != BLOCK_REGION_NONE;
$block['region'] = $block['status'] ? $block['region'] : '';
......@@ -72,6 +114,91 @@ function block_admin_display_submit($form, &$form_state) {
cache_clear_all();
}
/**
* Javascript callback for AHAH replacement. Re-generate the form with the
* updated values and return necessary html.
*/
function block_admin_display_js($theme = NULL) {
// Load the cached form.
$form_cache = cache_get('form_'. $_POST['form_build_id'], 'cache_form');
// Set the new weights and regions for each block.
$blocks = array();
foreach (element_children($form_cache->data) as $key) {
$field = $form_cache->data[$key];
if (isset($field['info'])) {
$block = array(
'module' => $field['module']['#value'],
'delta' => $field['delta']['#value'],
'info' => html_entity_decode($field['info']['#value'], ENT_QUOTES),
'region' => $_POST[$key]['region'],
'weight' => $_POST[$key]['weight'],
'status' => $_POST[$key]['region'] == BLOCK_REGION_NONE ? 0 : 1,
);
$throttle = module_exists('throttle');
if ($throttle) {
$block['throttle'] = $_POST[$key]['throttle'];
}
if ($block['weight'] != $form_cache->data[$key]['weight']['#default_value'] || $block['region'] != $form_cache->data[$key]['region']['#default_value']) {
$changed_block = $block['module'] .'_'. $block['delta'];
}
$blocks[] = $block;
}
}
// Resort the blocks with the new weights.
usort($blocks, '_block_compare');
// Create a form in the new order.
$form_state = array('submitted' => FALSE);
$form = block_admin_display_form($form_state, $blocks, $theme);
// Maintain classes set on individual blocks.
foreach (element_children($form_cache->data) as $key) {
if (isset($form_cache->data[$key]['#attributes'])) {
$form[$key]['#attributes'] = $form_cache->data[$key]['#attributes'];
}
}
// Preserve the order of the new form while merging the previous data.
$form_order = array_flip(array_keys($form)); // Save the form order.
$form = array_merge($form_cache->data, $form); // Merge the data.
$form = array_merge($form_order, $form); // Put back into the correct order.
// Add a permanent class to the changed block.
$form[$changed_block]['#attributes']['class'] = 'block-modified';
cache_set('form_'. $_POST['form_build_id'], $form, 'cache_form', $form_cache->expire);
// Add a temporary class to mark the new AHAH content.
$form[$changed_block]['#attributes']['class'] = empty($form[$changed_block]['#attributes']['class']) ? 'ahah-new-content' : $form[$changed_block]['#attributes']['class'] .' ahah-new-content';
$form['js_modified'] = array(
'#type' => 'value',
'#value' => TRUE,
);
$form['#post'] = $_POST;
$form['#theme'] = 'block_admin_display_form';
// Add messages to our output.
drupal_set_message(t('Your settings will not be saved until you click the <em>Save blocks</em> button.'), 'warn