summaryrefslogtreecommitdiffstats
path: root/chrome/browser/resources/standalone/standalone_hack.js
blob: c7d3c3358723724cb5a924b515e88690752345dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 *  @fileoverview LIS Standalone hack
 *  This file contains the code necessary to make the Touch LIS work
 *  as a stand-alone application (as opposed to being embedded into chrome).
 *  This is useful for rapid development and testing, but does not actually form
 *  part of the product.
 */

// Note that this file never gets concatenated and embeded into Chrome, so we
// can enable strict mode for the whole file just like normal.
'use strict';

/**
 * For non-Chrome browsers, create a dummy chrome object
 */
if (!window.chrome) {
  var chrome = {};
}

/**
 *  A replacement chrome.send method that supplies static data for the
 *  key APIs used by the LIS.
 *
 *  Note that the real chrome object also supplies data for most-viewed and
 *  recently-closed pages, but the tangent LIS doesn't use that data so we
 *  don't bother simulating it here.
 *
 *  We create this object by applying an anonymous function so that we can have
 *  local variables (avoid polluting the global object)
 */
chrome.send = (function() {
  var users = [
  {
    name: 'Alan Beaker',
    emailAddress: 'beaker@chromium.org',
    imageUrl: '../../app/theme/avatar_beaker.png',
    canRemove: false
  },
  {
    name: 'Alex Briefcase',
    emailAddress: 'briefcase@chromium.org',
    imageUrl: '../../app/theme/avatar_briefcase.png',
    canRemove: true
  },
  {
    name: 'Alex Circles',
    emailAddress: 'circles@chromium.org',
    imageUrl: '../../app/theme/avatar_circles.png',
    canRemove: true
  },
  {
    name: 'Guest',
    emailAddress: '',
    imageUrl: '',
    canRemove: false
  }
  ];

  /**
   * Invoke the getAppsCallback function with a snapshot of the current app
   * database.
   */
  function sendGetUsersCallback()
  {
    // We don't want to hand out our array directly because the NTP will
    // assume it owns the array and is free to modify it.  For now we make a
    // one-level deep copy of the array (since cloning the whole thing is
    // more work and unnecessary at the moment).
    getUsersCallback(users.slice(0));
  }

  /**
   * Like Array.prototype.indexOf but calls a predicate to test for match
   *
   * @param {Array} array The array to search.
   * @param {function(Object): boolean} predicate The function to invoke on
   *     each element.
   * @return {number} First index at which predicate returned true, or -1.
   */
  function indexOfPred(array, predicate) {
    for (var i = 0; i < array.length; i++) {
      if (predicate(array[i]))
        return i;
    }
    return -1;
  }

  /**
   * Get index into apps of an application object
   * Requires the specified app to be present
   *
   * @param {string} id The ID of the application to locate.
   * @return {number} The index in apps for an object with the specified ID.
   */
  function getUserIndex(name) {
    var i = indexOfPred(apps, function(e) { return e.name === name;});
    if (i == -1)
      alert('Error: got unexpected App ID');
    return i;
  }

  /**
   * Get an user object given the user name
   * Requires
   * @param {string} name The user name to search for.
   * @return {Object} The corresponding user object.
   */
  function getUser(name) {
    return users[getUserIndex(name)];
  }

  /**
   * Simlulate the login of a user
   *
   * @param {string} email_address the email address of the user logging in.
   * @param {string} password the password of the user logging in.
   */
  function login(email_address, password) {
    console.log('password', password);
    if (password == 'correct') {
      return true;
    }
    return false;
  }

  /**
   * The chrome server communication entrypoint.
   *
   * @param {string} command Name of the command to send.
   * @param {Array} args Array of command-specific arguments.
   */
  return function(command, args) {
    // Chrome API is async
    window.setTimeout(function() {
      switch (command) {
        // called to populate the list of applications
        case 'GetUsers':
          sendGetUsersCallback();
          break;

        // Called when a user is removed.
        case 'RemoveUser':
          break;

        // Called when a user attempts to login.
        case 'Login':
          login(args[0], args[1]);
          break;

        // Called when an app is moved to a different page
        case 'MoveUser':
          break;

        case 'SetGuestPosition':
          break;

        default:
          throw new Error('Unexpected chrome command: ' + command);
          break;
      }
    }, 0);
  };
})();

/*
 * On iOS we need a hack to avoid spurious click events
 * In particular, if the user delays briefly between first touching and starting
 * to drag, when the user releases a click event will be generated.
 * Note that this seems to happen regardless of whether we do preventDefault on
 * touchmove events.
 */
