Debian Codegraph @

closure-library/closure/goog/ui/prompt.js

raw
1 // Copyright 2006 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview DHTML prompt to replace javascript's prompt().
17 *
18 * @see ../demos/prompt.html
19 */
20
21
22 goog.provide('goog.ui.Prompt');
23
24 goog.require('goog.Timer');
25 goog.require('goog.dom');
26 goog.require('goog.dom.InputType');
27 goog.require('goog.dom.TagName');
28 goog.require('goog.events');
29 goog.require('goog.events.EventType');
30 goog.require('goog.functions');
31 goog.require('goog.html.SafeHtml');
32 goog.require('goog.ui.Component');
33 goog.require('goog.ui.Dialog');
34 goog.require('goog.userAgent');
35
36
37
38 /**
39 * Creates an object that represents a prompt (used in place of javascript's
40 * prompt). The html structure of the prompt is the same as the layout for
41 * dialog.js except for the addition of a text box which is placed inside the
42 * "Content area" and has the default class-name 'modal-dialog-userInput'
43 *
44 * @param {string} promptTitle The title of the prompt.
45 * @param {string|!goog.html.SafeHtml} promptBody The body of the prompt.
46 * String is treated as plain text and it will be HTML-escaped.
47 * @param {Function} callback The function to call when the user selects Ok or
48 * Cancel. The function should expect a single argument which represents
49 * what the user entered into the prompt. If the user presses cancel, the
50 * value of the argument will be null.
51 * @param {string=} opt_defaultValue Optional default value that should be in
52 * the text box when the prompt appears.
53 * @param {string=} opt_class Optional prefix for the classes.
54 * @param {boolean=} opt_useIframeForIE For IE, workaround windowed controls
55 * z-index issue by using a an iframe instead of a div for bg element.
56 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper; see {@link
57 * goog.ui.Component} for semantics.
58 * @constructor
59 * @extends {goog.ui.Dialog}
60 */
61 goog.ui.Prompt = function(
62 promptTitle, promptBody, callback, opt_defaultValue, opt_class,
63 opt_useIframeForIE, opt_domHelper) {
64 goog.ui.Prompt.base(
65 this, 'constructor', opt_class, opt_useIframeForIE, opt_domHelper);
66
67 /**
68 * The id of the input element.
69 * @type {string}
70 * @private
71 */
72 this.inputElementId_ = this.makeId('ie');
73
74 this.setTitle(promptTitle);
75
76 var label = goog.html.SafeHtml.create(
77 'label', {'for': this.inputElementId_},
78 goog.html.SafeHtml.htmlEscapePreservingNewlines(promptBody));
79 var br = goog.html.SafeHtml.BR;
80 this.setSafeHtmlContent(goog.html.SafeHtml.concat(label, br, br));
81
82 this.callback_ = callback;
83 this.defaultValue_ = goog.isDef(opt_defaultValue) ? opt_defaultValue : '';
84
85 /** @desc label for a dialog button. */
86 var MSG_PROMPT_OK = goog.getMsg('OK');
87 /** @desc label for a dialog button. */
88 var MSG_PROMPT_CANCEL = goog.getMsg('Cancel');
89 var buttonSet = new goog.ui.Dialog.ButtonSet(opt_domHelper);
90 buttonSet.set(goog.ui.Dialog.DefaultButtonKeys.OK, MSG_PROMPT_OK, true);
91 buttonSet.set(
92 goog.ui.Dialog.DefaultButtonKeys.CANCEL, MSG_PROMPT_CANCEL, false, true);
93 this.setButtonSet(buttonSet);
94 };
95 goog.inherits(goog.ui.Prompt, goog.ui.Dialog);
96 goog.tagUnsealableClass(goog.ui.Prompt);
97
98
99 /**
100 * Callback function which is invoked with the response to the prompt
101 * @type {Function}
102 * @private
103 */
104 goog.ui.Prompt.prototype.callback_ = goog.nullFunction;
105
106
107 /**
108 * Default value to display in prompt window
109 * @type {string}
110 * @private
111 */
112 goog.ui.Prompt.prototype.defaultValue_ = '';
113
114
115 /**
116 * Element in which user enters response (HTML <input> text box)
117 * @type {?HTMLInputElement|?HTMLTextAreaElement}
118 * @private
119 */
120 goog.ui.Prompt.prototype.userInputEl_ = null;
121
122
123 /**
124 * Tracks whether the prompt is in the process of closing to prevent multiple
125 * calls to the callback when the user presses enter.
126 * @type {boolean}
127 * @private
128 */
129 goog.ui.Prompt.prototype.isClosing_ = false;
130
131
132 /**
133 * Number of rows in the user input element.
134 * The default is 1 which means use an <input> element.
135 * @type {number}
136 * @private
137 */
138 goog.ui.Prompt.prototype.rows_ = 1;
139
140
141 /**
142 * Number of cols in the user input element.
143 * The default is 0 which means use browser default.
144 * @type {number}
145 * @private
146 */
147 goog.ui.Prompt.prototype.cols_ = 0;
148
149
150 /**
151 * The input decorator function.
152 * @type {function(Element)?}
153 * @private
154 */
155 goog.ui.Prompt.prototype.inputDecoratorFn_ = null;
156
157
158 /**
159 * A validation function that takes a string and returns true if the string is
160 * accepted, false otherwise.
161 * @type {function(string):boolean}
162 * @private
163 */
164 goog.ui.Prompt.prototype.validationFn_ = goog.functions.TRUE;
165
166
167 /**
168 * Sets the validation function that takes a string and returns true if the
169 * string is accepted, false otherwise.
170 * @param {function(string): boolean} fn The validation function to use on user
171 * input.
172 */
173 goog.ui.Prompt.prototype.setValidationFunction = function(fn) {
174 this.validationFn_ = fn;
175 };
176
177
178 /** @override */
179 goog.ui.Prompt.prototype.enterDocument = function() {
180 if (this.inputDecoratorFn_) {
181 this.inputDecoratorFn_(this.userInputEl_);
182 }
183 goog.ui.Prompt.superClass_.enterDocument.call(this);
184 this.getHandler().listen(
185 this, goog.ui.Dialog.EventType.SELECT, this.onPromptExit_);
186
187 this.getHandler().listen(
188 this.userInputEl_,
189 [goog.events.EventType.KEYUP, goog.events.EventType.CHANGE],
190 this.handleInputChanged_);
191 };
192
193
194 /**
195 * @return {?HTMLInputElement|?HTMLTextAreaElement} The user input element. May
196 * be null if the Prompt has not been rendered.
197 */
198 goog.ui.Prompt.prototype.getInputElement = function() {
199 return this.userInputEl_;
200 };
201
202
203 /**
204 * Sets an input decorator function. This function will be called in
205 * #enterDocument and will be passed the input element. This is useful for
206 * attaching handlers to the input element for specific change events,
207 * for example.
208 * @param {function(Element)} inputDecoratorFn A function to call on the input
209 * element on #enterDocument.
210 */
211 goog.ui.Prompt.prototype.setInputDecoratorFn = function(inputDecoratorFn) {
212 this.inputDecoratorFn_ = inputDecoratorFn;
213 };
214
215
216 /**
217 * Set the number of rows in the user input element.
218 * A values of 1 means use an `<input>` element. If the prompt is already
219 * rendered then you cannot change from `<input>` to `<textarea>` or vice versa.
220 * @param {number} rows Number of rows for user input element.
221 * @throws {goog.ui.Component.Error.ALREADY_RENDERED} If the component is
222 * already rendered and an attempt to change between `<input>` and
223 * `<textarea>` is made.
224 */
225 goog.ui.Prompt.prototype.setRows = function(rows) {
226 if (this.isInDocument()) {
227 if (this.userInputEl_.tagName == goog.dom.TagName.INPUT) {
228 if (rows > 1) {
229 throw new Error(goog.ui.Component.Error.ALREADY_RENDERED);
230 }
231 } else {
232 if (rows <= 1) {
233 throw new Error(goog.ui.Component.Error.ALREADY_RENDERED);
234 }
235 this.userInputEl_.rows = rows;
236 }
237 }
238 this.rows_ = rows;
239 };
240
241
242 /**
243 * @return {number} The number of rows in the user input element.
244 */
245 goog.ui.Prompt.prototype.getRows = function() {
246 return this.rows_;
247 };
248
249
250 /**
251 * Set the number of cols in the user input element.
252 * @param {number} cols Number of cols for user input element.
253 */
254 goog.ui.Prompt.prototype.setCols = function(cols) {
255 this.cols_ = cols;
256 if (this.userInputEl_) {
257 if (this.userInputEl_.tagName == goog.dom.TagName.INPUT) {
258 this.userInputEl_.size = cols;
259 } else {
260 this.userInputEl_.cols = cols;
261 }
262 }
263 };
264
265
266 /**
267 * @return {number} The number of cols in the user input element.
268 */
269 goog.ui.Prompt.prototype.getCols = function() {
270 return this.cols_;
271 };
272
273
274 /**
275 * Create the initial DOM representation for the prompt.
276 * @override
277 */
278 goog.ui.Prompt.prototype.createDom = function() {
279 goog.ui.Prompt.superClass_.createDom.call(this);
280
281 var cls = this.getClass();
282
283 // add input box to the content
284 if (this.rows_ == 1) {
285 // If rows == 1 then use an input element.
286 this.userInputEl_ = this.getDomHelper().createDom(goog.dom.TagName.INPUT, {
287 'className': goog.getCssName(cls, 'userInput'),
288 'value': this.defaultValue_
289 });
290 this.userInputEl_.type = goog.dom.InputType.TEXT;
291 if (this.cols_) {
292 this.userInputEl_.size = this.cols_;
293 }
294 } else {
295 // If rows > 1 then use a textarea.
296 this.userInputEl_ =
297 this.getDomHelper().createDom(goog.dom.TagName.TEXTAREA, {
298 'className': goog.getCssName(cls, 'userInput'),
299 'value': this.defaultValue_
300 });
301 this.userInputEl_.rows = this.rows_;
302 if (this.cols_) {
303 this.userInputEl_.cols = this.cols_;
304 }
305 }
306
307 this.userInputEl_.id = this.inputElementId_;
308 var contentEl = this.getContentElement();
309 contentEl.appendChild(
310 this.getDomHelper().createDom(
311 goog.dom.TagName.DIV, {'style': 'overflow: auto'},
312 this.userInputEl_));
313 };
314
315
316 /**
317 * Handles input change events on the input field. Disables the OK button if
318 * validation fails on the new input value.
319 * @private
320 */
321 goog.ui.Prompt.prototype.handleInputChanged_ = function() {
322 this.updateOkButtonState_();
323 };
324
325
326 /**
327 * Set OK button enabled/disabled state based on input.
328 * @private
329 */
330 goog.ui.Prompt.prototype.updateOkButtonState_ = function() {
331 var enableOkButton = this.validationFn_(this.userInputEl_.value);
332 var buttonSet = this.getButtonSet();
333 buttonSet.setButtonEnabled(
334 goog.ui.Dialog.DefaultButtonKeys.OK, enableOkButton);
335 };
336
337
338 /**
339 * Causes the prompt to appear, centered on the screen, gives focus
340 * to the text box, and selects the text
341 * @param {boolean} visible Whether the dialog should be visible.
342 * @override
343 */
344 goog.ui.Prompt.prototype.setVisible = function(visible) {
345 goog.ui.Prompt.base(this, 'setVisible', visible);
346
347 if (visible) {
348 this.isClosing_ = false;
349 this.userInputEl_.value = this.defaultValue_;
350 this.focus();
351 this.updateOkButtonState_();
352 }
353 };
354
355
356 /**
357 * Overrides setFocus to put focus on the input element.
358 * @override
359 */
360 goog.ui.Prompt.prototype.focus = function() {
361 goog.ui.Prompt.base(this, 'focus');
362
363 if (goog.userAgent.OPERA) {
364 // select() doesn't focus <input> elements in Opera.
365 this.userInputEl_.focus();
366 }
367 this.userInputEl_.select();
368 };
369
370
371 /**
372 * Sets the default value of the prompt when it is displayed.
373 * @param {string} defaultValue The default value to display.
374 */
375 goog.ui.Prompt.prototype.setDefaultValue = function(defaultValue) {
376 this.defaultValue_ = defaultValue;
377 };
378
379
380 /**
381 * Handles the closing of the prompt, invoking the callback function that was
382 * registered to handle the value returned by the prompt.
383 * @param {goog.ui.Dialog.Event} e The dialog's selection event.
384 * @private
385 */
386 goog.ui.Prompt.prototype.onPromptExit_ = function(e) {
387 /*
388 * The timeouts below are required for one edge case. If after the dialog
389 * hides, suppose validation of the input fails which displays an alert. If
390 * the user pressed the Enter key to dismiss the alert that was displayed it
391 * can trigger the event handler a second time. This timeout ensures that the
392 * alert is displayed only after the prompt is able to clean itself up.
393 */
394 if (!this.isClosing_) {
395 this.isClosing_ = true;
396 if (e.key == 'ok') {
397 goog.Timer.callOnce(
398 goog.bind(this.callback_, this, this.userInputEl_.value), 1);
399 } else {
400 goog.Timer.callOnce(goog.bind(this.callback_, this, null), 1);
401 }
402 }
403 };
404
405
406 /** @override */
407 goog.ui.Prompt.prototype.disposeInternal = function() {
408 goog.dom.removeNode(this.userInputEl_);
409
410 goog.events.unlisten(
411 this, goog.ui.Dialog.EventType.SELECT, this.onPromptExit_, true, this);
412
413 goog.ui.Prompt.superClass_.disposeInternal.call(this);
414
415 this.userInputEl_ = null;
416 };