JsBaseEngineHelper.php 19 KB

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