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