Publish Vulpes Preview 15 sources for desktop, Android and Tundra

Share Gaia assets and adapters, keep private profiles and development documents local, and update both public READMEs.
This commit is contained in:
OverSu 2026-09-30 23:13:03 +02:00
commit b38dea0597
50 changed files with 9982925 additions and 369 deletions

1224
gaia/apps/clock/js/alameda.js Executable file

File diff suppressed because it is too large Load diff

256
gaia/apps/clock/js/alarm.js Executable file
View file

@ -0,0 +1,256 @@
define(function(require, exports, module) {
'use strict';
/**
* Alarm represents one alarm instance. It tracks any mozAlarms it
* has registered, its IndexedDB ID, and any other properties
* relating to the alarm's schedule and firing options.
*/
function Alarm(opts) {
opts = opts || {};
var now = new Date();
var defaults = {
id: null,
registeredAlarms: {}, // keys: ('normal' or 'snooze') => mozAlarmID
// Map of weekdays { "0": true, "1": false, ... }
// "0" is for Sunday in Gregorian calendar
repeat: {},
hour: now.getHours(),
minute: now.getMinutes(),
label: '',
sound: 'ac_awake.opus',
vibrate: true,
snooze: 10 // Number of minutes to snooze
};
for (var key in defaults) {
this[key] = (key in opts ? opts[key] : defaults[key]);
}
}
Alarm.prototype = {
toJSON: function() {
return {
id: this.id,
registeredAlarms: this.registeredAlarms,
repeat: this.repeat,
hour: this.hour,
minute: this.minute,
label: this.label,
sound: this.sound,
vibrate: this.vibrate,
snooze: this.snooze
};
},
/**
* An alarm is enabled if and only if it has a registeredAlarm set
* with a type of 'normal'. To disable an alarm, any
* registeredAlarms are unregistered with mozAlarms and removed
* from this.registeredAlarms.
*/
isEnabled: function() {
for (var i in this.registeredAlarms) {
// Both 'normal' and 'snooze' registered alarms should be
// treated as enabled, because the alarm will imminently fire.
if (i === 'normal' || i === 'snooze') {
return true;
}
}
return false;
},
isRepeating: function() {
for (var key in this.repeat) {
if (this.repeat[key]) {
return true;
}
}
return false;
},
getNextAlarmFireTime: function(relativeTo) {
var now = relativeTo || new Date();
var nextFire = new Date(now.getTime());
nextFire.setHours(this.hour, this.minute, 0, 0);
while (nextFire <= now ||
(this.isRepeating() &&
!this.repeat[nextFire.getDay().toString()])) {
nextFire.setDate(nextFire.getDate() + 1);
}
return nextFire;
},
getNextSnoozeFireTime: function(relativeTo) {
var now = relativeTo || new Date();
return new Date(now.getTime() + this.snooze * 60 * 1000);
},
/**
* Schedule an alarm to ring in the future.
*
* @return {Promise}
* @param {'normal'|'snooze'} type
*/
schedule: function(type) {
var alarmDatabase = require('alarm_database'); // circular dependency
var firedate, promise;
if (type === 'normal') {
promise = this.cancel(); // Cancel both snooze and regular mozAlarms.
firedate = this.getNextAlarmFireTime();
} else if (type === 'snooze') {
promise = this.cancel('snooze'); // Cancel any snooze mozAlarms.
firedate = this.getNextSnoozeFireTime();
} else {
return Promise.reject('Invalid type for Alarm.schedule().');
}
// Save the alarm to the database first. This ensures we have a
// valid ID, and that we've saved any modified properties before
// attempting to schedule the alarm.
return promise.then(() => alarmDatabase.put(this)).then(() => {
return new Promise((resolve, reject) => {
// Then, schedule the alarm.
var req = navigator.mozAlarms.add(firedate, 'ignoreTimezone',
{ id: this.id, type: type });
req.onerror = reject;
req.onsuccess = (evt) => {
this.registeredAlarms[type] = evt.target.result;
resolve();
};
});
// After scheduling the alarm, this.registeredAlarms has
// changed, so we must save that too.
}).then(() => alarmDatabase.put(this))
.then(() => {
this._notifyChanged();
}).catch((e) => {
console.log('Alarm scheduling error: ' + e.toString());
throw e;
});
},
/**
* Cancel an alarm. If `type` is provided, cancel only that type
* ('normal' or 'snooze'). Returns a Promise.
*/
cancel: function(/* optional */ type) {
var types = (type ? [type] : Object.keys(this.registeredAlarms));
var alarmDatabase = require('alarm_database'); // circular dependency
types.forEach((type) => {
var id = this.registeredAlarms[type];
navigator.mozAlarms.remove(id);
delete this.registeredAlarms[type];
});
return alarmDatabase.put(this).then(() => {
this._notifyChanged();
}).catch((e) => {
console.log('Alarm cancel error: ' + e.toString());
throw e;
});
},
_notifyChanged: function(removed) {
// Only update the application if this alarm was actually saved
// (i.e. it has an ID).
if (this.id) {
var alarmDatabase = require('alarm_database');
// Updating Alarm info from the DataStore
alarmDatabase.getAll()
.then((alarms) => {
var storeAlarms = [];
alarms.forEach(function(a) {
// Grabbing alarms that are 'normal'
if(a.registeredAlarms.normal) {
storeAlarms.push(a.getNextAlarmFireTime());
}
});
return this.getNextAlarm(storeAlarms);
}).then((nextAlarm) => {
navigator.getDataStores('alarms')
.then((stores) => {
return [stores[0].getLength(), stores[0]];
}).then(([len, store]) => {
if(0 === len) {
return store.add(nextAlarm);
} else {
return store.put(nextAlarm, 1);
}
}).then((id) => {
if(id) {
console.log('[Clock] ==== Updated Alarm on LockScreen ====');
}
});
});
window.dispatchEvent(
new CustomEvent(removed ? 'alarm-removed' : 'alarm-changed', {
detail: { alarm: this }
})
);
}
},
/**
* Delete an alarm completely from the database, canceling any
* pending scheduled mozAlarms.
*/
delete: function() {
var alarmDatabase = require('alarm_database'); // circular dependency
return this.cancel().then(() => {
return alarmDatabase.delete(this.id).then(() => {
this._notifyChanged(/* removed = */ true);
});
});
},
/**
* Returns the next scheduled alarm within the next 24 hours
* @param {Array} type 'Date'
* @returns {Object} This is either an empty obj or hour and minute
*/
getNextAlarm: function(storeAlarms) {
var alarmIndex = [],
nextAlarm = {};
// remove alarms that have more than 24 hrs
storeAlarms.forEach( function(val,index) {
if((val.getTime() - new Date().getTime()) / 36e5 > 24 ) {
alarmIndex.push(index);
}
});
// remove last index first
alarmIndex.sort(function(a,b) {
return b - a;
});
alarmIndex.forEach( function(val) {
storeAlarms.splice(val, 1);
});
// sort alarms
storeAlarms.sort(function(a,b){
return new Date(a.getTime()) - new Date(b.getTime());
});
if(storeAlarms.length > 0) {
var mins = storeAlarms[0].getMinutes();
nextAlarm = {
hour : '' + storeAlarms[0].getHours(),
minute : mins < 10 ? '0' + mins : '' + mins
};
}
return nextAlarm;
}
};
module.exports = Alarm;
});

