JsBaseEngineHelper.php 18 KB

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