UNPKG

21.7 kBJavaScriptView Raw
1import _extends from 'babel-runtime/helpers/extends';
2import _typeof from 'babel-runtime/helpers/typeof';
3import _Promise from 'babel-runtime/core-js/promise';
4/*
5Copyright 2013-2015 ASIAL CORPORATION
6
7Licensed under the Apache License, Version 2.0 (the "License");
8you may not use this file except in compliance with the License.
9You may obtain a copy of the License at
10
11 http://www.apache.org/licenses/LICENSE-2.0
12
13Unless required by applicable law or agreed to in writing, software
14distributed under the License is distributed on an "AS IS" BASIS,
15WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16See the License for the specific language governing permissions and
17limitations under the License.
18
19*/
20
21import util from './util';
22import elements from './elements';
23import animit from './animit';
24import GestureDetector from './gesture-detector';
25import platform from './platform';
26import notification from './notification';
27import actionSheet from './action-sheet';
28import internal from './internal';
29import orientation from './orientation';
30import modifier from './modifier';
31import softwareKeyboard from './software-keyboard';
32import pageAttributeExpression from './page-attribute-expression';
33import autoStyle from './autostyle';
34import DoorLock from './doorlock';
35import { defaultPageLoader, PageLoader } from './page-loader';
36
37/**
38 * @object ons
39 * @category util
40 * @description
41 * [ja]Onsen UIで利用できるグローバルなオブジェクトです。[/ja]
42 * [en]A global object that's used in Onsen UI. [/en]
43 */
44var ons = {
45 animit: animit,
46 defaultPageLoader: defaultPageLoader,
47 elements: elements,
48 GestureDetector: GestureDetector,
49 modifier: modifier,
50 notification: notification,
51 orientation: orientation,
52 pageAttributeExpression: pageAttributeExpression,
53 PageLoader: PageLoader,
54 platform: platform,
55 softwareKeyboard: softwareKeyboard,
56 _autoStyle: autoStyle,
57 _internal: internal,
58 _readyLock: new DoorLock(),
59 _util: util
60};
61
62ons.platform.select((window.location.search.match(/platform=([\w-]+)/) || [])[1]);
63
64waitDeviceReady();
65
66var readyError = function readyError(after) {
67 return util.throw('This method must be called ' + (after ? 'after' : 'before') + ' ons.isReady() is true');
68};
69
70/**
71 * @method isReady
72 * @signature isReady()
73 * @return {Boolean}
74 * [en]Will be true if Onsen UI is initialized.[/en]
75 * [ja]初期化されているかどうかを返します。[/ja]
76 * @description
77 * [en]Returns true if Onsen UI is initialized.[/en]
78 * [ja]Onsen UIがすでに初期化されているかどうかを返すメソッドです。[/ja]
79 */
80ons.isReady = function () {
81 return !ons._readyLock.isLocked();
82};
83
84/**
85 * @method isWebView
86 * @signature isWebView()
87 * @return {Boolean}
88 * [en]Will be true if the app is running in Cordova.[/en]
89 * [ja]Cordovaで実行されている場合にtrueになります。[/ja]
90 * @description
91 * [en]Returns true if running inside Cordova.[/en]
92 * [ja]Cordovaで実行されているかどうかを返すメソッドです。[/ja]
93 */
94ons.isWebView = ons.platform.isWebView;
95
96/**
97 * @method ready
98 * @signature ready(callback)
99 * @description
100 * [ja]アプリの初期化に利用するメソッドです。渡された関数は、Onsen UIの初期化が終了している時点で必ず呼ばれます。[/ja]
101 * [en]Method used to wait for app initialization. Waits for `DOMContentLoaded` and `deviceready`, when necessary, before executing the callback.[/en]
102 * @param {Function} callback
103 * [en]Function that executes after Onsen UI has been initialized.[/en]
104 * [ja]Onsen UIが初期化が完了した後に呼び出される関数オブジェクトを指定します。[/ja]
105 */
106ons.ready = function (callback) {
107 if (ons.isReady()) {
108 callback();
109 } else {
110 ons._readyLock.waitUnlock(callback);
111 }
112};
113
114/**
115 * @method setDefaultDeviceBackButtonListener
116 * @signature setDefaultDeviceBackButtonListener(listener)
117 * @param {Function} listener
118 * [en]Function that executes when device back button is pressed. Must be called on `ons.ready`.[/en]
119 * [ja]デバイスのバックボタンが押された時に実行される関数オブジェクトを指定します。[/ja]
120 * @description
121 * [en]Set default handler for device back button.[/en]
122 * [ja]デバイスのバックボタンのためのデフォルトのハンドラを設定します。[/ja]
123 */
124ons.setDefaultDeviceBackButtonListener = function (listener) {
125 if (!ons.isReady()) {
126 readyError(true);
127 }
128 ons._defaultDeviceBackButtonHandler.setListener(listener);
129};
130
131/**
132 * @method disableDeviceBackButtonHandler
133 * @signature disableDeviceBackButtonHandler()
134 * @description
135 * [en]Disable device back button event handler. Must be called on `ons.ready`.[/en]
136 * [ja]デバイスのバックボタンのイベントを受け付けないようにします。[/ja]
137 */
138ons.disableDeviceBackButtonHandler = function () {
139 if (!ons.isReady()) {
140 readyError(true);
141 }
142 internal.dbbDispatcher.disable();
143};
144
145/**
146 * @method enableDeviceBackButtonHandler
147 * @signature enableDeviceBackButtonHandler()
148 * @description
149 * [en]Enable device back button event handler. Must be called on `ons.ready`.[/en]
150 * [ja]デバイスのバックボタンのイベントを受け付けるようにします。[/ja]
151 */
152ons.enableDeviceBackButtonHandler = function () {
153 if (!ons.isReady()) {
154 readyError(true);
155 }
156 internal.dbbDispatcher.enable();
157};
158
159ons.fireDeviceBackButtonEvent = function () {
160 internal.dbbDispatcher.fireDeviceBackButtonEvent();
161};
162
163/**
164 * @method enableAutoStatusBarFill
165 * @signature enableAutoStatusBarFill()
166 * @description
167 * [en]Enable status bar fill feature on iOS7 and above (except for iPhone X). Must be called before `ons.ready`.[/en]
168 * [ja]iOS7以上(iPhone Xは除く)で、ステータスバー部分の高さを自動的に埋める処理を有効にします。[/ja]
169 */
170ons.enableAutoStatusBarFill = function () {
171 if (ons.isReady()) {
172 readyError(false);
173 }
174 internal.config.autoStatusBarFill = true;
175};
176
177/**
178 * @method disableAutoStatusBarFill
179 * @signature disableAutoStatusBarFill()
180 * @description
181 * [en]Disable status bar fill feature on iOS7 and above (except for iPhone X). Must be called before `ons.ready`.[/en]
182 * [ja]iOS7以上(iPhone Xは除く)で、ステータスバー部分の高さを自動的に埋める処理を無効にします。[/ja]
183 */
184ons.disableAutoStatusBarFill = function () {
185 if (ons.isReady()) {
186 readyError(false);
187 }
188 internal.config.autoStatusBarFill = false;
189};
190
191/**
192 * @method mockStatusBar
193 * @signature mockStatusBar()
194 * @description
195 * [en]Creates a static element similar to iOS status bar. Only useful for browser testing. Must be called before `ons.ready`.[/en]
196 * [ja][/ja]
197 */
198ons.mockStatusBar = function () {
199 if (ons.isReady()) {
200 readyError(false);
201 }
202
203 var mock = function mock() {
204 if (!document.body.children[0] || !document.body.children[0].classList.contains('ons-status-bar-mock')) {
205 var android = platform.isAndroid(),
206 i = function i(_i) {
207 return '<i class="' + _i.split('-')[0] + ' ' + _i + '"></i>';
208 };
209 var left = android ? i('zmdi-twitter') + ' ' + i('zmdi-google-play') : 'No SIM ' + i('fa-wifi'),
210 center = android ? '' : '12:28 PM',
211 right = android ? i('zmdi-network') + ' ' + i('zmdi-wifi') + ' ' + i('zmdi-battery') + ' 12:28 PM' : '80% ' + i('fa-battery-three-quarters');
212
213 document.body.insertBefore(util.createElement('<div class="ons-status-bar-mock ' + (android ? 'android' : 'ios') + '">' + ('<div>' + left + '</div><div>' + center + '</div><div>' + right + '</div>') + '</div>'), document.body.firstChild);
214 }
215 };
216
217 document.body ? mock() : internal.waitDOMContentLoaded(mock);
218};
219
220/**
221 * @method disableAnimations
222 * @signature disableAnimations()
223 * @description
224 * [en]Disable all animations. Could be handy for testing and older devices.[/en]
225 * [ja]アニメーションを全て無効にします。テストの際に便利です。[/ja]
226 */
227ons.disableAnimations = function () {
228 internal.config.animationsDisabled = true;
229};
230
231/**
232 * @method enableAnimations
233 * @signature enableAnimations()
234 * @description
235 * [en]Enable animations (default).[/en]
236 * [ja]アニメーションを有効にします。[/ja]
237 */
238ons.enableAnimations = function () {
239 internal.config.animationsDisabled = false;
240};
241
242ons._disableWarnings = function () {
243 internal.config.warningsDisabled = true;
244};
245
246ons._enableWarnings = function () {
247 internal.config.warningsDisabled = false;
248};
249
250/**
251 * @method disableAutoStyling
252 * @signature disableAutoStyling()
253 * @description
254 * [en]Disable automatic styling.[/en]
255 * [ja][/ja]
256 */
257ons.disableAutoStyling = autoStyle.disable;
258
259/**
260 * @method enableAutoStyling
261 * @signature enableAutoStyling()
262 * @description
263 * [en]Enable automatic styling based on OS (default).[/en]
264 * [ja][/ja]
265 */
266ons.enableAutoStyling = autoStyle.enable;
267
268/**
269 * @method disableIconAutoPrefix
270 * @signature disableIconAutoPrefix()
271 * @description
272 * [en]Disable adding `fa-` prefix automatically to `ons-icon` classes. Useful when including custom icon packs.[/en]
273 * [ja][/ja]
274 */
275ons.disableIconAutoPrefix = function () {
276 util.checkMissingImport('Icon');
277 elements.Icon.setAutoPrefix(false);
278};
279
280/**
281 * @method forceUIWebViewScrollFix
282 * @signature forceUIWebViewScrollFix()
283 * @param {Boolean} force Enable or disable the fix.
284 * @description
285 * [en]Applies a fix for iOS UIWebView which prevents scroll events jumping to pages under the top layer. This may visually affect normal scrolling of UIWebView if you open a dialog/menu before the scroll momentum finished. Disabled by default.[/en]
286 * [ja][/ja]
287 */
288ons.forceUIWebViewScrollFix = function () {
289 var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
290
291 internal.config.forceUIWebViewScrollFix = force;
292};
293
294/**
295 * @method forcePlatformStyling
296 * @signature forcePlatformStyling(platform)
297 * @description
298 * [en]Refresh styling for the given platform. Only useful for demos. Use `ons.platform.select(...)` instead for development and production.[/en]
299 * [ja][/ja]
300 * @param {string} platform New platform to style the elements.
301 */
302ons.forcePlatformStyling = function (newPlatform) {
303 ons.enableAutoStyling();
304 ons.platform.select(newPlatform || 'ios');
305
306 ons._util.arrayFrom(document.querySelectorAll('*')).forEach(function (element) {
307 if (element.tagName.toLowerCase() === 'ons-if') {
308 element._platformUpdate();
309 } else if (element.tagName.match(/^ons-/i)) {
310 autoStyle.prepare(element, true);
311 if (element.tagName.toLowerCase() === 'ons-tabbar') {
312 element._updatePosition();
313 }
314 }
315 });
316};
317
318/**
319 * @method preload
320 * @signature preload(templatePaths)
321 * @param {String|Array} templatePaths
322 * [en]Set of HTML file paths containing 'ons-page' elements.[/en]
323 * [ja][/ja]
324 * @return {Promise}
325 * [en]Promise that resolves when all the templates are cached.[/en]
326 * [ja][/ja]
327 * @description
328 * [en]Separated files need to be requested on demand and this can slightly delay pushing new pages. This method requests and caches templates for later use.[/en]
329 * [ja][/ja]
330 */
331ons.preload = function () {
332 var templates = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
333
334 return _Promise.all((templates instanceof Array ? templates : [templates]).map(function (template) {
335 if (typeof template !== 'string') {
336 util.throw('Expected string arguments but got ' + (typeof template === 'undefined' ? 'undefined' : _typeof(template)));
337 }
338 return internal.getTemplateHTMLAsync(template);
339 }));
340};
341
342/**
343 * @method createElement
344 * @signature createElement(template, options)
345 * @param {String} template
346 * [en]Either an HTML file path, a `<template>` id or an HTML string such as `'<div id="foo">hoge</div>'`.[/en]
347 * [ja][/ja]
348 * @param {Object} [options]
349 * [en]Parameter object.[/en]
350 * [ja]オプションを指定するオブジェクト。[/ja]
351 * @param {Boolean|HTMLElement} [options.append]
352 * [en]Whether or not the element should be automatically appended to the DOM. Defaults to `false`. If `true` value is given, `document.body` will be used as the target.[/en]
353 * [ja][/ja]
354 * @param {HTMLElement} [options.insertBefore]
355 * [en]Reference node that becomes the next sibling of the new node (`options.append` element).[/en]
356 * [ja][/ja]
357 * @return {HTMLElement|Promise}
358 * [en]If the provided template was an inline HTML string, it returns the new element. Otherwise, it returns a promise that resolves to the new element.[/en]
359 * [ja][/ja]
360 * @description
361 * [en]Create a new element from a template. Both inline HTML and external files are supported although the return value differs.[/en]
362 * [ja][/ja]
363 */
364ons.createElement = function (template) {
365 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
366
367 template = template.trim();
368
369 var create = function create(html) {
370 var element = ons._util.createElement(html);
371 element.remove();
372
373 if (options.append) {
374 var target = options.append instanceof HTMLElement ? options.append : document.body;
375 target.insertBefore(element, options.insertBefore || null);
376 options.link instanceof Function && options.link(element);
377 }
378
379 return element;
380 };
381
382 return template.charAt(0) === '<' ? create(template) : internal.getPageHTMLAsync(template).then(create);
383};
384
385/**
386 * @method createPopover
387 * @signature createPopover(page, [options])
388 * @param {String} page
389 * [en]Page name. Can be either an HTML file or a <template> containing a <ons-dialog> component.[/en]
390 * [ja]pageのURLか、もしくは`<template>`で宣言したテンプレートのid属性の値を指定できます。[/ja]
391 * @param {Object} [options]
392 * [en]Parameter object.[/en]
393 * [ja]オプションを指定するオブジェクト。[/ja]
394 * @param {Object} [options.parentScope]
395 * [en]Parent scope of the dialog. Used to bind models and access scope methods from the dialog.[/en]
396 * [ja]ダイアログ内で利用する親スコープを指定します。ダイアログからモデルやスコープのメソッドにアクセスするのに使います。このパラメータはAngularJSバインディングでのみ利用できます。[/ja]
397 * @return {Promise}
398 * [en]Promise object that resolves to the popover component object.[/en]
399 * [ja]ポップオーバーのコンポーネントオブジェクトを解決するPromiseオブジェクトを返します。[/ja]
400 * @description
401 * [en]Create a popover instance from a template.[/en]
402 * [ja]テンプレートからポップオーバーのインスタンスを生成します。[/ja]
403 */
404/**
405 * @method createDialog
406 * @signature createDialog(page, [options])
407 * @param {String} page
408 * [en]Page name. Can be either an HTML file or an `<template>` containing a <ons-dialog> component.[/en]
409 * [ja]pageのURLか、もしくは`<template>`で宣言したテンプレートのid属性の値を指定できます。[/ja]
410 * @param {Object} [options]
411 * [en]Parameter object.[/en]
412 * [ja]オプションを指定するオブジェクト。[/ja]
413 * @return {Promise}
414 * [en]Promise object that resolves to the dialog component object.[/en]
415 * [ja]ダイアログのコンポーネントオブジェクトを解決するPromiseオブジェクトを返します。[/ja]
416 * @description
417 * [en]Create a dialog instance from a template.[/en]
418 * [ja]テンプレートからダイアログのインスタンスを生成します。[/ja]
419 */
420/**
421 * @method createAlertDialog
422 * @signature createAlertDialog(page, [options])
423 * @param {String} page
424 * [en]Page name. Can be either an HTML file or an `<template>` containing a <ons-alert-dialog> component.[/en]
425 * [ja]pageのURLか、もしくは`<template>`で宣言したテンプレートのid属性の値を指定できます。[/ja]
426 * @param {Object} [options]
427 * [en]Parameter object.[/en]
428 * [ja]オプションを指定するオブジェクト。[/ja]
429 * @return {Promise}
430 * [en]Promise object that resolves to the alert dialog component object.[/en]
431 * [ja]ダイアログのコンポーネントオブジェクトを解決するPromiseオブジェクトを返します。[/ja]
432 * @description
433 * [en]Create a alert dialog instance from a template.[/en]
434 * [ja]テンプレートからアラートダイアログのインスタンスを生成します。[/ja]
435 */
436ons.createPopover = ons.createDialog = ons.createAlertDialog = function (template) {
437 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
438 return ons.createElement(template, _extends({ append: true }, options));
439};
440
441/**
442 * @method openActionSheet
443 * @signature openActionSheet(options)
444 * @description
445 * [en]Shows an instant Action Sheet and lets the user choose an action.[/en]
446 * [ja][/ja]
447 * @param {Object} [options]
448 * [en]Parameter object.[/en]
449 * [ja]オプションを指定するオブジェクト。[/ja]
450 * @param {Array} [options.buttons]
451 * [en]Represent each button of the action sheet following the specified order. Every item can be either a string label or an object containing `label`, `icon` and `modifier` properties.[/en]
452 * [ja][/ja]
453 * @param {String} [options.title]
454 * [en]Optional title for the action sheet.[/en]
455 * [ja][/ja]
456 * @param {Number} [options.destructive]
457 * [en]Optional index of the "destructive" button (only for iOS). It can be specified in the button array as well.[/en]
458 * [ja][/ja]
459 * @param {Boolean} [options.cancelable]
460 * [en]Whether the action sheet can be canceled by tapping on the background mask or not.[/en]
461 * [ja][/ja]
462 * @param {String} [options.modifier]
463 * [en]Modifier attribute of the action sheet. E.g. `'destructive'`.[/en]
464 * [ja][/ja]
465 * @param {String} [options.maskColor]
466 * [en]Optionally change the background mask color.[/en]
467 * [ja][/ja]
468 * @param {String} [options.id]
469 * [en]The element's id attribute.[/en]
470 * [ja][/ja]
471 * @param {String} [options.class]
472 * [en]The element's class attribute.[/en]
473 * [ja][/ja]
474 * @return {Promise}
475 * [en]Will resolve when the action sheet is closed. The resolve value is either the index of the tapped button or -1 when canceled.[/en]
476 * [ja][/ja]
477 */
478ons.openActionSheet = actionSheet;
479
480/**
481 * @method resolveLoadingPlaceholder
482 * @signature resolveLoadingPlaceholder(page)
483 * @param {String} page
484 * [en]Page name. Can be either an HTML file or a `<template>` id.[/en]
485 * [ja]pageのURLか、もしくは`<template>`で宣言したテンプレートのid属性の値を指定できます。[/ja]
486 * @description
487 * [en]If no page is defined for the `ons-loading-placeholder` attribute it will wait for this method being called before loading the page.[/en]
488 * [ja]ons-loading-placeholderの属性値としてページが指定されていない場合は、ページロード前に呼ばれるons.resolveLoadingPlaceholder処理が行われるまで表示されません。[/ja]
489 */
490ons.resolveLoadingPlaceholder = function (page, link) {
491 var elements = ons._util.arrayFrom(window.document.querySelectorAll('[ons-loading-placeholder]'));
492 if (elements.length === 0) {
493 util.throw('No ons-loading-placeholder exists');
494 }
495
496 elements.filter(function (element) {
497 return !element.getAttribute('page');
498 }).forEach(function (element) {
499 element.setAttribute('ons-loading-placeholder', page);
500 ons._resolveLoadingPlaceholder(element, page, link);
501 });
502};
503
504ons._setupLoadingPlaceHolders = function () {
505 ons.ready(function () {
506 var elements = ons._util.arrayFrom(window.document.querySelectorAll('[ons-loading-placeholder]'));
507
508 elements.forEach(function (element) {
509 var page = element.getAttribute('ons-loading-placeholder');
510 if (typeof page === 'string') {
511 ons._resolveLoadingPlaceholder(element, page);
512 }
513 });
514 });
515};
516
517ons._resolveLoadingPlaceholder = function (parent, page) {
518 var link = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function (el, done) {
519 return done();
520 };
521
522 page && ons.createElement(page).then(function (element) {
523 element.style.display = 'none';
524 parent.appendChild(element);
525 link(element, function () {
526 while (parent.firstChild && parent.firstChild !== element) {
527 parent.removeChild(parent.firstChild);
528 }
529 element.style.display = '';
530 });
531 }).catch(function (error) {
532 return _Promise.reject('Unabled to resolve placeholder: ' + error);
533 });
534};
535
536function waitDeviceReady() {
537 var unlockDeviceReady = ons._readyLock.lock();
538 window.addEventListener('DOMContentLoaded', function () {
539 if (ons.isWebView()) {
540 window.document.addEventListener('deviceready', unlockDeviceReady, false);
541 } else {
542 unlockDeviceReady();
543 }
544 }, false);
545}
546
547/**
548 * @method getScriptPage
549 * @signature getScriptPage()
550 * @description
551 * [en]Access the last created page from the current `script` scope. Only works inside `<script></script>` tags that are direct children of `ons-page` element. Use this to add lifecycle hooks to a page.[/en]
552 * [ja][/ja]
553 * @return {HTMLElement}
554 * [en]Returns the corresponding page element.[/en]
555 * [ja][/ja]
556 */
557var getCS = 'currentScript' in document ? function () {
558 return document.currentScript;
559} : function () {
560 return document.scripts[document.scripts.length - 1];
561};
562ons.getScriptPage = function () {
563 return getCS() && /ons-page/i.test(getCS().parentElement.tagName) && getCS().parentElement || null;
564};
565
566export default ons;
\No newline at end of file