View file

@ -0,0 +1,205 @@
'use strict';
define(function(require) {
var sounds = require('./sounds');
/**
* The AlarmDatabase stores a list of alarms in IndexedDB. All
* mutation operations return Promises, for easy chaining and state
* management. This module returns the one-and-only instance of
* AlarmDatabase.
*/
function AlarmDatabase(dbName, storeName, version) {
this.dbName = dbName;
this.storeName = storeName;
this.version = version;
this.withDatabase = new Promise((resolve, reject) => {
var request = indexedDB.open(this.dbName, this.version);
request.onupgradeneeded = (event) => {
var db = event.target.result;
// Ensure the object store exists.
if (!db.objectStoreNames.contains(this.storeName)) {
db.createObjectStore(this.storeName, {
keyPath: 'id',
autoIncrement: true
});
}
};
request.onerror = (() => reject(request.errorCode));
request.onsuccess = ((event) => resolve(event.target.result));
}).then((db) => {
// Only return when all of the alarms have been upgraded.
return new Promise((resolve, reject) => {
// Go through existing alarms here, and make sure they conform
// to the latest spec (upgrade old versions, etc.).
var transaction = db.transaction(this.storeName, 'readwrite');
var store = transaction.objectStore(this.storeName);
var cursor = store.openCursor();
cursor.onsuccess = (event) => {
var cursor = event.target.result;
if (cursor) {
store.put(this.normalizeAlarmRecord(cursor.value));
cursor.continue();
}
};
transaction.oncomplete = (() => resolve(db));
transaction.onerror = ((evt) => reject(evt.target.errorCode));
});
}).catch(function(err) {
// Explicit err.toString() coercion needed to see a message.
console.error('AlarmDatabase Fatal Error:', err.toString());
});
}
AlarmDatabase.prototype = {
/**
* Given an Alarm's JSON data (as returned by IndexedDB),
* normalize any properties to ensure it conforms to the most
* current Alarm specification.
*/
normalizeAlarmRecord: function(alarm) {
if (!alarm.registeredAlarms) {
alarm.registeredAlarms = {};
}
if (typeof alarm.enabled !== 'undefined') {
delete alarm.enabled;
}
if (typeof alarm.normalAlarmId !== 'undefined') {
alarm.registeredAlarms.normal = alarm.normalAlarmId;
delete alarm.normalAlarmId;
}
if (typeof alarm.snoozeAlarmId !== 'undefined') {
alarm.registeredAlarms.snooze = alarm.snoozeAlarmId;
delete alarm.snoozeAlarmId;
}
var newRepeat = {};
var i;
// Map '1111100' string bitmap to a repeat object with day properties.
if (typeof alarm.repeat === 'string') {
for (i = 0; i < alarm.repeat.length; i++) {
if (alarm.repeat[i.toString()] === '1') {
newRepeat[i.toString()] = true;
}
}
alarm.repeat = newRepeat;
} else if (typeof alarm.repeat === 'object') {
var keys = Object.keys(alarm.repeat);
if (keys.length !== 0 && Number.isNaN(parseInt(keys[0]))) {
var oldKeys = ['sunday', 'monday', 'tuesday', 'wednesday',
'thursday', 'friday', 'saturday'];
for (i = 0; i < keys.length; i++) {
var index = oldKeys.indexOf(keys[i]);
if (index !== -1) {
newRepeat[index] = alarm.repeat[keys[i]];
}
}
alarm.repeat = newRepeat;
}
} else {
alarm.repeat = newRepeat;
}
// Pre-April-2014 code may have stored 'vibrate' and 'sound' as
// the string "0", and hour/minute as strings.
alarm.sound = sounds.normalizeSound(
alarm.sound !== '0' ? alarm.sound : null);
alarm.vibrate = (alarm.vibrate && alarm.vibrate !== '0') || false;
alarm.hour = parseInt(alarm.hour, 10);
alarm.minute = parseInt(alarm.minute, 10);
return alarm;
},
/**
* Execute a database store request with the given method and
* arguments, returning a Promise that will be fulfilled with the
* Store's result.
*/
withStoreRequest: function(method /*, args... */) {
var args = Array.slice(arguments, 1);
var readmode = (/get/.test(method) ? 'readonly' : 'readwrite');
return this.withDatabase.then((database) => {
var store = database
.transaction(this.storeName, readmode)
.objectStore(this.storeName);
if (method === 'getAll') {
return objectStoreGetAll(store);
} else {
return new Promise((resolve, reject) => {
var request = store[method].apply(store, args);
request.onsuccess = (() => resolve(request.result));
request.onerror = (() => reject(request.errorCode));
});
}
});
},
put: function(alarm) {
var data = alarm.toJSON();
if (!data.id) {
delete data.id; // IndexedDB requires _no_ ID key, not null/undefined.
}
return this.withStoreRequest('put', data).then((id) => {
alarm.id = id;
});
},
getAll: function() {
var Alarm = require('alarm'); // Circular dependency.
return this.withStoreRequest('getAll').then((alarms) => {
return alarms.map((data) => new Alarm(data));
});
},
get: function(id) {
var Alarm = require('alarm'); // Circular dependency.
return this.withStoreRequest('get', id).then((data) => {
return new Alarm(data);
});
},
delete: function(id) {
return this.withStoreRequest('delete', id);
}
};
/**
* Return all records from an ObjectStore. This function is
* non-standard, but is such a common pattern that it has actually
* been included in certain implementations of IndexedDB. It is
* extracted here for clarity.
*/
function objectStoreGetAll(objectStore) {
return new Promise((resolve, reject) => {
var items = [];
var cursor = objectStore.openCursor();
cursor.onerror = reject;
cursor.onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
items.push(cursor.value);
cursor.continue();
}
else {
resolve(items);
}
};
});
}
// For Clock, we only use one database and store, both named 'alarms'.
// Right now, we're on version 7.
return new AlarmDatabase('alarms', 'alarms', 7);
});

165
gaia/apps/clock/js/app.js Executable file
View file

@ -0,0 +1,165 @@
define(function(require) {
'use strict';
/* global IntlHelper */
var Tabs = require('tabs');
var View = require('view');
var connectionHandler = require('connection/handler');
/**
* Global Application event handling and paging
*/
var App = {
/**
* Load the Tabs and Panels, attach events and navigate to the default view.
*/
init: function() {
connectionHandler.init();
IntlHelper.define('digit-nopadding', 'number', {
style: 'decimal',
useGrouping: false
});
this.tabs = new Tabs(document.getElementById('clock-tabs'));
window.addEventListener('hashchange', this);
window.addEventListener('visibilitychange', this);
// Tell audio channel manager that we want to adjust the alarm channel
// if the user press the volumeup/volumedown buttons in Clock.
if (navigator.mozAudioChannelManager) {
navigator.mozAudioChannelManager.volumeControlChannel = 'alarm';
}
this.visible = !document.hidden;
this.panels = Array.prototype.map.call(
document.querySelectorAll('[data-panel-id]'),
function(element) {
var panel = {
el: element,
fragment: element.dataset.panelId.replace('_', '-') + '-panel',
instance: null
};
return panel;
}.bind(this)
);
window.performance.mark('navigationLoaded');
this.navigate({ hash: '#alarm-panel' }, function() {
// Dispatch an event to mark when we've finished loading.
// At this point, the navigation is usable, and the primary
// alarm list tab has begun loading.
window.performance.mark('navigationInteractive');
}.bind(this));
return this;
},
/**
* Load and instantiate the specified panel (when necessary).
*
* @param {Object} panel - An object describing the panel. It must contain
* either an `el` attribute (defining the panel's
* containing element) or an `instance` attribute
* (defining the instantiated Panel itself).
* @param {Function} [callback] - A function that will be invoked with the
* instantiated panel once it is loaded.
*/
loadPanel: function(panel, callback) {
if (panel.instance) {
callback && setTimeout(callback, 0, panel);
return;
}
var moduleId = 'panels/' + panel.el.dataset.panelId + '/main';
require([moduleId], function(PanelModule) {
panel.instance = View.instance(panel.el, PanelModule);
callback && callback(panel);
});
},
alarmListLoaded: function() {
// Performance testing markers. See <https://bugzil.la/996038>.
// At this point, the alarm list has been loaded, and all facets
// of Clock are now interactive. The other panels are lazily
// loaded when the user switches tabs.
window.performance.mark('visuallyLoaded');
window.performance.mark('contentInteractive');
window.performance.mark('fullyLoaded');
},
/**
* split each event handler into it's own method
*/
handleEvent: function(event) {
var handler = this['on' + event.type];
if (handler) {
return handler.apply(this, arguments);
}
},
/**
* navigate between pages.
*
* @param {object} data Options for navigation.
* @param {string} data.hash The hash of the panel id. I.E. '#alarm-panel'.
* @param {function} callback Callback to invoke when done.
*/
navigate: function(data, callback) {
var currentIndex = this.panels.indexOf(this.currentPanel);
this.panels.forEach(function(panel, panelIndex) {
if ('#' + panel.fragment === data.hash) {
this.loadPanel(panel, function() {
var instance = panel.instance;
instance.navData = data.data || null;
instance.active = true;
instance.visible = true;
if (currentIndex !== -1 && currentIndex !== panelIndex) {
var direction = currentIndex < panelIndex;
requestAnimationFrame(function startAnimation(oldPanel) {
instance.transition =
direction ? 'slide-in-right' : 'slide-in-left';
oldPanel.instance.transition =
direction ? 'slide-out-left' : 'slide-out-right';
}.bind(null, this.currentPanel));
}
this.currentPanel = panel;
callback && callback();
}.bind(this));
} else {
if (panel.instance) {
panel.instance.active = false;
}
}
}, this);
this.currentHash = data.hash;
},
/**
* Navigate to the new hash.
*/
onhashchange: function(event) {
if (this.currentHash === location.hash) {
return;
}
this.navigate({ hash: location.hash });
},
/**
* Whenever the application gains/loses focus, inform the current panel of
* its visibility loss.
*/
onvisibilitychange: function(event) {
this.visible = !document.hidden;
if (this.currentPanel) {
this.currentPanel.visible = this.visible;
}
}
};
return App;
});

View file

@ -0,0 +1,42 @@
'use strict';
define(function(require) {
/**
* A serial queue of functions. Call `.push()` to add a function to
* the task; when each function completes (as a result of calling
* 'done()'), the next item in the queue will be executed.
*/
function AsyncQueue() {
this.queue = [];
this.current = null;
}
AsyncQueue.prototype = {
/**
* Add a function to the execution queue. It should accept one
* argument, a 'done' callback.
*/
push: function(fn) {
if (!this.current) {
this._startTask(fn);
} else {
this.queue.push(fn);
}
},
_startTask: function(fn) {
this.current = fn;
fn(this._nextTask.bind(this));
},
_nextTask: function() {
this.current = null;
if (this.queue.length) {
this._startTask(this.queue.shift());
}
}
};
return AsyncQueue;
});

View file

@ -0,0 +1,185 @@
/* global define */
define(function(require) {
'use strict';
/**
* The Settings App stores volumes in the range [0, 15] inclusive.
* Whenever we need to play sounds, though, the Audio object
* requires a float between [0.0, 1.0]. The conversion has to happen
* somewhere. The AudioManager here draws the line right out of what
* gets read from mozSettings.
*
* In other words, the conversion is not important to clients of
* this class, who should treat the volume as a float with no
* conversion. The only weirdness here is that unit tests must be
* aware of the slight rounding differences when converting from a
* float to the system level.
*/
////////////////////////////////////////////////////////////////
// VolumeManager
function isValidVolume(volume) {
return (typeof volume === 'number' &&
volume <= 1.0 &&
volume >= 0.0);
}
var VOLUME_SETTING = 'audio.volume.alarm';
var SYSTEM_VOLUME_MAX = 15;
function systemVolumeToFloat(volume) {
return (volume / SYSTEM_VOLUME_MAX);
}
function floatToSystemVolume(volume) {
return Math.round(volume * SYSTEM_VOLUME_MAX);
}
function requestAlarmSystemVolume() {
// Asynchronously load the alarm volume from mozSettings.
return new Promise(function(resolve, reject) {
var lock = navigator.mozSettings.createLock();
var req = lock.get(VOLUME_SETTING);
req.onsuccess = function() {
var volume = systemVolumeToFloat(req.result[VOLUME_SETTING]);
if (isValidVolume(volume)) {
globalVolumeManager._volume = volume;
resolve(volume);
}
};
req.onerror = function() {
var DEFAULT_VOLUME = 1.0;
resolve(DEFAULT_VOLUME);
};
});
}
function VolumeManager() {
this.VOLUME_KEY = 'defaultAlarmVolume';
this.DEFAULT_VOLUME = 1.0;
this._volume = this.DEFAULT_VOLUME;
if (navigator.mozSettings) {
navigator.mozSettings.addObserver(
VOLUME_SETTING,
this.onSystemAlarmVolumeChange.bind(this));
}
}
VolumeManager.prototype = {
onSystemAlarmVolumeChange: function(e) {
// don't use the setter here
this._volume = systemVolumeToFloat(e.settingValue);
},
get volume() {
return this._volume;
},
set volume(volume) {
this.setVolume(volume);
},
/** Set the volume with an optional completion callback. */
setVolume: function(volume, cb) {
if (isValidVolume(volume)) {
this._volume = volume;
if (navigator.mozSettings) {
var lock = navigator.mozSettings.createLock();
var opts = {};
opts[VOLUME_SETTING] = floatToSystemVolume(volume);
var req = lock.set(opts);
if (cb) {
req.onsuccess = cb;
}
}
}
}
};
////////////////////////////////////////////////////////////////
// AudioPlayer
var globalVolumeManager = new VolumeManager();
/**
* The AudioPlayer class manages the playback of alarm ringtones. It
* is lazy-loading, so that you can instantiate it immediately;
* Audio objects are not actually created or loaded until you need
* to play a sound.
*/
function AudioPlayer() {
this._audio = null;
}
AudioPlayer.prototype = {
/**
* Play a ringtone from the shared/resources/media/alarms
* directory, using the current global volume settings by default.
* You can override the volume through opts.volume.
*
* @param {string} ringtoneName
* @param {number} opts.volume Value between 0 and 1
*/
playRingtone: function(ringtoneName, opts) {
var volume = globalVolumeManager.volume;
if (opts && 'volume' in opts) {
volume = opts.volume;
}
this._prepare(); // Load up the audio element.
this._audio.pause();
this._audio.src = 'shared/resources/media/alarms/' + ringtoneName;
this._audio.load(); // Required per MDN's HTMLMediaElement spec.
this._audio.volume = volume;
this._audio.play();
},
/**
* Pause the currently-playing audio, if possible.
*/
pause: function() {
if (this._audio) {
this._audio.pause();
}
},
// Private methods:
/**
* Instantiate the Audio element and prepare it for playback.
* For internal use only.
* @private
*/
_prepare: function() {
if (!this._audio) {
this._audio = new Audio();
this._audio.mozAudioChannelType = 'alarm';
this._audio.loop = true;
}
}
};
return {
getAlarmVolume: function() {
return globalVolumeManager.volume;
},
requestAlarmVolume: function() {
return requestAlarmSystemVolume();
},
setAlarmVolume: function(volume, cb) {
globalVolumeManager.setVolume(volume, cb);
},
createAudioPlayer: function() {
return new AudioPlayer();
},
// Exposed for tests:
systemVolumeToFloat: systemVolumeToFloat,
floatToSystemVolume: floatToSystemVolume
};
});

View file

@ -0,0 +1 @@
<p data-l10n-id="${noticeId}" data-l10n-args="${noticeArgs}"></p>

View file

@ -0,0 +1,88 @@
define(function(require) {
'use strict';
var Template = require('template');
var Utils = require('utils');
var html = require('text!banner/banner.html');
function Banner(node) {
// Accept a reference to an element or the element id
if (typeof node === 'string') {
this.notice = document.getElementById(node);
} else {
this.notice = node;
}
// Accept an optional reference to template element id
this.tmpl = new Template(html);
// Store a reference to timeout to debounce banner
this.timeout = null;
return this;
}
Banner.prototype = {
constructor: Banner,
render: function bn_render(alarmTime) {
var timeLeft, tl, countdownType, localTimes;
timeLeft = +alarmTime - Date.now();
// generate human readable numbers to pass to localization function
tl = Utils.dateMath.fromMS(timeLeft, {
unitsPartial: ['days', 'hours', 'minutes']
});
if (tl.days) {
countdownType = 'countdown_moreThanADay';
localTimes = {
'days': tl.days,
'hours': tl.hours
};
} else if (tl.hours > 0) {
countdownType = 'countdown_moreThanAnHour';
localTimes = {
'hours': tl.hours,
'minutes': tl.minutes
};
} else {
countdownType = 'countdown_lessThanAnHour';
localTimes = {
'minutes': tl.minutes
};
}
return {
noticeId: countdownType,
noticeArgs: JSON.stringify(localTimes)
};
},
show: function bn_show(alarmTime) {
// Render the Banner notice
this.notice.innerHTML = this.tmpl.interpolate(
this.render(alarmTime)
);
// 'visible' class controls the animation
this.notice.classList.add('visible');
// use this object rather than a function to retain context
this.notice.addEventListener('click', this);
// Debounce timer in case alarms are added more quickly than 4 seconds
if (this.timeout) {
clearTimeout(this.timeout);
}
// After 4 seconds, remove the banner
this.timeout = setTimeout(this.hide.bind(this), 4000);
},
hide: function bn_hide() {
this.notice.classList.remove('visible');
this.notice.removeEventListener('click', this);
},
handleEvent: function bn_handleEvent() {
this.hide();
}
};
return Banner;
});

View file

@ -0,0 +1,49 @@
define(function(require, exports) {
'use strict';
var Alarm = require('alarm');
var parseTime = require('ext/parse_loose_time');
exports.onmessage = function(event, port) {
if (event.data.type !== 'create') {
port.postMessage({
error: `Error: Invalid gaia_alarm message type "${event.data.type}"`
});
return;
}
var time = event.data.time;
var timeObject = typeof time === 'object' ? time : parseTime(time);
if (!isValidTime(timeObject)) {
port.postMessage({
error: `Invalid alarm time "${time}"`
});
return;
}
var alarm = new Alarm(timeObject);
alarm.schedule('normal').then(() => {
window.dispatchEvent(new CustomEvent('alarm-changed', {
detail: { alarm: alarm, showBanner: false }
}));
port.postMessage({
hour: timeObject.hour,
minute: timeObject.minute,
time: alarm.getNextAlarmFireTime().getTime()
});
}).catch(err => {
port.postMessage({
error: `${err.message} ${err.stack}`
});
});
};
function isValidTime(time) {
// time can be "null" and "typeof null === 'object'"
return time && typeof time === 'object' && 'hour' in time &&
time.hour >= 0 && time.hour <= 24 && 'minute' in time &&
time.minute >= 0 && time.minute <= 59;
}
});

View file

@ -0,0 +1,37 @@
define(function(require, exports) {
'use strict';
var handlers = {
'gaia_alarm': require('./alarm'),
'gaia_timer': require('./timer')
};
exports.init = function() {
navigator.mozSetMessageHandler('connection', req => {
var port = req.port;
var handler = handlers[req.keyword];
if (!handler) {
console.error(`can't find handler for connection "${req.keyword}"`);
return;
}
// IACMessagePort don't support onstart & onclose events as of 2015-07-21
// but for timer we do need to emulate this behavior
if (handler.onstart) {
handler.onstart(req);
}
if (handler.onmessage || handler.onclose) {
port.onmessage = event => {
if (event.data.type === 'close' && handler.onclose) {
handler.onclose(req);
return;
}
handler.onmessage && handler.onmessage(event, port);
};
}
});
};
});

View file

@ -0,0 +1,78 @@
define(function(require, exports) {
'use strict';
var Timer = require('timer');
var parseDuration = require('ext/parse_duration');
var port;
var timer;
exports.onstart = function(request) {
port = request.port;
window.addEventListener('timer-start', onTimerEvent);
window.addEventListener('timer-pause', onTimerEvent);
window.addEventListener('timer-end', onTimerEvent);
window.addEventListener('timer-tick', onTimerEvent);
};
exports.onclose = function() {
port = null;
timer = null;
window.removeEventListener('timer-start', onTimerEvent);
window.removeEventListener('timer-pause', onTimerEvent);
window.removeEventListener('timer-end', onTimerEvent);
window.removeEventListener('timer-tick', onTimerEvent);
};
function onTimerEvent(evt) {
if (!port) {
return;
}
port.postMessage({
type: evt.type,
remaining: evt.detail.remaining
});
}
exports.onmessage = function(event) {
if (timer) {
exec(event);
} else {
Timer.singleton((err, t) => {
timer = t;
exec(event);
});
}
};
function exec(event) {
var { type, duration } = event.data;
if (type === 'create') {
create(duration);
return;
}
// type: [start, pause, cancel]
timer[type]();
timer.commit();
}
function create(inputDuration) {
var duration = parseDuration(String(inputDuration));
if (!duration) {
port.postMessage({
error: `Invalid timer duration "${inputDuration}"`
});
return;
}
// we don't check the timer state since we assume the user wants to override
// any running timer and start it immediately
timer.duration = duration;
timer.start();
timer.commit();
}
});

View file

@ -0,0 +1,9 @@
define(function(require, exports) {
'use strict';
// ---------------------------------------------------------
// Constants
// Random day that happens to be Sunday
exports.KNOWN_SUNDAY = new Date(2015, 8, 20);
});

17
gaia/apps/clock/js/css.js Executable file
View file

@ -0,0 +1,17 @@
'use strict';
// Loader plugin for loading CSS. Does not guarantee loading via onload
// watching, just inserts link tag.
define({
load: function(id, require, onload, config) {
if (config.isBuild) {
return onload();
}
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = require.toUrl(id + '.css');
link.addEventListener('load', onload, false);
document.head.appendChild(link);
}
});

View file

@ -0,0 +1,70 @@
/**
* parse-duration v0.1.1
* Released under the MIT License
* https://github.com/jkroso/parse-duration
*/
define(function(require, exports, module) {
var duration = /(-?\d*\.?\d+(?:e[-+]?\d+)?)\s*([a-zμ]*)/ig
module.exports = parse
/**
* conversion ratios
*/
parse.nanosecond =
parse.ns = 1 / 1e6
parse.μs =
parse.microsecond = 1 / 1e3
parse.millisecond =
parse.ms = 1
parse.second =
parse.sec =
parse.s = parse.ms * 1000
parse.minute =
parse.min =
parse.m = parse.s * 60
parse.hour =
parse.hr =
parse.h = parse.m * 60
parse.day =
parse.d = parse.h * 24
parse.week =
parse.wk =
parse.w = parse.d * 7
parse.month = parse.d * (365.25 / 12)
parse.year =
parse.yr =
parse.y = parse.d * 365.25
/**
* convert `str` to ms
*
* @param {String} str
* @return {Number}
*/
function parse(str){
var result = 0
// ignore commas
str = str.replace(/(\d),(\d)/g, '$1$2')
str.replace(duration, function(_, n, units){
units = parse[units]
|| parse[units.toLowerCase().replace(/s$/, '')]
|| 1
result += parseFloat(n, 10) * units
})
return result
}
});

View file

@ -0,0 +1,138 @@
/**
* parse-loose-time v1.0.0
* https://github.com/millermedeiros/parse-loose-time/
* released under the MIT License
*/
define(function(require, exports, module) {
'use strict';
// Release the ZALGO!
var numeric = /\d{1,2}[^\d]*(\d{2})?/i;
var oclock = /\d+.*o.*clock/i;
var british = /(half|quarter|\d+).*(to|past)[^\d]*\d{1,2}/i;
var knownWords = [
'noon',
'noontime',
'midday',
'half-day',
'midnight'
];
// match "p" after digit for "pm"
var rPm = /\d\s*(o.*clock\s*)?p/i;
var checkKnowWords = {
test: function(str) {
return knownWords.indexOf(str) !== -1;
}
};
var map = [
[checkKnowWords, parseWords],
[british, parseBritish],
[oclock, parseOClock],
[numeric, parseNumeric]
];
module.exports = parseTime;
function parseTime(time) {
time = time.trim().toLowerCase();
// node 0.12 don't support Array#find :/
var fn;
map.some(function(a) {
if (a[0].test(time)) {
fn = a[1];
return true;
}
});
return fn ? fn(time) : null;
}
function parseNumeric(str) {
var hour;
var minute;
var num = extractNumbers(str);
switch (num.length) {
case 4:
hour = num.slice(0, 2);
minute = num.slice(2, 4);
break;
case 3:
hour = num.slice(0, 1);
minute = num.slice(1, 3);
break;
case 2:
case 1:
hour = num.slice(0, 2);
minute = 0;
break;
default:
return '';
}
hour = Number(hour);
minute = Number(minute);
if (num.length === 2 && hour > 24) {
return null;
}
if (hour < 12 && str.match(rPm)) {
hour += 12;
}
return {
hour: Math.min(hour, 24),
minute: Math.min(minute, 59)
};
}
function extractNumbers(str) {
return str.replace(/[^0-9]/g, '');
}
function parseOClock(str) {
// yes, we will consider "1:23 o'clock" the same as "1 o'clock"
var time = parseNumeric(str);
if (!time) {
return null;
}
time.minute = 0;
return time;
}
function parseBritish(str) {
// need to handle case where it is a custom numeric value
var parts = str.match(/(.+)(to|past)(.+)/i);
var time = parseNumeric(parts[3]);
if (!time) {
return null;
}
var diff;
if (str.indexOf('quarter') !== -1) {
diff = 15;
} else if (str.indexOf('half') !== -1) {
diff = 30;
} else {
diff = Number(extractNumbers(parts[1]));
}
var isTo = str.indexOf('to') !== -1;
if (isTo) {
time.hour -= 1;
time.minute = 60 - diff;
} else {
time.minute = diff;
}
return time;
}
function parseWords(str) {
if (str === 'midnight') {
return { hour: 0, minute: 0 };
}
return { hour: 12, minute: 0 };
}
});

