// ========================================================================== // Project: SproutCore - JavaScript Application Framework // Copyright: ©2006-2011 Strobe Inc. and contributors. // Portions ©2008-2011 Apple Inc. All rights reserved. // License: Licensed under MIT license (see license.js) // ========================================================================== sc_require('views/field'); sc_require('system/text_selection'); sc_require('mixins/static_layout'); sc_require('mixins/editable'); SC.AUTOCAPITALIZE_NONE = 'none'; SC.AUTOCAPITALIZE_SENTENCES = 'sentences'; SC.AUTOCAPITALIZE_WORDS = 'words'; SC.AUTOCAPITALIZE_CHARACTERS = 'characters'; /** @class A text field is an input element with type "text". This view adds support for hinted values, etc. @extends SC.FieldView @extends SC.Editable @author Charles Jolley */ SC.TextFieldView = SC.FieldView.extend(SC.Editable, /** @scope SC.TextFieldView.prototype */ { classNames: ['sc-text-field-view'], /** Walk like a duck. @type Boolean @default YES @readOnly */ isTextField: YES, // .......................................................... // PROPERTIES // /** When `applyImmediately` is turned on, every keystroke will set the value of the underlying object. Turning it off will only set the value on blur. @type String @default YES */ applyImmediately: YES, /** Flag indicating whether the editor should automatically commit if you click outside it. @type Boolean @default YES */ commitOnBlur: YES, /** @deprecated If `YES`, the field will hide its text from display. This value is deprecated. Please use `type` instead to `"password"`. @type Boolean @default NO */ isPassword: NO, /** If `YES` then allow multi-line input. This will also change the default tag type from "input" to "textarea". Otherwise, pressing return will trigger the default insertion handler. @type Boolean @default NO */ isTextArea: NO, /** Whether the text field is currently focused. @type Boolean @default NO */ focused: NO, /** The hint to display while the field is not active. @type String @default "" */ hint: '', /** The type attribute of the input. @type String @default "text" */ type: 'text', /** This property will set a tabindex="-1" on your view if set to NO. This gives us control over the native tabbing behavior. When nextValidKeyView reaches the end of the views in the pane views tree, it won't go to a textfield that can accept the default tabbing behavior in any other pane. This was a problem when you had an alert on top of a mainPane with textfields. Modal panes set this to NO on all textfields that don't belong to itself. @type Boolean @default YES */ isBrowserFocusable: YES, /** Whether the browser should automatically correct the input. When `autoCorrect` is set to `null`, the browser will use the system defaults. @type Boolean @default YES */ autoCorrect: YES, /** Specifies the autocapitalization behavior. Possible values are: - `SC.AUTOCAPITALIZE_NONE` -- Do not autocapitalize. - `SC.AUTOCAPITALIZE_SENTENCES` -- Autocapitalize the first letter of each sentence. - `SC.AUTOCAPITALIZE_WORDS` -- Autocapitalize the first letter of each word. - `SC.AUTOCAPITALIZE_CHARACTERS` -- Autocapitalize all characters. Boolean values are also supported, with YES interpreted as `SC.AUTOCAPITALIZE_NONE` and NO as `SC.AUTOCAPITALIZE_SENTENCES`. When `autoCapitalize` is set to `null`, the browser will use the system defaults. @type String SC.AUTOCAPITALIZE_NONE|SC.AUTOCAPITALIZE_SENTENCES|SC.AUTOCAPITALIZE_WORDS|SC.AUTOCAPITALIZE_CHARACTERS @default SC.CAPITALIZE_SENTENCES */ autoCapitalize: SC.CAPITALIZE_SENTENCES, /** Localizes the hint if necessary. @field @type String */ formattedHint: function () { var hint = this.get('hint'); return typeof(hint) === 'string' && this.get('localize') ? SC.String.loc(hint) : hint; }.property('hint', 'localize').cacheable(), /** Whether to show the hint while the field has focus. If `YES`, it will disappear as soon as any character is in the field. @type Boolean @default YES */ hintOnFocus: YES, /** Whether the hint should be localized or not. @type Boolean @default YES */ localize: YES, /** If `YES` then the text field is currently editing. @type Boolean @default NO */ isEditing: NO, /** If you set this property to false the tab key won't trigger its default behavior (tabbing to the next field). @type Boolean @default YES */ defaultTabbingEnabled: YES, /** Enabled context menu for textfields. @type Boolean @default YES */ isContextMenuEnabled: YES, /** @deprecated Use #applyImmediately instead. If true, every change to the text in the text field updates `value`. If false, `value` is only updated when commitEditing() is called (this is called automatically when the text field loses focus), or whenever the return key is pressed while editing the field. @type Boolean @default null */ continuouslyUpdatesValue: null, /** If no, will not allow transform or validation errors (SC.Error objects) to be passed to `value`. Upon focus lost, the text field will revert to its previous value. @type Boolean @default YES */ allowsErrorAsValue: YES, /** An optional view instance, or view class reference, which will be visible on the left side of the text field. Visually the accessory view will look to be inside the field but the text editing will not overlap the accessory view. The view will be rooted to the top-left of the text field. You should use a layout with 'left' and/or 'top' specified if you would like to adjust the offset from the top-left. One example use would be for a web site's icon, found to the left of the URL field, in many popular web browsers. Note: If you set a left accessory view, the left padding of the text field (really, the left offset of the padding element) will automatically be set to the width of the accessory view, overriding any CSS you may have defined on the "padding" element. If you would like to customize the amount of left padding used when the accessory view is visible, make the accessory view wider, with empty space on the right. @type SC.View @default null */ leftAccessoryView: null, /** An optional view instance, or view class reference, which will be visible on the right side of the text field. Visually the accessory view will look to be inside the field but the text editing will not overlap the accessory view. The view will be rooted to the top-right of the text field. You should use a layout with 'right' and/or 'top' specified if you would like to adjust the offset from the top-right. If 'left' is specified in the layout it will be cleared. One example use would be for a button to clear the contents of the text field. Note: If you set a right accessory view, the right padding of the text field (really, the right offset of the padding element) will automatically be set to the width of the accessory view, overriding any CSS you may have defined on the "padding" element. If you would like to customize the amount of right padding used when the accessory view is visible, make the accessory view wider, with empty space on the left. @type SC.View @default null */ rightAccessoryView: null, /** This property will enable disable HTML5 spell checking if available on the browser. As of today Safari 4+, Chrome 3+ and Firefox 3+ support it. @type Boolean @default YES */ spellCheckEnabled: YES, /** Maximum amount of characters this field will allow. @type Number @default 5096 */ maxLength: 5096, /** Whether to render a border or not. @type Boolean @default YES */ shouldRenderBorder: YES, // .......................................................... // SUPPORT FOR AUTOMATIC RESIZING // /** Text fields support auto resizing. @type Boolean @default YES @see SC.AutoResize#supportsAutoResize */ supportsAutoResize: YES, /** The layer to automatically resize. @type DOMElement @see SC.AutoResize#autoResizeLayer */ autoResizeLayer: function () { return this.$input()[0]; }.property('layer').cacheable(), /** The text to be used when automatically resizing the text field. @type String @see SC.AutoResize#autoResizeText */ autoResizeText: function () { return this.get('value'); }.property('value').cacheable(), /** How much padding should be used when automatically resizing. @type Number @default 20 @see SC.AutoResize#autoResizePadding */ autoResizePadding: SC.propertyFromRenderDelegate('autoResizePadding', 20), /** @private Whether to show hint or not. */ _hintON: YES, init: function () { var val = this.get('value'); this._hintON = ((!val || val && val.length === 0) && !this.get('hintOnFocus')) ? YES : NO; var continuouslyUpdatesValue = this.get('continouslyUpdatesValue'); if (continuouslyUpdatesValue !== null && continuouslyUpdatesValue !== undefined) { this.set('applyImmediately', continuouslyUpdatesValue); // @if (debug) SC.Logger.warn("SC.TextFieldView#continuouslyUpdatesValue is deprecated. Please use #applyImmediately instead."); // @endif } return sc_super(); }, /** This property indicates if the value in the text field can be changed. If set to `NO`, a `readOnly` attribute will be added to the DOM Element. Note if `isEnabledInPane` is `NO` this property will have no effect. @type Boolean @default YES */ isEditable: YES, /** The current selection of the text field, returned as an SC.TextSelection object. Note that if the selection changes a new object will be returned -- it is not the case that a previously-returned SC.TextSelection object will simply have its properties mutated. @field @type SC.TextSelection */ selection: function (key, value) { var element = this.$input()[0], range, start, end; // Are we being asked to set the value, or return the current value? if (value === undefined) { // The client is retrieving the value. if (element) { start = null; end = null; if (!element.value) { start = end = 0; } else { // In IE8, input elements don't have hasOwnProperty() defined. try { if ('selectionStart' in element) { start = element.selectionStart; } if ('selectionEnd' in element) { end = element.selectionEnd; } } // In Firefox when you ask the selectionStart or End of a hidden // input, sometimes it throws a weird error. // Adding this to just ignore it. catch (e) { return null; } // Support Internet Explorer. if (start === null || end === null) { var selection = document.selection; if (selection) { var type = selection.type; if (type && (type === 'None' || type === 'Text')) { range = selection.createRange(); if (!this.get('isTextArea')) { // Input tag support. Figure out the starting position by // moving the range's start position as far left as possible // and seeing how many characters it actually moved over. var length = range.text.length; start = Math.abs(range.moveStart('character', 0 - (element.value.length + 1))); end = start + length; } else { // Textarea support. Unfortunately, this case is a bit more // complicated than the input tag case. We need to create a // "dummy" range to help in the calculations. var dummyRange = range.duplicate(); dummyRange.moveToElementText(element); dummyRange.setEndPoint('EndToStart', range); start = dummyRange.text.length; end = start + range.text.length; } } } } } return SC.TextSelection.create({ start: start, end: end }); } else { return null; } } else { // The client is setting the value. Make sure the new value is a text // selection object. if (!value || !value.kindOf || !value.kindOf(SC.TextSelection)) { throw new Error("When setting the selection, you must specify an SC.TextSelection instance."); } if (element) { if (element.setSelectionRange) { element.setSelectionRange(value.get('start'), value.get('end')); } else { // Support Internet Explorer. range = element.createTextRange(); start = value.get('start'); range.move('character', start); range.moveEnd('character', value.get('end') - start); range.select(); } } return value; } // Implementation note: // There are certain ways users can add/remove text that we can't identify // via our key/mouse down/up handlers (such as the user choosing Paste // from a menu). So that's why we need to update our 'selection' property // whenever the field's value changes. }.property('fieldValue').cacheable(), // .......................................................... // INTERNAL SUPPORT // // Note: isEnabledInPane is required here because it is used in the renderMixin function of // SC.Control. It is not a display property directly in SC.Control, because the use of it in // SC.Control is only applied to input fields, which very few consumers of SC.Control have. // TODO: Pull the disabled attribute updating out of SC.Control. displayProperties: ['isBrowserFocusable', 'formattedHint', 'fieldValue', 'isEditing', 'isEditable', 'isEnabledInPane', 'leftAccessoryView', 'rightAccessoryView', 'isTextArea'], createChildViews: function () { sc_super(); this.accessoryViewObserver(); }, acceptsFirstResponder: function () { return this.get('isEnabledInPane'); }.property('isEnabledInPane'), accessoryViewObserver: function () { var classNames, viewProperties = ['leftAccessoryView', 'rightAccessoryView'], len = viewProperties.length, i, viewProperty, previousView, accessoryView; for (i = 0; i < len; i++) { viewProperty = viewProperties[i]; // Is there an accessory view specified? previousView = this['_' + viewProperty]; accessoryView = this.get(viewProperty); // If the view is the same, there's nothing to do. Otherwise, remove // the old one (if any) and add the new one. if (! (previousView && accessoryView && (previousView === accessoryView))) { // If there was a previous previous accessory view, remove it now. if (previousView) { // Remove the "sc-text-field-accessory-view" class name that we had // added earlier. classNames = previousView.get('classNames'); classNames = classNames.without('sc-text-field-accessory-view'); previousView.set('classNames', classNames); if (previousView.createdByParent) { this.removeChildAndDestroy(previousView); } else { this.removeChild(previousView); } // Tidy up. previousView = this['_' + viewProperty] = this['_created' + viewProperty] = null; } // If there's a new accessory view to add, do so now. if (accessoryView) { // If the user passed in a class rather than an instance, create an // instance now. accessoryView = this.createChildView(accessoryView); // Fix up right accessory views to be right positioned. if (viewProperty === 'rightAccessoryView') { var layout = accessoryView.get('layout'); accessoryView.adjust({ left: null, right: layout.right || 0 }); } // Add in the "sc-text-field-accessory-view" class name so that the // z-index gets set correctly. classNames = accessoryView.get('classNames'); var className = 'sc-text-field-accessory-view'; if (classNames.indexOf(className) < 0) { classNames = SC.clone(classNames); classNames.push(className); accessoryView.set('classNames', classNames); } // Actually add the view to our hierarchy and cache a reference. this.appendChild(accessoryView); this['_' + viewProperty] = accessoryView; } } } }.observes('leftAccessoryView', 'rightAccessoryView'), render: function (context, firstTime) { var v, accessoryViewWidths, leftAdjustment, rightAdjustment; // always have at least an empty string v = this.get('fieldValue'); if (SC.none(v)) v = ''; v = String(v); // update layer classes always context.setClass('not-empty', v.length > 0); // If we have accessory views, we'll want to update the padding on the // hint to compensate for the width of the accessory view. (It'd be nice // if we could add in the original padding, too, but there's no efficient // way to do that without first rendering the element somewhere on/off- // screen, and we don't want to take the performance hit.) accessoryViewWidths = this._getAccessoryViewWidths(); leftAdjustment = accessoryViewWidths.left; rightAdjustment = accessoryViewWidths.right; if (leftAdjustment) leftAdjustment += 'px'; if (rightAdjustment) rightAdjustment += 'px'; this._renderField(context, firstTime, v, leftAdjustment, rightAdjustment); }, /** @private If isTextArea is changed (this might happen in inlineeditor constantly) force the field render to render like the firsttime to avoid writing extra code. This can be useful also */ _forceRenderFirstTime: NO, /** @private */ _renderFieldLikeFirstTime: function () { this.set('_forceRenderFirstTime', YES); }.observes('isTextArea'), /** @private */ _renderField: function (context, firstTime, value, leftAdjustment, rightAdjustment) { // TODO: The cleanest thing might be to create a sub- rendering context // here, but currently SC.RenderContext will render sibling // contexts as parent/child. var hint = this.get('formattedHint'), hintOnFocus = this.get('hintOnFocus'), hintString = '', maxLength = this.get('maxLength'), isTextArea = this.get('isTextArea'), isEnabledInPane = this.get('isEnabledInPane'), isEditable = this.get('isEditable'), autoCorrect = this.get('autoCorrect'), autoCapitalize = this.get('autoCapitalize'), isBrowserFocusable = this.get('isBrowserFocusable'), spellCheckString = '', autocapitalizeString = '', autocorrectString = '', activeStateString = '', browserFocusableString = '', name, adjustmentStyle, type, paddingElementStyle, fieldClassNames, isOldSafari; context.setClass('text-area', isTextArea); //Adding this to differentiate between older and newer versions of safari //since the internal default field padding changed isOldSafari = SC.browser.isWebkit && SC.browser.compare(SC.browser.engineVersion, '532') < 0; context.setClass('oldWebKitFieldPadding', isOldSafari); if (firstTime || this._forceRenderFirstTime) { this._forceRenderFirstTime = NO; activeStateString = isEnabledInPane ? (isEditable ? '' : ' readonly="readonly"') : ' disabled="disabled"'; name = this.get('layerId'); spellCheckString = this.get('spellCheckEnabled') ? ' spellcheck="true"' : ' spellcheck="false"'; if (!SC.none(autoCorrect)) { autocorrectString = ' autocorrect=' + (!autoCorrect ? '"off"' : '"on"'); } if (!SC.none(autoCapitalize)) { if (SC.typeOf(autoCapitalize) === 'boolean') { autocapitalizeString = ' autocapitalize=' + (!autoCapitalize ? '"none"' : '"sentences"'); } else { autocapitalizeString = ' autocapitalize=' + autoCapitalize; } } if (!isBrowserFocusable) { browserFocusableString = ' tabindex="-1"'; } // if hint is on and we don't want it to show on focus, create one if (SC.platform.input.placeholder && !hintOnFocus) { hintString = ' placeholder="' + hint + '"'; } if (this.get('shouldRenderBorder')) context.push('
'); // Render the padding element, with any necessary positioning // adjustments to accommodate accessory views. adjustmentStyle = ''; if (leftAdjustment || rightAdjustment) { adjustmentStyle = 'style="'; if (leftAdjustment) adjustmentStyle += 'left:' + leftAdjustment + ';'; if (rightAdjustment) adjustmentStyle += 'right:' + rightAdjustment + ';'; adjustmentStyle += '"'; } context.push('