summaryrefslogtreecommitdiff
path: root/chromium/chrome/browser/resources/print_preview/search/destination_list_item.js
blob: d925eef5bda4a2b59502d6ffc7c4f670512b7fb6 (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
// Copyright (c) 2012 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.

cr.define('print_preview', function() {
  'use strict';

  /**
   * Component that renders a destination item in a destination list.
   * @param {!cr.EventTarget} eventTarget Event target to dispatch selection
   *     events to.
   * @param {!print_preview.Destination} destination Destination data object to
   *     render.
   * @param {RegExp} query Active filter query.
   * @constructor
   * @extends {print_preview.Component}
   */
  function DestinationListItem(eventTarget, destination, query) {
    print_preview.Component.call(this);

    /**
     * Event target to dispatch selection events to.
     * @type {!cr.EventTarget}
     * @private
     */
    this.eventTarget_ = eventTarget;

    /**
     * Destination that the list item renders.
     * @type {!print_preview.Destination}
     * @private
     */
    this.destination_ = destination;

    /**
     * Active filter query text.
     * @type {RegExp}
     * @private
     */
    this.query_ = query;
  }

  /**
   * Event types dispatched by the destination list item.
   * @enum {string}
   */
  DestinationListItem.EventType = {
    // Dispatched to check the printer needs to be configured before activation.
    CONFIGURE_REQUEST: 'print_preview.DestinationListItem.CONFIGURE_REQUEST',
    // Dispatched when the list item is activated.
    SELECT: 'print_preview.DestinationListItem.SELECT',
    REGISTER_PROMO_CLICKED:
        'print_preview.DestinationListItem.REGISTER_PROMO_CLICKED'
  };

  DestinationListItem.prototype = {
    __proto__: print_preview.Component.prototype,

    /** @override */
    createDom: function() {
      this.setElementInternal(
          this.cloneTemplateInternal('destination-list-item-template'));
      this.updateUi_();
    },

    /** @override */
    enterDocument: function() {
      print_preview.Component.prototype.enterDocument.call(this);
      this.tracker.add(this.getElement(), 'click', this.onActivate_.bind(this));
      this.tracker.add(
          this.getElement(), 'keydown', this.onKeyDown_.bind(this));
      this.tracker.add(
          this.getChildElement('.register-promo-button'), 'click',
          this.onRegisterPromoClicked_.bind(this));
    },

    /** @return {!print_preview.Destination} */
    get destination() {
      return this.destination_;
    },

    /**
     * Updates the list item UI state.
     * @param {!print_preview.Destination} destination Destination data object
     *     to render.
     * @param {RegExp} query Active filter query.
     */
    update: function(destination, query) {
      this.destination_ = destination;
      this.query_ = query;
      this.updateUi_();
    },

    /**
     * Called if the printer configuration request is accepted. Show the waiting
     * message to the user as the configuration might take longer than expected.
     */
    onConfigureRequestAccepted: function() {
      // It must be a Chrome OS CUPS printer which hasn't been set up before.
      assert(
          this.destination_.origin == print_preview.DestinationOrigin.CROS &&
          !this.destination_.capabilities);
      this.updateConfiguringMessage_(true);
    },

    /**
     * Called if the printer configuration request is rejected. The request is
     * rejected if another printer is setting up in process or the current
     * printer doesn't need to be setup.
     * @param {boolean} otherPrinterSetupInProgress
     */
    onConfigureRequestRejected: function(otherPrinterSetupInProgress) {
      // If another printer setup is in progress, the printer should not be
      // activated.
      if (!otherPrinterSetupInProgress)
        this.onDestinationActivated_();
    },

    /**
     * Called when the printer configuration request is resolved successful or
     * failed.
     * @param response {!print_preview.PrinterSetupResponse}
     */
    onConfigureResolved: function(response) {
      assert(response.printerId == this.destination_.id);
      if (response.success) {
        this.updateConfiguringMessage_(false);
        this.destination_.capabilities = response.capabilities;
        this.onDestinationActivated_();
      } else {
        this.updateConfiguringMessage_(false);
        setIsVisible(this.getChildElement('.configuring-failed-text'), true);
      }
    },

    /**
     * Initializes the element with destination's info.
     * @private
     */
    updateUi_: function() {
      var iconImg = this.getChildElement('.destination-list-item-icon');
      iconImg.src = this.destination_.iconUrl;

      var nameEl = this.getChildElement('.destination-list-item-name');
      var textContent = this.destination_.displayName;
      if (this.query_) {
        nameEl.textContent = '';
        // When search query is specified, make it obvious why this particular
        // printer made it to the list. Display name is always visible, even if
        // it does not match the search query.
        this.addTextWithHighlight_(nameEl, textContent);
        // Show the first matching property.
        this.destination_.extraPropertiesToMatch.some(function(property) {
          if (property.match(this.query_)) {
            var hintSpan = document.createElement('span');
            hintSpan.className = 'search-hint';
            nameEl.appendChild(hintSpan);
            this.addTextWithHighlight_(hintSpan, property);
            // Add the same property to the element title.
            textContent += ' (' + property + ')';
            return true;
          }
        }, this);
      } else {
        // Show just the display name and nothing else to lessen visual clutter.
        nameEl.textContent = textContent;
      }
      nameEl.title = textContent;

      if (this.destination_.isExtension) {
        var extensionNameEl = this.getChildElement('.extension-name');
        var extensionName = this.destination_.extensionName;
        extensionNameEl.title = this.destination_.extensionName;
        if (this.query_) {
          extensionNameEl.textContent = '';
          this.addTextWithHighlight_(extensionNameEl, extensionName);
        } else {
          extensionNameEl.textContent = this.destination_.extensionName;
        }

        var extensionIconEl = this.getChildElement('.extension-icon');
        extensionIconEl.style.backgroundImage = '-webkit-image-set(' +
            'url(chrome://extension-icon/' + this.destination_.extensionId +
            '/24/1) 1x,' +
            'url(chrome://extension-icon/' + this.destination_.extensionId +
            '/48/1) 2x)';
        extensionIconEl.title = loadTimeData.getStringF(
            'extensionDestinationIconTooltip', this.destination_.extensionName);
        extensionIconEl.onclick = this.onExtensionIconClicked_.bind(this);
        extensionIconEl.onkeydown = /** @type {function(Event)} */ (
            this.onExtensionIconKeyDown_.bind(this));
      }

      var extensionIndicatorEl =
          this.getChildElement('.extension-controlled-indicator');
      setIsVisible(extensionIndicatorEl, this.destination_.isExtension);

      // Initialize the element which renders the destination's offline status.
      this.getElement().classList.toggle('stale', this.destination_.isOffline);
      var offlineStatusEl = this.getChildElement('.offline-status');
      offlineStatusEl.textContent = this.destination_.offlineStatusText;
      setIsVisible(offlineStatusEl, this.destination_.isOffline);

      // Initialize registration promo element for Privet unregistered printers.
      setIsVisible(
          this.getChildElement('.register-promo'),
          this.destination_.connectionStatus ==
              print_preview.DestinationConnectionStatus.UNREGISTERED);

      if (cr.isChromeOS) {
        // Reset the configuring messages for CUPS printers.
        this.updateConfiguringMessage_(false);
        setIsVisible(this.getChildElement('.configuring-failed-text'), false);
      }
    },

    /**
     * Adds text to parent element wrapping search query matches in highlighted
     * spans.
     * @param {!Element} parent Element to build the text in.
     * @param {string} text The text string to highlight segments in.
     * @private
     */
    addTextWithHighlight_: function(parent, text) {
      var sections = text.split(this.query_);
      for (var i = 0; i < sections.length; ++i) {
        if (i % 2 == 0) {
          parent.appendChild(document.createTextNode(sections[i]));
        } else {
          var span = document.createElement('span');
          span.className = 'destination-list-item-query-highlight';
          span.textContent = sections[i];
          parent.appendChild(span);
        }
      }
    },

    /**
     * Shows/Hides the configuring in progress message and starts/stops its
     * animation accordingly.
     * @param {boolean} show If the message and animation should be shown.
     * @private
     */
    updateConfiguringMessage_: function(show) {
      setIsVisible(this.getChildElement('.configuring-in-progress-text'), show);
      this.getChildElement('.configuring-text-jumping-dots')
          .classList.toggle('jumping-dots', show);
    },

    /**
     * Called when the destination item is activated. Check if the printer needs
     * to be set up first before activation.
     * @private
     */
    onActivate_: function() {
      if (!cr.isChromeOS) {
        this.onDestinationActivated_();
        return;
      }

      // Check if the printer needs configuration before using. The user is only
      // allowed to set up one printer at one time.
      var configureEvent = new CustomEvent(
          DestinationListItem.EventType.CONFIGURE_REQUEST,
          {detail: {destination: this.destination_}});
      this.eventTarget_.dispatchEvent(configureEvent);
    },

    /**
     * Called when the destination has been resolved successfully and needs to
     * be activated. Dispatches a SELECT event on the given event target.
     * @private
     */
    onDestinationActivated_: function() {
      if (this.destination_.connectionStatus !=
          print_preview.DestinationConnectionStatus.UNREGISTERED) {
        var selectEvt = new Event(DestinationListItem.EventType.SELECT);
        selectEvt.destination = this.destination_;
        this.eventTarget_.dispatchEvent(selectEvt);
      }
    },

    /**
     * Called when the key is pressed on the destination item. Dispatches a
     * SELECT event when Enter is pressed.
     * @param {!KeyboardEvent} e Keyboard event to process.
     * @private
     */
    onKeyDown_: function(e) {
      if (!hasKeyModifiers(e)) {
        if (e.keyCode == 13) {
          var activeElementTag = document.activeElement ?
              document.activeElement.tagName.toUpperCase() :
              '';
          if (activeElementTag == 'LI') {
            e.stopPropagation();
            e.preventDefault();
            this.onActivate_();
          }
        }
      }
    },

    /**
     * Called when the registration promo is clicked.
     * @private
     */
    onRegisterPromoClicked_: function() {
      var promoClickedEvent =
          new Event(DestinationListItem.EventType.REGISTER_PROMO_CLICKED);
      promoClickedEvent.destination = this.destination_;
      this.eventTarget_.dispatchEvent(promoClickedEvent);
    },

    /**
     * Handles click and 'Enter' key down events for the extension icon element.
     * It opens extensions page with the extension associated with the
     * destination highlighted.
     * @param {Event} e The event to handle.
     * @private
     */
    onExtensionIconClicked_: function(e) {
      e.stopPropagation();
      window.open('chrome://extensions?id=' + this.destination_.extensionId);
    },

    /**
     * Handles key down event for the extensin icon element. Keys different than
     * 'Enter' are ignored.
     * @param {!Event} e The event to handle.
     * @private
     */
    onExtensionIconKeyDown_: function(e) {
      if (hasKeyModifiers(e))
        return;
      if (e.keyCode != 13 /* Enter */)
        return;
      this.onExtensionIconClicked_(e);
    }
  };

  // Export
  return {DestinationListItem: DestinationListItem};
});