if (/iPhone|iPod|iPad/.test(navigator.userAgent) &&
    !(/Chrome/.test(navigator.userAgent))) {
  // We have a real iOS device (no a ChromeOS device pretending to be iOS)
  (function() {
    // True if a gesture is occuring that should cause clicks to be swallowed
    var gestureActive = false;

    // The position a touch was last started
    var lastTouchStartPosition;

    // Distance which a touch needs to move to be considered a drag
    var DRAG_DISTANCE = 3;

    document.addEventListener('touchstart', function(event) {
      lastTouchStartPosition = {
        x: event.touches[0].clientX,
        y: event.touches[0].clientY
      };
      // A touchstart ALWAYS preceeds a click (valid or not), so cancel any
      // outstanding gesture. Also, any multi-touch is a gesture that should
      // prevent clicks.
      gestureActive = event.touches.length > 1;
    }, true);

    document.addEventListener('touchmove', function(event) {
      // When we see a move, measure the distance from the last touchStart
      // If this is a multi-touch then the work here is irrelevant
      // (gestureActive is already true)
      var t = event.touches[0];
      if (Math.abs(t.clientX - lastTouchStartPosition.x) > DRAG_DISTANCE ||
          Math.abs(t.clientY - lastTouchStartPosition.y) > DRAG_DISTANCE) {
        gestureActive = true;
      }
    }, true);

    document.addEventListener('click', function(event) {
      // If we got here without gestureActive being set then it means we had
      // a touchStart without any real dragging before touchEnd - we can allow
      // the click to proceed.
      if (gestureActive) {
        event.preventDefault();
        event.stopPropagation();
      }
    }, true);
  })();
}

/*  Hack to add Element.classList to older browsers that don't yet support it.
    From https://developer.mozilla.org/en/DOM/element.classList.
*/
if (typeof Element !== 'undefined' &&
    !Element.prototype.hasOwnProperty('classList')) {
  (function() {
    var classListProp = 'classList',
        protoProp = 'prototype',
        elemCtrProto = Element[protoProp],
        objCtr = Object,
        strTrim = String[protoProp].trim || function() {
          return this.replace(/^\s+|\s+$/g, '');
        },
        arrIndexOf = Array[protoProp].indexOf || function(item) {
          for (var i = 0, len = this.length; i < len; i++) {
            if (i in this && this[i] === item) {
              return i;
            }
          }
          return -1;
        },
        // Vendors: please allow content code to instantiate DOMExceptions
        /** @constructor  */
        DOMEx = function(type, message) {
          this.name = type;
          this.code = DOMException[type];
          this.message = message;
        },
        checkTokenAndGetIndex = function(classList, token) {
          if (token === '') {
            throw new DOMEx(
                'SYNTAX_ERR',
                'An invalid or illegal string was specified'
            );
          }
          if (/\s/.test(token)) {
            throw new DOMEx(
                'INVALID_CHARACTER_ERR',
                'String contains an invalid character'
            );
          }
          return arrIndexOf.call(classList, token);
        },
        /** @constructor
         *  @extends {Array} */
        ClassList = function(elem) {
          var trimmedClasses = strTrim.call(elem.className),
              classes = trimmedClasses ? trimmedClasses.split(/\s+/) : [];

          for (var i = 0, len = classes.length; i < len; i++) {
            this.push(classes[i]);
          }
          this._updateClassName = function() {
            elem.className = this.toString();
          };
        },
        classListProto = ClassList[protoProp] = [],
        classListGetter = function() {
          return new ClassList(this);
        };

    // Most DOMException implementations don't allow calling DOMException's
    // toString() on non-DOMExceptions. Error's toString() is sufficient here.
    DOMEx[protoProp] = Error[protoProp];
    classListProto.item = function(i) {
      return this[i] || null;
    };
    classListProto.contains = function(token) {
      token += '';
      return checkTokenAndGetIndex(this, token) !== -1;
    };
    classListProto.add = function(token) {
      token += '';
      if (checkTokenAndGetIndex(this, token) === -1) {
        this.push(token);
        this._updateClassName();
      }
    };
    classListProto.remove = function(token) {
      token += '';
      var index = checkTokenAndGetIndex(this, token);
      if (index !== -1) {
        this.splice(index, 1);
        this._updateClassName();
      }
    };
    classListProto.toggle = function(token) {
      token += '';
      if (checkTokenAndGetIndex(this, token) === -1) {
        this.add(token);
      } else {
        this.remove(token);
      }
    };
    classListProto.toString = function() {
      return this.join(' ');
    };

    if (objCtr.defineProperty) {
      var classListDescriptor = {
        get: classListGetter,
        enumerable: true,
        configurable: true
      };
      objCtr.defineProperty(elemCtrProto, classListProp, classListDescriptor);
    } else if (objCtr[protoProp].__defineGetter__) {
      elemCtrProto.__defineGetter__(classListProp, classListGetter);
    }
  }());
}

/* Hack to add Function.bind to older browsers that don't yet support it. From:
   https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
*/
if (!Function.prototype.bind) {
  /**
   * @param {Object} selfObj Specifies the object which |this| should
   *     point to when the function is run. If the value is null or undefined,
   *     it will default to the global object.
   * @param {...*} var_args Additional arguments that are partially
   *     applied to the function.
   * @return {!Function} A partially-applied form of the function bind() was
   *     invoked as a method of.
   *  @suppress {duplicate}
   */
  Function.prototype.bind = function(selfObj, var_args) {
    var slice = [].slice,
        args = slice.call(arguments, 1),
        self = this,
        /** @constructor  */
        nop = function() {},
        bound = function() {
          return self.apply(this instanceof nop ? this : (selfObj || {}),
                              args.concat(slice.call(arguments)));
        };
    nop.prototype = self.prototype;
    bound.prototype = new nop();
    return bound;
  };
}