summaryrefslogtreecommitdiffstats
path: root/backstretch_formatter.module
blob: 02e29c3b66eb66065d5aa25da5014eae1841ae96 (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
<?php

/**
 * @file
 * Main file for Backstretch Formatter module.
 */

/**
 * Implements hook_libraries_info().
 */
function backstretch_formatter_libraries_info() {
  $libraries = array();

  $libraries['jquery.backstretch'] = array(
    'name' => 'jQuery Backstretch',
    'vendor url' => 'http://srobbin.com/jquery-plugins/backstretch/',
    'download url' => 'https://raw.github.com/srobbin/jquery-backstretch/master/jquery.backstretch.min.js',
    'version arguments' => array(
      'file' => 'jquery.backstretch.min.js',
      'pattern' => '/ v([\d\.]+) /',
      'lines' => 1,
    ),
    'files' => array(
      'js' => array('jquery.backstretch.min.js'),
    ),
  );

  return $libraries;
}

/**
 * Implements hook_field_formatter_info().
 */
function backstretch_formatter_field_formatter_info() {
  return array(
    'backstretch' => array(
      'label' => t('Backstretch'),
      'field types' => array('image'),
      'settings' => array(
        'image_style' => '',
        'element' => '',
        'element_other' => '',
        'duration' => 5000,
        'fade' => 0,
        'center_x' => TRUE,
        'center_y' => TRUE,
      ),
    ),
  );
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function backstretch_formatter_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  // This gets the view mode where the settings are stored.
  $display = $instance['display'][$view_mode];
  // This gets the settings.
  $settings = $display['settings'];

  $element = array();

  $image_styles = image_style_options(FALSE);
  $element['image_style'] = array(
    '#title' => t('Image style'),
    '#type' => 'select',
    '#default_value' => $settings['image_style'],
    '#options' => $image_styles,
    '#empty_option' => t('None (original image)'),
  );

  $element['element'] = array(
    '#type' => 'select',
    '#title' => t('Attach to'),
    '#default_value' => $settings['element'],
    '#options' => array(
      'other' => t('Other element'),
    ),
    '#empty_option' => t('Whole page'),
    '#description' => t('Where the Backstretch should be attached to.'),
  );

  $element['element_other'] = array(
    '#type' => 'textfield',
    '#title' => t('Other element'),
    '#default_value' => $settings['element_other'],
    '#description' => t('Enter the CSS selector for the element.'),
    '#states' => array(
      'visible' => array(
        ':input[name$="[element]"]' => array('value' => 'other'),
      ),
    ),
  );

  // Make duration and fade setting only available for multiple value field.
  if ($field['cardinality'] != '1') {
    $element['duration'] = array(
      '#type' => 'textfield',
      '#title' => t('Duration'),
      '#default_value' => $settings['duration'],
      '#description' => t('Amount of time in between slides.'),
      '#size' => 10,
      '#field_suffix' => 'ms',
      '#element_validate' => array('element_validate_integer_positive'),
    );

    $element['fade'] = array(
      '#type' => 'textfield',
      '#title' => t('Fade'),
      '#default_value' => $settings['fade'],
      '#description' => t('Speed of fade transition between slides. Can be an integer or a string like: %slow or %fast.', array('%slow' => 'slow', '%fast' => 'fast')),
      '#size' => 10,
      '#element_validate' => array('backstretch_formatter_element_validate_duration'),
    );
  }

  $element['center_x'] = array(
    '#type' => 'checkbox',
    '#title' => t('Horizontal centered'),
    '#default_value' => $settings['center_x'],
    '#description' => t('Should we center the image on the X axis?'),
  );

  $element['center_y'] = array(
    '#type' => 'checkbox',
    '#title' => t('Vertically centered'),
    '#default_value' => $settings['center_y'],
    '#description' => t('Should we center the image on the Y axis?'),
  );

  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function backstretch_formatter_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  $options_info = backstretch_formatter_formatter_options();
  $options = array();

  foreach ($settings as $name => $value) {
    if (array_key_exists($name, $options_info)) {
      $option = $options_info[$name];
      $label = $option['label'];
      $suffix = isset($option['suffix']) ? $option['suffix'] : '';
      $type = isset($option['type']) ? $option['type'] : '';

      // We need some special handling with the element setting.
      if ($name == 'element') {
        continue;
      }
      if ($name == 'element_other') {
        $value = ($settings['element'] == '') ? t('Whole page') : $value;
      }
      if ($name == 'image_style' && $value == '') {
        continue;
      }
      // Display just the label when the setting is a boolean.
      if ($type != 'bool') {
        $options[$name] = $label . ': ' . $value . $suffix;
      }
      else {
        $options[$name] = $label . $suffix;
      }
    }
  }

  // Remove slideshow specific settings when only one image is allowed.
  if ($field['cardinality'] == '1') {
    unset($options['duration'], $options['fade']);
  }

  $summary = '<h3>jQuery Backstretch</h3>';
  $summary .= theme('item_list', array('items' => $options));

  return $summary;
}

/**
 * Implements hook_field_formatter_view().
 */
function backstretch_formatter_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  // Store the field formatter settings.
  $settings = $display['settings'];

  // Display an error message and return if jQuery is not at least 1.7.
  $jquery = drupal_get_library('system', 'jquery');
  if (version_compare($jquery['version'], '1.7', '<')) {
    drupal_set_message(t('The jQuery Backstretch plugin requires at least jQuery 1.7. Please change the version in the <a href="!url">settings</a>.', array('!url' => url('admin/config/development/jquery_update'))), 'error');
    return;
  }

  // We store the default values from Backstretch formatter here.
  $formatters = backstretch_formatter_field_formatter_info();
  $default = $formatters['backstretch']['settings'];

  // We need the js variable name.
  $options_info = backstretch_formatter_formatter_options();
  // Here we store all options later.
  $options = array();

  foreach ($settings as $name => $value) {
    if (array_key_exists($name, $options_info)) {
      $option = $options_info[$name];
      $js = $option['js'];

      // We need some special handling with the element settings.
      if ($name == 'element' || ($name == 'element_other' && $settings['element'] == '')) {
        continue;
      }

      // We only put the setting into $options when it is
      // not the default value.
      if ($value != $default[$name] && $js) {
        $options[$js] = $value;
      }
    }
  }

  // We need the entity id here because there could be multiple images with
  // Backstretch formatter.
  $ids = entity_extract_ids($entity_type, $entity);
  $id = str_replace('_', '-', $entity_type) . '-' . $ids[0];

  // Iterate all items and store the absolute url to it.
  foreach ($items as &$item) {
    $uri = $item['uri'];
    // Get url to image.
    if ($settings['image_style']) {
      $url = image_style_url($settings['image_style'], $uri);
    }
    else {
      $url = file_create_url($uri);
    }
    $options['items'][] = $url;
  }

  // Prepare a renderable array.
  $element = array(
    '#theme' => 'backstretch',
    '#id' => $id,
    '#options' => $options,
  );

  return $element;
}

