JsBaseEngineHelper.php 18 KB

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