📄 1019856700-common.js
字号:
// Copied from .../google3/javascript/common.js//------------------------------------------------------------------------// This file contains common utilities and basic javascript infrastructure.//// Notes:// * Press 'D' to toggle debug mode.//// Functions://// - Assertions// DEPRECATED: Use assert.js// AssertTrue(): assert an expression. Throws an exception if false.// Fail(): Throws an exception. (Mark block of code that should be unreachable)// AssertEquals(): assert that two values are equal.// AssertNumArgs(): assert number of arguments for the function// AssertType(): assert that a value has a particular type//// - Cookies// SetCookie(): Sets a cookie.// ExpireCookie(): Expires a cookie.// GetCookie(): Gets a cookie value.//// - Dynamic HTML/DOM utilities// MaybeGetElement(): get an element by its id// GetElement(): get an element by its id// GetParentNode(): Get the parent of an element// GetAttribute(): Get attribute value of a DOM node// SetInnerHTML(): set the inner HTML of a node// GetInnerHTML(): get the inner HTML of a node// ClearInnerHTML(): clear the inner HTML of a node// SetCssStyle(): Sets a CSS property of a node.// GetStyleProperty(): Get CSS property from a style attribute string// ShowElement(): Show/hide element by setting the "display" css property.// ShowBlockElement(): Show/hide block element// SetButtonText(): Set the text of a button element.// AppendNewElement(): Create and append a html element to a parent node.// CreateDIV(): Create a DIV element and append to the document.// CreateIFRAME(): Create an IFRAME and append to the document.// HasClass(): check if element has a given class// AddClass(): add a class to an element// RemoveClass(): remove a class from an element//// - Window/Screen utiltiies// GetPageOffsetLeft(): get the X page offset of an element// GetPageOffsetTop(): get the Y page offset of an element// GetPageOffset(): get the X and Y page offsets of an element// GetPageOffsetRight() : get X page offset of the right side of an element// GetPageOffsetRight() : get Y page offset of the bottom of an element// GetScrollTop(): get the vertical scrolling pos of a window.// GetScrollLeft(): get the horizontal scrolling pos of a window// IsScrollAtEnd(): check if window scrollbar has reached its maximum offset// ScrollTo(): scroll window to a position// ScrollIntoView(): scroll window so that an element is in view.// GetWindowWidth(): get width of a window.// GetWindowHeight(): get height of a window// GetAvailScreenWidth(): get available screen width// GetAvailScreenHeight(): get available screen height// GetNiceWindowHeight(): get a nice height for a new browser window.// Open{External/Internal}Window(): open a separate window// CloseWindow(): close a window//// - DOM walking utilities// AnnotateTerms(): find terms in a node and decorate them with some tag// AnnotateText(): find terms in a text node and decorate them with some tag//// - String utilties// HtmlEscape(): html escapes a string// HtmlUnescape(): remove html-escaping.// QuoteEscape(): escape " quotes.// CollapseWhitespace(): collapse multiple whitespace into one whitespace.// Trim(): trim whitespace on ends of string// IsEmpty(): check if CollapseWhiteSpace(String) == ""// IsLetterOrDigit(): check if a character is a letter or a digit// ConvertEOLToLF(): normalize the new-lines of a string.// HtmlEscapeInsertWbrs(): HtmlEscapes and inserts <wbr>s (word break tags)// after every n non-space chars and/or after or before certain special chars//// - TextArea utilities// GetCursorPos(): finds the cursor position of a textfield// SetCursorPos(): sets the cursor position in a textfield//// - Array utilities// FindInArray(): do a linear search to find an element value.// DeleteArrayElement(): return a new array with a specific value removed.// CloneObject(): clone an object, copying its values recursively.// CloneEvent(): clone an event; cannot use CloneObject because it// suffers from infinite recursion//// - Formatting utilities// PrintArray(): used to print/generate HTML by combining static text// and dynamic strings.// ImageHtml(): create html for an img tag// FormatJSLink(): formats a link that invokes js code when clicked.// MakeId3(): formats an id that has two id numbers, eg, foo_3_7//// - Miscellaneous// IsDefined(): returns true if argument is not undefined//------------------------------------------------------------------------// browser detectionvar agent = navigator.userAgent.toLowerCase();var is_ie = (agent.indexOf('msie') != -1);//var is_ie5 = (agent.indexOf('msie 5') != -1 && document.all);var is_konqueror = (agent.indexOf('konqueror') != -1);var is_safari = (agent.indexOf('safari') != -1) || is_konqueror;var is_nav = !is_ie && !is_safari && (agent.indexOf('mozilla') != -1);var is_win = (agent.indexOf('win') != -1);delete agent;var BACKSPACE_KEYCODE = 8;var COMMA_KEYCODE = 188; // ',' keyvar DEBUG_KEYCODE = 68; // 'D' keyvar DELETE_KEYCODE = 46;var DOWN_KEYCODE = 40; // DOWN arrow keyvar ENTER_KEYCODE = 13; // ENTER keyvar ESC_KEYCODE = 27; // ESC keyvar LEFT_KEYCODE = 37; // LEFT arrow keyvar RIGHT_KEYCODE = 39; // RIGHT arrow keyvar SPACE_KEYCODE = 32; // space barvar TAB_KEYCODE = 9; // TAB keyvar UP_KEYCODE = 38; // UP arrow keyvar SHIFT_KEYCODE = 16;// This is a "constant" but has different values depending on the browservar semicolon_keycode = (is_ie ? 186 : 59);var MAX_EMAIL_ADDRESS_LENGTH = 320; // 64 + '@' + 255var MAX_SIGNATURE_LENGTH = 1000; // 1000 chars of maximum signature//------------------------------------------------------------------------// Assertions// DEPRECATED: Use assert.js//------------------------------------------------------------------------/** * DEPRECATED: Use assert.js */function raise(msg) { if (typeof Error != 'undefined') { throw new Error(msg || 'Assertion Failed'); } else { throw (msg); }}/** * DEPRECATED: Use assert.js * * Fail() is useful for marking logic paths that should * not be reached. For example, if you have a class that uses * ints for enums: * * MyClass.ENUM_FOO = 1; * MyClass.ENUM_BAR = 2; * MyClass.ENUM_BAZ = 3; * * And a switch statement elsewhere in your code that * has cases for each of these enums, then you can * "protect" your code as follows: * * switch(type) { * case MyClass.ENUM_FOO: doFooThing(); break; * case MyClass.ENUM_BAR: doBarThing(); break; * case MyClass.ENUM_BAZ: doBazThing(); break; * default: * Fail("No enum in MyClass with value: " + type); * } * * This way, if someone introduces a new value for this enum * without noticing this switch statement, then the code will * fail if the logic allows it to reach the switch with the * new value, alerting the developer that he should add a * case to the switch to handle the new value he has introduced. * * @param {string} opt_msg to display for failure * DEFAULT: "Assertion failed" */function Fail(opt_msg) { if (opt_msg === undefined) opt_msg = 'Assertion failed'; if (IsDefined(DumpError)) DumpError(opt_msg + '\n'); raise(opt_msg);}/** * DEPRECATED: Use assert.js * * Asserts that an expression is true (non-zero and non-null). * * Note that it is critical not to pass logic * with side-effects as the expression for AssertTrue * because if the assertions are removed by the * JSCompiler, then the expression will be removed * as well, in which case the side-effects will * be lost. So instead of this: * * AssertTrue( criticalComputation() ); * * Do this: * * var result = criticalComputation(); * AssertTrue(result); * * @param {anything} expression to evaluate * @param {string} opt_msg to display if the assertion fails * */function AssertTrue(expression, opt_msg) { if (!expression) { if (opt_msg === undefined) opt_msg = 'Assertion failed'; Fail(opt_msg); }}/** * DEPRECATED: Use assert.js * * Asserts that two values are the same. * * @param {anything} val1 * @param {anything} val2 * @param {string} opt_msg to display if the assertion fails */function AssertEquals(val1, val2, opt_msg) { if (val1 != val2) { if (opt_msg === undefined) { opt_msg = "AssertEquals failed: <" + val1 + "> != <" + val2 + ">"; } Fail(opt_msg); }}/** * DEPRECATED: Use assert.js * * Asserts that a value is of the provided type. * * AssertType(6, Number); * AssertType("ijk", String); * AssertType([], Array); * AssertType({}, Object); * AssertType(ICAL_Date.now(), ICAL_Date); * * @param {anything} value * @param {constructor function} type * @param {string} opt_msg to display if the assertion fails */function AssertType(value, type, opt_msg) { // for backwards compatability only if (typeof value == type) return; if (value || value == "") { try { if (type == AssertTypeMap[typeof value] || value instanceof type) return; } catch (e) { /* failure, type was an illegal argument to instanceof */ } } if (opt_msg === undefined) { if (typeof type == 'function') { var match = type.toString().match(/^\s*function\s+([^\s\{]+)/); if (match) type = match[1]; } opt_msg = "AssertType failed: <" + value + "> not typeof "+ type; } Fail(opt_msg);}var AssertTypeMap = { 'string' : String, 'number' : Number, 'boolean' : Boolean};/** * DEPRECATED: Use assert.js * * Asserts that the number of arguments to a * function is num. For example: * * function myFunc(one, two, three) [ * AssertNumArgs(3); * ... * } * * myFunc(1, 2); // assertion fails! * * Note that AssertNumArgs does not take the function * as an argument; it is simply used in the context * of the function. * * @param {int} number of arguments expected * @param {string} opt_msg to display if the assertion fails */function AssertNumArgs(num, opt_msg) { var caller = AssertNumArgs.caller; // This is not supported in safari 1.0 if (caller && caller.arguments.length != num) { if (opt_msg === undefined) { opt_msg = caller.name + ' expected ' + num + ' arguments ' + ' but received ' + caller.arguments.length; } Fail(opt_msg); }}//------------------------------------------------------------------------// Cookies//------------------------------------------------------------------------var ILLEGAL_COOKIE_CHARS_RE = /[\s;]//** * Sets a cookie. * The max_age can be -1 to set a session cookie. To expire cookies, use * ExpireCookie() instead. * * @param name The cookie name. * @param value The cookie value. * @param opt_max_age The max age in seconds (from now). Use -1 to set a * session cookie. If not provided, the default is -1 (i.e. set a session * cookie). * @param opt_path The path of the cookie, or null to not specify a path * attribute (browser will use the full request path). If not provided, the * default is '/' (i.e. path=/). * @param opt_domain The domain of the cookie, or null to not specify a domain * attribute (brower will use the full request host name). If not provided, * the default is null (i.e. let browser use full request host name). * @return Void. */function SetCookie(name, value, opt_max_age, opt_path, opt_domain) { value = '' + value; AssertTrue((typeof name == 'string' && typeof value == 'string' && !name.match(ILLEGAL_COOKIE_CHARS_RE) && !value.match(ILLEGAL_COOKIE_CHARS_RE)), 'trying to set an invalid cookie'); if (!IsDefined(opt_max_age)) opt_max_age = -1; if (!IsDefined(opt_path)) opt_path = '/'; if (!IsDefined(opt_domain)) opt_domain = null; var domain_str = (opt_domain == null) ? '' : ';domain=' + opt_domain; var path_str = (opt_path == null) ? '' : ';path=' + opt_path; var expires_str; // Case 1: Set a session cookie. if (opt_max_age < 0) { expires_str = ''; // Case 2: Expire the cookie. // Note: We don't tell people about this option in the function doc because // we prefer people to use ExpireCookie() to expire cookies. } else if (opt_max_age == 0) { // Note: Don't use Jan 1, 1970 for date because NS 4.76 will try to convert // it to local time, and if the local time is before Jan 1, 1970, then the // browser will ignore the Expires attribute altogether. var pastDate = new Date(1970, 1 /*Feb*/, 1); // Feb 1, 1970 expires_str = ';expires=' + pastDate.toUTCString(); // Case 3: Set a persistent cookie. } else { var futureDate = new Date(Now() + opt_max_age * 1000); expires_str = ';expires=' + futureDate.toUTCString(); } document.cookie = name + '=' + value + domain_str + path_str + expires_str;}var EXPIRED_COOKIE_VALUE = 'EXPIRED';/** * Expires a cookie. * * @param name The cookie name. * @param opt_path The path of the cookie, or null to expire a cookie set at * the full request path. If not provided, the default is '/' (i.e. path=/). * @param opt_domain The domain of the cookie, or null to expire a cookie set * at the full request host name. If not provided, the default is null (i.e. * cookie at full request host name). * @return Void. */function ExpireCookie(name, opt_path, opt_domain) { SetCookie(name, EXPIRED_COOKIE_VALUE, 0, opt_path, opt_domain);}/** Returns the value for the first cookie with the given name * @param name : string * @return a string or the empty string if no cookie found. */function GetCookie(name) { var nameeq = name + "="; var cookie = String(document.cookie); for (var pos = -1; (pos = cookie.indexOf(nameeq, pos + 1)) >= 0;) { var i = pos; // walk back along string skipping whitespace and looking for a ; before // the name to make sure that we don't match cookies whose name contains // the given name as a suffix. while (--i >= 0) { var ch = cookie.charAt(i); if (ch == ';') { i = -1; // indicate success break; } else if (' \t'.indexOf(ch) < 0) { break; } } if (-1 === i) { // first cookie in the string or we found a ; var end = cookie.indexOf(';', pos); if (end < 0) { end = cookie.length; } return cookie.substring(pos + nameeq.length, end); } }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -