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 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. 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.Helper
  26. */
  27. abstract class JsBaseEngineHelper extends AppHelper {
  28. /**
  29. * The js snippet for the current selection.
  30. *
  31. * @var string
  32. */
  33. public $selection;
  34. /**
  35. * Collection of option maps. Option maps allow other helpers to use generic names for engine
  36. * callbacks and options. Allowing uniform code access for all engine types. Their use is optional
  37. * for end user use though.
  38. *
  39. * @var array
  40. */
  41. protected $_optionMap = array();
  42. /**
  43. * An array of lowercase method names in the Engine that are buffered unless otherwise disabled.
  44. * This allows specific 'end point' methods to be automatically buffered by the JsHelper.
  45. *
  46. * @var array
  47. */
  48. public $bufferedMethods = array('event', 'sortable', 'drag', 'drop', 'slider');
  49. /**
  50. * Contains a list of callback names -> default arguments.
  51. *
  52. * @var array
  53. */
  54. protected $_callbackArguments = array();
  55. /**
  56. * Constructor.
  57. *
  58. * @param View $View
  59. * @param array $settings
  60. */
  61. public function __construct($View, $settings = array()) {
  62. parent::__construct($View, $settings);
  63. }
  64. /**
  65. * Create an `alert()` message in Javascript
  66. *
  67. * @param string $message Message you want to alter.
  68. * @return string completed alert()
  69. */
  70. public function alert($message) {
  71. return 'alert("' . $this->escape($message) . '");';
  72. }
  73. /**
  74. * Redirects to a URL. Creates a window.location modification snippet
  75. * that can be used to trigger 'redirects' from Javascript.
  76. *
  77. * @param mixed $url
  78. * @param array $options
  79. * @return string completed redirect in javascript
  80. */
  81. public function redirect($url = null) {
  82. return 'window.location = "' . Router::url($url) . '";';
  83. }
  84. /**
  85. * Create a `confirm()` message
  86. *
  87. * @param string $message Message you want confirmed.
  88. * @return string completed confirm()
  89. */
  90. public function confirm($message) {
  91. return 'confirm("' . $this->escape($message) . '");';
  92. }
  93. /**
  94. * Generate a confirm snippet that returns false from the current
  95. * function scope.
  96. *
  97. * @param string $message Message to use in the confirm dialog.
  98. * @return string completed confirm with return script
  99. */
  100. public function confirmReturn($message) {
  101. $out = 'var _confirm = ' . $this->confirm($message);
  102. $out .= "if (!_confirm) {\n\treturn false;\n}";
  103. return $out;
  104. }
  105. /**
  106. * Create a `prompt()` Javascript function
  107. *
  108. * @param string $message Message you want to prompt.
  109. * @param string $default Default message
  110. * @return string completed prompt()
  111. */
  112. public function prompt($message, $default = '') {
  113. return 'prompt("' . $this->escape($message) . '", "' . $this->escape($default) . '");';
  114. }
  115. /**
  116. * Generates a JavaScript object in JavaScript Object Notation (JSON)
  117. * from an array. Will use native JSON encode method if available, and $useNative == true
  118. *
  119. * ### Options:
  120. *
  121. * - `prefix` - String prepended to the returned data.
  122. * - `postfix` - String appended to the returned data.
  123. *
  124. * @param array $data Data to be converted.
  125. * @param array $options Set of options, see above.
  126. * @return string A JSON code block
  127. */
  128. public function object($data = array(), $options = array()) {
  129. $defaultOptions = array(
  130. 'prefix' => '', 'postfix' => '',
  131. );
  132. $options = array_merge($defaultOptions, $options);
  133. return $options['prefix'] . json_encode($data) . $options['postfix'];
  134. }
  135. /**
  136. * Converts a PHP-native variable of any type to a JSON-equivalent representation
  137. *
  138. * @param mixed $val A PHP variable to be converted to JSON
  139. * @param boolean $quoteString If false, leaves string values unquoted
  140. * @return string a JavaScript-safe/JSON representation of $val
  141. */
  142. public function value($val, $quoteString = true) {
  143. switch (true) {
  144. case (is_array($val) || is_object($val)):
  145. $val = $this->object($val);
  146. break;
  147. case ($val === null):
  148. $val = 'null';
  149. break;
  150. case (is_bool($val)):
  151. $val = ($val === true) ? 'true' : 'false';
  152. break;
  153. case (is_int($val)):
  154. $val = $val;
  155. break;
  156. case (is_float($val)):
  157. $val = sprintf("%.11f", $val);
  158. break;
  159. default:
  160. $val = $this->escape($val);
  161. if ($quoteString) {
  162. $val = '"' . $val . '"';
  163. }
  164. break;
  165. }
  166. return $val;
  167. }
  168. /**
  169. * Escape a string to be JSON friendly.
  170. *
  171. * List of escaped elements:
  172. *
  173. * - "\r" => '\n'
  174. * - "\n" => '\n'
  175. * - '"' => '\"'
  176. *
  177. * @param string $string String that needs to get escaped.
  178. * @return string Escaped string.
  179. */
  180. public function escape($string) {
  181. return $this->_utf8ToHex($string);
  182. }
  183. /**
  184. * Encode a string into JSON. Converts and escapes necessary characters.
  185. *
  186. * @param string $string The string that needs to be utf8->hex encoded
  187. * @return void
  188. */
  189. protected function _utf8ToHex($string) {
  190. $length = strlen($string);
  191. $return = '';
  192. for ($i = 0; $i < $length; ++$i) {
  193. $ord = ord($string{$i});
  194. switch (true) {
  195. case $ord == 0x08:
  196. $return .= '\b';
  197. break;
  198. case $ord == 0x09:
  199. $return .= '\t';
  200. break;
  201. case $ord == 0x0A:
  202. $return .= '\n';
  203. break;
  204. case $ord == 0x0C:
  205. $return .= '\f';
  206. break;
  207. case $ord == 0x0D:
  208. $return .= '\r';
  209. break;
  210. case $ord == 0x22:
  211. case $ord == 0x2F:
  212. case $ord == 0x5C:
  213. $return .= '\\' . $string{$i};
  214. break;
  215. case (($ord >= 0x20) && ($ord <= 0x7F)):
  216. $return .= $string{$i};
  217. break;
  218. case (($ord & 0xE0) == 0xC0):
  219. if ($i + 1 >= $length) {
  220. $i += 1;
  221. $return .= '?';
  222. break;
  223. }
  224. $charbits = $string{$i} . $string{$i + 1};
  225. $char = Multibyte::utf8($charbits);
  226. $return .= sprintf('\u%04s', dechex($char[0]));
  227. $i += 1;
  228. break;
  229. case (($ord & 0xF0) == 0xE0):
  230. if ($i + 2 >= $length) {
  231. $i += 2;
  232. $return .= '?';
  233. break;
  234. }
  235. $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2};
  236. $char = Multibyte::utf8($charbits);
  237. $return .= sprintf('\u%04s', dechex($char[0]));
  238. $i += 2;
  239. break;
  240. case (($ord & 0xF8) == 0xF0):
  241. if ($i + 3 >= $length) {
  242. $i += 3;
  243. $return .= '?';
  244. break;
  245. }
  246. $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3};
  247. $char = Multibyte::utf8($charbits);
  248. $return .= sprintf('\u%04s', dechex($char[0]));
  249. $i += 3;
  250. break;
  251. case (($ord & 0xFC) == 0xF8):
  252. if ($i + 4 >= $length) {
  253. $i += 4;
  254. $return .= '?';
  255. break;
  256. }
  257. $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4};
  258. $char = Multibyte::utf8($charbits);
  259. $return .= sprintf('\u%04s', dechex($char[0]));
  260. $i += 4;
  261. break;
  262. case (($ord & 0xFE) == 0xFC):
  263. if ($i + 5 >= $length) {
  264. $i += 5;
  265. $return .= '?';
  266. break;
  267. }
  268. $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4} . $string{$i + 5};
  269. $char = Multibyte::utf8($charbits);
  270. $return .= sprintf('\u%04s', dechex($char[0]));
  271. $i += 5;
  272. break;
  273. }
  274. }
  275. return $return;
  276. }
  277. /**
  278. * Create javascript selector for a CSS rule
  279. *
  280. * @param string $selector The selector that is targeted
  281. * @return JsBaseEngineHelper instance of $this. Allows chained methods.
  282. */
  283. abstract public function get($selector);
  284. /**
  285. * Add an event to the script cache. Operates on the currently selected elements.
  286. *
  287. * ### Options
  288. *
  289. * - `wrap` - Whether you want the callback wrapped in an anonymous function. (defaults to true)
  290. * - `stop` - Whether you want the event to stopped. (defaults to true)
  291. *
  292. * @param string $type Type of event to bind to the current dom id
  293. * @param string $callback The Javascript function you wish to trigger or the function literal
  294. * @param array $options Options for the event.
  295. * @return string completed event handler
  296. */
  297. abstract public function event($type, $callback, $options = array());
  298. /**
  299. * Create a domReady event. This is a special event in many libraries
  300. *
  301. * @param string $functionBody The code to run on domReady
  302. * @return string completed domReady method
  303. */
  304. abstract public function domReady($functionBody);
  305. /**
  306. * Create an iteration over the current selection result.
  307. *
  308. * @param string $callback The function body you wish to apply during the iteration.
  309. * @return string completed iteration
  310. */
  311. abstract public function each($callback);
  312. /**
  313. * Trigger an Effect.
  314. *
  315. * ### Supported Effects
  316. *
  317. * The following effects are supported by all core JsEngines
  318. *
  319. * - `show` - reveal an element.
  320. * - `hide` - hide an element.
  321. * - `fadeIn` - Fade in an element.
  322. * - `fadeOut` - Fade out an element.
  323. * - `slideIn` - Slide an element in.
  324. * - `slideOut` - Slide an element out.
  325. *
  326. * ### Options
  327. *
  328. * - `speed` - Speed at which the animation should occur. Accepted values are 'slow', 'fast'. Not all effects use
  329. * the speed option.
  330. *
  331. * @param string $name The name of the effect to trigger.
  332. * @param array $options Array of options for the effect.
  333. * @return string completed string with effect.
  334. */
  335. abstract public function effect($name, $options = array());
  336. /**
  337. * Make an XHR request
  338. *
  339. * ### Event Options
  340. *
  341. * - `complete` - Callback to fire on complete.
  342. * - `success` - Callback to fire on success.
  343. * - `before` - Callback to fire on request initialization.
  344. * - `error` - Callback to fire on request failure.
  345. *
  346. * ### Options
  347. *
  348. * - `method` - The method to make the request with defaults to GET in more libraries
  349. * - `async` - Whether or not you want an asynchronous request.
  350. * - `data` - Additional data to send.
  351. * - `update` - Dom id to update with the content of the request.
  352. * - `type` - Data type for response. 'json' and 'html' are supported. Default is html for most libraries.
  353. * - `evalScripts` - Whether or not <script> tags should be eval'ed.
  354. * - `dataExpression` - Should the `data` key be treated as a callback. Useful for supplying `$options['data']` as
  355. * another Javascript expression.
  356. *
  357. * @param mixed $url Array or String URL to target with the request.
  358. * @param array $options Array of options. See above for cross library supported options
  359. * @return string XHR request.
  360. */
  361. abstract public function request($url, $options = array());
  362. /**
  363. * Create a draggable element. Works on the currently selected element.
  364. * Additional options may be supported by the library implementation.
  365. *
  366. * ### Options
  367. *
  368. * - `handle` - selector to the handle element.
  369. * - `snapGrid` - The pixel grid that movement snaps to, an array(x, y)
  370. * - `container` - The element that acts as a bounding box for the draggable element.
  371. *
  372. * ### Event Options
  373. *
  374. * - `start` - Event fired when the drag starts
  375. * - `drag` - Event fired on every step of the drag
  376. * - `stop` - Event fired when dragging stops (mouse release)
  377. *
  378. * @param array $options Options array see above.
  379. * @return string Completed drag script
  380. */
  381. abstract public function drag($options = array());
  382. /**
  383. * Create a droppable element. Allows for draggable elements to be dropped on it.
  384. * Additional options may be supported by the library implementation.
  385. *
  386. * ### Options
  387. *
  388. * - `accept` - Selector for elements this droppable will accept.
  389. * - `hoverclass` - Class to add to droppable when a draggable is over.
  390. *
  391. * ### Event Options
  392. *
  393. * - `drop` - Event fired when an element is dropped into the drop zone.
  394. * - `hover` - Event fired when a drag enters a drop zone.
  395. * - `leave` - Event fired when a drag is removed from a drop zone without being dropped.
  396. *
  397. * @param array $options Array of options for the drop. See above.
  398. * @return string Completed drop script
  399. */
  400. abstract public function drop($options = array());
  401. /**
  402. * Create a sortable element.
  403. * Additional options may be supported by the library implementation.
  404. *
  405. * ### Options
  406. *
  407. * - `containment` - Container for move action
  408. * - `handle` - Selector to handle element. Only this element will start sort action.
  409. * - `revert` - Whether or not to use an effect to move sortable into final position.
  410. * - `opacity` - Opacity of the placeholder
  411. * - `distance` - Distance a sortable must be dragged before sorting starts.
  412. *
  413. * ### Event Options
  414. *
  415. * - `start` - Event fired when sorting starts
  416. * - `sort` - Event fired during sorting
  417. * - `complete` - Event fired when sorting completes.
  418. *
  419. * @param array $options Array of options for the sortable. See above.
  420. * @return string Completed sortable script.
  421. */
  422. abstract public function sortable($options = array());
  423. /**
  424. * Create a slider UI widget. Comprised of a track and knob.
  425. * Additional options may be supported by the library implementation.
  426. *
  427. * ### Options
  428. *
  429. * - `handle` - The id of the element used in sliding.
  430. * - `direction` - The direction of the slider either 'vertical' or 'horizontal'
  431. * - `min` - The min value for the slider.
  432. * - `max` - The max value for the slider.
  433. * - `step` - The number of steps or ticks the slider will have.
  434. * - `value` - The initial offset of the slider.
  435. *
  436. * ### Events
  437. *
  438. * - `change` - Fired when the slider's value is updated
  439. * - `complete` - Fired when the user stops sliding the handle
  440. *
  441. * @param array $options Array of options for the slider. See above.
  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. }