196
gaia/apps/clock/js/form_button.js Executable file
View file

@ -0,0 +1,196 @@
// outer IIFE
define(function(require) {
'use strict';
var Utils = require('utils');
function createButton(formButton) {
var button = document.createElement(formButton.tagName);
button.className = formButton.className;
if (formButton.id) {
button.id = formButton.id;
}
var input = formButton.input;
input.parentNode.insertBefore(button, input.nextSibling);
formButton.button = button;
}
/**
* A FormButton is a button that triggers an input. The text
* of the currently selected value will display on the buttons's face.
*
* The `config` paramater supports the following optional properties.
* `formatLabel` - A function that is given the current value of the input
* and should return a string which will be used as the textContent of
* the button.
*
* `tagName` - The name of the tag to create and insert into the
* document as the main button used to trigger the input. The default
* value is 'button'
*
* `className` The value of the className property that will be assigned to
* the button element the default value is 'icon icon-dialog'.
*
* `id` - A string that is used as the id of the button element.
*
* @constructor
* @param {HTMLElement} input The input element to trigger.
* @param {Object} config An optional config object.
*
*/
function FormButton(input, config) {
config = config || {};
Utils.extend(this, config);
this.input = input;
createButton(this);
this.input.classList.add('form-button-input');
// hide input
this.input.classList.add('form-button-hide');
// set isSelect
Object.defineProperty(this, 'isSelect', {
value: this.input.nodeName === 'SELECT'
});
this.button.addEventListener('click', this.focus.bind(this), false);
input.addEventListener('change', this.refresh.bind(this), false);
input.addEventListener('blur', this.refresh.bind(this), false);
// Bind this.refresh so that the listener can be easily removed.
this.refresh = this.refresh.bind(this);
// Update the dropdown when the language changes.
window.addEventListener('localized', this.refresh);
window.addEventListener('timeformatchange', this.refresh);
}
FormButton.prototype = {
/** Remove all event handlers. */
destroy: function() {
window.removeEventListener('localized', this.refresh);
},
/**
* focus Triggers a focus event on the input associated with this
* FormButton.
*
* @param {Object} event an event object.
*/
focus: function(event) {
event.preventDefault();
setTimeout(this.input.focus.bind(this.input), 10);
},
/**
* refresh Updates the label text on the button to reflect
* the current value of the input.
*
*/
refresh: function() {
var value = this.value;
var label = this.formatLabel(value);
// In some cases formatLabel returns a Promise that returns l10nId
var labelPromise = label.then ? label : Promise.resolve(label);
return labelPromise.then((l10nId) => {
if (typeof l10nId === 'string') {
this.button.setAttribute('data-l10n-id', l10nId);
} else if (l10nId.raw) {
this.button.removeAttribute('data-l10n-id');
this.button.textContent = l10nId.raw;
} else if (l10nId.id) {
document.l10n.setAttributes(this.button, l10nId.id, l10nId.args);
}
});
},
/**
* value Returns the current value of the input.
*
* @return {String|Object} The value of the input.
*
*/
get value() {
if (this.isSelect) {
if (this.input.multiple) {
var selectedOptions = {};
var options = this.input.options;
for (var i = 0; i < options.length; i++) {
if (options[i].selected) {
selectedOptions[options[i].value] = true;
}
}
return selectedOptions;
}
if (this.input.selectedIndex !== -1) {
return Utils.getSelectedValueByIndex(this.input);
}
return null;
}
// input node
return this.input.value;
},
/**
* value sets the current value of the input and update's the
* button text.
*
* @param {String|Object} value A string of the current values or an
* object with properties that map to input options if the input is
* a multi select.
*
*/
set value(value) {
if (this.isSelect) {
if (this.input.multiple) {
// multi select
var options = this.input.options;
for (var i = 0; i < options.length; i++) {
options[i].selected = value[options[i].value] === true;
}
} else {
// normal select element
Utils.changeSelectByValue(this.input, value);
}
} else {
// input element
this.input.value = value;
}
// Update the text on the button to reflect the new input value
this.refresh();
},
/**
* An overrideable method that is called when updating the textContent
* of the button.
*
* @return {L10nId} The formatted text to display in the label.
*
*/
formatLabel: function(value) {
return { raw: value };
},
/**
* tagName The the name of the tag to insert into the document to use
* as the button element.
*/
tagName: 'button',
/**
* class The value to assign to the className property on the
* generated button element.
*/
className: 'icon icon-dialog'
};
return FormButton;
// end outer IIFE
});

6
gaia/apps/clock/js/onring.js Executable file
View file

@ -0,0 +1,6 @@
'use strict';
requirejs(['require_config'], function() {
requirejs(['ring_view'], function(RingView) {
window.ringView = new RingView();
});
});

96
gaia/apps/clock/js/panel.js Executable file
View file

@ -0,0 +1,96 @@
define(function(require) {
'use strict';
var View = require('view');
var priv = new WeakMap();
/**
* A Panel is a "full screen" style tab/dialog. Panels have an active state
* which can be true or false, and can transition in and out using CSS3
* classes and animation events.
*
* @constructor
* @param {HTMLElement} element The element to wrap.
*/
function Panel(element) {
View.apply(this, arguments);
priv.set(this, {
active: element.classList.contains('active'),
transition: false
});
element.addEventListener('animationend', this);
}
Panel.prototype = Object.create(View.prototype);
/**
* Handles the "animationend" event. Sets the transition state to false
* and hides the element if the Panel is not active.
*/
Panel.prototype.handleEvent = function(event) {
if (event.target !== this.element) {
return;
}
// remove visibility if transition finishes on non-active view
if (!this.active) {
this.visible = false;
}
this.transition = false;
};
Object.defineProperties(Panel.prototype, {
/**
* Panel.prototype.active - Boolean
*
* Sets the internal active state, and adds or removes the "active"
* class on the element.
*/
active: {
get: function() {
return priv.get(this).active;
},
set: function(value) {
var state = priv.get(this);
value = !!value;
if (state.active !== value) {
state.active = value;
if (value) {
this.element.classList.add('active');
} else {
this.pendingVisible = true;
this.element.classList.remove('active');
}
}
return value;
}
},
/**
* Panel.prototype.transition - String or false
*
* Sets the internal transition state. When set, adds the class specified
* to the element, removing the old transition class if it exists.
*
* When set to false, it removes the current transition class.
*/
transition: {
get: function() {
return priv.get(this).transition;
},
set: function(value) {
var state = priv.get(this);
if (value) {
if (state.transition) {
this.element.classList.remove(state.transition);
}
this.element.classList.add(value);
} else if (state.transition) {
this.element.classList.remove(state.transition);
}
state.transition = value;
return value;
}
}
});
return Panel;
});

View file

@ -0,0 +1,229 @@
define(function(require) {
'use strict';
var App = require('app');
var alarmDatabase = require('alarm_database');
var Timer = require('timer');
var Utils = require('utils');
var ChildWindowManager = require('./child_window_manager');
var PostMessageProxy = require('./post_message_proxy');
/**
* ActiveAlarm handles the system event that fires when an alarm
* goes off. This includes opening an attention window and updating
* an alarm's schedule when the user taps 'snooze'. The interaction
* is mediated through a PostMessageProxy (as `this.ringView`),
* which makes it trivial to interact with a JavaScript object
* hosted in another window.
*/
function ActiveAlarm() {
this.alertWindow = new ChildWindowManager(
window.location.origin + '/onring.html');
// Handle the system's alarm event.
navigator.mozSetMessageHandler('alarm', this.onMozAlarm.bind(this));
window.addEventListener('test-alarm', this.onMozAlarm.bind(this));
// Handle events transparently from the child window.
PostMessageProxy.receive('activeAlarm', this);
this.ringView = PostMessageProxy.create(null, 'ringView');
}
function logForAlarmDebugging() {
// The following logs are included for debugging reported
// problems with alarm firing times: <https://bugzil.la/1052245>
console.log('[Clock] =====================================\n');
console.log('[Clock] Alarm Debug:', JSON.stringify({
'now': new Date().toJSON(),
'tz': new Date().getTimezoneOffset()
}));
alarmDatabase.getAll().then((alarms) => {
console.log('[Clock] ===== Raw IndexedDB Alarm Data: =====\n');
// Logging in a loop to ensure we don't overrun the line buffer:
alarms.forEach(function(a) {
console.log('[Clock] ', JSON.stringify(a.toJSON()));
});
console.log('[Clock] -------------------------------------\n');
});
var request = navigator.mozAlarms.getAll();
request.onsuccess = function() {
console.log('[Clock] ======= Remaining mozAlarms: ========\n');
if (!request.result) {
console.log('[Clock] mozAlarm API invariant failure?');
} else {
request.result.forEach(function(alarm) {
console.log('[Clock] ', JSON.stringify(alarm));
});
}
console.log('[Clock] -------------------------------------\n');
};
request.onerror = function() {
console.error('[Clock] Failed to get list of mozAlarms:', this.error);
};
}
// Log at startup.
logForAlarmDebugging();
// Log periodically when the Clock app is running.
setInterval(logForAlarmDebugging, 10 * 60 * 1000);
ActiveAlarm.prototype = {
/**
* Fired when the system triggers an alarm. We acquire a wake lock
* here to ensure that the system doesn't fall asleep before we
* have a chance to present the attention alert window.
*/
onMozAlarm: function(message) {
// message.detail in only for marionette test.
// We pass it via AlarmActions.fire method.
var data = message.data || message.detail;
data.date = message.date || message.detail.date;
console.log('[Clock] ### ALARM FIRED! ### Details:',
JSON.stringify(message));
logForAlarmDebugging(message);
Utils.safeWakeLock({ timeoutMs: 30000 }, (done) => {
switch (data.type) {
case 'normal':
case 'snooze':
this.onAlarmFired(data, done);
break;
case 'timer':
this.onTimerFired(data, done);
break;
}
});
},
/**
* Add `alert` to the attention screen. The child alert window
* expects to receive any number of alert messages; if the child
* window has not been presented yet, this function opens the
* window before passing along the alert.
*
* An Alert object (which can represent a timer or an alarm)
* adheres to the following structure:
*
* @param {Alert} alert An alert to pass to the child window.
* @param {string} alert.type 'alarm' or 'timer'
* @param {string} [alert.label] Optional label
* @param {string} [alert.sound] Optional filename of a sound to play
* @param {boolean} alert.vibrate True if the alarm should vibrate
* @param {Date} alert.time The time the alert was supposed to fire
* @param {string} [alert.id] The ID of the alert, if type === 'alarm'
*/
popAlert: function(alert) {
this.alertWindow.whenReady(() => {
this.ringView.window = this.alertWindow.childWindow;
this.ringView.addAlert(alert);
});
},
/**
* Handle an alarm firing. Immediately reschedule the alarm for
* its next firing interval (if the alarm was a repeat alarm).
*
* @param {object} message The message as retrieved by mozAlarm
* @param {function} done Callback to release the wake lock.
*/
onAlarmFired: function(data, done) {
var id = data.id;
var date = data.date;
var type = data.type;
alarmDatabase.get(id).then((alarm) => {
this.popAlert({
type: 'alarm',
label: alarm.label,
sound: alarm.sound,
vibrate: alarm.vibrate,
time: date,
hour: alarm.hour,
minute: alarm.minute,
id: alarm.id
});
if (type === 'normal') {
// The alarm instance doesn't yet know that a mozAlarm has
// fired, so we call .cancel() to wipe this mozAlarm ID from
// alarm.registeredAlarms().
alarm.cancel();
if (alarm.isRepeating()) {
alarm.schedule('normal').then(done);
} else {
done();
}
} else if (type === 'snooze') {
// Inform the Alarm instance that a mozAlarm snooze has fired.
alarm.cancel('snooze');
done();
} else {
done();
}
});
},
/**
* Handle a timer firing.
*
* @param {object} message The message as retrieved by mozAlarm
* @param {function} done Callback to release the wake lock.
*/
onTimerFired: function(data, done) {
Timer.getFromStorage((timer) => {
this.popAlert({
type: 'timer',
label: timer.label,
sound: timer.sound,
vibrate: timer.vibrate,
time: new Date(timer.startTime + timer.duration)
});
done();
});
},
/**
* Snooze the given alarm.
*
* @param {string} alarmId The ID of the alarm.
*/
snoozeAlarm: function(alarmId) {
alarmDatabase.get(alarmId).then((alarm) => {
alarm.schedule('snooze');
});
},
/**
* Close the current alert window.
*
* @param {string} type 'alarm' or 'timer'
* @param {string} alarmId The ID of the alarm, if type === 'alarm'
*/
close: function(type, alarmId) {
this.alertWindow.close();
if (type === 'timer') {
App.navigate({ hash: '#timer-panel' });
Timer.singleton(function(err, timer) {
if (!err) {
timer.cancel();
timer.save();
}
});
} else if (type === 'alarm') {
App.navigate({ hash: '#alarm-panel' });
}
}
};
return ActiveAlarm;
});

View file

@ -0,0 +1,211 @@
define(function(require) {
'use strict';
/* global IntlHelper */
var Banner = require('banner/main');
var alarmDatabase = require('alarm_database');
var Utils = require('utils');
var App = require('app');
var alarmTemplate = require('tmpl!panels/alarm/list_item.html');
var AsyncQueue = require('async_queue');
/**
* AlarmListPanel displays the list of alarms on the Clock tab.
*/
function AlarmListPanel(element) {
this.alarms = element;
this.newAlarmButton.addEventListener(
'click', this.onClickNewAlarm.bind(this));
this.alarms.addEventListener('click', this.onClickAlarmItem.bind(this));
this.banner = new Banner('banner-countdown');
alarmDatabase.getAll().then((alarms) => {
for (var i = 0; alarms && i < alarms.length; i++) {
this.addOrUpdateAlarm(alarms[i]);
}
this.updateAlarmStatusBar();
App.alarmListLoaded();
});
// This will be fired on language and timeformat changes
IntlHelper.observe('time-html', this.refreshDisplay.bind(this));
window.addEventListener('alarm-changed', (evt) => {
var alarm = evt.detail.alarm;
this.addOrUpdateAlarm(alarm);
if (evt.detail.showBanner) {
this.banner.show(alarm.getNextAlarmFireTime());
}
this.updateAlarmStatusBar();
});
window.addEventListener('alarm-removed', (evt) => {
this.removeAlarm(evt.detail.alarm);
this.updateAlarmStatusBar();
});
}
AlarmListPanel.prototype = {
alarmIdMap: {},
refreshDisplay: function(evt) {
for (var key in this.alarmIdMap) {
var alarm = this.alarmIdMap[key];
this.addOrUpdateAlarm(alarm);
}
},
onClickNewAlarm: function(evt) {
evt.preventDefault();
App.navigate({ hash: '#alarm-edit-panel', data: null });
},
onClickAlarmItem: function(evt) {
var link = evt.target;
var alarm = this.alarmIdMap[link.dataset.id];
if (link.classList.contains('input-enable')) {
this.toggleAlarm(alarm, link.checked);
} else if (link.classList.contains('alarm-item')) {
App.navigate({ hash: '#alarm-edit-panel', data: alarm });
evt.preventDefault();
}
},
/**
* Render an alarm into a DOM node.
*
* @param alarm The alarm to render.
* @param {Element} [li] Existing element to re-use, if any.
*/
renderAlarm: function(alarm) {
var li = (this.alarms.querySelector('#alarm-' + alarm.id) ||
alarmTemplate.cloneNode(true));
var isActive = ('normal' in alarm.registeredAlarms ||
'snooze' in alarm.registeredAlarms);
var d = new Date();
d.setHours(alarm.hour);
d.setMinutes(alarm.minute);
li.id = 'alarm-' + alarm.id;
li.dataset.id = alarm.id;
var enableButton = li.querySelector('.input-enable');
enableButton.dataset.id = alarm.id;
enableButton.checked = isActive;
var link = li.querySelector('.alarm-item');
link.classList.toggle('with-repeat', alarm.isRepeating());
link.dataset.id = alarm.id;
li.querySelector('.time').innerHTML = Utils.getLocalizedTimeHtml(d);
if (alarm.label) {
li.querySelector('.label').removeAttribute('data-l10n-id');
li.querySelector('.label').textContent = alarm.label;
} else {
li.querySelector('.label').setAttribute('data-l10n-id', 'alarm');
}
if (alarm.isRepeating()) {
Utils.summarizeDaysOfWeek(alarm.repeat).then(l10nId => {
if (typeof l10nId === 'string') {
li.querySelector('.repeat').setAttribute('data-l10n-id', l10nId);
} else if (l10nId.raw) {
li.querySelector('.repeat').removeAttribute('data-l10n-id');
li.querySelector('.repeat').textContent = l10nId.raw;
}
});
} else {
li.querySelector('.repeat').removeAttribute('data-l10n-id');
li.querySelector('.repeat').textContent = '';
}
return li;
},
refreshClockView: function() {
window.dispatchEvent(new CustomEvent('alarm-list-changed'));
},
addOrUpdateAlarm: function(alarm) {
this.alarmIdMap[alarm.id] = alarm;
var li = this.renderAlarm(alarm);
var liId = parseInt(li.dataset.id, 10) || null;
// Go through the list of existing alarms, inserting this alarm
// before the first alarm that has a lower ID than this one.
var node = this.alarms.firstChild;
while (true) {
var nodeId = (node ? parseInt(node.dataset.id, 10) : -1);
if (nodeId < liId) {
this.alarms.insertBefore(li, node);
break;
}
node = node.nextSibling;
}
this.refreshClockView();
},
removeAlarm: function(alarm) {
delete this.alarmIdMap[alarm.id];
var li = this.alarms.querySelector('#alarm-' + alarm.id);
if (li) {
li.parentNode.removeChild(li);
}
this.refreshClockView();
},
toggleAlarmQueue: new AsyncQueue(),
/**
* Toggle an alarm's enabled state. To ensure that the database
* state remains consistent with the DOM, perform operations
* serially in a queue.
*
* @param {Alarm} alarm
* @param {boolean} enabled
* @param {function} callback Optional callback.
*/
toggleAlarm: function(alarm, enabled) {
this.toggleAlarmQueue.push((done) => {
if (enabled) {
alarm.schedule('normal').then(() => {
this.addOrUpdateAlarm(alarm);
this.updateAlarmStatusBar();
if (alarm.isEnabled()) {
this.banner.show(alarm.getNextAlarmFireTime());
}
}).then(done, done);
} else {
alarm.cancel().then(done);
}
});
},
updateAlarmStatusBar: function() {
if (navigator.mozSettings) {
var anyAlarmEnabled = false;
for (var id in this.alarmIdMap) {
if (this.alarmIdMap[id].isEnabled()) {
anyAlarmEnabled = true;
break;
}
}
navigator.mozSettings.createLock().set({
'alarm.enabled': anyAlarmEnabled
});
}
}
};
Utils.extendWithDomGetters(AlarmListPanel.prototype, {
title: '#alarms-title',
newAlarmButton: '#alarm-new'
});
return AlarmListPanel;
});

Some files were not shown because too many files have changed in this diff Show more