/**
 * Implements hook_theme().
 */
function backstretch_formatter_theme() {
  return array(
    'backstretch' => array(
      'variables' => array('id' => 0, 'options' => array()),
    ),
  );
}

/**
 * Theme function for a Backstretch.
 */
function theme_backstretch($variables) {
  // Normalize the variables.
  $id = $variables['id'];
  $options = $variables['options'];

  // Load necessary for the Backstretch.
  libraries_load('jquery.backstretch');
  drupal_add_js(drupal_get_path('module', 'backstretch_formatter') . '/js/backstretch_formatter.js');
  drupal_add_js(array('backstretchFormatter' => array($id => $options)), 'setting');

  return '';
}

/**
 * Helper function which returns the options.
 *
 * @return array
 *   An array which contains the options.
 *   Every item has a label and their Javascript name.
 *   Optionally with a suffix which will be append to the value in summary.
 */
function backstretch_formatter_formatter_options() {
  return array(
    'image_style' => array(
      'label' => t('Image style'),
      'js' => '',
    ),
    'element_other' => array(
      'label' => t('Attach to'),
      'js' => 'selector',
    ),
    'fade' => array(
      'label' => t('Fade speed'),
      'js' => 'fade',
    ),
    'duration' => array(
      'label' => t('Time between slides'),
      'js' => 'duration',
      'suffix' => 'ms',
    ),
    'center_x' => array(
      'label' => t('Horizontally centerd'),
      'js' => 'centeredX',
      'type' => 'bool',
    ),
    'center_y' => array(
      'label' => t('Vertically centered'),
      'js' => 'centeredY',
      'type' => 'bool',
    ),
  );
}

/**
 * Form element validation handler for elements that must be a duration.
 */
function backstretch_formatter_element_validate_duration($element, &$form_state) {
  $value = $element['#value'];
  // A duration can be an integer or a string like 'slow' or 'fast'.
  if ($value !== '' && !(is_numeric($value) && intval($value) == $value && $value >= 0) && ($value != 'slow' && $value != 'fast')) {
    form_error($element, t('%name must be an integer, "slow" or "fast".', array('%name' => $element['#title'])));
  }
}