1: <?php
2: /**
3: * JsEngineBaseClass
4: *
5: * PHP 5
6: *
7: * CakePHP : Rapid Development Framework (http://cakephp.org)
8: * Copyright 2005-2011, Cake Software Foundation, Inc.
9: *
10: * Licensed under The MIT License
11: * Redistributions of files must retain the above copyright notice.
12: *
13: * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
14: * @link http://cakephp.org CakePHP(tm) Project
15: * @package Cake.View.Helper
16: * @since CakePHP(tm) v 2.0
17: * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
18: */
19:
20: App::uses('AppHelper', 'View/Helper');
21:
22: /**
23: * JsEngineBaseClass
24: *
25: * Abstract Base Class for All JsEngines to extend. Provides generic methods.
26: *
27: * @package Cake.View.Helper
28: */
29: abstract class JsBaseEngineHelper extends AppHelper {
30:
31: /**
32: * The js snippet for the current selection.
33: *
34: * @var string
35: */
36: public $selection;
37:
38: /**
39: * Collection of option maps. Option maps allow other helpers to use generic names for engine
40: * callbacks and options. Allowing uniform code access for all engine types. Their use is optional
41: * for end user use though.
42: *
43: * @var array
44: */
45: protected $_optionMap = array();
46:
47: /**
48: * An array of lowercase method names in the Engine that are buffered unless otherwise disabled.
49: * This allows specific 'end point' methods to be automatically buffered by the JsHelper.
50: *
51: * @var array
52: */
53: public $bufferedMethods = array('event', 'sortable', 'drag', 'drop', 'slider');
54:
55: /**
56: * Contains a list of callback names -> default arguments.
57: *
58: * @var array
59: */
60: protected $_callbackArguments = array();
61:
62: /**
63: * Constructor.
64: *
65: * @param View $View
66: * @param array $settings
67: */
68: public function __construct($View, $settings = array()) {
69: parent::__construct($View, $settings);
70: }
71:
72: /**
73: * Create an `alert()` message in Javascript
74: *
75: * @param string $message Message you want to alter.
76: * @return string completed alert()
77: */
78: public function alert($message) {
79: return 'alert("' . $this->escape($message) . '");';
80: }
81:
82: /**
83: * Redirects to a URL. Creates a window.location modification snippet
84: * that can be used to trigger 'redirects' from Javascript.
85: *
86: * @param mixed $url
87: * @param array $options
88: * @return string completed redirect in javascript
89: */
90: public function redirect($url = null) {
91: return 'window.location = "' . Router::url($url) . '";';
92: }
93:
94: /**
95: * Create a `confirm()` message
96: *
97: * @param string $message Message you want confirmed.
98: * @return string completed confirm()
99: */
100: public function confirm($message) {
101: return 'confirm("' . $this->escape($message) . '");';
102: }
103:
104: /**
105: * Generate a confirm snippet that returns false from the current
106: * function scope.
107: *
108: * @param string $message Message to use in the confirm dialog.
109: * @return string completed confirm with return script
110: */
111: public function confirmReturn($message) {
112: $out = 'var _confirm = ' . $this->confirm($message);
113: $out .= "if (!_confirm) {\n\treturn false;\n}";
114: return $out;
115: }
116:
117: /**
118: * Create a `prompt()` Javascript function
119: *
120: * @param string $message Message you want to prompt.
121: * @param string $default Default message
122: * @return string completed prompt()
123: */
124: public function prompt($message, $default = '') {
125: return 'prompt("' . $this->escape($message) . '", "' . $this->escape($default) . '");';
126: }
127:
128: /**
129: * Generates a JavaScript object in JavaScript Object Notation (JSON)
130: * from an array. Will use native JSON encode method if available, and $useNative == true
131: *
132: * ### Options:
133: *
134: * - `prefix` - String prepended to the returned data.
135: * - `postfix` - String appended to the returned data.
136: *
137: * @param array $data Data to be converted.
138: * @param array $options Set of options, see above.
139: * @return string A JSON code block
140: */
141: public function object($data = array(), $options = array()) {
142: $defaultOptions = array(
143: 'prefix' => '', 'postfix' => '',
144: );
145: $options = array_merge($defaultOptions, $options);
146:
147: return $options['prefix'] . json_encode($data) . $options['postfix'];
148: }
149:
150: /**
151: * Converts a PHP-native variable of any type to a JSON-equivalent representation
152: *
153: * @param mixed $val A PHP variable to be converted to JSON
154: * @param boolean $quoteString If false, leaves string values unquoted
155: * @return string a JavaScript-safe/JSON representation of $val
156: */
157: public function value($val = array(), $quoteString = null, $key = 'value') {
158: if ($quoteString === null) {
159: $quoteString = true;
160: }
161: switch (true) {
162: case (is_array($val) || is_object($val)):
163: $val = $this->object($val);
164: break;
165: case ($val === null):
166: $val = 'null';
167: break;
168: case (is_bool($val)):
169: $val = ($val === true) ? 'true' : 'false';
170: break;
171: case (is_int($val)):
172: $val = $val;
173: break;
174: case (is_float($val)):
175: $val = sprintf("%.11f", $val);
176: break;
177: default:
178: $val = $this->escape($val);
179: if ($quoteString) {
180: $val = '"' . $val . '"';
181: }
182: break;
183: }
184: return $val;
185: }
186:
187: /**
188: * Escape a string to be JSON friendly.
189: *
190: * List of escaped elements:
191: *
192: * - "\r" => '\n'
193: * - "\n" => '\n'
194: * - '"' => '\"'
195: *
196: * @param string $string String that needs to get escaped.
197: * @return string Escaped string.
198: */
199: public function escape($string) {
200: return $this->_utf8ToHex($string);
201: }
202:
203: /**
204: * Encode a string into JSON. Converts and escapes necessary characters.
205: *
206: * @param string $string The string that needs to be utf8->hex encoded
207: * @return void
208: */
209: protected function _utf8ToHex($string) {
210: $length = strlen($string);
211: $return = '';
212: for ($i = 0; $i < $length; ++$i) {
213: $ord = ord($string{$i});
214: switch (true) {
215: case $ord == 0x08:
216: $return .= '\b';
217: break;
218: case $ord == 0x09:
219: $return .= '\t';
220: break;
221: case $ord == 0x0A:
222: $return .= '\n';
223: break;
224: case $ord == 0x0C:
225: $return .= '\f';
226: break;
227: case $ord == 0x0D:
228: $return .= '\r';
229: break;
230: case $ord == 0x22:
231: case $ord == 0x2F:
232: case $ord == 0x5C:
233: $return .= '\\' . $string{$i};
234: break;
235: case (($ord >= 0x20) && ($ord <= 0x7F)):
236: $return .= $string{$i};
237: break;
238: case (($ord & 0xE0) == 0xC0):
239: if ($i + 1 >= $length) {
240: $i += 1;
241: $return .= '?';
242: break;
243: }
244: $charbits = $string{$i} . $string{$i + 1};
245: $char = Multibyte::utf8($charbits);
246: $return .= sprintf('\u%04s', dechex($char[0]));
247: $i += 1;
248: break;
249: case (($ord & 0xF0) == 0xE0):
250: if ($i + 2 >= $length) {
251: $i += 2;
252: $return .= '?';
253: break;
254: }
255: $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2};
256: $char = Multibyte::utf8($charbits);
257: $return .= sprintf('\u%04s', dechex($char[0]));
258: $i += 2;
259: break;
260: case (($ord & 0xF8) == 0xF0):
261: if ($i + 3 >= $length) {
262: $i += 3;
263: $return .= '?';
264: break;
265: }
266: $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3};
267: $char = Multibyte::utf8($charbits);
268: $return .= sprintf('\u%04s', dechex($char[0]));
269: $i += 3;
270: break;
271: case (($ord & 0xFC) == 0xF8):
272: if ($i + 4 >= $length) {
273: $i += 4;
274: $return .= '?';
275: break;
276: }
277: $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4};
278: $char = Multibyte::utf8($charbits);
279: $return .= sprintf('\u%04s', dechex($char[0]));
280: $i += 4;
281: break;
282: case (($ord & 0xFE) == 0xFC):
283: if ($i + 5 >= $length) {
284: $i += 5;
285: $return .= '?';
286: break;
287: }
288: $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4} . $string{$i + 5};
289: $char = Multibyte::utf8($charbits);
290: $return .= sprintf('\u%04s', dechex($char[0]));
291: $i += 5;
292: break;
293: }
294: }
295: return $return;
296: }
297:
298: /**
299: * Create javascript selector for a CSS rule
300: *
301: * @param string $selector The selector that is targeted
302: * @return JsBaseEngineHelper instance of $this. Allows chained methods.
303: */
304: abstract public function get($selector);
305:
306: /**
307: * Add an event to the script cache. Operates on the currently selected elements.
308: *
309: * ### Options
310: *
311: * - `wrap` - Whether you want the callback wrapped in an anonymous function. (defaults to true)
312: * - `stop` - Whether you want the event to stopped. (defaults to true)
313: *
314: * @param string $type Type of event to bind to the current dom id
315: * @param string $callback The Javascript function you wish to trigger or the function literal
316: * @param array $options Options for the event.
317: * @return string completed event handler
318: */
319: abstract public function event($type, $callback, $options = array());
320:
321: /**
322: * Create a domReady event. This is a special event in many libraries
323: *
324: * @param string $functionBody The code to run on domReady
325: * @return string completed domReady method
326: */
327: abstract public function domReady($functionBody);
328:
329: /**
330: * Create an iteration over the current selection result.
331: *
332: * @param string $callback The function body you wish to apply during the iteration.
333: * @return string completed iteration
334: */
335: abstract public function each($callback);
336:
337: /**
338: * Trigger an Effect.
339: *
340: * ### Supported Effects
341: *
342: * The following effects are supported by all core JsEngines
343: *
344: * - `show` - reveal an element.
345: * - `hide` - hide an element.
346: * - `fadeIn` - Fade in an element.
347: * - `fadeOut` - Fade out an element.
348: * - `slideIn` - Slide an element in.
349: * - `slideOut` - Slide an element out.
350: *
351: * ### Options
352: *
353: * - `speed` - Speed at which the animation should occur. Accepted values are 'slow', 'fast'. Not all effects use
354: * the speed option.
355: *
356: * @param string $name The name of the effect to trigger.
357: * @param array $options Array of options for the effect.
358: * @return string completed string with effect.
359: */
360: abstract public function effect($name, $options = array());
361:
362: /**
363: * Make an XHR request
364: *
365: * ### Event Options
366: *
367: * - `complete` - Callback to fire on complete.
368: * - `success` - Callback to fire on success.
369: * - `before` - Callback to fire on request initialization.
370: * - `error` - Callback to fire on request failure.
371: *
372: * ### Options
373: *
374: * - `method` - The method to make the request with defaults to GET in more libraries
375: * - `async` - Whether or not you want an asynchronous request.
376: * - `data` - Additional data to send.
377: * - `update` - Dom id to update with the content of the request.
378: * - `type` - Data type for response. 'json' and 'html' are supported. Default is html for most libraries.
379: * - `evalScripts` - Whether or not <script> tags should be eval'ed.
380: * - `dataExpression` - Should the `data` key be treated as a callback. Useful for supplying `$options['data']` as
381: * another Javascript expression.
382: *
383: * @param mixed $url Array or String URL to target with the request.
384: * @param array $options Array of options. See above for cross library supported options
385: * @return string XHR request.
386: */
387: abstract public function request($url, $options = array());
388:
389: /**
390: * Create a draggable element. Works on the currently selected element.
391: * Additional options may be supported by the library implementation.
392: *
393: * ### Options
394: *
395: * - `handle` - selector to the handle element.
396: * - `snapGrid` - The pixel grid that movement snaps to, an array(x, y)
397: * - `container` - The element that acts as a bounding box for the draggable element.
398: *
399: * ### Event Options
400: *
401: * - `start` - Event fired when the drag starts
402: * - `drag` - Event fired on every step of the drag
403: * - `stop` - Event fired when dragging stops (mouse release)
404: *
405: * @param array $options Options array see above.
406: * @return string Completed drag script
407: */
408: abstract public function drag($options = array());
409:
410: /**
411: * Create a droppable element. Allows for draggable elements to be dropped on it.
412: * Additional options may be supported by the library implementation.
413: *
414: * ### Options
415: *
416: * - `accept` - Selector for elements this droppable will accept.
417: * - `hoverclass` - Class to add to droppable when a draggable is over.
418: *
419: * ### Event Options
420: *
421: * - `drop` - Event fired when an element is dropped into the drop zone.
422: * - `hover` - Event fired when a drag enters a drop zone.
423: * - `leave` - Event fired when a drag is removed from a drop zone without being dropped.
424: *
425: * @param array $options Array of options for the drop. See above.
426: * @return string Completed drop script
427: */
428: abstract public function drop($options = array());
429:
430: /**
431: * Create a sortable element.
432: * Additional options may be supported by the library implementation.
433: *
434: * ### Options
435: *
436: * - `containment` - Container for move action
437: * - `handle` - Selector to handle element. Only this element will start sort action.
438: * - `revert` - Whether or not to use an effect to move sortable into final position.
439: * - `opacity` - Opacity of the placeholder
440: * - `distance` - Distance a sortable must be dragged before sorting starts.
441: *
442: * ### Event Options
443: *
444: * - `start` - Event fired when sorting starts
445: * - `sort` - Event fired during sorting
446: * - `complete` - Event fired when sorting completes.
447: *
448: * @param array $options Array of options for the sortable. See above.
449: * @return string Completed sortable script.
450: */
451: abstract public function sortable($options = array());
452:
453: /**
454: * Create a slider UI widget. Comprised of a track and knob.
455: * Additional options may be supported by the library implementation.
456: *
457: * ### Options
458: *
459: * - `handle` - The id of the element used in sliding.
460: * - `direction` - The direction of the slider either 'vertical' or 'horizontal'
461: * - `min` - The min value for the slider.
462: * - `max` - The max value for the slider.
463: * - `step` - The number of steps or ticks the slider will have.
464: * - `value` - The initial offset of the slider.
465: *
466: * ### Events
467: *
468: * - `change` - Fired when the slider's value is updated
469: * - `complete` - Fired when the user stops sliding the handle
470: *
471: * @param array $options Array of options for the slider. See above.
472: * @return string Completed slider script
473: */
474: abstract public function slider($options = array());
475:
476: /**
477: * Serialize the form attached to $selector.
478: * Pass `true` for $isForm if the current selection is a form element.
479: * Converts the form or the form element attached to the current selection into a string/json object
480: * (depending on the library implementation) for use with XHR operations.
481: *
482: * ### Options
483: *
484: * - `isForm` - is the current selection a form, or an input? (defaults to false)
485: * - `inline` - is the rendered statement going to be used inside another JS statement? (defaults to false)
486: *
487: * @param array $options options for serialization generation.
488: * @return string completed form serialization script
489: */
490: abstract public function serializeForm($options = array());
491:
492: /**
493: * Parse an options assoc array into an Javascript object literal.
494: * Similar to object() but treats any non-integer value as a string,
495: * does not include `{ }`
496: *
497: * @param array $options Options to be converted
498: * @param array $safeKeys Keys that should not be escaped.
499: * @return string Parsed JSON options without enclosing { }.
500: */
501: protected function _parseOptions($options, $safeKeys = array()) {
502: $out = array();
503: $safeKeys = array_flip($safeKeys);
504: foreach ($options as $key => $value) {
505: if (!is_int($value) && !isset($safeKeys[$key])) {
506: $value = $this->value($value);
507: }
508: $out[] = $key . ':' . $value;
509: }
510: sort($out);
511: return join(', ', $out);
512: }
513:
514: /**
515: * Maps Abstract options to engine specific option names.
516: * If attributes are missing from the map, they are not changed.
517: *
518: * @param string $method Name of method whose options are being worked with.
519: * @param array $options Array of options to map.
520: * @return array Array of mapped options.
521: */
522: protected function _mapOptions($method, $options) {
523: if (!isset($this->_optionMap[$method])) {
524: return $options;
525: }
526: foreach ($this->_optionMap[$method] as $abstract => $concrete) {
527: if (isset($options[$abstract])) {
528: $options[$concrete] = $options[$abstract];
529: unset($options[$abstract]);
530: }
531: }
532: return $options;
533: }
534:
535: /**
536: * Prepare callbacks and wrap them with function ([args]) { } as defined in
537: * _callbackArgs array.
538: *
539: * @param string $method Name of the method you are preparing callbacks for.
540: * @param array $options Array of options being parsed
541: * @param string $callbacks Additional Keys that contain callbacks
542: * @return array Array of options with callbacks added.
543: */
544: protected function _prepareCallbacks($method, $options, $callbacks = array()) {
545: $wrapCallbacks = true;
546: if (isset($options['wrapCallbacks'])) {
547: $wrapCallbacks = $options['wrapCallbacks'];
548: }
549: unset($options['wrapCallbacks']);
550: if (!$wrapCallbacks) {
551: return $options;
552: }
553: $callbackOptions = array();
554: if (isset($this->_callbackArguments[$method])) {
555: $callbackOptions = $this->_callbackArguments[$method];
556: }
557: $callbacks = array_unique(array_merge(array_keys($callbackOptions), (array)$callbacks));
558:
559: foreach ($callbacks as $callback) {
560: if (empty($options[$callback])) {
561: continue;
562: }
563: $args = null;
564: if (!empty($callbackOptions[$callback])) {
565: $args = $callbackOptions[$callback];
566: }
567: $options[$callback] = 'function (' . $args . ') {' . $options[$callback] . '}';
568: }
569: return $options;
570: }
571:
572: /**
573: * Convenience wrapper method for all common option processing steps.
574: * Runs _mapOptions, _prepareCallbacks, and _parseOptions in order.
575: *
576: * @param string $method Name of method processing options for.
577: * @param array $options Array of options to process.
578: * @return string Parsed options string.
579: */
580: protected function _processOptions($method, $options) {
581: $options = $this->_mapOptions($method, $options);
582: $options = $this->_prepareCallbacks($method, $options);
583: $options = $this->_parseOptions($options, array_keys($this->_callbackArguments[$method]));
584: return $options;
585: }
586:
587: /**
588: * Convert an array of data into a query string
589: *
590: * @param array $parameters Array of parameters to convert to a query string
591: * @return string Querystring fragment
592: */
593: protected function _toQuerystring($parameters) {
594: $out = '';
595: $keys = array_keys($parameters);
596: $count = count($parameters);
597: for ($i = 0; $i < $count; $i++) {
598: $out .= $keys[$i] . '=' . $parameters[$keys[$i]];
599: if ($i < $count - 1) {
600: $out .= '&';
601: }
602: }
603: return $out;
604: }
605: }
606: