統計
| ブランチ: | リビジョン:

pictcode_admin / lib / Cake / View / Helper / JsBaseEngineHelper.php @ 5ad38a95

履歴 | 表示 | アノテート | ダウンロード (17.672 KB)

1 5ad38a95 spyder1211
<?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 a 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 += $defaultOptions;
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 bool $quoteString If false, leaves string values unquoted
141
 * @param string $key Key name.
142
 * @return string a JavaScript-safe/JSON representation of $val
143
 */
144
        public function value($val = array(), $quoteString = null, $key = 'value') {
145
                if ($quoteString === null) {
146
                        $quoteString = true;
147
                }
148
                switch (true) {
149
                        case (is_array($val) || is_object($val)):
150
                                $val = $this->object($val);
151
                                break;
152
                        case ($val === null):
153
                                $val = 'null';
154
                                break;
155
                        case (is_bool($val)):
156
                                $val = ($val === true) ? 'true' : 'false';
157
                                break;
158
                        case (is_int($val)):
159
                                $val = $val;
160
                                break;
161
                        case (is_float($val)):
162
                                $val = sprintf("%.11f", $val);
163
                                break;
164
                        default:
165
                                $val = $this->escape($val);
166
                                if ($quoteString) {
167
                                        $val = '"' . $val . '"';
168
                                }
169
                }
170
                return $val;
171
        }
172
173
/**
174
 * Escape a string to be JSON friendly.
175
 *
176
 * List of escaped elements:
177
 *
178
 * - "\r" => '\n'
179
 * - "\n" => '\n'
180
 * - '"' => '\"'
181
 *
182
 * @param string $string String that needs to get escaped.
183
 * @return string Escaped string.
184
 */
185
        public function escape($string) {
186
                return $this->_utf8ToHex($string);
187
        }
188
189
/**
190
 * Encode a string into JSON. Converts and escapes necessary characters.
191
 *
192
 * @param string $string The string that needs to be utf8->hex encoded
193
 * @return void
194
 */
195
        protected function _utf8ToHex($string) {
196
                $length = strlen($string);
197
                $return = '';
198
                for ($i = 0; $i < $length; ++$i) {
199
                        $ord = ord($string{$i});
200
                        switch (true) {
201
                                case $ord == 0x08:
202
                                        $return .= '\b';
203
                                        break;
204
                                case $ord == 0x09:
205
                                        $return .= '\t';
206
                                        break;
207
                                case $ord == 0x0A:
208
                                        $return .= '\n';
209
                                        break;
210
                                case $ord == 0x0C:
211
                                        $return .= '\f';
212
                                        break;
213
                                case $ord == 0x0D:
214
                                        $return .= '\r';
215
                                        break;
216
                                case $ord == 0x22:
217
                                case $ord == 0x2F:
218
                                case $ord == 0x5C:
219
                                        $return .= '\\' . $string{$i};
220
                                        break;
221
                                case (($ord >= 0x20) && ($ord <= 0x7F)):
222
                                        $return .= $string{$i};
223
                                        break;
224
                                case (($ord & 0xE0) == 0xC0):
225
                                        if ($i + 1 >= $length) {
226
                                                $i += 1;
227
                                                $return .= '?';
228
                                                break;
229
                                        }
230
                                        $charbits = $string{$i} . $string{$i + 1};
231
                                        $char = Multibyte::utf8($charbits);
232
                                        $return .= sprintf('\u%04s', dechex($char[0]));
233
                                        $i += 1;
234
                                        break;
235
                                case (($ord & 0xF0) == 0xE0):
236
                                        if ($i + 2 >= $length) {
237
                                                $i += 2;
238
                                                $return .= '?';
239
                                                break;
240
                                        }
241
                                        $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2};
242
                                        $char = Multibyte::utf8($charbits);
243
                                        $return .= sprintf('\u%04s', dechex($char[0]));
244
                                        $i += 2;
245
                                        break;
246
                                case (($ord & 0xF8) == 0xF0):
247
                                        if ($i + 3 >= $length) {
248
                                                $i += 3;
249
                                                $return .= '?';
250
                                                break;
251
                                        }
252
                                        $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3};
253
                                        $char = Multibyte::utf8($charbits);
254
                                        $return .= sprintf('\u%04s', dechex($char[0]));
255
                                        $i += 3;
256
                                        break;
257
                                case (($ord & 0xFC) == 0xF8):
258
                                        if ($i + 4 >= $length) {
259
                                                $i += 4;
260
                                                $return .= '?';
261
                                                break;
262
                                        }
263
                                        $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4};
264
                                        $char = Multibyte::utf8($charbits);
265
                                        $return .= sprintf('\u%04s', dechex($char[0]));
266
                                        $i += 4;
267
                                        break;
268
                                case (($ord & 0xFE) == 0xFC):
269
                                        if ($i + 5 >= $length) {
270
                                                $i += 5;
271
                                                $return .= '?';
272
                                                break;
273
                                        }
274
                                        $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4} . $string{$i + 5};
275
                                        $char = Multibyte::utf8($charbits);
276
                                        $return .= sprintf('\u%04s', dechex($char[0]));
277
                                        $i += 5;
278
                                        break;
279
                        }
280
                }
281
                return $return;
282
        }
283
284
/**
285
 * Create javascript selector for a CSS rule
286
 *
287
 * @param string $selector The selector that is targeted
288
 * @return JsBaseEngineHelper instance of $this. Allows chained methods.
289
 */
290
        abstract public function get($selector);
291
292
/**
293
 * Add an event to the script cache. Operates on the currently selected elements.
294
 *
295
 * ### Options
296
 *
297
 * - `wrap` - Whether you want the callback wrapped in an anonymous function. (defaults to true)
298
 * - `stop` - Whether you want the event to stopped. (defaults to true)
299
 *
300
 * @param string $type Type of event to bind to the current dom id
301
 * @param string $callback The JavaScript function you wish to trigger or the function literal
302
 * @param array $options Options for the event.
303
 * @return string completed event handler
304
 */
305
        abstract public function event($type, $callback, $options = array());
306
307
/**
308
 * Create a domReady event. This is a special event in many libraries
309
 *
310
 * @param string $functionBody The code to run on domReady
311
 * @return string completed domReady method
312
 */
313
        abstract public function domReady($functionBody);
314
315
/**
316
 * Create an iteration over the current selection result.
317
 *
318
 * @param string $callback The function body you wish to apply during the iteration.
319
 * @return string completed iteration
320
 */
321
        abstract public function each($callback);
322
323
/**
324
 * Trigger an Effect.
325
 *
326
 * ### Supported Effects
327
 *
328
 * The following effects are supported by all core JsEngines
329
 *
330
 * - `show` - reveal an element.
331
 * - `hide` - hide an element.
332
 * - `fadeIn` - Fade in an element.
333
 * - `fadeOut` - Fade out an element.
334
 * - `slideIn` - Slide an element in.
335
 * - `slideOut` - Slide an element out.
336
 *
337
 * ### Options
338
 *
339
 * - `speed` - Speed at which the animation should occur. Accepted values are 'slow', 'fast'. Not all effects use
340
 *   the speed option.
341
 *
342
 * @param string $name The name of the effect to trigger.
343
 * @param array $options Array of options for the effect.
344
 * @return string completed string with effect.
345
 */
346
        abstract public function effect($name, $options = array());
347
348
/**
349
 * Make an XHR request
350
 *
351
 * ### Event Options
352
 *
353
 * - `complete` - Callback to fire on complete.
354
 * - `success` - Callback to fire on success.
355
 * - `before` - Callback to fire on request initialization.
356
 * - `error` - Callback to fire on request failure.
357
 *
358
 * ### Options
359
 *
360
 * - `method` - The method to make the request with defaults to GET in more libraries
361
 * - `async` - Whether or not you want an asynchronous request.
362
 * - `data` - Additional data to send.
363
 * - `update` - Dom id to update with the content of the request.
364
 * - `type` - Data type for response. 'json' and 'html' are supported. Default is html for most libraries.
365
 * - `evalScripts` - Whether or not <script> tags should be eval'ed.
366
 * - `dataExpression` - Should the `data` key be treated as a callback. Useful for supplying `$options['data']` as
367
 *    another JavaScript expression.
368
 *
369
 * @param string|array $url Array or String URL to target with the request.
370
 * @param array $options Array of options. See above for cross library supported options
371
 * @return string XHR request.
372
 */
373
        abstract public function request($url, $options = array());
374
375
/**
376
 * Create a draggable element. Works on the currently selected element.
377
 * Additional options may be supported by the library implementation.
378
 *
379
 * ### Options
380
 *
381
 * - `handle` - selector to the handle element.
382
 * - `snapGrid` - The pixel grid that movement snaps to, an array(x, y)
383
 * - `container` - The element that acts as a bounding box for the draggable element.
384
 *
385
 * ### Event Options
386
 *
387
 * - `start` - Event fired when the drag starts
388
 * - `drag` - Event fired on every step of the drag
389
 * - `stop` - Event fired when dragging stops (mouse release)
390
 *
391
 * @param array $options Options array see above.
392
 * @return string Completed drag script
393
 */
394
        abstract public function drag($options = array());
395
396
/**
397
 * Create a droppable element. Allows for draggable elements to be dropped on it.
398
 * Additional options may be supported by the library implementation.
399
 *
400
 * ### Options
401
 *
402
 * - `accept` - Selector for elements this droppable will accept.
403
 * - `hoverclass` - Class to add to droppable when a draggable is over.
404
 *
405
 * ### Event Options
406
 *
407
 * - `drop` - Event fired when an element is dropped into the drop zone.
408
 * - `hover` - Event fired when a drag enters a drop zone.
409
 * - `leave` - Event fired when a drag is removed from a drop zone without being dropped.
410
 *
411
 * @param array $options Array of options for the drop. See above.
412
 * @return string Completed drop script
413
 */
414
        abstract public function drop($options = array());
415
416
/**
417
 * Create a sortable element.
418
 * Additional options may be supported by the library implementation.
419
 *
420
 * ### Options
421
 *
422
 * - `containment` - Container for move action
423
 * - `handle` - Selector to handle element. Only this element will start sort action.
424
 * - `revert` - Whether or not to use an effect to move sortable into final position.
425
 * - `opacity` - Opacity of the placeholder
426
 * - `distance` - Distance a sortable must be dragged before sorting starts.
427
 *
428
 * ### Event Options
429
 *
430
 * - `start` - Event fired when sorting starts
431
 * - `sort` - Event fired during sorting
432
 * - `complete` - Event fired when sorting completes.
433
 *
434
 * @param array $options Array of options for the sortable. See above.
435
 * @return string Completed sortable script.
436
 */
437
        abstract public function sortable($options = array());
438
439
/**
440
 * Create a slider UI widget. Comprised of a track and knob.
441
 * Additional options may be supported by the library implementation.
442
 *
443
 * ### Options
444
 *
445
 * - `handle` - The id of the element used in sliding.
446
 * - `direction` - The direction of the slider either 'vertical' or 'horizontal'
447
 * - `min` - The min value for the slider.
448
 * - `max` - The max value for the slider.
449
 * - `step` - The number of steps or ticks the slider will have.
450
 * - `value` - The initial offset of the slider.
451
 *
452
 * ### Events
453
 *
454
 * - `change` - Fired when the slider's value is updated
455
 * - `complete` - Fired when the user stops sliding the handle
456
 *
457
 * @param array $options Array of options for the slider. See above.
458
 * @return string Completed slider script
459
 */
460
        abstract public function slider($options = array());
461
462
/**
463
 * Serialize the form attached to $selector.
464
 * Pass `true` for $isForm if the current selection is a form element.
465
 * Converts the form or the form element attached to the current selection into a string/json object
466
 * (depending on the library implementation) for use with XHR operations.
467
 *
468
 * ### Options
469
 *
470
 * - `isForm` - is the current selection a form, or an input? (defaults to false)
471
 * - `inline` - is the rendered statement going to be used inside another JS statement? (defaults to false)
472
 *
473
 * @param array $options options for serialization generation.
474
 * @return string completed form serialization script
475
 */
476
        abstract public function serializeForm($options = array());
477
478
/**
479
 * Parse an options assoc array into a JavaScript object literal.
480
 * Similar to object() but treats any non-integer value as a string,
481
 * does not include `{ }`
482
 *
483
 * @param array $options Options to be converted
484
 * @param array $safeKeys Keys that should not be escaped.
485
 * @return string Parsed JSON options without enclosing { }.
486
 */
487
        protected function _parseOptions($options, $safeKeys = array()) {
488
                $out = array();
489
                $safeKeys = array_flip($safeKeys);
490
                foreach ($options as $key => $value) {
491
                        if (!is_int($value) && !isset($safeKeys[$key])) {
492
                                $value = $this->value($value);
493
                        }
494
                        $out[] = $key . ':' . $value;
495
                }
496
                sort($out);
497
                return implode(', ', $out);
498
        }
499
500
/**
501
 * Maps Abstract options to engine specific option names.
502
 * If attributes are missing from the map, they are not changed.
503
 *
504
 * @param string $method Name of method whose options are being worked with.
505
 * @param array $options Array of options to map.
506
 * @return array Array of mapped options.
507
 */
508
        protected function _mapOptions($method, $options) {
509
                if (!isset($this->_optionMap[$method])) {
510
                        return $options;
511
                }
512
                foreach ($this->_optionMap[$method] as $abstract => $concrete) {
513
                        if (isset($options[$abstract])) {
514
                                $options[$concrete] = $options[$abstract];
515
                                unset($options[$abstract]);
516
                        }
517
                }
518
                return $options;
519
        }
520
521
/**
522
 * Prepare callbacks and wrap them with function ([args]) { } as defined in
523
 * _callbackArgs array.
524
 *
525
 * @param string $method Name of the method you are preparing callbacks for.
526
 * @param array $options Array of options being parsed
527
 * @param array $callbacks Additional Keys that contain callbacks
528
 * @return array Array of options with callbacks added.
529
 */
530
        protected function _prepareCallbacks($method, $options, $callbacks = array()) {
531
                $wrapCallbacks = true;
532
                if (isset($options['wrapCallbacks'])) {
533
                        $wrapCallbacks = $options['wrapCallbacks'];
534
                }
535
                unset($options['wrapCallbacks']);
536
                if (!$wrapCallbacks) {
537
                        return $options;
538
                }
539
                $callbackOptions = array();
540
                if (isset($this->_callbackArguments[$method])) {
541
                        $callbackOptions = $this->_callbackArguments[$method];
542
                }
543
                $callbacks = array_unique(array_merge(array_keys($callbackOptions), (array)$callbacks));
544
545
                foreach ($callbacks as $callback) {
546
                        if (empty($options[$callback])) {
547
                                continue;
548
                        }
549
                        $args = null;
550
                        if (!empty($callbackOptions[$callback])) {
551
                                $args = $callbackOptions[$callback];
552
                        }
553
                        $options[$callback] = 'function (' . $args . ') {' . $options[$callback] . '}';
554
                }
555
                return $options;
556
        }
557
558
/**
559
 * Convenience wrapper method for all common option processing steps.
560
 * Runs _mapOptions, _prepareCallbacks, and _parseOptions in order.
561
 *
562
 * @param string $method Name of method processing options for.
563
 * @param array $options Array of options to process.
564
 * @return string Parsed options string.
565
 */
566
        protected function _processOptions($method, $options) {
567
                $options = $this->_mapOptions($method, $options);
568
                $options = $this->_prepareCallbacks($method, $options);
569
                $options = $this->_parseOptions($options, array_keys($this->_callbackArguments[$method]));
570
                return $options;
571
        }
572
573
/**
574
 * Convert an array of data into a query string
575
 *
576
 * @param array $parameters Array of parameters to convert to a query string
577
 * @return string Querystring fragment
578
 */
579
        protected function _toQuerystring($parameters) {
580
                $out = '';
581
                $keys = array_keys($parameters);
582
                $count = count($parameters);
583
                for ($i = 0; $i < $count; $i++) {
584
                        $out .= $keys[$i] . '=' . $parameters[$keys[$i]];
585
                        if ($i < $count - 1) {
586
                                $out .= '&';
587
                        }
588
                }
589
                return $out;
590
        }
591
592
}