code
stringlengths
1
2.08M
language
stringclasses
1 value
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function ($) { "use strict"; /*global document, window, jQuery, console */ var KEY, Util, DropDown, ResultList, Selection, Select2, Queries; function createClass(def) { var type = function (attrs) { var self = this; if (def.attrs !== undefined) { $.each(def.attrs, function (name, body) { if (attrs[name] !== undefined) { self[name] = attrs[name]; } else { if (body.required === true) { throw "Value for required attribute: " + name + " not defined"; } if (body.init !== undefined) { self[name] = typeof (body.init) === "function" ? body.init.apply(self) : body.init; } } }); } if (def.methods !== undefined && def.methods.init !== undefined) { self.init(attrs); } }; if (def.methods !== undefined) { if (def.methods.bind !== undefined) { throw "Class cannot declare a method called 'bind'"; } $.each(def.methods, function (name, body) { type.prototype[name] = body; }); type.prototype.bind = function (func) { var self = this; return function () { func.apply(self, arguments); }; }; } return type; } KEY = { TAB: 9, ENTER: 13, ESC: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, SHIFT: 16, CTRL: 17, ALT: 18, PAGE_UP: 33, PAGE_DOWN: 34, HOME: 36, END: 35, BACKSPACE: 8, DELETE: 46 }; Util = {}; Util.debounce = function (threshold, fn) { var timeout; return function () { window.clearTimeout(timeout); timeout = window.setTimeout(fn, threshold); }; }; Util.debounceEvent = function (element, threshold, event, debouncedEvent, direct) { debouncedEvent = debouncedEvent || event + "-debounced"; direct = direct || true; var notify = Util.debounce(threshold, function (e) { element.trigger(debouncedEvent, e); }); element.on(event, function (e) { if (direct && element.get().indexOf(e.target) < 0) { return; } notify(e); }); }; (function () { var lastpos; /** * Filters mouse events so an event is fired only if the mouse moved. * Filters out mouse events that occur when mouse is stationary but * the elements under the pointer are scrolled */ Util.filterMouseEvent = function (element, event, filteredEvent, direct) { filteredEvent = filteredEvent || event + "-filtered"; direct = direct || false; element.on(event, "*", function (e) { if (direct && element.get().indexOf(e.target) < 0) { return; } if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) { $(e.target).trigger(filteredEvent, e); lastpos = {x: e.pageX, y: e.pageY}; } }); }; }()); DropDown = createClass({ attrs: { container: {required: true}, element: {required: true}, bus: {required: true} }, methods: { open: function () { if (this.isOpen()) { return; } this.container.addClass("select2-dropdown-open"); // register click-outside-closes-dropdown listener $(document).on("mousedown.dropdown", this.bind(function (e) { var inside = false, container = this.container.get(0); $(e.target).parents().each(function () { return !(inside = (this === container)); }); if (!inside) { this.close(); } })); this.element.show(); this.bus.trigger("opened"); }, close: function () { if (!this.isOpen()) { return; } this.container.removeClass("select2-dropdown-open"); $(document).off("mousedown.dropdown"); this.element.hide(); this.bus.trigger("closed"); }, isOpen: function () { return this.container.hasClass("select2-dropdown-open"); }, toggle: function () { if (this.isOpen()) { this.close(); } else { this.open(); } } } }); ResultList = createClass({ attrs: { element: {required: true}, bus: {required: true}, formatInputTooShort: {required: true}, formatNoMatches: {required: true}, formatResult: {required: true}, minimumInputLength: {required: true}, query: {required: true}, selection: {required: true} }, methods: { init: function () { var self = this; this.search = this.element.find("input"); this.results = this.element.find("ul"); this.scrollPosition = 0; this.vars = {}; this.search.on("keyup", function (e) { if (e.which >= 48 || e.which === KEY.SPACE || e.which === KEY.BACKSPACE || e.which === KEY.DELETE) { self.update(); } }); this.search.on("keydown", function (e) { switch (e.which) { case KEY.TAB: e.preventDefault(); self.select(); return; case KEY.ENTER: e.preventDefault(); e.stopPropagation(); self.select(); return; case KEY.UP: self.moveSelection(-1); e.preventDefault(); e.stopPropagation(); return; case KEY.DOWN: self.moveSelection(1); e.preventDefault(); e.stopPropagation(); return; case KEY.ESC: e.preventDefault(); e.stopPropagation(); self.cancel(); return; } }); // this.results.on("mouseleave", "li.select2-result", this.bind(this.unhighlight)); Util.filterMouseEvent(this.results, "mousemove"); this.results.on("mousemove-filtered", this.bind(function (e) { var el = $(e.target).closest("li.select2-result"); if (el.length < 1) { return; } this.setSelection(el.index()); })); this.results.on("click", this.bind(function (e) { var el = $(e.target).closest("li.select2-result"); if (el.length < 1) { return; } this.bus.trigger("selected", [el.data("select2-result")]); })); Util.debounceEvent(this.results, 100, "scroll"); this.results.on("scroll-debounced", this.bind(function (e) { this.scrollPosition = this.results.scrollTop(); var more = this.results.find("li.select2-more-results"), below; if (more.length === 0) { return; } // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible below = more.offset().top - this.results.offset().top - this.results.height(); if (below <= 0) { more.addClass("select2-active"); this.query({term: this.search.val(), vars: this.vars, callback: this.bind(this.append)}); } })); }, open: function (e) { this.search.focus(); this.results.scrollTop(this.scrollPosition); if (this.results.children().length === 0) { // first time the dropdown is opened, update the results this.update(); } }, close: function () { //this.search.val(""); //this.clear(); }, clear: function () { this.results.empty(); }, showInputTooShort: function () { this.show("<li class='select2-no-results'>" + this.formatInputTooShort(this.search.val(), this.minimumInputLength) + "</li>"); }, showNoMatches: function () { this.show("<li class='select2-no-results'>" + this.formatNoMatches(this.search.val()) + "</li>"); }, show: function (html) { this.results.html(html); this.results.scrollTop(0); this.search.removeClass("select2-active"); }, update: function () { var html = ""; if (this.search.val().length < this.minimumInputLength) { this.showInputTooShort(); return; } this.search.addClass("select2-active"); this.vars = {}; this.query({term: this.search.val(), vars: this.vars, callback: this.bind(this.process)}); }, process: function (data) { if (data.results.length === 0) { this.showNoMatches(); return; } var html = this.stringizeResults(data.results), selectedId = this.selection.val(), selectedIndex = 0; if (data.more === true) { html += "<li class='select2-more-results'>Loading more results...</li>"; } this.vars = data.vars || {}; this.show(html); this.findChoices().each(function (i) { if (selectedId === data.results[i].id) { selectedIndex = i; } $(this).data("select2-result", data.results[i]); }); this.setSelection(selectedIndex); }, append: function (data) { var more = this.results.find("li.select2-more-results"), html, offset; this.vars = data.vars || {}; if (data.results.length === 0) { more.remove(); return; } html = this.stringizeResults(data.results); offset = this.results.find("li.select2-result").length; more.before(html); this.results.find("li.select2-result").each(function (i) { if (i >= offset) { $(this).data("select2-result", data.results[i - offset]); } }); if (data.more !== true) { more.remove(); } else { more.removeClass("select2-active"); } }, stringizeResults: function (results, html) { var i, l, classes; html = html || ""; for (i = 0, l = results.length; i < l; i += 1) { html += "<li class='select2-result'>"; html += this.formatResult(results[i]); html += "</li>"; } return html; }, findChoices: function () { return this.results.children("li.select2-result"); }, removeSelection: function () { this.findChoices().each(function () { $(this).removeClass("select2-highlighted"); }); }, setSelection: function (index) { this.removeSelection(); var children = this.findChoices(), child = $(children[index]), hb, rb, y, more; child.addClass("select2-highlighted"); this.search.focus(); hb = child.offset().top + child.outerHeight(); // if this is the last child lets also make sure select2-more-results is visible if (index === children.length - 1) { more = this.results.find("li.select2-more-results"); if (more.length > 0) { hb = more.offset().top + more.outerHeight(); } } rb = this.results.offset().top + this.results.outerHeight(); if (hb > rb) { this.results.scrollTop(this.results.scrollTop() + (hb - rb)); } y = child.offset().top - this.results.offset().top; // make sure the top of the element is visible if (y < 0) { this.results.scrollTop(this.results.scrollTop() + y); // y is negative } }, getSelectionIndex: function () { var children = this.findChoices(), i = 0, l = children.length; for (; i < l; i += 1) { if ($(children[i]).hasClass("select2-highlighted")) { return i; } } return -1; }, moveSelection: function (delta) { var current = this.getSelectionIndex(), children = this.findChoices(), next = current + delta; if (current >= 0 && next >= 0 && next < children.length) { this.setSelection(next); } }, select: function () { var selected = this.results.find("li.select2-highlighted"); if (selected.length > 0) { this.bus.trigger("selected", [selected.data("select2-result")]); } }, cancel: function () { this.bus.trigger("cancelled"); }, val: function (data) { var choices = this.findChoices(), index; choices.each(function (i) { if ($(this).data("select2-result").id === data) { index = i; return false; } }); if (index === undefined && data.id !== undefined) { choices.each(function (i) { if ($(this).data("select2-result").id === data.id) { index = i; return false; } }); } if (index !== undefined) { this.setSelection(index); this.select(); return; } this.bus.trigger("selected", data); } } }); Selection = createClass({ attrs: { bus: {required: true}, element: {required: true}, display: {init: function () { return this.element.find("span"); }}, hidden: {required: true}, formatSelection: {required: true}, placeholder: {}, dropdown: {required: true} }, methods: { init: function () { if (this.placeholder) { this.select(this.placeholder); } this.element.click(this.dropdown.bind(this.dropdown.toggle)); var self = this; this.element.on("keydown", function (e) { switch (e.which) { case KEY.TAB: case KEY.SHIFT: case KEY.CTRL: case KEY.ALT: case KEY.LEFT: case KEY.RIGHT: return; } self.dropdown.open(); }); }, select: function (data) { this.display.html(this.formatSelection(data)); this.hidden.val(data.id); }, focus: function () { this.element.focus(); }, val: function () { return this.hidden.val(); } } }); Queries = {}; Queries.select = function (select2, element) { var options = []; element.find("option").each(function () { var e = $(this); options.push({id: e.attr("value"), text: e.text()}); }); return function (query) { var data = {results: [], more: false}, text = query.term.toUpperCase(); $.each(options, function (i) { if (this.text.toUpperCase().indexOf(text) >= 0) { data.results.push(this); } }); query.callback(data); }; }; Queries.ajax = function (select2, el) { var timeout, // current scheduled but not yet executed request requestSequence = 0, // sequence used to drop out-of-order responses quietMillis = select2.ajax.quietMillis || 100; return function (query) { window.clearTimeout(timeout); timeout = window.setTimeout(function () { requestSequence += 1; // increment the sequence var requestNumber = requestSequence, // this request's sequence number options = select2.ajax, // ajax parameters data = options.data; // ajax data function data = data.call(this, query.term, query.vars); $.ajax({ url: options.url, dataType: options.dataType, data: data }).success( function (data) { if (requestNumber < requestSequence) { return; } query.callback(options.results(data, query.vars)); } ); }, quietMillis); }; }; Select2 = createClass({ attrs: { el: {required: true}, formatResult: {init: function () { return function (data) { return data.text; }; }}, formatSelection: {init: function () { return function (data) { return data.text; }; }}, formatNoMatches: {init: function () { return function () { return "No matches found"; }; }}, formatInputTooShort: {init: function () { return function (input, min) { return "Please enter " + (min - input.length) + " more characters to start search"; }; }}, minimumInputLength: {init: 0}, placeholder: {init: undefined}, ajax: {init: undefined}, query: {init: undefined} }, methods: { init: function () { var self = this, width, dropdown, results, selected, select; this.el = $(this.el); width = this.el.outerWidth(); this.container = $("<div></div>", { "class": "select2-container", "id": "id"+this.el.attr("name"), style: "width: " + width + "px" }); this.container.html( " <a href='javascript:void(0)' class='select2-choice'>" + " <span></span>" + " <div><b></b></div>" + "</a>" + "<div class='select2-drop' id='select2-drop"+this.el.attr("name")+"' style='display:none;'>" + " <div class='select2-search'>" + " <input type='text' autocomplete='off'/>" + " </div>" + " <ul class='select2-results'>" + " </ul>" + "</div>" + "<input type='hidden'/>" ); this.el.data("select2", this); this.el.hide(); this.el.after(self.container); if (this.el.attr("class") !== undefined) { this.container.addClass(this.el.attr("class")); } this.container.data("select2", this); this.container.find("input[type=hidden]").attr("name", this.el.attr("name")); this.container.find("input[type=hidden]").attr("id", this.el.attr("name")+'data'); if (this.query === undefined && this.el.get(0).tagName.toUpperCase() === "SELECT") { this.query = "select"; select = true; } if (Queries[this.query] !== undefined) { this.query = Queries[this.query](this, this.el); } (function () { var dropdown, searchContainer, search, width; function getSideBorderPadding(e) { return e.outerWidth() - e.width(); } // position and size dropdown dropdown = self.container.find("div.select2-drop"); width = self.container.outerWidth() - getSideBorderPadding(dropdown); dropdown.css({top: self.container.height(), width: width}); // size search field searchContainer = self.container.find(".select2-search"); search = searchContainer.find("input"); width = dropdown.width(); width -= getSideBorderPadding(searchContainer); width -= getSideBorderPadding(search); search.css({width: width}); }()); dropdown = new DropDown({ element: this.container.find("div.select2-drop"), container: this.container, bus: this.el }); this.selection = new Selection({ bus: this.el, element: this.container.find(".select2-choice"), hidden: this.container.find("input[type=hidden]"), formatSelection: this.formatSelection, placeholder: this.placeholder, dropdown: dropdown }); this.results = new ResultList({ element: this.container.find("div.select2-drop"), bus: this.el, formatInputTooShort: this.formatInputTooShort, formatNoMatches: this.formatNoMatches, formatResult: this.formatResult, minimumInputLength: this.minimumInputLength, query: this.query, selection: this.selection }); this.el.on("selected", function (e, result) { dropdown.close(); self.selection.select(result); }); this.el.on("cancelled", function () { dropdown.close(); }); this.el.on("opened", this.bind(function () { this.results.open(); })); this.el.on("closed", this.bind(function () { this.container.removeClass("select2-dropdown-open"); this.results.close(); this.selection.focus(); })); // if attached to a select do some default initialization if (select) { this.results.update(); // build the results selected = this.el.find("option[selected]"); if (selected.length < 1 && this.placeholder === undefined) { selected = $(this.el.find("option")[0]); } if (selected.length > 0) { this.val({id: selected.attr("value"), text: selected.text()}); } } }, val: function () { var data; if (arguments.length === 0) { return this.selection.val(); } else { data = arguments[0]; this.results.val(data); } } } }); $.fn.select2 = function () { var args = Array.prototype.slice.call(arguments, 0), value, tmp; this.each(function () { if (args.length === 0) { tmp = new Select2({el: this}); } else if (typeof (args[0]) === "object") { args[0].el = this; tmp = new Select2(args[0]); } else if (typeof (args[0]) === "string") { var select2 = $(this).data("select2"); value = select2[args[0]].apply(select2, args.slice(1)); return false; } else { throw "Invalid arguments to select2 plugin: " + args; } }); return (value === undefined) ? this : value; }; }(jQuery));
JavaScript
function showrecentpostswiththumbs(json) { document.write('<ul class="recent_posts_with_thumbs">'); for (var i = 0; i < numposts; i++) { var entry = json.feed.entry[i]; var posttitle = entry.title.$t; var posturl;if (i == json.feed.entry.length) break; for (var k = 0; k < entry.link.length;k++){ if(entry.link[k].rel=='replies'&&entry.link[k].type=='text/html'){ var commenttext=entry.link[k].title; var commenturl=entry.link[k].href; } if (entry.link[k].rel == 'alternate') { posturl = entry.link[k].href;break; } } if("content"in entry){ var postcontent=entry.content.$t; } var vidid = postcontent.substring(postcontent.indexOf("http://www.youtube.com/watch?v=")+31,postcontent.indexOf("endofvid")); try {thumburl='http://i2.ytimg.com/vi/'+vidid+'/default.jpg';}catch (error){ thumburl='http://1.bp.blogspot.com/_u4gySN2ZgqE/SmWGbEU9sgI/AAAAAAAAAhc/1C_WxeHhfoA/s800/noimagethumb.png'; } var postdate = entry.published.$t; var cdyear = postdate.substring(0,4); var cdmonth = postdate.substring(5,7); var cdday = postdate.substring(8,10); var monthnames = new Array(); monthnames[1] = "Jan";monthnames[2] = "Feb";monthnames[3] = "Mar";monthnames[4] = "Apr";monthnames[5] = "May";monthnames[6] = "Jun";monthnames[7] = "Jul";monthnames[8] = "Aug";monthnames[9] = "Sep";monthnames[10] = "Oct";monthnames[11] = "Nov";monthnames[12] = "Dec"; document.write('<li class="clearfix">'); if(showpostthumbnails==true) document.write('<a href="'+ posturl + '"><img class="recent_thumb" src="'+thumburl+'"/></a>'); document.write('<div class="recent_video_title"><a href="'+posturl+'" target ="_top">'+posttitle+'</a></div><br>'); var textinside = postcontent.substring(postcontent.indexOf("[starttext]")+11,postcontent.indexOf("[endtext]")); var re = /<\S[^>]*>/g; postcontent = textinside.replace(re, ""); if (showpostsummary == true) { if (postcontent.length < numchars) { document.write('<div class="recent_video_desc">'); document.write(postcontent); document.write('</div>');} else { document.write('<div class="recent_video_desc">'); postcontent = postcontent.substring(0, numchars); var quoteEnd = postcontent.lastIndexOf(" "); postcontent = postcontent.substring(0,quoteEnd); document.write(postcontent + '...'); document.write('</div>');} } var towrite='';var flag=0; document.write('<br><div class="recent_video_footer">'); if(showpostdate==true) {towrite=towrite+monthnames[parseInt(cdmonth,10)]+' '+cdday+' , '+cdyear;flag=1;} if(showcommentnum==true) { if (flag==1) {towrite=towrite+' | ';} if(commenttext=='1 Comments') commenttext='1 Comment'; if(commenttext=='0 Comments') commenttext='No Comments'; commenttext = '<a href="'+commenturl+'" target ="_top">'+commenttext+'</a>'; towrite=towrite+commenttext; flag=1; ; } document.write(towrite); document.write('</div></li>'); if(displayseparator==true) if (i!=(numposts-1)) document.write('<hr size=0.5>'); }document.write('</ul>'); }
JavaScript
document.write('76');
JavaScript
document.write("<b>84 <a href=''></a></b>")
JavaScript
document.write('76');
JavaScript
document.write("<b>84 <a href=''></a></b>")
JavaScript
/* PIE: CSS3 rendering for IE Version 1.0.0 http://css3pie.com Dual-licensed for use under the Apache License Version 2.0 or the General Public License (GPL) Version 2. */ (function(){ var doc = document;var PIE = window['PIE']; if( !PIE ) { PIE = window['PIE'] = { CSS_PREFIX: '-pie-', STYLE_PREFIX: 'Pie', CLASS_PREFIX: 'pie_', tableCellTags: { 'TD': 1, 'TH': 1 }, /** * Lookup table of elements which cannot take custom children. */ childlessElements: { 'TABLE':1, 'THEAD':1, 'TBODY':1, 'TFOOT':1, 'TR':1, 'INPUT':1, 'TEXTAREA':1, 'SELECT':1, 'OPTION':1, 'IMG':1, 'HR':1 }, /** * Elements that can receive user focus */ focusableElements: { 'A':1, 'INPUT':1, 'TEXTAREA':1, 'SELECT':1, 'BUTTON':1 }, /** * Values of the type attribute for input elements displayed as buttons */ inputButtonTypes: { 'submit':1, 'button':1, 'reset':1 }, emptyFn: function() {} }; // Force the background cache to be used. No reason it shouldn't be. try { doc.execCommand( 'BackgroundImageCache', false, true ); } catch(e) {} (function() { /* * IE version detection approach by James Padolsey, with modifications -- from * http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/ */ var ieVersion = 4, div = doc.createElement('div'), all = div.getElementsByTagName('i'), shape; while ( div.innerHTML = '<!--[if gt IE ' + (++ieVersion) + ']><i></i><![endif]-->', all[0] ) {} PIE.ieVersion = ieVersion; // Detect IE6 if( ieVersion === 6 ) { // IE6 can't access properties with leading dash, but can without it. PIE.CSS_PREFIX = PIE.CSS_PREFIX.replace( /^-/, '' ); } PIE.ieDocMode = doc.documentMode || PIE.ieVersion; // Detect VML support (a small number of IE installs don't have a working VML engine) div.innerHTML = '<v:shape adj="1"/>'; shape = div.firstChild; shape.style['behavior'] = 'url(#default#VML)'; PIE.supportsVML = (typeof shape['adj'] === "object"); }()); /** * Utility functions */ (function() { var vmlCreatorDoc, idNum = 0, imageSizes = {}; PIE.Util = { /** * To create a VML element, it must be created by a Document which has the VML * namespace set. Unfortunately, if you try to add the namespace programatically * into the main document, you will get an "Unspecified error" when trying to * access document.namespaces before the document is finished loading. To get * around this, we create a DocumentFragment, which in IE land is apparently a * full-fledged Document. It allows adding namespaces immediately, so we add the * namespace there and then have it create the VML element. * @param {string} tag The tag name for the VML element * @return {Element} The new VML element */ createVmlElement: function( tag ) { var vmlPrefix = 'css3vml'; if( !vmlCreatorDoc ) { vmlCreatorDoc = doc.createDocumentFragment(); vmlCreatorDoc.namespaces.add( vmlPrefix, 'urn:schemas-microsoft-com:vml' ); } return vmlCreatorDoc.createElement( vmlPrefix + ':' + tag ); }, /** * Generate and return a unique ID for a given object. The generated ID is stored * as a property of the object for future reuse. * @param {Object} obj */ getUID: function( obj ) { return obj && obj[ '_pieId' ] || ( obj[ '_pieId' ] = '_' + ++idNum ); }, /** * Simple utility for merging objects * @param {Object} obj1 The main object into which all others will be merged * @param {...Object} var_args Other objects which will be merged into the first, in order */ merge: function( obj1 ) { var i, len, p, objN, args = arguments; for( i = 1, len = args.length; i < len; i++ ) { objN = args[i]; for( p in objN ) { if( objN.hasOwnProperty( p ) ) { obj1[ p ] = objN[ p ]; } } } return obj1; }, /** * Execute a callback function, passing it the dimensions of a given image once * they are known. * @param {string} src The source URL of the image * @param {function({w:number, h:number})} func The callback function to be called once the image dimensions are known * @param {Object} ctx A context object which will be used as the 'this' value within the executed callback function */ withImageSize: function( src, func, ctx ) { var size = imageSizes[ src ], img, queue; if( size ) { // If we have a queue, add to it if( Object.prototype.toString.call( size ) === '[object Array]' ) { size.push( [ func, ctx ] ); } // Already have the size cached, call func right away else { func.call( ctx, size ); } } else { queue = imageSizes[ src ] = [ [ func, ctx ] ]; //create queue img = new Image(); img.onload = function() { size = imageSizes[ src ] = { w: img.width, h: img.height }; for( var i = 0, len = queue.length; i < len; i++ ) { queue[ i ][ 0 ].call( queue[ i ][ 1 ], size ); } img.onload = null; }; img.src = src; } } }; })();/** * Utility functions for handling gradients */ PIE.GradientUtil = { getGradientMetrics: function( el, width, height, gradientInfo ) { var angle = gradientInfo.angle, startPos = gradientInfo.gradientStart, startX, startY, endX, endY, startCornerX, startCornerY, endCornerX, endCornerY, deltaX, deltaY, p, UNDEF; // Find the "start" and "end" corners; these are the corners furthest along the gradient line. // This is used below to find the start/end positions of the CSS3 gradient-line, and also in finding // the total length of the VML rendered gradient-line corner to corner. function findCorners() { startCornerX = ( angle >= 90 && angle < 270 ) ? width : 0; startCornerY = angle < 180 ? height : 0; endCornerX = width - startCornerX; endCornerY = height - startCornerY; } // Normalize the angle to a value between [0, 360) function normalizeAngle() { while( angle < 0 ) { angle += 360; } angle = angle % 360; } // Find the start and end points of the gradient if( startPos ) { startPos = startPos.coords( el, width, height ); startX = startPos.x; startY = startPos.y; } if( angle ) { angle = angle.degrees(); normalizeAngle(); findCorners(); // If no start position was specified, then choose a corner as the starting point. if( !startPos ) { startX = startCornerX; startY = startCornerY; } // Find the end position by extending a perpendicular line from the gradient-line which // intersects the corner opposite from the starting corner. p = PIE.GradientUtil.perpendicularIntersect( startX, startY, angle, endCornerX, endCornerY ); endX = p[0]; endY = p[1]; } else if( startPos ) { // Start position but no angle specified: find the end point by rotating 180deg around the center endX = width - startX; endY = height - startY; } else { // Neither position nor angle specified; create vertical gradient from top to bottom startX = startY = endX = 0; endY = height; } deltaX = endX - startX; deltaY = endY - startY; if( angle === UNDEF ) { // Get the angle based on the change in x/y from start to end point. Checks first for horizontal // or vertical angles so they get exact whole numbers rather than what atan2 gives. angle = ( !deltaX ? ( deltaY < 0 ? 90 : 270 ) : ( !deltaY ? ( deltaX < 0 ? 180 : 0 ) : -Math.atan2( deltaY, deltaX ) / Math.PI * 180 ) ); normalizeAngle(); findCorners(); } return { angle: angle, startX: startX, startY: startY, endX: endX, endY: endY, startCornerX: startCornerX, startCornerY: startCornerY, endCornerX: endCornerX, endCornerY: endCornerY, deltaX: deltaX, deltaY: deltaY, lineLength: PIE.GradientUtil.distance( startX, startY, endX, endY ) } }, /** * Find the point along a given line (defined by a starting point and an angle), at which * that line is intersected by a perpendicular line extending through another point. * @param x1 - x coord of the starting point * @param y1 - y coord of the starting point * @param angle - angle of the line extending from the starting point (in degrees) * @param x2 - x coord of point along the perpendicular line * @param y2 - y coord of point along the perpendicular line * @return [ x, y ] */ perpendicularIntersect: function( x1, y1, angle, x2, y2 ) { // Handle straight vertical and horizontal angles, for performance and to avoid // divide-by-zero errors. if( angle === 0 || angle === 180 ) { return [ x2, y1 ]; } else if( angle === 90 || angle === 270 ) { return [ x1, y2 ]; } else { // General approach: determine the Ax+By=C formula for each line (the slope of the second // line is the negative inverse of the first) and then solve for where both formulas have // the same x/y values. var a1 = Math.tan( -angle * Math.PI / 180 ), c1 = a1 * x1 - y1, a2 = -1 / a1, c2 = a2 * x2 - y2, d = a2 - a1, endX = ( c2 - c1 ) / d, endY = ( a1 * c2 - a2 * c1 ) / d; return [ endX, endY ]; } }, /** * Find the distance between two points * @param {Number} p1x * @param {Number} p1y * @param {Number} p2x * @param {Number} p2y * @return {Number} the distance */ distance: function( p1x, p1y, p2x, p2y ) { var dx = p2x - p1x, dy = p2y - p1y; return Math.abs( dx === 0 ? dy : dy === 0 ? dx : Math.sqrt( dx * dx + dy * dy ) ); } };/** * */ PIE.Observable = function() { /** * List of registered observer functions */ this.observers = []; /** * Hash of function ids to their position in the observers list, for fast lookup */ this.indexes = {}; }; PIE.Observable.prototype = { observe: function( fn ) { var id = PIE.Util.getUID( fn ), indexes = this.indexes, observers = this.observers; if( !( id in indexes ) ) { indexes[ id ] = observers.length; observers.push( fn ); } }, unobserve: function( fn ) { var id = PIE.Util.getUID( fn ), indexes = this.indexes; if( id && id in indexes ) { delete this.observers[ indexes[ id ] ]; delete indexes[ id ]; } }, fire: function() { var o = this.observers, i = o.length; while( i-- ) { o[ i ] && o[ i ](); } } };/* * Simple heartbeat timer - this is a brute-force workaround for syncing issues caused by IE not * always firing the onmove and onresize events when elements are moved or resized. We check a few * times every second to make sure the elements have the correct position and size. See Element.js * which adds heartbeat listeners based on the custom -pie-poll flag, which defaults to true in IE8-9 * and false elsewhere. */ PIE.Heartbeat = new PIE.Observable(); PIE.Heartbeat.run = function() { var me = this, interval; if( !me.running ) { interval = doc.documentElement.currentStyle.getAttribute( PIE.CSS_PREFIX + 'poll-interval' ) || 250; (function beat() { me.fire(); setTimeout(beat, interval); })(); me.running = 1; } }; /** * Create an observable listener for the onunload event */ (function() { PIE.OnUnload = new PIE.Observable(); function handleUnload() { PIE.OnUnload.fire(); window.detachEvent( 'onunload', handleUnload ); window[ 'PIE' ] = null; } window.attachEvent( 'onunload', handleUnload ); /** * Attach an event which automatically gets detached onunload */ PIE.OnUnload.attachManagedEvent = function( target, name, handler ) { target.attachEvent( name, handler ); this.observe( function() { target.detachEvent( name, handler ); } ); }; })()/** * Create a single observable listener for window resize events. */ PIE.OnResize = new PIE.Observable(); PIE.OnUnload.attachManagedEvent( window, 'onresize', function() { PIE.OnResize.fire(); } ); /** * Create a single observable listener for scroll events. Used for lazy loading based * on the viewport, and for fixed position backgrounds. */ (function() { PIE.OnScroll = new PIE.Observable(); function scrolled() { PIE.OnScroll.fire(); } PIE.OnUnload.attachManagedEvent( window, 'onscroll', scrolled ); PIE.OnResize.observe( scrolled ); })(); /** * Listen for printing events, destroy all active PIE instances when printing, and * restore them afterward. */ (function() { var elements; function beforePrint() { elements = PIE.Element.destroyAll(); } function afterPrint() { if( elements ) { for( var i = 0, len = elements.length; i < len; i++ ) { PIE[ 'attach' ]( elements[i] ); } elements = 0; } } if( PIE.ieDocMode < 9 ) { PIE.OnUnload.attachManagedEvent( window, 'onbeforeprint', beforePrint ); PIE.OnUnload.attachManagedEvent( window, 'onafterprint', afterPrint ); } })();/** * Create a single observable listener for document mouseup events. */ PIE.OnMouseup = new PIE.Observable(); PIE.OnUnload.attachManagedEvent( doc, 'onmouseup', function() { PIE.OnMouseup.fire(); } ); /** * Wrapper for length and percentage style values. The value is immutable. A singleton instance per unique * value is returned from PIE.getLength() - always use that instead of instantiating directly. * @constructor * @param {string} val The CSS string representing the length. It is assumed that this will already have * been validated as a valid length or percentage syntax. */ PIE.Length = (function() { var lengthCalcEl = doc.createElement( 'length-calc' ), parent = doc.body || doc.documentElement, s = lengthCalcEl.style, conversions = {}, units = [ 'mm', 'cm', 'in', 'pt', 'pc' ], i = units.length, instances = {}; s.position = 'absolute'; s.top = s.left = '-9999px'; parent.appendChild( lengthCalcEl ); while( i-- ) { s.width = '100' + units[i]; conversions[ units[i] ] = lengthCalcEl.offsetWidth / 100; } parent.removeChild( lengthCalcEl ); // All calcs from here on will use 1em s.width = '1em'; function Length( val ) { this.val = val; } Length.prototype = { /** * Regular expression for matching the length unit * @private */ unitRE: /(px|em|ex|mm|cm|in|pt|pc|%)$/, /** * Get the numeric value of the length * @return {number} The value */ getNumber: function() { var num = this.num, UNDEF; if( num === UNDEF ) { num = this.num = parseFloat( this.val ); } return num; }, /** * Get the unit of the length * @return {string} The unit */ getUnit: function() { var unit = this.unit, m; if( !unit ) { m = this.val.match( this.unitRE ); unit = this.unit = ( m && m[0] ) || 'px'; } return unit; }, /** * Determine whether this is a percentage length value * @return {boolean} */ isPercentage: function() { return this.getUnit() === '%'; }, /** * Resolve this length into a number of pixels. * @param {Element} el - the context element, used to resolve font-relative values * @param {(function():number|number)=} pct100 - the number of pixels that equal a 100% percentage. This can be either a number or a * function which will be called to return the number. */ pixels: function( el, pct100 ) { var num = this.getNumber(), unit = this.getUnit(); switch( unit ) { case "px": return num; case "%": return num * ( typeof pct100 === 'function' ? pct100() : pct100 ) / 100; case "em": return num * this.getEmPixels( el ); case "ex": return num * this.getEmPixels( el ) / 2; default: return num * conversions[ unit ]; } }, /** * The em and ex units are relative to the font-size of the current element, * however if the font-size is set using non-pixel units then we get that value * rather than a pixel conversion. To get around this, we keep a floating element * with width:1em which we insert into the target element and then read its offsetWidth. * For elements that won't accept a child we insert into the parent node and perform * additional calculation. If the font-size *is* specified in pixels, then we use that * directly to avoid the expensive DOM manipulation. * @param {Element} el * @return {number} */ getEmPixels: function( el ) { var fs = el.currentStyle.fontSize, px, parent, me; if( fs.indexOf( 'px' ) > 0 ) { return parseFloat( fs ); } else if( el.tagName in PIE.childlessElements ) { me = this; parent = el.parentNode; return PIE.getLength( fs ).pixels( parent, function() { return me.getEmPixels( parent ); } ); } else { el.appendChild( lengthCalcEl ); px = lengthCalcEl.offsetWidth; if( lengthCalcEl.parentNode === el ) { //not sure how this could be false but it sometimes is el.removeChild( lengthCalcEl ); } return px; } } }; /** * Retrieve a PIE.Length instance for the given value. A shared singleton instance is returned for each unique value. * @param {string} val The CSS string representing the length. It is assumed that this will already have * been validated as a valid length or percentage syntax. */ PIE.getLength = function( val ) { return instances[ val ] || ( instances[ val ] = new Length( val ) ); }; return Length; })(); /** * Wrapper for a CSS3 bg-position value. Takes up to 2 position keywords and 2 lengths/percentages. * @constructor * @param {Array.<PIE.Tokenizer.Token>} tokens The tokens making up the background position value. */ PIE.BgPosition = (function() { var length_fifty = PIE.getLength( '50%' ), vert_idents = { 'top': 1, 'center': 1, 'bottom': 1 }, horiz_idents = { 'left': 1, 'center': 1, 'right': 1 }; function BgPosition( tokens ) { this.tokens = tokens; } BgPosition.prototype = { /** * Normalize the values into the form: * [ xOffsetSide, xOffsetLength, yOffsetSide, yOffsetLength ] * where: xOffsetSide is either 'left' or 'right', * yOffsetSide is either 'top' or 'bottom', * and x/yOffsetLength are both PIE.Length objects. * @return {Array} */ getValues: function() { if( !this._values ) { var tokens = this.tokens, len = tokens.length, Tokenizer = PIE.Tokenizer, identType = Tokenizer.Type, length_zero = PIE.getLength( '0' ), type_ident = identType.IDENT, type_length = identType.LENGTH, type_percent = identType.PERCENT, type, value, vals = [ 'left', length_zero, 'top', length_zero ]; // If only one value, the second is assumed to be 'center' if( len === 1 ) { tokens.push( new Tokenizer.Token( type_ident, 'center' ) ); len++; } // Two values - CSS2 if( len === 2 ) { // If both idents, they can appear in either order, so switch them if needed if( type_ident & ( tokens[0].tokenType | tokens[1].tokenType ) && tokens[0].tokenValue in vert_idents && tokens[1].tokenValue in horiz_idents ) { tokens.push( tokens.shift() ); } if( tokens[0].tokenType & type_ident ) { if( tokens[0].tokenValue === 'center' ) { vals[1] = length_fifty; } else { vals[0] = tokens[0].tokenValue; } } else if( tokens[0].isLengthOrPercent() ) { vals[1] = PIE.getLength( tokens[0].tokenValue ); } if( tokens[1].tokenType & type_ident ) { if( tokens[1].tokenValue === 'center' ) { vals[3] = length_fifty; } else { vals[2] = tokens[1].tokenValue; } } else if( tokens[1].isLengthOrPercent() ) { vals[3] = PIE.getLength( tokens[1].tokenValue ); } } // Three or four values - CSS3 else { // TODO } this._values = vals; } return this._values; }, /** * Find the coordinates of the background image from the upper-left corner of the background area. * Note that these coordinate values are not rounded. * @param {Element} el * @param {number} width - the width for percentages (background area width minus image width) * @param {number} height - the height for percentages (background area height minus image height) * @return {Object} { x: Number, y: Number } */ coords: function( el, width, height ) { var vals = this.getValues(), pxX = vals[1].pixels( el, width ), pxY = vals[3].pixels( el, height ); return { x: vals[0] === 'right' ? width - pxX : pxX, y: vals[2] === 'bottom' ? height - pxY : pxY }; } }; return BgPosition; })(); /** * Wrapper for a CSS3 background-size value. * @constructor * @param {String|PIE.Length} w The width parameter * @param {String|PIE.Length} h The height parameter, if any */ PIE.BgSize = (function() { var CONTAIN = 'contain', COVER = 'cover', AUTO = 'auto'; function BgSize( w, h ) { this.w = w; this.h = h; } BgSize.prototype = { pixels: function( el, areaW, areaH, imgW, imgH ) { var me = this, w = me.w, h = me.h, areaRatio = areaW / areaH, imgRatio = imgW / imgH; if ( w === CONTAIN ) { w = imgRatio > areaRatio ? areaW : areaH * imgRatio; h = imgRatio > areaRatio ? areaW / imgRatio : areaH; } else if ( w === COVER ) { w = imgRatio < areaRatio ? areaW : areaH * imgRatio; h = imgRatio < areaRatio ? areaW / imgRatio : areaH; } else if ( w === AUTO ) { h = ( h === AUTO ? imgH : h.pixels( el, areaH ) ); w = h * imgRatio; } else { w = w.pixels( el, areaW ); h = ( h === AUTO ? w / imgRatio : h.pixels( el, areaH ) ); } return { w: w, h: h }; } }; BgSize.DEFAULT = new BgSize( AUTO, AUTO ); return BgSize; })(); /** * Wrapper for angle values; handles conversion to degrees from all allowed angle units * @constructor * @param {string} val The raw CSS value for the angle. It is assumed it has been pre-validated. */ PIE.Angle = (function() { function Angle( val ) { this.val = val; } Angle.prototype = { unitRE: /[a-z]+$/i, /** * @return {string} The unit of the angle value */ getUnit: function() { return this._unit || ( this._unit = this.val.match( this.unitRE )[0].toLowerCase() ); }, /** * Get the numeric value of the angle in degrees. * @return {number} The degrees value */ degrees: function() { var deg = this._deg, u, n; if( deg === undefined ) { u = this.getUnit(); n = parseFloat( this.val, 10 ); deg = this._deg = ( u === 'deg' ? n : u === 'rad' ? n / Math.PI * 180 : u === 'grad' ? n / 400 * 360 : u === 'turn' ? n * 360 : 0 ); } return deg; } }; return Angle; })();/** * Abstraction for colors values. Allows detection of rgba values. A singleton instance per unique * value is returned from PIE.getColor() - always use that instead of instantiating directly. * @constructor * @param {string} val The raw CSS string value for the color */ PIE.Color = (function() { var instances = {}; function Color( val ) { this.val = val; } /** * Regular expression for matching rgba colors and extracting their components * @type {RegExp} */ Color.rgbaRE = /\s*rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d+|\d*\.\d+)\s*\)\s*/; Color.names = { "aliceblue":"F0F8FF", "antiquewhite":"FAEBD7", "aqua":"0FF", "aquamarine":"7FFFD4", "azure":"F0FFFF", "beige":"F5F5DC", "bisque":"FFE4C4", "black":"000", "blanchedalmond":"FFEBCD", "blue":"00F", "blueviolet":"8A2BE2", "brown":"A52A2A", "burlywood":"DEB887", "cadetblue":"5F9EA0", "chartreuse":"7FFF00", "chocolate":"D2691E", "coral":"FF7F50", "cornflowerblue":"6495ED", "cornsilk":"FFF8DC", "crimson":"DC143C", "cyan":"0FF", "darkblue":"00008B", "darkcyan":"008B8B", "darkgoldenrod":"B8860B", "darkgray":"A9A9A9", "darkgreen":"006400", "darkkhaki":"BDB76B", "darkmagenta":"8B008B", "darkolivegreen":"556B2F", "darkorange":"FF8C00", "darkorchid":"9932CC", "darkred":"8B0000", "darksalmon":"E9967A", "darkseagreen":"8FBC8F", "darkslateblue":"483D8B", "darkslategray":"2F4F4F", "darkturquoise":"00CED1", "darkviolet":"9400D3", "deeppink":"FF1493", "deepskyblue":"00BFFF", "dimgray":"696969", "dodgerblue":"1E90FF", "firebrick":"B22222", "floralwhite":"FFFAF0", "forestgreen":"228B22", "fuchsia":"F0F", "gainsboro":"DCDCDC", "ghostwhite":"F8F8FF", "gold":"FFD700", "goldenrod":"DAA520", "gray":"808080", "green":"008000", "greenyellow":"ADFF2F", "honeydew":"F0FFF0", "hotpink":"FF69B4", "indianred":"CD5C5C", "indigo":"4B0082", "ivory":"FFFFF0", "khaki":"F0E68C", "lavender":"E6E6FA", "lavenderblush":"FFF0F5", "lawngreen":"7CFC00", "lemonchiffon":"FFFACD", "lightblue":"ADD8E6", "lightcoral":"F08080", "lightcyan":"E0FFFF", "lightgoldenrodyellow":"FAFAD2", "lightgreen":"90EE90", "lightgrey":"D3D3D3", "lightpink":"FFB6C1", "lightsalmon":"FFA07A", "lightseagreen":"20B2AA", "lightskyblue":"87CEFA", "lightslategray":"789", "lightsteelblue":"B0C4DE", "lightyellow":"FFFFE0", "lime":"0F0", "limegreen":"32CD32", "linen":"FAF0E6", "magenta":"F0F", "maroon":"800000", "mediumauqamarine":"66CDAA", "mediumblue":"0000CD", "mediumorchid":"BA55D3", "mediumpurple":"9370D8", "mediumseagreen":"3CB371", "mediumslateblue":"7B68EE", "mediumspringgreen":"00FA9A", "mediumturquoise":"48D1CC", "mediumvioletred":"C71585", "midnightblue":"191970", "mintcream":"F5FFFA", "mistyrose":"FFE4E1", "moccasin":"FFE4B5", "navajowhite":"FFDEAD", "navy":"000080", "oldlace":"FDF5E6", "olive":"808000", "olivedrab":"688E23", "orange":"FFA500", "orangered":"FF4500", "orchid":"DA70D6", "palegoldenrod":"EEE8AA", "palegreen":"98FB98", "paleturquoise":"AFEEEE", "palevioletred":"D87093", "papayawhip":"FFEFD5", "peachpuff":"FFDAB9", "peru":"CD853F", "pink":"FFC0CB", "plum":"DDA0DD", "powderblue":"B0E0E6", "purple":"800080", "red":"F00", "rosybrown":"BC8F8F", "royalblue":"4169E1", "saddlebrown":"8B4513", "salmon":"FA8072", "sandybrown":"F4A460", "seagreen":"2E8B57", "seashell":"FFF5EE", "sienna":"A0522D", "silver":"C0C0C0", "skyblue":"87CEEB", "slateblue":"6A5ACD", "slategray":"708090", "snow":"FFFAFA", "springgreen":"00FF7F", "steelblue":"4682B4", "tan":"D2B48C", "teal":"008080", "thistle":"D8BFD8", "tomato":"FF6347", "turquoise":"40E0D0", "violet":"EE82EE", "wheat":"F5DEB3", "white":"FFF", "whitesmoke":"F5F5F5", "yellow":"FF0", "yellowgreen":"9ACD32" }; Color.prototype = { /** * @private */ parse: function() { if( !this._color ) { var me = this, v = me.val, vLower, m = v.match( Color.rgbaRE ); if( m ) { me._color = 'rgb(' + m[1] + ',' + m[2] + ',' + m[3] + ')'; me._alpha = parseFloat( m[4] ); } else { if( ( vLower = v.toLowerCase() ) in Color.names ) { v = '#' + Color.names[vLower]; } me._color = v; me._alpha = ( v === 'transparent' ? 0 : 1 ); } } }, /** * Retrieve the value of the color in a format usable by IE natively. This will be the same as * the raw input value, except for rgba values which will be converted to an rgb value. * @param {Element} el The context element, used to get 'currentColor' keyword value. * @return {string} Color value */ colorValue: function( el ) { this.parse(); return this._color === 'currentColor' ? el.currentStyle.color : this._color; }, /** * Retrieve the alpha value of the color. Will be 1 for all values except for rgba values * with an alpha component. * @return {number} The alpha value, from 0 to 1. */ alpha: function() { this.parse(); return this._alpha; } }; /** * Retrieve a PIE.Color instance for the given value. A shared singleton instance is returned for each unique value. * @param {string} val The CSS string representing the color. It is assumed that this will already have * been validated as a valid color syntax. */ PIE.getColor = function(val) { return instances[ val ] || ( instances[ val ] = new Color( val ) ); }; return Color; })();/** * A tokenizer for CSS value strings. * @constructor * @param {string} css The CSS value string */ PIE.Tokenizer = (function() { function Tokenizer( css ) { this.css = css; this.ch = 0; this.tokens = []; this.tokenIndex = 0; } /** * Enumeration of token type constants. * @enum {number} */ var Type = Tokenizer.Type = { ANGLE: 1, CHARACTER: 2, COLOR: 4, DIMEN: 8, FUNCTION: 16, IDENT: 32, LENGTH: 64, NUMBER: 128, OPERATOR: 256, PERCENT: 512, STRING: 1024, URL: 2048 }; /** * A single token * @constructor * @param {number} type The type of the token - see PIE.Tokenizer.Type * @param {string} value The value of the token */ Tokenizer.Token = function( type, value ) { this.tokenType = type; this.tokenValue = value; }; Tokenizer.Token.prototype = { isLength: function() { return this.tokenType & Type.LENGTH || ( this.tokenType & Type.NUMBER && this.tokenValue === '0' ); }, isLengthOrPercent: function() { return this.isLength() || this.tokenType & Type.PERCENT; } }; Tokenizer.prototype = { whitespace: /\s/, number: /^[\+\-]?(\d*\.)?\d+/, url: /^url\(\s*("([^"]*)"|'([^']*)'|([!#$%&*-~]*))\s*\)/i, ident: /^\-?[_a-z][\w-]*/i, string: /^("([^"]*)"|'([^']*)')/, operator: /^[\/,]/, hash: /^#[\w]+/, hashColor: /^#([\da-f]{6}|[\da-f]{3})/i, unitTypes: { 'px': Type.LENGTH, 'em': Type.LENGTH, 'ex': Type.LENGTH, 'mm': Type.LENGTH, 'cm': Type.LENGTH, 'in': Type.LENGTH, 'pt': Type.LENGTH, 'pc': Type.LENGTH, 'deg': Type.ANGLE, 'rad': Type.ANGLE, 'grad': Type.ANGLE }, colorFunctions: { 'rgb': 1, 'rgba': 1, 'hsl': 1, 'hsla': 1 }, /** * Advance to and return the next token in the CSS string. If the end of the CSS string has * been reached, null will be returned. * @param {boolean} forget - if true, the token will not be stored for the purposes of backtracking with prev(). * @return {PIE.Tokenizer.Token} */ next: function( forget ) { var css, ch, firstChar, match, val, me = this; function newToken( type, value ) { var tok = new Tokenizer.Token( type, value ); if( !forget ) { me.tokens.push( tok ); me.tokenIndex++; } return tok; } function failure() { me.tokenIndex++; return null; } // In case we previously backed up, return the stored token in the next slot if( this.tokenIndex < this.tokens.length ) { return this.tokens[ this.tokenIndex++ ]; } // Move past leading whitespace characters while( this.whitespace.test( this.css.charAt( this.ch ) ) ) { this.ch++; } if( this.ch >= this.css.length ) { return failure(); } ch = this.ch; css = this.css.substring( this.ch ); firstChar = css.charAt( 0 ); switch( firstChar ) { case '#': if( match = css.match( this.hashColor ) ) { this.ch += match[0].length; return newToken( Type.COLOR, match[0] ); } break; case '"': case "'": if( match = css.match( this.string ) ) { this.ch += match[0].length; return newToken( Type.STRING, match[2] || match[3] || '' ); } break; case "/": case ",": this.ch++; return newToken( Type.OPERATOR, firstChar ); case 'u': if( match = css.match( this.url ) ) { this.ch += match[0].length; return newToken( Type.URL, match[2] || match[3] || match[4] || '' ); } } // Numbers and values starting with numbers if( match = css.match( this.number ) ) { val = match[0]; this.ch += val.length; // Check if it is followed by a unit if( css.charAt( val.length ) === '%' ) { this.ch++; return newToken( Type.PERCENT, val + '%' ); } if( match = css.substring( val.length ).match( this.ident ) ) { val += match[0]; this.ch += match[0].length; return newToken( this.unitTypes[ match[0].toLowerCase() ] || Type.DIMEN, val ); } // Plain ol' number return newToken( Type.NUMBER, val ); } // Identifiers if( match = css.match( this.ident ) ) { val = match[0]; this.ch += val.length; // Named colors if( val.toLowerCase() in PIE.Color.names || val === 'currentColor' || val === 'transparent' ) { return newToken( Type.COLOR, val ); } // Functions if( css.charAt( val.length ) === '(' ) { this.ch++; // Color values in function format: rgb, rgba, hsl, hsla if( val.toLowerCase() in this.colorFunctions ) { function isNum( tok ) { return tok && tok.tokenType & Type.NUMBER; } function isNumOrPct( tok ) { return tok && ( tok.tokenType & ( Type.NUMBER | Type.PERCENT ) ); } function isValue( tok, val ) { return tok && tok.tokenValue === val; } function next() { return me.next( 1 ); } if( ( val.charAt(0) === 'r' ? isNumOrPct( next() ) : isNum( next() ) ) && isValue( next(), ',' ) && isNumOrPct( next() ) && isValue( next(), ',' ) && isNumOrPct( next() ) && ( val === 'rgb' || val === 'hsa' || ( isValue( next(), ',' ) && isNum( next() ) ) ) && isValue( next(), ')' ) ) { return newToken( Type.COLOR, this.css.substring( ch, this.ch ) ); } return failure(); } return newToken( Type.FUNCTION, val ); } // Other identifier return newToken( Type.IDENT, val ); } // Standalone character this.ch++; return newToken( Type.CHARACTER, firstChar ); }, /** * Determine whether there is another token * @return {boolean} */ hasNext: function() { var next = this.next(); this.prev(); return !!next; }, /** * Back up and return the previous token * @return {PIE.Tokenizer.Token} */ prev: function() { return this.tokens[ this.tokenIndex-- - 2 ]; }, /** * Retrieve all the tokens in the CSS string * @return {Array.<PIE.Tokenizer.Token>} */ all: function() { while( this.next() ) {} return this.tokens; }, /** * Return a list of tokens from the current position until the given function returns * true. The final token will not be included in the list. * @param {function():boolean} func - test function * @param {boolean} require - if true, then if the end of the CSS string is reached * before the test function returns true, null will be returned instead of the * tokens that have been found so far. * @return {Array.<PIE.Tokenizer.Token>} */ until: function( func, require ) { var list = [], t, hit; while( t = this.next() ) { if( func( t ) ) { hit = true; this.prev(); break; } list.push( t ); } return require && !hit ? null : list; } }; return Tokenizer; })();/** * Handles calculating, caching, and detecting changes to size and position of the element. * @constructor * @param {Element} el the target element */ PIE.BoundsInfo = function( el ) { this.targetElement = el; }; PIE.BoundsInfo.prototype = { _locked: 0, positionChanged: function() { var last = this._lastBounds, bounds; return !last || ( ( bounds = this.getBounds() ) && ( last.x !== bounds.x || last.y !== bounds.y ) ); }, sizeChanged: function() { var last = this._lastBounds, bounds; return !last || ( ( bounds = this.getBounds() ) && ( last.w !== bounds.w || last.h !== bounds.h ) ); }, getLiveBounds: function() { var el = this.targetElement, rect = el.getBoundingClientRect(), isIE9 = PIE.ieDocMode === 9, isIE7 = PIE.ieVersion === 7, width = rect.right - rect.left; return { x: rect.left, y: rect.top, // In some cases scrolling the page will cause IE9 to report incorrect dimensions // in the rect returned by getBoundingClientRect, so we must query offsetWidth/Height // instead. Also IE7 is inconsistent in using logical vs. device pixels in measurements // so we must calculate the ratio and use it in certain places as a position adjustment. w: isIE9 || isIE7 ? el.offsetWidth : width, h: isIE9 || isIE7 ? el.offsetHeight : rect.bottom - rect.top, logicalZoomRatio: ( isIE7 && width ) ? el.offsetWidth / width : 1 }; }, getBounds: function() { return this._locked ? ( this._lockedBounds || ( this._lockedBounds = this.getLiveBounds() ) ) : this.getLiveBounds(); }, hasBeenQueried: function() { return !!this._lastBounds; }, lock: function() { ++this._locked; }, unlock: function() { if( !--this._locked ) { if( this._lockedBounds ) this._lastBounds = this._lockedBounds; this._lockedBounds = null; } } }; (function() { function cacheWhenLocked( fn ) { var uid = PIE.Util.getUID( fn ); return function() { if( this._locked ) { var cache = this._lockedValues || ( this._lockedValues = {} ); return ( uid in cache ) ? cache[ uid ] : ( cache[ uid ] = fn.call( this ) ); } else { return fn.call( this ); } } } PIE.StyleInfoBase = { _locked: 0, /** * Create a new StyleInfo class, with the standard constructor, and augmented by * the StyleInfoBase's members. * @param proto */ newStyleInfo: function( proto ) { function StyleInfo( el ) { this.targetElement = el; this._lastCss = this.getCss(); } PIE.Util.merge( StyleInfo.prototype, PIE.StyleInfoBase, proto ); StyleInfo._propsCache = {}; return StyleInfo; }, /** * Get an object representation of the target CSS style, caching it for each unique * CSS value string. * @return {Object} */ getProps: function() { var css = this.getCss(), cache = this.constructor._propsCache; return css ? ( css in cache ? cache[ css ] : ( cache[ css ] = this.parseCss( css ) ) ) : null; }, /** * Get the raw CSS value for the target style * @return {string} */ getCss: cacheWhenLocked( function() { var el = this.targetElement, ctor = this.constructor, s = el.style, cs = el.currentStyle, cssProp = this.cssProperty, styleProp = this.styleProperty, prefixedCssProp = ctor._prefixedCssProp || ( ctor._prefixedCssProp = PIE.CSS_PREFIX + cssProp ), prefixedStyleProp = ctor._prefixedStyleProp || ( ctor._prefixedStyleProp = PIE.STYLE_PREFIX + styleProp.charAt(0).toUpperCase() + styleProp.substring(1) ); return s[ prefixedStyleProp ] || cs.getAttribute( prefixedCssProp ) || s[ styleProp ] || cs.getAttribute( cssProp ); } ), /** * Determine whether the target CSS style is active. * @return {boolean} */ isActive: cacheWhenLocked( function() { return !!this.getProps(); } ), /** * Determine whether the target CSS style has changed since the last time it was used. * @return {boolean} */ changed: cacheWhenLocked( function() { var currentCss = this.getCss(), changed = currentCss !== this._lastCss; this._lastCss = currentCss; return changed; } ), cacheWhenLocked: cacheWhenLocked, lock: function() { ++this._locked; }, unlock: function() { if( !--this._locked ) { delete this._lockedValues; } } }; })();/** * Handles parsing, caching, and detecting changes to background (and -pie-background) CSS * @constructor * @param {Element} el the target element */ PIE.BackgroundStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: PIE.CSS_PREFIX + 'background', styleProperty: PIE.STYLE_PREFIX + 'Background', attachIdents: { 'scroll':1, 'fixed':1, 'local':1 }, repeatIdents: { 'repeat-x':1, 'repeat-y':1, 'repeat':1, 'no-repeat':1 }, originAndClipIdents: { 'padding-box':1, 'border-box':1, 'content-box':1 }, positionIdents: { 'top':1, 'right':1, 'bottom':1, 'left':1, 'center':1 }, sizeIdents: { 'contain':1, 'cover':1 }, propertyNames: { CLIP: 'backgroundClip', COLOR: 'backgroundColor', IMAGE: 'backgroundImage', ORIGIN: 'backgroundOrigin', POSITION: 'backgroundPosition', REPEAT: 'backgroundRepeat', SIZE: 'backgroundSize' }, /** * For background styles, we support the -pie-background property but fall back to the standard * backround* properties. The reason we have to use the prefixed version is that IE natively * parses the standard properties and if it sees something it doesn't know how to parse, for example * multiple values or gradient definitions, it will throw that away and not make it available through * currentStyle. * * Format of return object: * { * color: <PIE.Color>, * bgImages: [ * { * imgType: 'image', * imgUrl: 'image.png', * imgRepeat: <'no-repeat' | 'repeat-x' | 'repeat-y' | 'repeat'>, * bgPosition: <PIE.BgPosition>, * bgAttachment: <'scroll' | 'fixed' | 'local'>, * bgOrigin: <'border-box' | 'padding-box' | 'content-box'>, * bgClip: <'border-box' | 'padding-box'>, * bgSize: <PIE.BgSize>, * origString: 'url(img.png) no-repeat top left' * }, * { * imgType: 'linear-gradient', * gradientStart: <PIE.BgPosition>, * angle: <PIE.Angle>, * stops: [ * { color: <PIE.Color>, offset: <PIE.Length> }, * { color: <PIE.Color>, offset: <PIE.Length> }, ... * ] * } * ] * } * @param {String} css * @override */ parseCss: function( css ) { var el = this.targetElement, cs = el.currentStyle, tokenizer, token, image, tok_type = PIE.Tokenizer.Type, type_operator = tok_type.OPERATOR, type_ident = tok_type.IDENT, type_color = tok_type.COLOR, tokType, tokVal, beginCharIndex = 0, positionIdents = this.positionIdents, gradient, stop, width, height, props = { bgImages: [] }; function isBgPosToken( token ) { return token && token.isLengthOrPercent() || ( token.tokenType & type_ident && token.tokenValue in positionIdents ); } function sizeToken( token ) { return token && ( ( token.isLengthOrPercent() && PIE.getLength( token.tokenValue ) ) || ( token.tokenValue === 'auto' && 'auto' ) ); } // If the CSS3-specific -pie-background property is present, parse it if( this.getCss3() ) { tokenizer = new PIE.Tokenizer( css ); image = {}; while( token = tokenizer.next() ) { tokType = token.tokenType; tokVal = token.tokenValue; if( !image.imgType && tokType & tok_type.FUNCTION && tokVal === 'linear-gradient' ) { gradient = { stops: [], imgType: tokVal }; stop = {}; while( token = tokenizer.next() ) { tokType = token.tokenType; tokVal = token.tokenValue; // If we reached the end of the function and had at least 2 stops, flush the info if( tokType & tok_type.CHARACTER && tokVal === ')' ) { if( stop.color ) { gradient.stops.push( stop ); } if( gradient.stops.length > 1 ) { PIE.Util.merge( image, gradient ); } break; } // Color stop - must start with color if( tokType & type_color ) { // if we already have an angle/position, make sure that the previous token was a comma if( gradient.angle || gradient.gradientStart ) { token = tokenizer.prev(); if( token.tokenType !== type_operator ) { break; //fail } tokenizer.next(); } stop = { color: PIE.getColor( tokVal ) }; // check for offset following color token = tokenizer.next(); if( token.isLengthOrPercent() ) { stop.offset = PIE.getLength( token.tokenValue ); } else { tokenizer.prev(); } } // Angle - can only appear in first spot else if( tokType & tok_type.ANGLE && !gradient.angle && !stop.color && !gradient.stops.length ) { gradient.angle = new PIE.Angle( token.tokenValue ); } else if( isBgPosToken( token ) && !gradient.gradientStart && !stop.color && !gradient.stops.length ) { tokenizer.prev(); gradient.gradientStart = new PIE.BgPosition( tokenizer.until( function( t ) { return !isBgPosToken( t ); }, false ) ); } else if( tokType & type_operator && tokVal === ',' ) { if( stop.color ) { gradient.stops.push( stop ); stop = {}; } } else { // Found something we didn't recognize; fail without adding image break; } } } else if( !image.imgType && tokType & tok_type.URL ) { image.imgUrl = tokVal; image.imgType = 'image'; } else if( isBgPosToken( token ) && !image.bgPosition ) { tokenizer.prev(); image.bgPosition = new PIE.BgPosition( tokenizer.until( function( t ) { return !isBgPosToken( t ); }, false ) ); } else if( tokType & type_ident ) { if( tokVal in this.repeatIdents && !image.imgRepeat ) { image.imgRepeat = tokVal; } else if( tokVal in this.originAndClipIdents && !image.bgOrigin ) { image.bgOrigin = tokVal; if( ( token = tokenizer.next() ) && ( token.tokenType & type_ident ) && token.tokenValue in this.originAndClipIdents ) { image.bgClip = token.tokenValue; } else { image.bgClip = tokVal; tokenizer.prev(); } } else if( tokVal in this.attachIdents && !image.bgAttachment ) { image.bgAttachment = tokVal; } else { return null; } } else if( tokType & type_color && !props.color ) { props.color = PIE.getColor( tokVal ); } else if( tokType & type_operator && tokVal === '/' && !image.bgSize && image.bgPosition ) { // background size token = tokenizer.next(); if( token.tokenType & type_ident && token.tokenValue in this.sizeIdents ) { image.bgSize = new PIE.BgSize( token.tokenValue ); } else if( width = sizeToken( token ) ) { height = sizeToken( tokenizer.next() ); if ( !height ) { height = width; tokenizer.prev(); } image.bgSize = new PIE.BgSize( width, height ); } else { return null; } } // new layer else if( tokType & type_operator && tokVal === ',' && image.imgType ) { image.origString = css.substring( beginCharIndex, tokenizer.ch - 1 ); beginCharIndex = tokenizer.ch; props.bgImages.push( image ); image = {}; } else { // Found something unrecognized; chuck everything return null; } } // leftovers if( image.imgType ) { image.origString = css.substring( beginCharIndex ); props.bgImages.push( image ); } } // Otherwise, use the standard background properties; let IE give us the values rather than parsing them else { this.withActualBg( PIE.ieDocMode < 9 ? function() { var propNames = this.propertyNames, posX = cs[propNames.POSITION + 'X'], posY = cs[propNames.POSITION + 'Y'], img = cs[propNames.IMAGE], color = cs[propNames.COLOR]; if( color !== 'transparent' ) { props.color = PIE.getColor( color ) } if( img !== 'none' ) { props.bgImages = [ { imgType: 'image', imgUrl: new PIE.Tokenizer( img ).next().tokenValue, imgRepeat: cs[propNames.REPEAT], bgPosition: new PIE.BgPosition( new PIE.Tokenizer( posX + ' ' + posY ).all() ) } ]; } } : function() { var propNames = this.propertyNames, splitter = /\s*,\s*/, images = cs[propNames.IMAGE].split( splitter ), color = cs[propNames.COLOR], repeats, positions, origins, clips, sizes, i, len, image, sizeParts; if( color !== 'transparent' ) { props.color = PIE.getColor( color ) } len = images.length; if( len && images[0] !== 'none' ) { repeats = cs[propNames.REPEAT].split( splitter ); positions = cs[propNames.POSITION].split( splitter ); origins = cs[propNames.ORIGIN].split( splitter ); clips = cs[propNames.CLIP].split( splitter ); sizes = cs[propNames.SIZE].split( splitter ); props.bgImages = []; for( i = 0; i < len; i++ ) { image = images[ i ]; if( image && image !== 'none' ) { sizeParts = sizes[i].split( ' ' ); props.bgImages.push( { origString: image + ' ' + repeats[ i ] + ' ' + positions[ i ] + ' / ' + sizes[ i ] + ' ' + origins[ i ] + ' ' + clips[ i ], imgType: 'image', imgUrl: new PIE.Tokenizer( image ).next().tokenValue, imgRepeat: repeats[ i ], bgPosition: new PIE.BgPosition( new PIE.Tokenizer( positions[ i ] ).all() ), bgOrigin: origins[ i ], bgClip: clips[ i ], bgSize: new PIE.BgSize( sizeParts[ 0 ], sizeParts[ 1 ] ) } ); } } } } ); } return ( props.color || props.bgImages[0] ) ? props : null; }, /** * Execute a function with the actual background styles (not overridden with runtimeStyle * properties set by the renderers) available via currentStyle. * @param fn */ withActualBg: function( fn ) { var isIE9 = PIE.ieDocMode > 8, propNames = this.propertyNames, rs = this.targetElement.runtimeStyle, rsImage = rs[propNames.IMAGE], rsColor = rs[propNames.COLOR], rsRepeat = rs[propNames.REPEAT], rsClip, rsOrigin, rsSize, rsPosition, ret; if( rsImage ) rs[propNames.IMAGE] = ''; if( rsColor ) rs[propNames.COLOR] = ''; if( rsRepeat ) rs[propNames.REPEAT] = ''; if( isIE9 ) { rsClip = rs[propNames.CLIP]; rsOrigin = rs[propNames.ORIGIN]; rsPosition = rs[propNames.POSITION]; rsSize = rs[propNames.SIZE]; if( rsClip ) rs[propNames.CLIP] = ''; if( rsOrigin ) rs[propNames.ORIGIN] = ''; if( rsPosition ) rs[propNames.POSITION] = ''; if( rsSize ) rs[propNames.SIZE] = ''; } ret = fn.call( this ); if( rsImage ) rs[propNames.IMAGE] = rsImage; if( rsColor ) rs[propNames.COLOR] = rsColor; if( rsRepeat ) rs[propNames.REPEAT] = rsRepeat; if( isIE9 ) { if( rsClip ) rs[propNames.CLIP] = rsClip; if( rsOrigin ) rs[propNames.ORIGIN] = rsOrigin; if( rsPosition ) rs[propNames.POSITION] = rsPosition; if( rsSize ) rs[propNames.SIZE] = rsSize; } return ret; }, getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { return this.getCss3() || this.withActualBg( function() { var cs = this.targetElement.currentStyle, propNames = this.propertyNames; return cs[propNames.COLOR] + ' ' + cs[propNames.IMAGE] + ' ' + cs[propNames.REPEAT] + ' ' + cs[propNames.POSITION + 'X'] + ' ' + cs[propNames.POSITION + 'Y']; } ); } ), getCss3: PIE.StyleInfoBase.cacheWhenLocked( function() { var el = this.targetElement; return el.style[ this.styleProperty ] || el.currentStyle.getAttribute( this.cssProperty ); } ), /** * Tests if style.PiePngFix or the -pie-png-fix property is set to true in IE6. */ isPngFix: function() { var val = 0, el; if( PIE.ieVersion < 7 ) { el = this.targetElement; val = ( '' + ( el.style[ PIE.STYLE_PREFIX + 'PngFix' ] || el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'png-fix' ) ) === 'true' ); } return val; }, /** * The isActive logic is slightly different, because getProps() always returns an object * even if it is just falling back to the native background properties. But we only want * to report is as being "active" if either the -pie-background override property is present * and parses successfully or '-pie-png-fix' is set to true in IE6. */ isActive: PIE.StyleInfoBase.cacheWhenLocked( function() { return (this.getCss3() || this.isPngFix()) && !!this.getProps(); } ) } );/** * Handles parsing, caching, and detecting changes to border CSS * @constructor * @param {Element} el the target element */ PIE.BorderStyleInfo = PIE.StyleInfoBase.newStyleInfo( { sides: [ 'Top', 'Right', 'Bottom', 'Left' ], namedWidths: { 'thin': '1px', 'medium': '3px', 'thick': '5px' }, parseCss: function( css ) { var w = {}, s = {}, c = {}, active = false, colorsSame = true, stylesSame = true, widthsSame = true; this.withActualBorder( function() { var el = this.targetElement, cs = el.currentStyle, i = 0, style, color, width, lastStyle, lastColor, lastWidth, side, ltr; for( ; i < 4; i++ ) { side = this.sides[ i ]; ltr = side.charAt(0).toLowerCase(); style = s[ ltr ] = cs[ 'border' + side + 'Style' ]; color = cs[ 'border' + side + 'Color' ]; width = cs[ 'border' + side + 'Width' ]; if( i > 0 ) { if( style !== lastStyle ) { stylesSame = false; } if( color !== lastColor ) { colorsSame = false; } if( width !== lastWidth ) { widthsSame = false; } } lastStyle = style; lastColor = color; lastWidth = width; c[ ltr ] = PIE.getColor( color ); width = w[ ltr ] = PIE.getLength( s[ ltr ] === 'none' ? '0' : ( this.namedWidths[ width ] || width ) ); if( width.pixels( this.targetElement ) > 0 ) { active = true; } } } ); return active ? { widths: w, styles: s, colors: c, widthsSame: widthsSame, colorsSame: colorsSame, stylesSame: stylesSame } : null; }, getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { var el = this.targetElement, cs = el.currentStyle, css; // Don't redraw or hide borders for cells in border-collapse:collapse tables if( !( el.tagName in PIE.tableCellTags && el.offsetParent.currentStyle.borderCollapse === 'collapse' ) ) { this.withActualBorder( function() { css = cs.borderWidth + '|' + cs.borderStyle + '|' + cs.borderColor; } ); } return css; } ), /** * Execute a function with the actual border styles (not overridden with runtimeStyle * properties set by the renderers) available via currentStyle. * @param fn */ withActualBorder: function( fn ) { var rs = this.targetElement.runtimeStyle, rsWidth = rs.borderWidth, rsColor = rs.borderColor, ret; if( rsWidth ) rs.borderWidth = ''; if( rsColor ) rs.borderColor = ''; ret = fn.call( this ); if( rsWidth ) rs.borderWidth = rsWidth; if( rsColor ) rs.borderColor = rsColor; return ret; } } ); /** * Handles parsing, caching, and detecting changes to border-radius CSS * @constructor * @param {Element} el the target element */ (function() { PIE.BorderRadiusStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: 'border-radius', styleProperty: 'borderRadius', parseCss: function( css ) { var p = null, x, y, tokenizer, token, length, hasNonZero = false; if( css ) { tokenizer = new PIE.Tokenizer( css ); function collectLengths() { var arr = [], num; while( ( token = tokenizer.next() ) && token.isLengthOrPercent() ) { length = PIE.getLength( token.tokenValue ); num = length.getNumber(); if( num < 0 ) { return null; } if( num > 0 ) { hasNonZero = true; } arr.push( length ); } return arr.length > 0 && arr.length < 5 ? { 'tl': arr[0], 'tr': arr[1] || arr[0], 'br': arr[2] || arr[0], 'bl': arr[3] || arr[1] || arr[0] } : null; } // Grab the initial sequence of lengths if( x = collectLengths() ) { // See if there is a slash followed by more lengths, for the y-axis radii if( token ) { if( token.tokenType & PIE.Tokenizer.Type.OPERATOR && token.tokenValue === '/' ) { y = collectLengths(); } } else { y = x; } // Treat all-zero values the same as no value if( hasNonZero && x && y ) { p = { x: x, y : y }; } } } return p; } } ); var zero = PIE.getLength( '0' ), zeros = { 'tl': zero, 'tr': zero, 'br': zero, 'bl': zero }; PIE.BorderRadiusStyleInfo.ALL_ZERO = { x: zeros, y: zeros }; })();/** * Handles parsing, caching, and detecting changes to border-image CSS * @constructor * @param {Element} el the target element */ PIE.BorderImageStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: 'border-image', styleProperty: 'borderImage', repeatIdents: { 'stretch':1, 'round':1, 'repeat':1, 'space':1 }, parseCss: function( css ) { var p = null, tokenizer, token, type, value, slices, widths, outsets, slashCount = 0, Type = PIE.Tokenizer.Type, IDENT = Type.IDENT, NUMBER = Type.NUMBER, PERCENT = Type.PERCENT; if( css ) { tokenizer = new PIE.Tokenizer( css ); p = {}; function isSlash( token ) { return token && ( token.tokenType & Type.OPERATOR ) && ( token.tokenValue === '/' ); } function isFillIdent( token ) { return token && ( token.tokenType & IDENT ) && ( token.tokenValue === 'fill' ); } function collectSlicesEtc() { slices = tokenizer.until( function( tok ) { return !( tok.tokenType & ( NUMBER | PERCENT ) ); } ); if( isFillIdent( tokenizer.next() ) && !p.fill ) { p.fill = true; } else { tokenizer.prev(); } if( isSlash( tokenizer.next() ) ) { slashCount++; widths = tokenizer.until( function( token ) { return !token.isLengthOrPercent() && !( ( token.tokenType & IDENT ) && token.tokenValue === 'auto' ); } ); if( isSlash( tokenizer.next() ) ) { slashCount++; outsets = tokenizer.until( function( token ) { return !token.isLength(); } ); } } else { tokenizer.prev(); } } while( token = tokenizer.next() ) { type = token.tokenType; value = token.tokenValue; // Numbers and/or 'fill' keyword: slice values. May be followed optionally by width values, followed optionally by outset values if( type & ( NUMBER | PERCENT ) && !slices ) { tokenizer.prev(); collectSlicesEtc(); } else if( isFillIdent( token ) && !p.fill ) { p.fill = true; collectSlicesEtc(); } // Idents: one or values for 'repeat' else if( ( type & IDENT ) && this.repeatIdents[value] && !p.repeat ) { p.repeat = { h: value }; if( token = tokenizer.next() ) { if( ( token.tokenType & IDENT ) && this.repeatIdents[token.tokenValue] ) { p.repeat.v = token.tokenValue; } else { tokenizer.prev(); } } } // URL of the image else if( ( type & Type.URL ) && !p.src ) { p.src = value; } // Found something unrecognized; exit. else { return null; } } // Validate what we collected if( !p.src || !slices || slices.length < 1 || slices.length > 4 || ( widths && widths.length > 4 ) || ( slashCount === 1 && widths.length < 1 ) || ( outsets && outsets.length > 4 ) || ( slashCount === 2 && outsets.length < 1 ) ) { return null; } // Fill in missing values if( !p.repeat ) { p.repeat = { h: 'stretch' }; } if( !p.repeat.v ) { p.repeat.v = p.repeat.h; } function distributeSides( tokens, convertFn ) { return { 't': convertFn( tokens[0] ), 'r': convertFn( tokens[1] || tokens[0] ), 'b': convertFn( tokens[2] || tokens[0] ), 'l': convertFn( tokens[3] || tokens[1] || tokens[0] ) }; } p.slice = distributeSides( slices, function( tok ) { return PIE.getLength( ( tok.tokenType & NUMBER ) ? tok.tokenValue + 'px' : tok.tokenValue ); } ); if( widths && widths[0] ) { p.widths = distributeSides( widths, function( tok ) { return tok.isLengthOrPercent() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue; } ); } if( outsets && outsets[0] ) { p.outset = distributeSides( outsets, function( tok ) { return tok.isLength() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue; } ); } } return p; } } );/** * Handles parsing, caching, and detecting changes to box-shadow CSS * @constructor * @param {Element} el the target element */ PIE.BoxShadowStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: 'box-shadow', styleProperty: 'boxShadow', parseCss: function( css ) { var props, getLength = PIE.getLength, Type = PIE.Tokenizer.Type, tokenizer; if( css ) { tokenizer = new PIE.Tokenizer( css ); props = { outset: [], inset: [] }; function parseItem() { var token, type, value, color, lengths, inset, len; while( token = tokenizer.next() ) { value = token.tokenValue; type = token.tokenType; if( type & Type.OPERATOR && value === ',' ) { break; } else if( token.isLength() && !lengths ) { tokenizer.prev(); lengths = tokenizer.until( function( token ) { return !token.isLength(); } ); } else if( type & Type.COLOR && !color ) { color = value; } else if( type & Type.IDENT && value === 'inset' && !inset ) { inset = true; } else { //encountered an unrecognized token; fail. return false; } } len = lengths && lengths.length; if( len > 1 && len < 5 ) { ( inset ? props.inset : props.outset ).push( { xOffset: getLength( lengths[0].tokenValue ), yOffset: getLength( lengths[1].tokenValue ), blur: getLength( lengths[2] ? lengths[2].tokenValue : '0' ), spread: getLength( lengths[3] ? lengths[3].tokenValue : '0' ), color: PIE.getColor( color || 'currentColor' ) } ); return true; } return false; } while( parseItem() ) {} } return props && ( props.inset.length || props.outset.length ) ? props : null; } } ); /** * Retrieves the state of the element's visibility and display * @constructor * @param {Element} el the target element */ PIE.VisibilityStyleInfo = PIE.StyleInfoBase.newStyleInfo( { getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { var cs = this.targetElement.currentStyle; return cs.visibility + '|' + cs.display; } ), parseCss: function() { var el = this.targetElement, rs = el.runtimeStyle, cs = el.currentStyle, rsVis = rs.visibility, csVis; rs.visibility = ''; csVis = cs.visibility; rs.visibility = rsVis; return { visible: csVis !== 'hidden', displayed: cs.display !== 'none' } }, /** * Always return false for isActive, since this property alone will not trigger * a renderer to do anything. */ isActive: function() { return false; } } ); PIE.RendererBase = { /** * Create a new Renderer class, with the standard constructor, and augmented by * the RendererBase's members. * @param proto */ newRenderer: function( proto ) { function Renderer( el, boundsInfo, styleInfos, parent ) { this.targetElement = el; this.boundsInfo = boundsInfo; this.styleInfos = styleInfos; this.parent = parent; } PIE.Util.merge( Renderer.prototype, PIE.RendererBase, proto ); return Renderer; }, /** * Flag indicating the element has already been positioned at least once. * @type {boolean} */ isPositioned: false, /** * Determine if the renderer needs to be updated * @return {boolean} */ needsUpdate: function() { return false; }, /** * Run any preparation logic that would affect the main update logic of this * renderer or any of the other renderers, e.g. things that might affect the * element's size or style properties. */ prepareUpdate: PIE.emptyFn, /** * Tell the renderer to update based on modified properties */ updateProps: function() { this.destroy(); if( this.isActive() ) { this.draw(); } }, /** * Tell the renderer to update based on modified element position */ updatePos: function() { this.isPositioned = true; }, /** * Tell the renderer to update based on modified element dimensions */ updateSize: function() { if( this.isActive() ) { this.draw(); } else { this.destroy(); } }, /** * Add a layer element, with the given z-order index, to the renderer's main box element. We can't use * z-index because that breaks when the root rendering box's z-index is 'auto' in IE8+ standards mode. * So instead we make sure they are inserted into the DOM in the correct order. * @param {number} index * @param {Element} el */ addLayer: function( index, el ) { this.removeLayer( index ); for( var layers = this._layers || ( this._layers = [] ), i = index + 1, len = layers.length, layer; i < len; i++ ) { layer = layers[i]; if( layer ) { break; } } layers[index] = el; this.getBox().insertBefore( el, layer || null ); }, /** * Retrieve a layer element by its index, or null if not present * @param {number} index * @return {Element} */ getLayer: function( index ) { var layers = this._layers; return layers && layers[index] || null; }, /** * Remove a layer element by its index * @param {number} index */ removeLayer: function( index ) { var layer = this.getLayer( index ), box = this._box; if( layer && box ) { box.removeChild( layer ); this._layers[index] = null; } }, /** * Get a VML shape by name, creating it if necessary. * @param {string} name A name identifying the element * @param {string=} subElName If specified a subelement of the shape will be created with this tag name * @param {Element} parent The parent element for the shape; will be ignored if 'group' is specified * @param {number=} group If specified, an ordinal group for the shape. 1 or greater. Groups are rendered * using container elements in the correct order, to get correct z stacking without z-index. */ getShape: function( name, subElName, parent, group ) { var shapes = this._shapes || ( this._shapes = {} ), shape = shapes[ name ], s; if( !shape ) { shape = shapes[ name ] = PIE.Util.createVmlElement( 'shape' ); if( subElName ) { shape.appendChild( shape[ subElName ] = PIE.Util.createVmlElement( subElName ) ); } if( group ) { parent = this.getLayer( group ); if( !parent ) { this.addLayer( group, doc.createElement( 'group' + group ) ); parent = this.getLayer( group ); } } parent.appendChild( shape ); s = shape.style; s.position = 'absolute'; s.left = s.top = 0; s['behavior'] = 'url(#default#VML)'; } return shape; }, /** * Delete a named shape which was created by getShape(). Returns true if a shape with the * given name was found and deleted, or false if there was no shape of that name. * @param {string} name * @return {boolean} */ deleteShape: function( name ) { var shapes = this._shapes, shape = shapes && shapes[ name ]; if( shape ) { shape.parentNode.removeChild( shape ); delete shapes[ name ]; } return !!shape; }, /** * For a given set of border radius length/percentage values, convert them to concrete pixel * values based on the current size of the target element. * @param {Object} radii * @return {Object} */ getRadiiPixels: function( radii ) { var el = this.targetElement, bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, tlX, tlY, trX, trY, brX, brY, blX, blY, f; tlX = radii.x['tl'].pixels( el, w ); tlY = radii.y['tl'].pixels( el, h ); trX = radii.x['tr'].pixels( el, w ); trY = radii.y['tr'].pixels( el, h ); brX = radii.x['br'].pixels( el, w ); brY = radii.y['br'].pixels( el, h ); blX = radii.x['bl'].pixels( el, w ); blY = radii.y['bl'].pixels( el, h ); // If any corner ellipses overlap, reduce them all by the appropriate factor. This formula // is taken straight from the CSS3 Backgrounds and Borders spec. f = Math.min( w / ( tlX + trX ), h / ( trY + brY ), w / ( blX + brX ), h / ( tlY + blY ) ); if( f < 1 ) { tlX *= f; tlY *= f; trX *= f; trY *= f; brX *= f; brY *= f; blX *= f; blY *= f; } return { x: { 'tl': tlX, 'tr': trX, 'br': brX, 'bl': blX }, y: { 'tl': tlY, 'tr': trY, 'br': brY, 'bl': blY } } }, /** * Return the VML path string for the element's background box, with corners rounded. * @param {Object.<{t:number, r:number, b:number, l:number}>} shrink - if present, specifies number of * pixels to shrink the box path inward from the element's four sides. * @param {number=} mult If specified, all coordinates will be multiplied by this number * @param {Object=} radii If specified, this will be used for the corner radii instead of the properties * from this renderer's borderRadiusInfo object. * @return {string} the VML path */ getBoxPath: function( shrink, mult, radii ) { mult = mult || 1; var r, str, bounds = this.boundsInfo.getBounds(), w = bounds.w * mult, h = bounds.h * mult, radInfo = this.styleInfos.borderRadiusInfo, floor = Math.floor, ceil = Math.ceil, shrinkT = shrink ? shrink.t * mult : 0, shrinkR = shrink ? shrink.r * mult : 0, shrinkB = shrink ? shrink.b * mult : 0, shrinkL = shrink ? shrink.l * mult : 0, tlX, tlY, trX, trY, brX, brY, blX, blY; if( radii || radInfo.isActive() ) { r = this.getRadiiPixels( radii || radInfo.getProps() ); tlX = r.x['tl'] * mult; tlY = r.y['tl'] * mult; trX = r.x['tr'] * mult; trY = r.y['tr'] * mult; brX = r.x['br'] * mult; brY = r.y['br'] * mult; blX = r.x['bl'] * mult; blY = r.y['bl'] * mult; str = 'm' + floor( shrinkL ) + ',' + floor( tlY ) + 'qy' + floor( tlX ) + ',' + floor( shrinkT ) + 'l' + ceil( w - trX ) + ',' + floor( shrinkT ) + 'qx' + ceil( w - shrinkR ) + ',' + floor( trY ) + 'l' + ceil( w - shrinkR ) + ',' + ceil( h - brY ) + 'qy' + ceil( w - brX ) + ',' + ceil( h - shrinkB ) + 'l' + floor( blX ) + ',' + ceil( h - shrinkB ) + 'qx' + floor( shrinkL ) + ',' + ceil( h - blY ) + ' x e'; } else { // simplified path for non-rounded box str = 'm' + floor( shrinkL ) + ',' + floor( shrinkT ) + 'l' + ceil( w - shrinkR ) + ',' + floor( shrinkT ) + 'l' + ceil( w - shrinkR ) + ',' + ceil( h - shrinkB ) + 'l' + floor( shrinkL ) + ',' + ceil( h - shrinkB ) + 'xe'; } return str; }, /** * Get the container element for the shapes, creating it if necessary. */ getBox: function() { var box = this.parent.getLayer( this.boxZIndex ), s; if( !box ) { box = doc.createElement( this.boxName ); s = box.style; s.position = 'absolute'; s.top = s.left = 0; this.parent.addLayer( this.boxZIndex, box ); } return box; }, /** * Hide the actual border of the element. In IE7 and up we can just set its color to transparent; * however IE6 does not support transparent borders so we have to get tricky with it. Also, some elements * like form buttons require removing the border width altogether, so for those we increase the padding * by the border size. */ hideBorder: function() { var el = this.targetElement, cs = el.currentStyle, rs = el.runtimeStyle, tag = el.tagName, isIE6 = PIE.ieVersion === 6, sides, side, i; if( ( isIE6 && ( tag in PIE.childlessElements || tag === 'FIELDSET' ) ) || tag === 'BUTTON' || ( tag === 'INPUT' && el.type in PIE.inputButtonTypes ) ) { rs.borderWidth = ''; sides = this.styleInfos.borderInfo.sides; for( i = sides.length; i--; ) { side = sides[ i ]; rs[ 'padding' + side ] = ''; rs[ 'padding' + side ] = ( PIE.getLength( cs[ 'padding' + side ] ) ).pixels( el ) + ( PIE.getLength( cs[ 'border' + side + 'Width' ] ) ).pixels( el ) + ( PIE.ieVersion !== 8 && i % 2 ? 1 : 0 ); //needs an extra horizontal pixel to counteract the extra "inner border" going away } rs.borderWidth = 0; } else if( isIE6 ) { // Wrap all the element's children in a custom element, set the element to visiblity:hidden, // and set the wrapper element to visiblity:visible. This hides the outer element's decorations // (background and border) but displays all the contents. // TODO find a better way to do this that doesn't mess up the DOM parent-child relationship, // as this can interfere with other author scripts which add/modify/delete children. Also, this // won't work for elements which cannot take children, e.g. input/button/textarea/img/etc. Look into // using a compositor filter or some other filter which masks the border. if( el.childNodes.length !== 1 || el.firstChild.tagName !== 'ie6-mask' ) { var cont = doc.createElement( 'ie6-mask' ), s = cont.style, child; s.visibility = 'visible'; s.zoom = 1; while( child = el.firstChild ) { cont.appendChild( child ); } el.appendChild( cont ); rs.visibility = 'hidden'; } } else { rs.borderColor = 'transparent'; } }, unhideBorder: function() { }, /** * Destroy the rendered objects. This is a base implementation which handles common renderer * structures, but individual renderers may override as necessary. */ destroy: function() { this.parent.removeLayer( this.boxZIndex ); delete this._shapes; delete this._layers; } }; /** * Root renderer; creates the outermost container element and handles keeping it aligned * with the target element's size and position. * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects */ PIE.RootRenderer = PIE.RendererBase.newRenderer( { isActive: function() { var children = this.childRenderers; for( var i in children ) { if( children.hasOwnProperty( i ) && children[ i ].isActive() ) { return true; } } return false; }, needsUpdate: function() { return this.styleInfos.visibilityInfo.changed(); }, updatePos: function() { if( this.isActive() ) { var el = this.getPositioningElement(), par = el, docEl, parRect, tgtCS = el.currentStyle, tgtPos = tgtCS.position, boxPos, s = this.getBox().style, cs, x = 0, y = 0, elBounds = this.boundsInfo.getBounds(), logicalZoomRatio = elBounds.logicalZoomRatio; if( tgtPos === 'fixed' && PIE.ieVersion > 6 ) { x = elBounds.x * logicalZoomRatio; y = elBounds.y * logicalZoomRatio; boxPos = tgtPos; } else { // Get the element's offsets from its nearest positioned ancestor. Uses // getBoundingClientRect for accuracy and speed. do { par = par.offsetParent; } while( par && ( par.currentStyle.position === 'static' ) ); if( par ) { parRect = par.getBoundingClientRect(); cs = par.currentStyle; x = ( elBounds.x - parRect.left ) * logicalZoomRatio - ( parseFloat(cs.borderLeftWidth) || 0 ); y = ( elBounds.y - parRect.top ) * logicalZoomRatio - ( parseFloat(cs.borderTopWidth) || 0 ); } else { docEl = doc.documentElement; x = ( elBounds.x + docEl.scrollLeft - docEl.clientLeft ) * logicalZoomRatio; y = ( elBounds.y + docEl.scrollTop - docEl.clientTop ) * logicalZoomRatio; } boxPos = 'absolute'; } s.position = boxPos; s.left = x; s.top = y; s.zIndex = tgtPos === 'static' ? -1 : tgtCS.zIndex; this.isPositioned = true; } }, updateSize: PIE.emptyFn, updateVisibility: function() { var vis = this.styleInfos.visibilityInfo.getProps(); this.getBox().style.display = ( vis.visible && vis.displayed ) ? '' : 'none'; }, updateProps: function() { if( this.isActive() ) { this.updateVisibility(); } else { this.destroy(); } }, getPositioningElement: function() { var el = this.targetElement; return el.tagName in PIE.tableCellTags ? el.offsetParent : el; }, getBox: function() { var box = this._box, el; if( !box ) { el = this.getPositioningElement(); box = this._box = doc.createElement( 'css3-container' ); box.style['direction'] = 'ltr'; //fix positioning bug in rtl environments this.updateVisibility(); el.parentNode.insertBefore( box, el ); } return box; }, finishUpdate: PIE.emptyFn, destroy: function() { var box = this._box, par; if( box && ( par = box.parentNode ) ) { par.removeChild( box ); } delete this._box; delete this._layers; } } ); /** * Renderer for element backgrounds. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BackgroundRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 2, boxName: 'background', needsUpdate: function() { var si = this.styleInfos; return si.backgroundInfo.changed() || si.borderRadiusInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.borderImageInfo.isActive() || si.borderRadiusInfo.isActive() || si.backgroundInfo.isActive() || ( si.boxShadowInfo.isActive() && si.boxShadowInfo.getProps().inset ); }, /** * Draw the shapes */ draw: function() { var bounds = this.boundsInfo.getBounds(); if( bounds.w && bounds.h ) { this.drawBgColor(); this.drawBgImages(); } }, /** * Draw the background color shape */ drawBgColor: function() { var props = this.styleInfos.backgroundInfo.getProps(), bounds = this.boundsInfo.getBounds(), el = this.targetElement, color = props && props.color, shape, w, h, s, alpha; if( color && color.alpha() > 0 ) { this.hideBackground(); shape = this.getShape( 'bgColor', 'fill', this.getBox(), 1 ); w = bounds.w; h = bounds.h; shape.stroked = false; shape.coordsize = w * 2 + ',' + h * 2; shape.coordorigin = '1,1'; shape.path = this.getBoxPath( null, 2 ); s = shape.style; s.width = w; s.height = h; shape.fill.color = color.colorValue( el ); alpha = color.alpha(); if( alpha < 1 ) { shape.fill.opacity = alpha; } } else { this.deleteShape( 'bgColor' ); } }, /** * Draw all the background image layers */ drawBgImages: function() { var props = this.styleInfos.backgroundInfo.getProps(), bounds = this.boundsInfo.getBounds(), images = props && props.bgImages, img, shape, w, h, s, i; if( images ) { this.hideBackground(); w = bounds.w; h = bounds.h; i = images.length; while( i-- ) { img = images[i]; shape = this.getShape( 'bgImage' + i, 'fill', this.getBox(), 2 ); shape.stroked = false; shape.fill.type = 'tile'; shape.fillcolor = 'none'; shape.coordsize = w * 2 + ',' + h * 2; shape.coordorigin = '1,1'; shape.path = this.getBoxPath( 0, 2 ); s = shape.style; s.width = w; s.height = h; if( img.imgType === 'linear-gradient' ) { this.addLinearGradient( shape, img ); } else { shape.fill.src = img.imgUrl; this.positionBgImage( shape, i ); } } } // Delete any bgImage shapes previously created which weren't used above i = images ? images.length : 0; while( this.deleteShape( 'bgImage' + i++ ) ) {} }, /** * Set the position and clipping of the background image for a layer * @param {Element} shape * @param {number} index */ positionBgImage: function( shape, index ) { var me = this; PIE.Util.withImageSize( shape.fill.src, function( size ) { var el = me.targetElement, bounds = me.boundsInfo.getBounds(), elW = bounds.w, elH = bounds.h; // It's possible that the element dimensions are zero now but weren't when the original // update executed, make sure that's not the case to avoid divide-by-zero error if( elW && elH ) { var fill = shape.fill, si = me.styleInfos, border = si.borderInfo.getProps(), bw = border && border.widths, bwT = bw ? bw['t'].pixels( el ) : 0, bwR = bw ? bw['r'].pixels( el ) : 0, bwB = bw ? bw['b'].pixels( el ) : 0, bwL = bw ? bw['l'].pixels( el ) : 0, bg = si.backgroundInfo.getProps().bgImages[ index ], bgPos = bg.bgPosition ? bg.bgPosition.coords( el, elW - size.w - bwL - bwR, elH - size.h - bwT - bwB ) : { x:0, y:0 }, repeat = bg.imgRepeat, pxX, pxY, clipT = 0, clipL = 0, clipR = elW + 1, clipB = elH + 1, //make sure the default clip region is not inside the box (by a subpixel) clipAdjust = PIE.ieVersion === 8 ? 0 : 1; //prior to IE8 requires 1 extra pixel in the image clip region // Positioning - find the pixel offset from the top/left and convert to a ratio // The position is shifted by half a pixel, to adjust for the half-pixel coordorigin shift which is // needed to fix antialiasing but makes the bg image fuzzy. pxX = Math.round( bgPos.x ) + bwL + 0.5; pxY = Math.round( bgPos.y ) + bwT + 0.5; fill.position = ( pxX / elW ) + ',' + ( pxY / elH ); // Set the size of the image. We have to actually set it to px values otherwise it will not honor // the user's browser zoom level and always display at its natural screen size. fill['size']['x'] = 1; //Can be any value, just has to be set to "prime" it so the next line works. Weird! fill['size'] = size.w + 'px,' + size.h + 'px'; // Repeating - clip the image shape if( repeat && repeat !== 'repeat' ) { if( repeat === 'repeat-x' || repeat === 'no-repeat' ) { clipT = pxY + 1; clipB = pxY + size.h + clipAdjust; } if( repeat === 'repeat-y' || repeat === 'no-repeat' ) { clipL = pxX + 1; clipR = pxX + size.w + clipAdjust; } shape.style.clip = 'rect(' + clipT + 'px,' + clipR + 'px,' + clipB + 'px,' + clipL + 'px)'; } } } ); }, /** * Draw the linear gradient for a gradient layer * @param {Element} shape * @param {Object} info The object holding the information about the gradient */ addLinearGradient: function( shape, info ) { var el = this.targetElement, bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, fill = shape.fill, stops = info.stops, stopCount = stops.length, PI = Math.PI, GradientUtil = PIE.GradientUtil, perpendicularIntersect = GradientUtil.perpendicularIntersect, distance = GradientUtil.distance, metrics = GradientUtil.getGradientMetrics( el, w, h, info ), angle = metrics.angle, startX = metrics.startX, startY = metrics.startY, startCornerX = metrics.startCornerX, startCornerY = metrics.startCornerY, endCornerX = metrics.endCornerX, endCornerY = metrics.endCornerY, deltaX = metrics.deltaX, deltaY = metrics.deltaY, lineLength = metrics.lineLength, vmlAngle, vmlGradientLength, vmlColors, stopPx, vmlOffsetPct, p, i, j, before, after; // In VML land, the angle of the rendered gradient depends on the aspect ratio of the shape's // bounding box; for example specifying a 45 deg angle actually results in a gradient // drawn diagonally from one corner to its opposite corner, which will only appear to the // viewer as 45 degrees if the shape is equilateral. We adjust for this by taking the x/y deltas // between the start and end points, multiply one of them by the shape's aspect ratio, // and get their arctangent, resulting in an appropriate VML angle. If the angle is perfectly // horizontal or vertical then we don't need to do this conversion. vmlAngle = ( angle % 90 ) ? Math.atan2( deltaX * w / h, deltaY ) / PI * 180 : ( angle + 90 ); // VML angles are 180 degrees offset from CSS angles vmlAngle += 180; vmlAngle = vmlAngle % 360; // Add all the stops to the VML 'colors' list, including the first and last stops. // For each, we find its pixel offset along the gradient-line; if the offset of a stop is less // than that of its predecessor we increase it to be equal. We then map that pixel offset to a // percentage along the VML gradient-line, which runs from shape corner to corner. p = perpendicularIntersect( startCornerX, startCornerY, angle, endCornerX, endCornerY ); vmlGradientLength = distance( startCornerX, startCornerY, p[0], p[1] ); vmlColors = []; p = perpendicularIntersect( startX, startY, angle, startCornerX, startCornerY ); vmlOffsetPct = distance( startX, startY, p[0], p[1] ) / vmlGradientLength * 100; // Find the pixel offsets along the CSS3 gradient-line for each stop. stopPx = []; for( i = 0; i < stopCount; i++ ) { stopPx.push( stops[i].offset ? stops[i].offset.pixels( el, lineLength ) : i === 0 ? 0 : i === stopCount - 1 ? lineLength : null ); } // Fill in gaps with evenly-spaced offsets for( i = 1; i < stopCount; i++ ) { if( stopPx[ i ] === null ) { before = stopPx[ i - 1 ]; j = i; do { after = stopPx[ ++j ]; } while( after === null ); stopPx[ i ] = before + ( after - before ) / ( j - i + 1 ); } // Make sure each stop's offset is no less than the one before it stopPx[ i ] = Math.max( stopPx[ i ], stopPx[ i - 1 ] ); } // Convert to percentage along the VML gradient line and add to the VML 'colors' value for( i = 0; i < stopCount; i++ ) { vmlColors.push( ( vmlOffsetPct + ( stopPx[ i ] / vmlGradientLength * 100 ) ) + '% ' + stops[i].color.colorValue( el ) ); } // Now, finally, we're ready to render the gradient fill. Set the start and end colors to // the first and last stop colors; this just sets outer bounds for the gradient. fill['angle'] = vmlAngle; fill['type'] = 'gradient'; fill['method'] = 'sigma'; fill['color'] = stops[0].color.colorValue( el ); fill['color2'] = stops[stopCount - 1].color.colorValue( el ); if( fill['colors'] ) { //sometimes the colors object isn't initialized so we have to assign it directly (?) fill['colors'].value = vmlColors.join( ',' ); } else { fill['colors'] = vmlColors.join( ',' ); } }, /** * Hide the actual background image and color of the element. */ hideBackground: function() { var rs = this.targetElement.runtimeStyle; rs.backgroundImage = 'url(about:blank)'; //ensures the background area reacts to mouse events rs.backgroundColor = 'transparent'; }, destroy: function() { PIE.RendererBase.destroy.call( this ); var rs = this.targetElement.runtimeStyle; rs.backgroundImage = rs.backgroundColor = ''; } } ); /** * Renderer for element borders. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BorderRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 4, boxName: 'border', needsUpdate: function() { var si = this.styleInfos; return si.borderInfo.changed() || si.borderRadiusInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.borderRadiusInfo.isActive() && !si.borderImageInfo.isActive() && si.borderInfo.isActive(); //check BorderStyleInfo last because it's the most expensive }, /** * Draw the border shape(s) */ draw: function() { var el = this.targetElement, props = this.styleInfos.borderInfo.getProps(), bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, shape, stroke, s, segments, seg, i, len; if( props ) { this.hideBorder(); segments = this.getBorderSegments( 2 ); for( i = 0, len = segments.length; i < len; i++) { seg = segments[i]; shape = this.getShape( 'borderPiece' + i, seg.stroke ? 'stroke' : 'fill', this.getBox() ); shape.coordsize = w * 2 + ',' + h * 2; shape.coordorigin = '1,1'; shape.path = seg.path; s = shape.style; s.width = w; s.height = h; shape.filled = !!seg.fill; shape.stroked = !!seg.stroke; if( seg.stroke ) { stroke = shape.stroke; stroke['weight'] = seg.weight + 'px'; stroke.color = seg.color.colorValue( el ); stroke['dashstyle'] = seg.stroke === 'dashed' ? '2 2' : seg.stroke === 'dotted' ? '1 1' : 'solid'; stroke['linestyle'] = seg.stroke === 'double' && seg.weight > 2 ? 'ThinThin' : 'Single'; } else { shape.fill.color = seg.fill.colorValue( el ); } } // remove any previously-created border shapes which didn't get used above while( this.deleteShape( 'borderPiece' + i++ ) ) {} } }, /** * Get the VML path definitions for the border segment(s). * @param {number=} mult If specified, all coordinates will be multiplied by this number * @return {Array.<string>} */ getBorderSegments: function( mult ) { var el = this.targetElement, bounds, elW, elH, borderInfo = this.styleInfos.borderInfo, segments = [], floor, ceil, wT, wR, wB, wL, round = Math.round, borderProps, radiusInfo, radii, widths, styles, colors; if( borderInfo.isActive() ) { borderProps = borderInfo.getProps(); widths = borderProps.widths; styles = borderProps.styles; colors = borderProps.colors; if( borderProps.widthsSame && borderProps.stylesSame && borderProps.colorsSame ) { if( colors['t'].alpha() > 0 ) { // shortcut for identical border on all sides - only need 1 stroked shape wT = widths['t'].pixels( el ); //thickness wR = wT / 2; //shrink segments.push( { path: this.getBoxPath( { t: wR, r: wR, b: wR, l: wR }, mult ), stroke: styles['t'], color: colors['t'], weight: wT } ); } } else { mult = mult || 1; bounds = this.boundsInfo.getBounds(); elW = bounds.w; elH = bounds.h; wT = round( widths['t'].pixels( el ) ); wR = round( widths['r'].pixels( el ) ); wB = round( widths['b'].pixels( el ) ); wL = round( widths['l'].pixels( el ) ); var pxWidths = { 't': wT, 'r': wR, 'b': wB, 'l': wL }; radiusInfo = this.styleInfos.borderRadiusInfo; if( radiusInfo.isActive() ) { radii = this.getRadiiPixels( radiusInfo.getProps() ); } floor = Math.floor; ceil = Math.ceil; function radius( xy, corner ) { return radii ? radii[ xy ][ corner ] : 0; } function curve( corner, shrinkX, shrinkY, startAngle, ccw, doMove ) { var rx = radius( 'x', corner), ry = radius( 'y', corner), deg = 65535, isRight = corner.charAt( 1 ) === 'r', isBottom = corner.charAt( 0 ) === 'b'; return ( rx > 0 && ry > 0 ) ? ( doMove ? 'al' : 'ae' ) + ( isRight ? ceil( elW - rx ) : floor( rx ) ) * mult + ',' + // center x ( isBottom ? ceil( elH - ry ) : floor( ry ) ) * mult + ',' + // center y ( floor( rx ) - shrinkX ) * mult + ',' + // width ( floor( ry ) - shrinkY ) * mult + ',' + // height ( startAngle * deg ) + ',' + // start angle ( 45 * deg * ( ccw ? 1 : -1 ) // angle change ) : ( ( doMove ? 'm' : 'l' ) + ( isRight ? elW - shrinkX : shrinkX ) * mult + ',' + ( isBottom ? elH - shrinkY : shrinkY ) * mult ); } function line( side, shrink, ccw, doMove ) { var start = ( side === 't' ? floor( radius( 'x', 'tl') ) * mult + ',' + ceil( shrink ) * mult : side === 'r' ? ceil( elW - shrink ) * mult + ',' + floor( radius( 'y', 'tr') ) * mult : side === 'b' ? ceil( elW - radius( 'x', 'br') ) * mult + ',' + floor( elH - shrink ) * mult : // side === 'l' ? floor( shrink ) * mult + ',' + ceil( elH - radius( 'y', 'bl') ) * mult ), end = ( side === 't' ? ceil( elW - radius( 'x', 'tr') ) * mult + ',' + ceil( shrink ) * mult : side === 'r' ? ceil( elW - shrink ) * mult + ',' + ceil( elH - radius( 'y', 'br') ) * mult : side === 'b' ? floor( radius( 'x', 'bl') ) * mult + ',' + floor( elH - shrink ) * mult : // side === 'l' ? floor( shrink ) * mult + ',' + floor( radius( 'y', 'tl') ) * mult ); return ccw ? ( doMove ? 'm' + end : '' ) + 'l' + start : ( doMove ? 'm' + start : '' ) + 'l' + end; } function addSide( side, sideBefore, sideAfter, cornerBefore, cornerAfter, baseAngle ) { var vert = side === 'l' || side === 'r', sideW = pxWidths[ side ], beforeX, beforeY, afterX, afterY; if( sideW > 0 && styles[ side ] !== 'none' && colors[ side ].alpha() > 0 ) { beforeX = pxWidths[ vert ? side : sideBefore ]; beforeY = pxWidths[ vert ? sideBefore : side ]; afterX = pxWidths[ vert ? side : sideAfter ]; afterY = pxWidths[ vert ? sideAfter : side ]; if( styles[ side ] === 'dashed' || styles[ side ] === 'dotted' ) { segments.push( { path: curve( cornerBefore, beforeX, beforeY, baseAngle + 45, 0, 1 ) + curve( cornerBefore, 0, 0, baseAngle, 1, 0 ), fill: colors[ side ] } ); segments.push( { path: line( side, sideW / 2, 0, 1 ), stroke: styles[ side ], weight: sideW, color: colors[ side ] } ); segments.push( { path: curve( cornerAfter, afterX, afterY, baseAngle, 0, 1 ) + curve( cornerAfter, 0, 0, baseAngle - 45, 1, 0 ), fill: colors[ side ] } ); } else { segments.push( { path: curve( cornerBefore, beforeX, beforeY, baseAngle + 45, 0, 1 ) + line( side, sideW, 0, 0 ) + curve( cornerAfter, afterX, afterY, baseAngle, 0, 0 ) + ( styles[ side ] === 'double' && sideW > 2 ? curve( cornerAfter, afterX - floor( afterX / 3 ), afterY - floor( afterY / 3 ), baseAngle - 45, 1, 0 ) + line( side, ceil( sideW / 3 * 2 ), 1, 0 ) + curve( cornerBefore, beforeX - floor( beforeX / 3 ), beforeY - floor( beforeY / 3 ), baseAngle, 1, 0 ) + 'x ' + curve( cornerBefore, floor( beforeX / 3 ), floor( beforeY / 3 ), baseAngle + 45, 0, 1 ) + line( side, floor( sideW / 3 ), 1, 0 ) + curve( cornerAfter, floor( afterX / 3 ), floor( afterY / 3 ), baseAngle, 0, 0 ) : '' ) + curve( cornerAfter, 0, 0, baseAngle - 45, 1, 0 ) + line( side, 0, 1, 0 ) + curve( cornerBefore, 0, 0, baseAngle, 1, 0 ), fill: colors[ side ] } ); } } } addSide( 't', 'l', 'r', 'tl', 'tr', 90 ); addSide( 'r', 't', 'b', 'tr', 'br', 0 ); addSide( 'b', 'r', 'l', 'br', 'bl', -90 ); addSide( 'l', 'b', 't', 'bl', 'tl', -180 ); } } return segments; }, destroy: function() { var me = this; if (me.finalized || !me.styleInfos.borderImageInfo.isActive()) { me.targetElement.runtimeStyle.borderColor = ''; } PIE.RendererBase.destroy.call( me ); } } ); /** * Renderer for border-image * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BorderImageRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 5, pieceNames: [ 't', 'tr', 'r', 'br', 'b', 'bl', 'l', 'tl', 'c' ], needsUpdate: function() { return this.styleInfos.borderImageInfo.changed(); }, isActive: function() { return this.styleInfos.borderImageInfo.isActive(); }, draw: function() { this.getBox(); //make sure pieces are created var props = this.styleInfos.borderImageInfo.getProps(), borderProps = this.styleInfos.borderInfo.getProps(), bounds = this.boundsInfo.getBounds(), el = this.targetElement, pieces = this.pieces; PIE.Util.withImageSize( props.src, function( imgSize ) { var elW = bounds.w, elH = bounds.h, zero = PIE.getLength( '0' ), widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ), widthT = widths['t'].pixels( el ), widthR = widths['r'].pixels( el ), widthB = widths['b'].pixels( el ), widthL = widths['l'].pixels( el ), slices = props.slice, sliceT = slices['t'].pixels( el ), sliceR = slices['r'].pixels( el ), sliceB = slices['b'].pixels( el ), sliceL = slices['l'].pixels( el ); // Piece positions and sizes function setSizeAndPos( piece, w, h, x, y ) { var s = pieces[piece].style, max = Math.max; s.width = max(w, 0); s.height = max(h, 0); s.left = x; s.top = y; } setSizeAndPos( 'tl', widthL, widthT, 0, 0 ); setSizeAndPos( 't', elW - widthL - widthR, widthT, widthL, 0 ); setSizeAndPos( 'tr', widthR, widthT, elW - widthR, 0 ); setSizeAndPos( 'r', widthR, elH - widthT - widthB, elW - widthR, widthT ); setSizeAndPos( 'br', widthR, widthB, elW - widthR, elH - widthB ); setSizeAndPos( 'b', elW - widthL - widthR, widthB, widthL, elH - widthB ); setSizeAndPos( 'bl', widthL, widthB, 0, elH - widthB ); setSizeAndPos( 'l', widthL, elH - widthT - widthB, 0, widthT ); setSizeAndPos( 'c', elW - widthL - widthR, elH - widthT - widthB, widthL, widthT ); // image croppings function setCrops( sides, crop, val ) { for( var i=0, len=sides.length; i < len; i++ ) { pieces[ sides[i] ]['imagedata'][ crop ] = val; } } // corners setCrops( [ 'tl', 't', 'tr' ], 'cropBottom', ( imgSize.h - sliceT ) / imgSize.h ); setCrops( [ 'tl', 'l', 'bl' ], 'cropRight', ( imgSize.w - sliceL ) / imgSize.w ); setCrops( [ 'bl', 'b', 'br' ], 'cropTop', ( imgSize.h - sliceB ) / imgSize.h ); setCrops( [ 'tr', 'r', 'br' ], 'cropLeft', ( imgSize.w - sliceR ) / imgSize.w ); // edges and center // TODO right now this treats everything like 'stretch', need to support other schemes //if( props.repeat.v === 'stretch' ) { setCrops( [ 'l', 'r', 'c' ], 'cropTop', sliceT / imgSize.h ); setCrops( [ 'l', 'r', 'c' ], 'cropBottom', sliceB / imgSize.h ); //} //if( props.repeat.h === 'stretch' ) { setCrops( [ 't', 'b', 'c' ], 'cropLeft', sliceL / imgSize.w ); setCrops( [ 't', 'b', 'c' ], 'cropRight', sliceR / imgSize.w ); //} // center fill pieces['c'].style.display = props.fill ? '' : 'none'; }, this ); }, getBox: function() { var box = this.parent.getLayer( this.boxZIndex ), s, piece, i, pieceNames = this.pieceNames, len = pieceNames.length; if( !box ) { box = doc.createElement( 'border-image' ); s = box.style; s.position = 'absolute'; this.pieces = {}; for( i = 0; i < len; i++ ) { piece = this.pieces[ pieceNames[i] ] = PIE.Util.createVmlElement( 'rect' ); piece.appendChild( PIE.Util.createVmlElement( 'imagedata' ) ); s = piece.style; s['behavior'] = 'url(#default#VML)'; s.position = "absolute"; s.top = s.left = 0; piece['imagedata'].src = this.styleInfos.borderImageInfo.getProps().src; piece.stroked = false; piece.filled = false; box.appendChild( piece ); } this.parent.addLayer( this.boxZIndex, box ); } return box; }, prepareUpdate: function() { if (this.isActive()) { var me = this, el = me.targetElement, rs = el.runtimeStyle, widths = me.styleInfos.borderImageInfo.getProps().widths; // Force border-style to solid so it doesn't collapse rs.borderStyle = 'solid'; // If widths specified in border-image shorthand, override border-width // NOTE px units needed here as this gets used by the IE9 renderer too if ( widths ) { rs.borderTopWidth = widths['t'].pixels( el ) + 'px'; rs.borderRightWidth = widths['r'].pixels( el ) + 'px'; rs.borderBottomWidth = widths['b'].pixels( el ) + 'px'; rs.borderLeftWidth = widths['l'].pixels( el ) + 'px'; } // Make the border transparent me.hideBorder(); } }, destroy: function() { var me = this, rs = me.targetElement.runtimeStyle; rs.borderStyle = ''; if (me.finalized || !me.styleInfos.borderInfo.isActive()) { rs.borderColor = rs.borderWidth = ''; } PIE.RendererBase.destroy.call( this ); } } ); /** * Renderer for outset box-shadows * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BoxShadowOutsetRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 1, boxName: 'outset-box-shadow', needsUpdate: function() { var si = this.styleInfos; return si.boxShadowInfo.changed() || si.borderRadiusInfo.changed(); }, isActive: function() { var boxShadowInfo = this.styleInfos.boxShadowInfo; return boxShadowInfo.isActive() && boxShadowInfo.getProps().outset[0]; }, draw: function() { var me = this, el = this.targetElement, box = this.getBox(), styleInfos = this.styleInfos, shadowInfos = styleInfos.boxShadowInfo.getProps().outset, radii = styleInfos.borderRadiusInfo.getProps(), len = shadowInfos.length, i = len, j, bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, clipAdjust = PIE.ieVersion === 8 ? 1 : 0, //workaround for IE8 bug where VML leaks out top/left of clip region by 1px corners = [ 'tl', 'tr', 'br', 'bl' ], corner, shadowInfo, shape, fill, ss, xOff, yOff, spread, blur, shrink, color, alpha, path, totalW, totalH, focusX, focusY, isBottom, isRight; function getShadowShape( index, corner, xOff, yOff, color, blur, path ) { var shape = me.getShape( 'shadow' + index + corner, 'fill', box, len - index ), fill = shape.fill; // Position and size shape['coordsize'] = w * 2 + ',' + h * 2; shape['coordorigin'] = '1,1'; // Color and opacity shape['stroked'] = false; shape['filled'] = true; fill.color = color.colorValue( el ); if( blur ) { fill['type'] = 'gradienttitle'; //makes the VML gradient follow the shape's outline - hooray for undocumented features?!?! fill['color2'] = fill.color; fill['opacity'] = 0; } // Path shape.path = path; // This needs to go last for some reason, to prevent rendering at incorrect size ss = shape.style; ss.left = xOff; ss.top = yOff; ss.width = w; ss.height = h; return shape; } while( i-- ) { shadowInfo = shadowInfos[ i ]; xOff = shadowInfo.xOffset.pixels( el ); yOff = shadowInfo.yOffset.pixels( el ); spread = shadowInfo.spread.pixels( el ); blur = shadowInfo.blur.pixels( el ); color = shadowInfo.color; // Shape path shrink = -spread - blur; if( !radii && blur ) { // If blurring, use a non-null border radius info object so that getBoxPath will // round the corners of the expanded shadow shape rather than squaring them off. radii = PIE.BorderRadiusStyleInfo.ALL_ZERO; } path = this.getBoxPath( { t: shrink, r: shrink, b: shrink, l: shrink }, 2, radii ); if( blur ) { totalW = ( spread + blur ) * 2 + w; totalH = ( spread + blur ) * 2 + h; focusX = totalW ? blur * 2 / totalW : 0; focusY = totalH ? blur * 2 / totalH : 0; if( blur - spread > w / 2 || blur - spread > h / 2 ) { // If the blur is larger than half the element's narrowest dimension, we cannot do // this with a single shape gradient, because its focussize would have to be less than // zero which results in ugly artifacts. Instead we create four shapes, each with its // gradient focus past center, and then clip them so each only shows the quadrant // opposite the focus. for( j = 4; j--; ) { corner = corners[j]; isBottom = corner.charAt( 0 ) === 'b'; isRight = corner.charAt( 1 ) === 'r'; shape = getShadowShape( i, corner, xOff, yOff, color, blur, path ); fill = shape.fill; fill['focusposition'] = ( isRight ? 1 - focusX : focusX ) + ',' + ( isBottom ? 1 - focusY : focusY ); fill['focussize'] = '0,0'; // Clip to show only the appropriate quadrant. Add 1px to the top/left clip values // in IE8 to prevent a bug where IE8 displays one pixel outside the clip region. shape.style.clip = 'rect(' + ( ( isBottom ? totalH / 2 : 0 ) + clipAdjust ) + 'px,' + ( isRight ? totalW : totalW / 2 ) + 'px,' + ( isBottom ? totalH : totalH / 2 ) + 'px,' + ( ( isRight ? totalW / 2 : 0 ) + clipAdjust ) + 'px)'; } } else { // TODO delete old quadrant shapes if resizing expands past the barrier shape = getShadowShape( i, '', xOff, yOff, color, blur, path ); fill = shape.fill; fill['focusposition'] = focusX + ',' + focusY; fill['focussize'] = ( 1 - focusX * 2 ) + ',' + ( 1 - focusY * 2 ); } } else { shape = getShadowShape( i, '', xOff, yOff, color, blur, path ); alpha = color.alpha(); if( alpha < 1 ) { // shape.style.filter = 'alpha(opacity=' + ( alpha * 100 ) + ')'; // ss.filter = 'progid:DXImageTransform.Microsoft.BasicImage(opacity=' + ( alpha ) + ')'; shape.fill.opacity = alpha; } } } } } ); /** * Renderer for re-rendering img elements using VML. Kicks in if the img has * a border-radius applied, or if the -pie-png-fix flag is set. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.ImgRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 6, boxName: 'imgEl', needsUpdate: function() { var si = this.styleInfos; return this.targetElement.src !== this._lastSrc || si.borderRadiusInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.borderRadiusInfo.isActive() || si.backgroundInfo.isPngFix(); }, draw: function() { this._lastSrc = src; this.hideActualImg(); var shape = this.getShape( 'img', 'fill', this.getBox() ), fill = shape.fill, bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, borderProps = this.styleInfos.borderInfo.getProps(), borderWidths = borderProps && borderProps.widths, el = this.targetElement, src = el.src, round = Math.round, cs = el.currentStyle, getLength = PIE.getLength, s, zero; // In IE6, the BorderRenderer will have hidden the border by moving the border-width to // the padding; therefore we want to pretend the borders have no width so they aren't doubled // when adding in the current padding value below. if( !borderWidths || PIE.ieVersion < 7 ) { zero = PIE.getLength( '0' ); borderWidths = { 't': zero, 'r': zero, 'b': zero, 'l': zero }; } shape.stroked = false; fill.type = 'frame'; fill.src = src; fill.position = (w ? 0.5 / w : 0) + ',' + (h ? 0.5 / h : 0); shape.coordsize = w * 2 + ',' + h * 2; shape.coordorigin = '1,1'; shape.path = this.getBoxPath( { t: round( borderWidths['t'].pixels( el ) + getLength( cs.paddingTop ).pixels( el ) ), r: round( borderWidths['r'].pixels( el ) + getLength( cs.paddingRight ).pixels( el ) ), b: round( borderWidths['b'].pixels( el ) + getLength( cs.paddingBottom ).pixels( el ) ), l: round( borderWidths['l'].pixels( el ) + getLength( cs.paddingLeft ).pixels( el ) ) }, 2 ); s = shape.style; s.width = w; s.height = h; }, hideActualImg: function() { this.targetElement.runtimeStyle.filter = 'alpha(opacity=0)'; }, destroy: function() { PIE.RendererBase.destroy.call( this ); this.targetElement.runtimeStyle.filter = ''; } } ); /** * Root renderer for IE9; manages the rendering layers in the element's background * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects */ PIE.IE9RootRenderer = PIE.RendererBase.newRenderer( { updatePos: PIE.emptyFn, updateSize: PIE.emptyFn, updateVisibility: PIE.emptyFn, updateProps: PIE.emptyFn, outerCommasRE: /^,+|,+$/g, innerCommasRE: /,+/g, setBackgroundLayer: function(zIndex, bg) { var me = this, bgLayers = me._bgLayers || ( me._bgLayers = [] ), undef; bgLayers[zIndex] = bg || undef; }, finishUpdate: function() { var me = this, bgLayers = me._bgLayers, bg; if( bgLayers && ( bg = bgLayers.join( ',' ).replace( me.outerCommasRE, '' ).replace( me.innerCommasRE, ',' ) ) !== me._lastBg ) { me._lastBg = me.targetElement.runtimeStyle.background = bg; } }, destroy: function() { this.targetElement.runtimeStyle.background = ''; delete this._bgLayers; } } ); /** * Renderer for element backgrounds, specific for IE9. Only handles translating CSS3 gradients * to an equivalent SVG data URI. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects */ PIE.IE9BackgroundRenderer = PIE.RendererBase.newRenderer( { bgLayerZIndex: 1, needsUpdate: function() { var si = this.styleInfos; return si.backgroundInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.backgroundInfo.isActive() || si.borderImageInfo.isActive(); }, draw: function() { var me = this, props = me.styleInfos.backgroundInfo.getProps(), bg, images, i = 0, img, bgAreaSize, bgSize; if ( props ) { bg = []; images = props.bgImages; if ( images ) { while( img = images[ i++ ] ) { if (img.imgType === 'linear-gradient' ) { bgAreaSize = me.getBgAreaSize( img.bgOrigin ); bgSize = ( img.bgSize || PIE.BgSize.DEFAULT ).pixels( me.targetElement, bgAreaSize.w, bgAreaSize.h, bgAreaSize.w, bgAreaSize.h ), bg.push( 'url(data:image/svg+xml,' + escape( me.getGradientSvg( img, bgSize.w, bgSize.h ) ) + ') ' + me.bgPositionToString( img.bgPosition ) + ' / ' + bgSize.w + 'px ' + bgSize.h + 'px ' + ( img.bgAttachment || '' ) + ' ' + ( img.bgOrigin || '' ) + ' ' + ( img.bgClip || '' ) ); } else { bg.push( img.origString ); } } } if ( props.color ) { bg.push( props.color.val ); } me.parent.setBackgroundLayer(me.bgLayerZIndex, bg.join(',')); } }, bgPositionToString: function( bgPosition ) { return bgPosition ? bgPosition.tokens.map(function(token) { return token.tokenValue; }).join(' ') : '0 0'; }, getBgAreaSize: function( bgOrigin ) { var me = this, el = me.targetElement, bounds = me.boundsInfo.getBounds(), elW = bounds.w, elH = bounds.h, w = elW, h = elH, borders, getLength, cs; if( bgOrigin !== 'border-box' ) { borders = me.styleInfos.borderInfo.getProps(); if( borders && ( borders = borders.widths ) ) { w -= borders[ 'l' ].pixels( el ) + borders[ 'l' ].pixels( el ); h -= borders[ 't' ].pixels( el ) + borders[ 'b' ].pixels( el ); } } if ( bgOrigin === 'content-box' ) { getLength = PIE.getLength; cs = el.currentStyle; w -= getLength( cs.paddingLeft ).pixels( el ) + getLength( cs.paddingRight ).pixels( el ); h -= getLength( cs.paddingTop ).pixels( el ) + getLength( cs.paddingBottom ).pixels( el ); } return { w: w, h: h }; }, getGradientSvg: function( info, bgWidth, bgHeight ) { var el = this.targetElement, stopsInfo = info.stops, stopCount = stopsInfo.length, metrics = PIE.GradientUtil.getGradientMetrics( el, bgWidth, bgHeight, info ), startX = metrics.startX, startY = metrics.startY, endX = metrics.endX, endY = metrics.endY, lineLength = metrics.lineLength, stopPx, i, j, before, after, svg; // Find the pixel offsets along the CSS3 gradient-line for each stop. stopPx = []; for( i = 0; i < stopCount; i++ ) { stopPx.push( stopsInfo[i].offset ? stopsInfo[i].offset.pixels( el, lineLength ) : i === 0 ? 0 : i === stopCount - 1 ? lineLength : null ); } // Fill in gaps with evenly-spaced offsets for( i = 1; i < stopCount; i++ ) { if( stopPx[ i ] === null ) { before = stopPx[ i - 1 ]; j = i; do { after = stopPx[ ++j ]; } while( after === null ); stopPx[ i ] = before + ( after - before ) / ( j - i + 1 ); } } svg = [ '<svg width="' + bgWidth + '" height="' + bgHeight + '" xmlns="http://www.w3.org/2000/svg">' + '<defs>' + '<linearGradient id="g" gradientUnits="userSpaceOnUse"' + ' x1="' + ( startX / bgWidth * 100 ) + '%" y1="' + ( startY / bgHeight * 100 ) + '%" x2="' + ( endX / bgWidth * 100 ) + '%" y2="' + ( endY / bgHeight * 100 ) + '%">' ]; // Convert to percentage along the SVG gradient line and add to the stops list for( i = 0; i < stopCount; i++ ) { svg.push( '<stop offset="' + ( stopPx[ i ] / lineLength ) + '" stop-color="' + stopsInfo[i].color.colorValue( el ) + '" stop-opacity="' + stopsInfo[i].color.alpha() + '"/>' ); } svg.push( '</linearGradient>' + '</defs>' + '<rect width="100%" height="100%" fill="url(#g)"/>' + '</svg>' ); return svg.join( '' ); }, destroy: function() { this.parent.setBackgroundLayer( this.bgLayerZIndex ); } } ); /** * Renderer for border-image * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.IE9BorderImageRenderer = PIE.RendererBase.newRenderer( { REPEAT: 'repeat', STRETCH: 'stretch', ROUND: 'round', bgLayerZIndex: 0, needsUpdate: function() { return this.styleInfos.borderImageInfo.changed(); }, isActive: function() { return this.styleInfos.borderImageInfo.isActive(); }, draw: function() { var me = this, props = me.styleInfos.borderImageInfo.getProps(), borderProps = me.styleInfos.borderInfo.getProps(), bounds = me.boundsInfo.getBounds(), repeat = props.repeat, repeatH = repeat.h, repeatV = repeat.v, el = me.targetElement, isAsync = 0; PIE.Util.withImageSize( props.src, function( imgSize ) { var elW = bounds.w, elH = bounds.h, imgW = imgSize.w, imgH = imgSize.h, // The image cannot be referenced as a URL directly in the SVG because IE9 throws a strange // security exception (perhaps due to cross-origin policy within data URIs?) Therefore we // work around this by converting the image data into a data URI itself using a transient // canvas. This unfortunately requires the border-image src to be within the same domain, // which isn't a limitation in true border-image, so we need to try and find a better fix. imgSrc = me.imageToDataURI( props.src, imgW, imgH ), REPEAT = me.REPEAT, STRETCH = me.STRETCH, ROUND = me.ROUND, ceil = Math.ceil, zero = PIE.getLength( '0' ), widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ), widthT = widths['t'].pixels( el ), widthR = widths['r'].pixels( el ), widthB = widths['b'].pixels( el ), widthL = widths['l'].pixels( el ), slices = props.slice, sliceT = slices['t'].pixels( el ), sliceR = slices['r'].pixels( el ), sliceB = slices['b'].pixels( el ), sliceL = slices['l'].pixels( el ), centerW = elW - widthL - widthR, middleH = elH - widthT - widthB, imgCenterW = imgW - sliceL - sliceR, imgMiddleH = imgH - sliceT - sliceB, // Determine the size of each tile - 'round' is handled below tileSizeT = repeatH === STRETCH ? centerW : imgCenterW * widthT / sliceT, tileSizeR = repeatV === STRETCH ? middleH : imgMiddleH * widthR / sliceR, tileSizeB = repeatH === STRETCH ? centerW : imgCenterW * widthB / sliceB, tileSizeL = repeatV === STRETCH ? middleH : imgMiddleH * widthL / sliceL, svg, patterns = [], rects = [], i = 0; // For 'round', subtract from each tile's size enough so that they fill the space a whole number of times if (repeatH === ROUND) { tileSizeT -= (tileSizeT - (centerW % tileSizeT || tileSizeT)) / ceil(centerW / tileSizeT); tileSizeB -= (tileSizeB - (centerW % tileSizeB || tileSizeB)) / ceil(centerW / tileSizeB); } if (repeatV === ROUND) { tileSizeR -= (tileSizeR - (middleH % tileSizeR || tileSizeR)) / ceil(middleH / tileSizeR); tileSizeL -= (tileSizeL - (middleH % tileSizeL || tileSizeL)) / ceil(middleH / tileSizeL); } // Build the SVG for the border-image rendering. Add each piece as a pattern, which is then stretched // or repeated as the fill of a rect of appropriate size. svg = [ '<svg width="' + elW + '" height="' + elH + '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">' ]; function addImage( x, y, w, h, cropX, cropY, cropW, cropH, tileW, tileH ) { patterns.push( '<pattern patternUnits="userSpaceOnUse" id="pattern' + i + '" ' + 'x="' + (repeatH === REPEAT ? x + w / 2 - tileW / 2 : x) + '" ' + 'y="' + (repeatV === REPEAT ? y + h / 2 - tileH / 2 : y) + '" ' + 'width="' + tileW + '" height="' + tileH + '">' + '<svg width="' + tileW + '" height="' + tileH + '" viewBox="' + cropX + ' ' + cropY + ' ' + cropW + ' ' + cropH + '" preserveAspectRatio="none">' + '<image xlink:href="' + imgSrc + '" x="0" y="0" width="' + imgW + '" height="' + imgH + '" />' + '</svg>' + '</pattern>' ); rects.push( '<rect x="' + x + '" y="' + y + '" width="' + w + '" height="' + h + '" fill="url(#pattern' + i + ')" />' ); i++; } addImage( 0, 0, widthL, widthT, 0, 0, sliceL, sliceT, widthL, widthT ); // top left addImage( widthL, 0, centerW, widthT, sliceL, 0, imgCenterW, sliceT, tileSizeT, widthT ); // top center addImage( elW - widthR, 0, widthR, widthT, imgW - sliceR, 0, sliceR, sliceT, widthR, widthT ); // top right addImage( 0, widthT, widthL, middleH, 0, sliceT, sliceL, imgMiddleH, widthL, tileSizeL ); // middle left if ( props.fill ) { // center fill addImage( widthL, widthT, centerW, middleH, sliceL, sliceT, imgCenterW, imgMiddleH, tileSizeT || tileSizeB || imgCenterW, tileSizeL || tileSizeR || imgMiddleH ); } addImage( elW - widthR, widthT, widthR, middleH, imgW - sliceR, sliceT, sliceR, imgMiddleH, widthR, tileSizeR ); // middle right addImage( 0, elH - widthB, widthL, widthB, 0, imgH - sliceB, sliceL, sliceB, widthL, widthB ); // bottom left addImage( widthL, elH - widthB, centerW, widthB, sliceL, imgH - sliceB, imgCenterW, sliceB, tileSizeB, widthB ); // bottom center addImage( elW - widthR, elH - widthB, widthR, widthB, imgW - sliceR, imgH - sliceB, sliceR, sliceB, widthR, widthB ); // bottom right svg.push( '<defs>' + patterns.join('\n') + '</defs>' + rects.join('\n') + '</svg>' ); me.parent.setBackgroundLayer( me.bgLayerZIndex, 'url(data:image/svg+xml,' + escape( svg.join( '' ) ) + ') no-repeat border-box border-box' ); // If the border-image's src wasn't immediately available, the SVG for its background layer // will have been created asynchronously after the main element's update has finished; we'll // therefore need to force the root renderer to sync to the final background once finished. if( isAsync ) { me.parent.finishUpdate(); } }, me ); isAsync = 1; }, /** * Convert a given image to a data URI */ imageToDataURI: (function() { var uris = {}; return function( src, width, height ) { var uri = uris[ src ], image, canvas; if ( !uri ) { image = new Image(); canvas = doc.createElement( 'canvas' ); image.src = src; canvas.width = width; canvas.height = height; canvas.getContext( '2d' ).drawImage( image, 0, 0 ); uri = uris[ src ] = canvas.toDataURL(); } return uri; } })(), prepareUpdate: PIE.BorderImageRenderer.prototype.prepareUpdate, destroy: function() { var me = this, rs = me.targetElement.runtimeStyle; me.parent.setBackgroundLayer( me.bgLayerZIndex ); rs.borderColor = rs.borderStyle = rs.borderWidth = ''; } } ); PIE.Element = (function() { var wrappers = {}, lazyInitCssProp = PIE.CSS_PREFIX + 'lazy-init', pollCssProp = PIE.CSS_PREFIX + 'poll', trackActiveCssProp = PIE.CSS_PREFIX + 'track-active', trackHoverCssProp = PIE.CSS_PREFIX + 'track-hover', hoverClass = PIE.CLASS_PREFIX + 'hover', activeClass = PIE.CLASS_PREFIX + 'active', focusClass = PIE.CLASS_PREFIX + 'focus', firstChildClass = PIE.CLASS_PREFIX + 'first-child', ignorePropertyNames = { 'background':1, 'bgColor':1, 'display': 1 }, classNameRegExes = {}, dummyArray = []; function addClass( el, className ) { el.className += ' ' + className; } function removeClass( el, className ) { var re = classNameRegExes[ className ] || ( classNameRegExes[ className ] = new RegExp( '\\b' + className + '\\b', 'g' ) ); el.className = el.className.replace( re, '' ); } function delayAddClass( el, className /*, className2*/ ) { var classes = dummyArray.slice.call( arguments, 1 ), i = classes.length; setTimeout( function() { if( el ) { while( i-- ) { addClass( el, classes[ i ] ); } } }, 0 ); } function delayRemoveClass( el, className /*, className2*/ ) { var classes = dummyArray.slice.call( arguments, 1 ), i = classes.length; setTimeout( function() { if( el ) { while( i-- ) { removeClass( el, classes[ i ] ); } } }, 0 ); } function Element( el ) { var renderers, rootRenderer, boundsInfo = new PIE.BoundsInfo( el ), styleInfos, styleInfosArr, initializing, initialized, eventsAttached, eventListeners = [], delayed, destroyed, poll; /** * Initialize PIE for this element. */ function init() { if( !initialized ) { var docEl, bounds, ieDocMode = PIE.ieDocMode, cs = el.currentStyle, lazy = cs.getAttribute( lazyInitCssProp ) === 'true', trackActive = cs.getAttribute( trackActiveCssProp ) !== 'false', trackHover = cs.getAttribute( trackHoverCssProp ) !== 'false', childRenderers; // Polling for size/position changes: default to on in IE8, off otherwise, overridable by -pie-poll poll = cs.getAttribute( pollCssProp ); poll = ieDocMode > 7 ? poll !== 'false' : poll === 'true'; // Force layout so move/resize events will fire. Set this as soon as possible to avoid layout changes // after load, but make sure it only gets called the first time through to avoid recursive calls to init(). if( !initializing ) { initializing = 1; el.runtimeStyle.zoom = 1; initFirstChildPseudoClass(); } boundsInfo.lock(); // If the -pie-lazy-init:true flag is set, check if the element is outside the viewport and if so, delay initialization if( lazy && ( bounds = boundsInfo.getBounds() ) && ( docEl = doc.documentElement || doc.body ) && ( bounds.y > docEl.clientHeight || bounds.x > docEl.clientWidth || bounds.y + bounds.h < 0 || bounds.x + bounds.w < 0 ) ) { if( !delayed ) { delayed = 1; PIE.OnScroll.observe( init ); } } else { initialized = 1; delayed = initializing = 0; PIE.OnScroll.unobserve( init ); // Create the style infos and renderers if ( ieDocMode === 9 ) { styleInfos = { backgroundInfo: new PIE.BackgroundStyleInfo( el ), borderImageInfo: new PIE.BorderImageStyleInfo( el ), borderInfo: new PIE.BorderStyleInfo( el ) }; styleInfosArr = [ styleInfos.backgroundInfo, styleInfos.borderImageInfo ]; rootRenderer = new PIE.IE9RootRenderer( el, boundsInfo, styleInfos ); childRenderers = [ new PIE.IE9BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.IE9BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer ) ]; } else { styleInfos = { backgroundInfo: new PIE.BackgroundStyleInfo( el ), borderInfo: new PIE.BorderStyleInfo( el ), borderImageInfo: new PIE.BorderImageStyleInfo( el ), borderRadiusInfo: new PIE.BorderRadiusStyleInfo( el ), boxShadowInfo: new PIE.BoxShadowStyleInfo( el ), visibilityInfo: new PIE.VisibilityStyleInfo( el ) }; styleInfosArr = [ styleInfos.backgroundInfo, styleInfos.borderInfo, styleInfos.borderImageInfo, styleInfos.borderRadiusInfo, styleInfos.boxShadowInfo, styleInfos.visibilityInfo ]; rootRenderer = new PIE.RootRenderer( el, boundsInfo, styleInfos ); childRenderers = [ new PIE.BoxShadowOutsetRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ), //new PIE.BoxShadowInsetRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.BorderRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer ) ]; if( el.tagName === 'IMG' ) { childRenderers.push( new PIE.ImgRenderer( el, boundsInfo, styleInfos, rootRenderer ) ); } rootRenderer.childRenderers = childRenderers; // circular reference, can't pass in constructor; TODO is there a cleaner way? } renderers = [ rootRenderer ].concat( childRenderers ); // Add property change listeners to ancestors if requested initAncestorEventListeners(); // Add to list of polled elements in IE8 if( poll ) { PIE.Heartbeat.observe( update ); PIE.Heartbeat.run(); } // Trigger rendering update( 1 ); } if( !eventsAttached ) { eventsAttached = 1; if( ieDocMode < 9 ) { addListener( el, 'onmove', handleMoveOrResize ); } addListener( el, 'onresize', handleMoveOrResize ); addListener( el, 'onpropertychange', propChanged ); if( trackHover ) { addListener( el, 'onmouseenter', mouseEntered ); } if( trackHover || trackActive ) { addListener( el, 'onmouseleave', mouseLeft ); } if( trackActive ) { addListener( el, 'onmousedown', mousePressed ); } if( el.tagName in PIE.focusableElements ) { addListener( el, 'onfocus', focused ); addListener( el, 'onblur', blurred ); } PIE.OnResize.observe( handleMoveOrResize ); PIE.OnUnload.observe( removeEventListeners ); } boundsInfo.unlock(); } } /** * Event handler for onmove and onresize events. Invokes update() only if the element's * bounds have previously been calculated, to prevent multiple runs during page load when * the element has no initial CSS3 properties. */ function handleMoveOrResize() { if( boundsInfo && boundsInfo.hasBeenQueried() ) { update(); } } /** * Update position and/or size as necessary. Both move and resize events call * this rather than the updatePos/Size functions because sometimes, particularly * during page load, one will fire but the other won't. */ function update( force ) { if( !destroyed ) { if( initialized ) { var i, len = renderers.length; lockAll(); for( i = 0; i < len; i++ ) { renderers[i].prepareUpdate(); } if( force || boundsInfo.positionChanged() ) { /* TODO just using getBoundingClientRect (used internally by BoundsInfo) for detecting position changes may not always be accurate; it's possible that an element will actually move relative to its positioning parent, but its position relative to the viewport will stay the same. Need to come up with a better way to track movement. The most accurate would be the same logic used in RootRenderer.updatePos() but that is a more expensive operation since it does some DOM walking, and we want this check to be as fast as possible. */ for( i = 0; i < len; i++ ) { renderers[i].updatePos(); } } if( force || boundsInfo.sizeChanged() ) { for( i = 0; i < len; i++ ) { renderers[i].updateSize(); } } rootRenderer.finishUpdate(); unlockAll(); } else if( !initializing ) { init(); } } } /** * Handle property changes to trigger update when appropriate. */ function propChanged() { var i, len = renderers.length, renderer, e = event; // Some elements like <table> fire onpropertychange events for old-school background properties // ('background', 'bgColor') when runtimeStyle background properties are changed, which // results in an infinite loop; therefore we filter out those property names. Also, 'display' // is ignored because size calculations don't work correctly immediately when its onpropertychange // event fires, and because it will trigger an onresize event anyway. if( !destroyed && !( e && e.propertyName in ignorePropertyNames ) ) { if( initialized ) { lockAll(); for( i = 0; i < len; i++ ) { renderers[i].prepareUpdate(); } for( i = 0; i < len; i++ ) { renderer = renderers[i]; // Make sure position is synced if the element hasn't already been rendered. // TODO this feels sloppy - look into merging propChanged and update functions if( !renderer.isPositioned ) { renderer.updatePos(); } if( renderer.needsUpdate() ) { renderer.updateProps(); } } rootRenderer.finishUpdate(); unlockAll(); } else if( !initializing ) { init(); } } } /** * Handle mouseenter events. Adds a custom class to the element to allow IE6 to add * hover styles to non-link elements, and to trigger a propertychange update. */ function mouseEntered() { //must delay this because the mouseenter event fires before the :hover styles are added. delayAddClass( el, hoverClass ); } /** * Handle mouseleave events */ function mouseLeft() { //must delay this because the mouseleave event fires before the :hover styles are removed. delayRemoveClass( el, hoverClass, activeClass ); } /** * Handle mousedown events. Adds a custom class to the element to allow IE6 to add * active styles to non-link elements, and to trigger a propertychange update. */ function mousePressed() { //must delay this because the mousedown event fires before the :active styles are added. delayAddClass( el, activeClass ); // listen for mouseups on the document; can't just be on the element because the user might // have dragged out of the element while the mouse button was held down PIE.OnMouseup.observe( mouseReleased ); } /** * Handle mouseup events */ function mouseReleased() { //must delay this because the mouseup event fires before the :active styles are removed. delayRemoveClass( el, activeClass ); PIE.OnMouseup.unobserve( mouseReleased ); } /** * Handle focus events. Adds a custom class to the element to trigger a propertychange update. */ function focused() { //must delay this because the focus event fires before the :focus styles are added. delayAddClass( el, focusClass ); } /** * Handle blur events */ function blurred() { //must delay this because the blur event fires before the :focus styles are removed. delayRemoveClass( el, focusClass ); } /** * Handle property changes on ancestors of the element; see initAncestorEventListeners() * which adds these listeners as requested with the -pie-watch-ancestors CSS property. */ function ancestorPropChanged() { var name = event.propertyName; if( name === 'className' || name === 'id' ) { propChanged(); } } function lockAll() { boundsInfo.lock(); for( var i = styleInfosArr.length; i--; ) { styleInfosArr[i].lock(); } } function unlockAll() { for( var i = styleInfosArr.length; i--; ) { styleInfosArr[i].unlock(); } boundsInfo.unlock(); } function addListener( targetEl, type, handler ) { targetEl.attachEvent( type, handler ); eventListeners.push( [ targetEl, type, handler ] ); } /** * Remove all event listeners from the element and any monitored ancestors. */ function removeEventListeners() { if (eventsAttached) { var i = eventListeners.length, listener; while( i-- ) { listener = eventListeners[ i ]; listener[ 0 ].detachEvent( listener[ 1 ], listener[ 2 ] ); } PIE.OnUnload.unobserve( removeEventListeners ); eventsAttached = 0; eventListeners = []; } } /** * Clean everything up when the behavior is removed from the element, or the element * is manually destroyed. */ function destroy() { if( !destroyed ) { var i, len; removeEventListeners(); destroyed = 1; // destroy any active renderers if( renderers ) { for( i = 0, len = renderers.length; i < len; i++ ) { renderers[i].finalized = 1; renderers[i].destroy(); } } // Remove from list of polled elements in IE8 if( poll ) { PIE.Heartbeat.unobserve( update ); } // Stop onresize listening PIE.OnResize.unobserve( update ); // Kill references renderers = boundsInfo = styleInfos = styleInfosArr = el = null; } } /** * If requested via the custom -pie-watch-ancestors CSS property, add onpropertychange and * other event listeners to ancestor(s) of the element so we can pick up style changes * based on CSS rules using descendant selectors. */ function initAncestorEventListeners() { var watch = el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'watch-ancestors' ), i, a; if( watch ) { watch = parseInt( watch, 10 ); i = 0; a = el.parentNode; while( a && ( watch === 'NaN' || i++ < watch ) ) { addListener( a, 'onpropertychange', ancestorPropChanged ); addListener( a, 'onmouseenter', mouseEntered ); addListener( a, 'onmouseleave', mouseLeft ); addListener( a, 'onmousedown', mousePressed ); if( a.tagName in PIE.focusableElements ) { addListener( a, 'onfocus', focused ); addListener( a, 'onblur', blurred ); } a = a.parentNode; } } } /** * If the target element is a first child, add a pie_first-child class to it. This allows using * the added class as a workaround for the fact that PIE's rendering element breaks the :first-child * pseudo-class selector. */ function initFirstChildPseudoClass() { var tmpEl = el, isFirst = 1; while( tmpEl = tmpEl.previousSibling ) { if( tmpEl.nodeType === 1 ) { isFirst = 0; break; } } if( isFirst ) { addClass( el, firstChildClass ); } } // These methods are all already bound to this instance so there's no need to wrap them // in a closure to maintain the 'this' scope object when calling them. this.init = init; this.update = update; this.destroy = destroy; this.el = el; } Element.getInstance = function( el ) { var id = PIE.Util.getUID( el ); return wrappers[ id ] || ( wrappers[ id ] = new Element( el ) ); }; Element.destroy = function( el ) { var id = PIE.Util.getUID( el ), wrapper = wrappers[ id ]; if( wrapper ) { wrapper.destroy(); delete wrappers[ id ]; } }; Element.destroyAll = function() { var els = [], wrapper; if( wrappers ) { for( var w in wrappers ) { if( wrappers.hasOwnProperty( w ) ) { wrapper = wrappers[ w ]; els.push( wrapper.el ); wrapper.destroy(); } } wrappers = {}; } return els; }; return Element; })(); /* * This file exposes the public API for invoking PIE. */ /** * @property supportsVML * True if the current IE browser environment has a functioning VML engine. Should be true * in most IEs, but in rare cases may be false. If false, PIE will exit immediately when * attached to an element; this property may be used for debugging or by external scripts * to perform some special action when VML support is absent. * @type {boolean} */ PIE[ 'supportsVML' ] = PIE.supportsVML; /** * Programatically attach PIE to a single element. * @param {Element} el */ PIE[ 'attach' ] = function( el ) { if (PIE.ieDocMode < 10 && PIE.supportsVML) { PIE.Element.getInstance( el ).init(); } }; /** * Programatically detach PIE from a single element. * @param {Element} el */ PIE[ 'detach' ] = function( el ) { PIE.Element.destroy( el ); }; } // if( !PIE ) })();
JavaScript
/* PIE: CSS3 rendering for IE Version 1.0.0 http://css3pie.com Dual-licensed for use under the Apache License Version 2.0 or the General Public License (GPL) Version 2. */ (function(){ var doc = document;var PIE = window['PIE']; if( !PIE ) { PIE = window['PIE'] = { CSS_PREFIX: '-pie-', STYLE_PREFIX: 'Pie', CLASS_PREFIX: 'pie_', tableCellTags: { 'TD': 1, 'TH': 1 }, /** * Lookup table of elements which cannot take custom children. */ childlessElements: { 'TABLE':1, 'THEAD':1, 'TBODY':1, 'TFOOT':1, 'TR':1, 'INPUT':1, 'TEXTAREA':1, 'SELECT':1, 'OPTION':1, 'IMG':1, 'HR':1 }, /** * Elements that can receive user focus */ focusableElements: { 'A':1, 'INPUT':1, 'TEXTAREA':1, 'SELECT':1, 'BUTTON':1 }, /** * Values of the type attribute for input elements displayed as buttons */ inputButtonTypes: { 'submit':1, 'button':1, 'reset':1 }, emptyFn: function() {} }; // Force the background cache to be used. No reason it shouldn't be. try { doc.execCommand( 'BackgroundImageCache', false, true ); } catch(e) {} (function() { /* * IE version detection approach by James Padolsey, with modifications -- from * http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/ */ var ieVersion = 4, div = doc.createElement('div'), all = div.getElementsByTagName('i'), shape; while ( div.innerHTML = '<!--[if gt IE ' + (++ieVersion) + ']><i></i><![endif]-->', all[0] ) {} PIE.ieVersion = ieVersion; // Detect IE6 if( ieVersion === 6 ) { // IE6 can't access properties with leading dash, but can without it. PIE.CSS_PREFIX = PIE.CSS_PREFIX.replace( /^-/, '' ); } PIE.ieDocMode = doc.documentMode || PIE.ieVersion; // Detect VML support (a small number of IE installs don't have a working VML engine) div.innerHTML = '<v:shape adj="1"/>'; shape = div.firstChild; shape.style['behavior'] = 'url(#default#VML)'; PIE.supportsVML = (typeof shape['adj'] === "object"); }()); /** * Utility functions */ (function() { var vmlCreatorDoc, idNum = 0, imageSizes = {}; PIE.Util = { /** * To create a VML element, it must be created by a Document which has the VML * namespace set. Unfortunately, if you try to add the namespace programatically * into the main document, you will get an "Unspecified error" when trying to * access document.namespaces before the document is finished loading. To get * around this, we create a DocumentFragment, which in IE land is apparently a * full-fledged Document. It allows adding namespaces immediately, so we add the * namespace there and then have it create the VML element. * @param {string} tag The tag name for the VML element * @return {Element} The new VML element */ createVmlElement: function( tag ) { var vmlPrefix = 'css3vml'; if( !vmlCreatorDoc ) { vmlCreatorDoc = doc.createDocumentFragment(); vmlCreatorDoc.namespaces.add( vmlPrefix, 'urn:schemas-microsoft-com:vml' ); } return vmlCreatorDoc.createElement( vmlPrefix + ':' + tag ); }, /** * Generate and return a unique ID for a given object. The generated ID is stored * as a property of the object for future reuse. * @param {Object} obj */ getUID: function( obj ) { return obj && obj[ '_pieId' ] || ( obj[ '_pieId' ] = '_' + ++idNum ); }, /** * Simple utility for merging objects * @param {Object} obj1 The main object into which all others will be merged * @param {...Object} var_args Other objects which will be merged into the first, in order */ merge: function( obj1 ) { var i, len, p, objN, args = arguments; for( i = 1, len = args.length; i < len; i++ ) { objN = args[i]; for( p in objN ) { if( objN.hasOwnProperty( p ) ) { obj1[ p ] = objN[ p ]; } } } return obj1; }, /** * Execute a callback function, passing it the dimensions of a given image once * they are known. * @param {string} src The source URL of the image * @param {function({w:number, h:number})} func The callback function to be called once the image dimensions are known * @param {Object} ctx A context object which will be used as the 'this' value within the executed callback function */ withImageSize: function( src, func, ctx ) { var size = imageSizes[ src ], img, queue; if( size ) { // If we have a queue, add to it if( Object.prototype.toString.call( size ) === '[object Array]' ) { size.push( [ func, ctx ] ); } // Already have the size cached, call func right away else { func.call( ctx, size ); } } else { queue = imageSizes[ src ] = [ [ func, ctx ] ]; //create queue img = new Image(); img.onload = function() { size = imageSizes[ src ] = { w: img.width, h: img.height }; for( var i = 0, len = queue.length; i < len; i++ ) { queue[ i ][ 0 ].call( queue[ i ][ 1 ], size ); } img.onload = null; }; img.src = src; } } }; })();/** * Utility functions for handling gradients */ PIE.GradientUtil = { getGradientMetrics: function( el, width, height, gradientInfo ) { var angle = gradientInfo.angle, startPos = gradientInfo.gradientStart, startX, startY, endX, endY, startCornerX, startCornerY, endCornerX, endCornerY, deltaX, deltaY, p, UNDEF; // Find the "start" and "end" corners; these are the corners furthest along the gradient line. // This is used below to find the start/end positions of the CSS3 gradient-line, and also in finding // the total length of the VML rendered gradient-line corner to corner. function findCorners() { startCornerX = ( angle >= 90 && angle < 270 ) ? width : 0; startCornerY = angle < 180 ? height : 0; endCornerX = width - startCornerX; endCornerY = height - startCornerY; } // Normalize the angle to a value between [0, 360) function normalizeAngle() { while( angle < 0 ) { angle += 360; } angle = angle % 360; } // Find the start and end points of the gradient if( startPos ) { startPos = startPos.coords( el, width, height ); startX = startPos.x; startY = startPos.y; } if( angle ) { angle = angle.degrees(); normalizeAngle(); findCorners(); // If no start position was specified, then choose a corner as the starting point. if( !startPos ) { startX = startCornerX; startY = startCornerY; } // Find the end position by extending a perpendicular line from the gradient-line which // intersects the corner opposite from the starting corner. p = PIE.GradientUtil.perpendicularIntersect( startX, startY, angle, endCornerX, endCornerY ); endX = p[0]; endY = p[1]; } else if( startPos ) { // Start position but no angle specified: find the end point by rotating 180deg around the center endX = width - startX; endY = height - startY; } else { // Neither position nor angle specified; create vertical gradient from top to bottom startX = startY = endX = 0; endY = height; } deltaX = endX - startX; deltaY = endY - startY; if( angle === UNDEF ) { // Get the angle based on the change in x/y from start to end point. Checks first for horizontal // or vertical angles so they get exact whole numbers rather than what atan2 gives. angle = ( !deltaX ? ( deltaY < 0 ? 90 : 270 ) : ( !deltaY ? ( deltaX < 0 ? 180 : 0 ) : -Math.atan2( deltaY, deltaX ) / Math.PI * 180 ) ); normalizeAngle(); findCorners(); } return { angle: angle, startX: startX, startY: startY, endX: endX, endY: endY, startCornerX: startCornerX, startCornerY: startCornerY, endCornerX: endCornerX, endCornerY: endCornerY, deltaX: deltaX, deltaY: deltaY, lineLength: PIE.GradientUtil.distance( startX, startY, endX, endY ) } }, /** * Find the point along a given line (defined by a starting point and an angle), at which * that line is intersected by a perpendicular line extending through another point. * @param x1 - x coord of the starting point * @param y1 - y coord of the starting point * @param angle - angle of the line extending from the starting point (in degrees) * @param x2 - x coord of point along the perpendicular line * @param y2 - y coord of point along the perpendicular line * @return [ x, y ] */ perpendicularIntersect: function( x1, y1, angle, x2, y2 ) { // Handle straight vertical and horizontal angles, for performance and to avoid // divide-by-zero errors. if( angle === 0 || angle === 180 ) { return [ x2, y1 ]; } else if( angle === 90 || angle === 270 ) { return [ x1, y2 ]; } else { // General approach: determine the Ax+By=C formula for each line (the slope of the second // line is the negative inverse of the first) and then solve for where both formulas have // the same x/y values. var a1 = Math.tan( -angle * Math.PI / 180 ), c1 = a1 * x1 - y1, a2 = -1 / a1, c2 = a2 * x2 - y2, d = a2 - a1, endX = ( c2 - c1 ) / d, endY = ( a1 * c2 - a2 * c1 ) / d; return [ endX, endY ]; } }, /** * Find the distance between two points * @param {Number} p1x * @param {Number} p1y * @param {Number} p2x * @param {Number} p2y * @return {Number} the distance */ distance: function( p1x, p1y, p2x, p2y ) { var dx = p2x - p1x, dy = p2y - p1y; return Math.abs( dx === 0 ? dy : dy === 0 ? dx : Math.sqrt( dx * dx + dy * dy ) ); } };/** * */ PIE.Observable = function() { /** * List of registered observer functions */ this.observers = []; /** * Hash of function ids to their position in the observers list, for fast lookup */ this.indexes = {}; }; PIE.Observable.prototype = { observe: function( fn ) { var id = PIE.Util.getUID( fn ), indexes = this.indexes, observers = this.observers; if( !( id in indexes ) ) { indexes[ id ] = observers.length; observers.push( fn ); } }, unobserve: function( fn ) { var id = PIE.Util.getUID( fn ), indexes = this.indexes; if( id && id in indexes ) { delete this.observers[ indexes[ id ] ]; delete indexes[ id ]; } }, fire: function() { var o = this.observers, i = o.length; while( i-- ) { o[ i ] && o[ i ](); } } };/* * Simple heartbeat timer - this is a brute-force workaround for syncing issues caused by IE not * always firing the onmove and onresize events when elements are moved or resized. We check a few * times every second to make sure the elements have the correct position and size. See Element.js * which adds heartbeat listeners based on the custom -pie-poll flag, which defaults to true in IE8-9 * and false elsewhere. */ PIE.Heartbeat = new PIE.Observable(); PIE.Heartbeat.run = function() { var me = this, interval; if( !me.running ) { interval = doc.documentElement.currentStyle.getAttribute( PIE.CSS_PREFIX + 'poll-interval' ) || 250; (function beat() { me.fire(); setTimeout(beat, interval); })(); me.running = 1; } }; /** * Create an observable listener for the onunload event */ (function() { PIE.OnUnload = new PIE.Observable(); function handleUnload() { PIE.OnUnload.fire(); window.detachEvent( 'onunload', handleUnload ); window[ 'PIE' ] = null; } window.attachEvent( 'onunload', handleUnload ); /** * Attach an event which automatically gets detached onunload */ PIE.OnUnload.attachManagedEvent = function( target, name, handler ) { target.attachEvent( name, handler ); this.observe( function() { target.detachEvent( name, handler ); } ); }; })()/** * Create a single observable listener for window resize events. */ PIE.OnResize = new PIE.Observable(); PIE.OnUnload.attachManagedEvent( window, 'onresize', function() { PIE.OnResize.fire(); } ); /** * Create a single observable listener for scroll events. Used for lazy loading based * on the viewport, and for fixed position backgrounds. */ (function() { PIE.OnScroll = new PIE.Observable(); function scrolled() { PIE.OnScroll.fire(); } PIE.OnUnload.attachManagedEvent( window, 'onscroll', scrolled ); PIE.OnResize.observe( scrolled ); })(); /** * Listen for printing events, destroy all active PIE instances when printing, and * restore them afterward. */ (function() { var elements; function beforePrint() { elements = PIE.Element.destroyAll(); } function afterPrint() { if( elements ) { for( var i = 0, len = elements.length; i < len; i++ ) { PIE[ 'attach' ]( elements[i] ); } elements = 0; } } if( PIE.ieDocMode < 9 ) { PIE.OnUnload.attachManagedEvent( window, 'onbeforeprint', beforePrint ); PIE.OnUnload.attachManagedEvent( window, 'onafterprint', afterPrint ); } })();/** * Create a single observable listener for document mouseup events. */ PIE.OnMouseup = new PIE.Observable(); PIE.OnUnload.attachManagedEvent( doc, 'onmouseup', function() { PIE.OnMouseup.fire(); } ); /** * Wrapper for length and percentage style values. The value is immutable. A singleton instance per unique * value is returned from PIE.getLength() - always use that instead of instantiating directly. * @constructor * @param {string} val The CSS string representing the length. It is assumed that this will already have * been validated as a valid length or percentage syntax. */ PIE.Length = (function() { var lengthCalcEl = doc.createElement( 'length-calc' ), parent = doc.body || doc.documentElement, s = lengthCalcEl.style, conversions = {}, units = [ 'mm', 'cm', 'in', 'pt', 'pc' ], i = units.length, instances = {}; s.position = 'absolute'; s.top = s.left = '-9999px'; parent.appendChild( lengthCalcEl ); while( i-- ) { s.width = '100' + units[i]; conversions[ units[i] ] = lengthCalcEl.offsetWidth / 100; } parent.removeChild( lengthCalcEl ); // All calcs from here on will use 1em s.width = '1em'; function Length( val ) { this.val = val; } Length.prototype = { /** * Regular expression for matching the length unit * @private */ unitRE: /(px|em|ex|mm|cm|in|pt|pc|%)$/, /** * Get the numeric value of the length * @return {number} The value */ getNumber: function() { var num = this.num, UNDEF; if( num === UNDEF ) { num = this.num = parseFloat( this.val ); } return num; }, /** * Get the unit of the length * @return {string} The unit */ getUnit: function() { var unit = this.unit, m; if( !unit ) { m = this.val.match( this.unitRE ); unit = this.unit = ( m && m[0] ) || 'px'; } return unit; }, /** * Determine whether this is a percentage length value * @return {boolean} */ isPercentage: function() { return this.getUnit() === '%'; }, /** * Resolve this length into a number of pixels. * @param {Element} el - the context element, used to resolve font-relative values * @param {(function():number|number)=} pct100 - the number of pixels that equal a 100% percentage. This can be either a number or a * function which will be called to return the number. */ pixels: function( el, pct100 ) { var num = this.getNumber(), unit = this.getUnit(); switch( unit ) { case "px": return num; case "%": return num * ( typeof pct100 === 'function' ? pct100() : pct100 ) / 100; case "em": return num * this.getEmPixels( el ); case "ex": return num * this.getEmPixels( el ) / 2; default: return num * conversions[ unit ]; } }, /** * The em and ex units are relative to the font-size of the current element, * however if the font-size is set using non-pixel units then we get that value * rather than a pixel conversion. To get around this, we keep a floating element * with width:1em which we insert into the target element and then read its offsetWidth. * For elements that won't accept a child we insert into the parent node and perform * additional calculation. If the font-size *is* specified in pixels, then we use that * directly to avoid the expensive DOM manipulation. * @param {Element} el * @return {number} */ getEmPixels: function( el ) { var fs = el.currentStyle.fontSize, px, parent, me; if( fs.indexOf( 'px' ) > 0 ) { return parseFloat( fs ); } else if( el.tagName in PIE.childlessElements ) { me = this; parent = el.parentNode; return PIE.getLength( fs ).pixels( parent, function() { return me.getEmPixels( parent ); } ); } else { el.appendChild( lengthCalcEl ); px = lengthCalcEl.offsetWidth; if( lengthCalcEl.parentNode === el ) { //not sure how this could be false but it sometimes is el.removeChild( lengthCalcEl ); } return px; } } }; /** * Retrieve a PIE.Length instance for the given value. A shared singleton instance is returned for each unique value. * @param {string} val The CSS string representing the length. It is assumed that this will already have * been validated as a valid length or percentage syntax. */ PIE.getLength = function( val ) { return instances[ val ] || ( instances[ val ] = new Length( val ) ); }; return Length; })(); /** * Wrapper for a CSS3 bg-position value. Takes up to 2 position keywords and 2 lengths/percentages. * @constructor * @param {Array.<PIE.Tokenizer.Token>} tokens The tokens making up the background position value. */ PIE.BgPosition = (function() { var length_fifty = PIE.getLength( '50%' ), vert_idents = { 'top': 1, 'center': 1, 'bottom': 1 }, horiz_idents = { 'left': 1, 'center': 1, 'right': 1 }; function BgPosition( tokens ) { this.tokens = tokens; } BgPosition.prototype = { /** * Normalize the values into the form: * [ xOffsetSide, xOffsetLength, yOffsetSide, yOffsetLength ] * where: xOffsetSide is either 'left' or 'right', * yOffsetSide is either 'top' or 'bottom', * and x/yOffsetLength are both PIE.Length objects. * @return {Array} */ getValues: function() { if( !this._values ) { var tokens = this.tokens, len = tokens.length, Tokenizer = PIE.Tokenizer, identType = Tokenizer.Type, length_zero = PIE.getLength( '0' ), type_ident = identType.IDENT, type_length = identType.LENGTH, type_percent = identType.PERCENT, type, value, vals = [ 'left', length_zero, 'top', length_zero ]; // If only one value, the second is assumed to be 'center' if( len === 1 ) { tokens.push( new Tokenizer.Token( type_ident, 'center' ) ); len++; } // Two values - CSS2 if( len === 2 ) { // If both idents, they can appear in either order, so switch them if needed if( type_ident & ( tokens[0].tokenType | tokens[1].tokenType ) && tokens[0].tokenValue in vert_idents && tokens[1].tokenValue in horiz_idents ) { tokens.push( tokens.shift() ); } if( tokens[0].tokenType & type_ident ) { if( tokens[0].tokenValue === 'center' ) { vals[1] = length_fifty; } else { vals[0] = tokens[0].tokenValue; } } else if( tokens[0].isLengthOrPercent() ) { vals[1] = PIE.getLength( tokens[0].tokenValue ); } if( tokens[1].tokenType & type_ident ) { if( tokens[1].tokenValue === 'center' ) { vals[3] = length_fifty; } else { vals[2] = tokens[1].tokenValue; } } else if( tokens[1].isLengthOrPercent() ) { vals[3] = PIE.getLength( tokens[1].tokenValue ); } } // Three or four values - CSS3 else { // TODO } this._values = vals; } return this._values; }, /** * Find the coordinates of the background image from the upper-left corner of the background area. * Note that these coordinate values are not rounded. * @param {Element} el * @param {number} width - the width for percentages (background area width minus image width) * @param {number} height - the height for percentages (background area height minus image height) * @return {Object} { x: Number, y: Number } */ coords: function( el, width, height ) { var vals = this.getValues(), pxX = vals[1].pixels( el, width ), pxY = vals[3].pixels( el, height ); return { x: vals[0] === 'right' ? width - pxX : pxX, y: vals[2] === 'bottom' ? height - pxY : pxY }; } }; return BgPosition; })(); /** * Wrapper for a CSS3 background-size value. * @constructor * @param {String|PIE.Length} w The width parameter * @param {String|PIE.Length} h The height parameter, if any */ PIE.BgSize = (function() { var CONTAIN = 'contain', COVER = 'cover', AUTO = 'auto'; function BgSize( w, h ) { this.w = w; this.h = h; } BgSize.prototype = { pixels: function( el, areaW, areaH, imgW, imgH ) { var me = this, w = me.w, h = me.h, areaRatio = areaW / areaH, imgRatio = imgW / imgH; if ( w === CONTAIN ) { w = imgRatio > areaRatio ? areaW : areaH * imgRatio; h = imgRatio > areaRatio ? areaW / imgRatio : areaH; } else if ( w === COVER ) { w = imgRatio < areaRatio ? areaW : areaH * imgRatio; h = imgRatio < areaRatio ? areaW / imgRatio : areaH; } else if ( w === AUTO ) { h = ( h === AUTO ? imgH : h.pixels( el, areaH ) ); w = h * imgRatio; } else { w = w.pixels( el, areaW ); h = ( h === AUTO ? w / imgRatio : h.pixels( el, areaH ) ); } return { w: w, h: h }; } }; BgSize.DEFAULT = new BgSize( AUTO, AUTO ); return BgSize; })(); /** * Wrapper for angle values; handles conversion to degrees from all allowed angle units * @constructor * @param {string} val The raw CSS value for the angle. It is assumed it has been pre-validated. */ PIE.Angle = (function() { function Angle( val ) { this.val = val; } Angle.prototype = { unitRE: /[a-z]+$/i, /** * @return {string} The unit of the angle value */ getUnit: function() { return this._unit || ( this._unit = this.val.match( this.unitRE )[0].toLowerCase() ); }, /** * Get the numeric value of the angle in degrees. * @return {number} The degrees value */ degrees: function() { var deg = this._deg, u, n; if( deg === undefined ) { u = this.getUnit(); n = parseFloat( this.val, 10 ); deg = this._deg = ( u === 'deg' ? n : u === 'rad' ? n / Math.PI * 180 : u === 'grad' ? n / 400 * 360 : u === 'turn' ? n * 360 : 0 ); } return deg; } }; return Angle; })();/** * Abstraction for colors values. Allows detection of rgba values. A singleton instance per unique * value is returned from PIE.getColor() - always use that instead of instantiating directly. * @constructor * @param {string} val The raw CSS string value for the color */ PIE.Color = (function() { var instances = {}; function Color( val ) { this.val = val; } /** * Regular expression for matching rgba colors and extracting their components * @type {RegExp} */ Color.rgbaRE = /\s*rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d+|\d*\.\d+)\s*\)\s*/; Color.names = { "aliceblue":"F0F8FF", "antiquewhite":"FAEBD7", "aqua":"0FF", "aquamarine":"7FFFD4", "azure":"F0FFFF", "beige":"F5F5DC", "bisque":"FFE4C4", "black":"000", "blanchedalmond":"FFEBCD", "blue":"00F", "blueviolet":"8A2BE2", "brown":"A52A2A", "burlywood":"DEB887", "cadetblue":"5F9EA0", "chartreuse":"7FFF00", "chocolate":"D2691E", "coral":"FF7F50", "cornflowerblue":"6495ED", "cornsilk":"FFF8DC", "crimson":"DC143C", "cyan":"0FF", "darkblue":"00008B", "darkcyan":"008B8B", "darkgoldenrod":"B8860B", "darkgray":"A9A9A9", "darkgreen":"006400", "darkkhaki":"BDB76B", "darkmagenta":"8B008B", "darkolivegreen":"556B2F", "darkorange":"FF8C00", "darkorchid":"9932CC", "darkred":"8B0000", "darksalmon":"E9967A", "darkseagreen":"8FBC8F", "darkslateblue":"483D8B", "darkslategray":"2F4F4F", "darkturquoise":"00CED1", "darkviolet":"9400D3", "deeppink":"FF1493", "deepskyblue":"00BFFF", "dimgray":"696969", "dodgerblue":"1E90FF", "firebrick":"B22222", "floralwhite":"FFFAF0", "forestgreen":"228B22", "fuchsia":"F0F", "gainsboro":"DCDCDC", "ghostwhite":"F8F8FF", "gold":"FFD700", "goldenrod":"DAA520", "gray":"808080", "green":"008000", "greenyellow":"ADFF2F", "honeydew":"F0FFF0", "hotpink":"FF69B4", "indianred":"CD5C5C", "indigo":"4B0082", "ivory":"FFFFF0", "khaki":"F0E68C", "lavender":"E6E6FA", "lavenderblush":"FFF0F5", "lawngreen":"7CFC00", "lemonchiffon":"FFFACD", "lightblue":"ADD8E6", "lightcoral":"F08080", "lightcyan":"E0FFFF", "lightgoldenrodyellow":"FAFAD2", "lightgreen":"90EE90", "lightgrey":"D3D3D3", "lightpink":"FFB6C1", "lightsalmon":"FFA07A", "lightseagreen":"20B2AA", "lightskyblue":"87CEFA", "lightslategray":"789", "lightsteelblue":"B0C4DE", "lightyellow":"FFFFE0", "lime":"0F0", "limegreen":"32CD32", "linen":"FAF0E6", "magenta":"F0F", "maroon":"800000", "mediumauqamarine":"66CDAA", "mediumblue":"0000CD", "mediumorchid":"BA55D3", "mediumpurple":"9370D8", "mediumseagreen":"3CB371", "mediumslateblue":"7B68EE", "mediumspringgreen":"00FA9A", "mediumturquoise":"48D1CC", "mediumvioletred":"C71585", "midnightblue":"191970", "mintcream":"F5FFFA", "mistyrose":"FFE4E1", "moccasin":"FFE4B5", "navajowhite":"FFDEAD", "navy":"000080", "oldlace":"FDF5E6", "olive":"808000", "olivedrab":"688E23", "orange":"FFA500", "orangered":"FF4500", "orchid":"DA70D6", "palegoldenrod":"EEE8AA", "palegreen":"98FB98", "paleturquoise":"AFEEEE", "palevioletred":"D87093", "papayawhip":"FFEFD5", "peachpuff":"FFDAB9", "peru":"CD853F", "pink":"FFC0CB", "plum":"DDA0DD", "powderblue":"B0E0E6", "purple":"800080", "red":"F00", "rosybrown":"BC8F8F", "royalblue":"4169E1", "saddlebrown":"8B4513", "salmon":"FA8072", "sandybrown":"F4A460", "seagreen":"2E8B57", "seashell":"FFF5EE", "sienna":"A0522D", "silver":"C0C0C0", "skyblue":"87CEEB", "slateblue":"6A5ACD", "slategray":"708090", "snow":"FFFAFA", "springgreen":"00FF7F", "steelblue":"4682B4", "tan":"D2B48C", "teal":"008080", "thistle":"D8BFD8", "tomato":"FF6347", "turquoise":"40E0D0", "violet":"EE82EE", "wheat":"F5DEB3", "white":"FFF", "whitesmoke":"F5F5F5", "yellow":"FF0", "yellowgreen":"9ACD32" }; Color.prototype = { /** * @private */ parse: function() { if( !this._color ) { var me = this, v = me.val, vLower, m = v.match( Color.rgbaRE ); if( m ) { me._color = 'rgb(' + m[1] + ',' + m[2] + ',' + m[3] + ')'; me._alpha = parseFloat( m[4] ); } else { if( ( vLower = v.toLowerCase() ) in Color.names ) { v = '#' + Color.names[vLower]; } me._color = v; me._alpha = ( v === 'transparent' ? 0 : 1 ); } } }, /** * Retrieve the value of the color in a format usable by IE natively. This will be the same as * the raw input value, except for rgba values which will be converted to an rgb value. * @param {Element} el The context element, used to get 'currentColor' keyword value. * @return {string} Color value */ colorValue: function( el ) { this.parse(); return this._color === 'currentColor' ? el.currentStyle.color : this._color; }, /** * Retrieve the alpha value of the color. Will be 1 for all values except for rgba values * with an alpha component. * @return {number} The alpha value, from 0 to 1. */ alpha: function() { this.parse(); return this._alpha; } }; /** * Retrieve a PIE.Color instance for the given value. A shared singleton instance is returned for each unique value. * @param {string} val The CSS string representing the color. It is assumed that this will already have * been validated as a valid color syntax. */ PIE.getColor = function(val) { return instances[ val ] || ( instances[ val ] = new Color( val ) ); }; return Color; })();/** * A tokenizer for CSS value strings. * @constructor * @param {string} css The CSS value string */ PIE.Tokenizer = (function() { function Tokenizer( css ) { this.css = css; this.ch = 0; this.tokens = []; this.tokenIndex = 0; } /** * Enumeration of token type constants. * @enum {number} */ var Type = Tokenizer.Type = { ANGLE: 1, CHARACTER: 2, COLOR: 4, DIMEN: 8, FUNCTION: 16, IDENT: 32, LENGTH: 64, NUMBER: 128, OPERATOR: 256, PERCENT: 512, STRING: 1024, URL: 2048 }; /** * A single token * @constructor * @param {number} type The type of the token - see PIE.Tokenizer.Type * @param {string} value The value of the token */ Tokenizer.Token = function( type, value ) { this.tokenType = type; this.tokenValue = value; }; Tokenizer.Token.prototype = { isLength: function() { return this.tokenType & Type.LENGTH || ( this.tokenType & Type.NUMBER && this.tokenValue === '0' ); }, isLengthOrPercent: function() { return this.isLength() || this.tokenType & Type.PERCENT; } }; Tokenizer.prototype = { whitespace: /\s/, number: /^[\+\-]?(\d*\.)?\d+/, url: /^url\(\s*("([^"]*)"|'([^']*)'|([!#$%&*-~]*))\s*\)/i, ident: /^\-?[_a-z][\w-]*/i, string: /^("([^"]*)"|'([^']*)')/, operator: /^[\/,]/, hash: /^#[\w]+/, hashColor: /^#([\da-f]{6}|[\da-f]{3})/i, unitTypes: { 'px': Type.LENGTH, 'em': Type.LENGTH, 'ex': Type.LENGTH, 'mm': Type.LENGTH, 'cm': Type.LENGTH, 'in': Type.LENGTH, 'pt': Type.LENGTH, 'pc': Type.LENGTH, 'deg': Type.ANGLE, 'rad': Type.ANGLE, 'grad': Type.ANGLE }, colorFunctions: { 'rgb': 1, 'rgba': 1, 'hsl': 1, 'hsla': 1 }, /** * Advance to and return the next token in the CSS string. If the end of the CSS string has * been reached, null will be returned. * @param {boolean} forget - if true, the token will not be stored for the purposes of backtracking with prev(). * @return {PIE.Tokenizer.Token} */ next: function( forget ) { var css, ch, firstChar, match, val, me = this; function newToken( type, value ) { var tok = new Tokenizer.Token( type, value ); if( !forget ) { me.tokens.push( tok ); me.tokenIndex++; } return tok; } function failure() { me.tokenIndex++; return null; } // In case we previously backed up, return the stored token in the next slot if( this.tokenIndex < this.tokens.length ) { return this.tokens[ this.tokenIndex++ ]; } // Move past leading whitespace characters while( this.whitespace.test( this.css.charAt( this.ch ) ) ) { this.ch++; } if( this.ch >= this.css.length ) { return failure(); } ch = this.ch; css = this.css.substring( this.ch ); firstChar = css.charAt( 0 ); switch( firstChar ) { case '#': if( match = css.match( this.hashColor ) ) { this.ch += match[0].length; return newToken( Type.COLOR, match[0] ); } break; case '"': case "'": if( match = css.match( this.string ) ) { this.ch += match[0].length; return newToken( Type.STRING, match[2] || match[3] || '' ); } break; case "/": case ",": this.ch++; return newToken( Type.OPERATOR, firstChar ); case 'u': if( match = css.match( this.url ) ) { this.ch += match[0].length; return newToken( Type.URL, match[2] || match[3] || match[4] || '' ); } } // Numbers and values starting with numbers if( match = css.match( this.number ) ) { val = match[0]; this.ch += val.length; // Check if it is followed by a unit if( css.charAt( val.length ) === '%' ) { this.ch++; return newToken( Type.PERCENT, val + '%' ); } if( match = css.substring( val.length ).match( this.ident ) ) { val += match[0]; this.ch += match[0].length; return newToken( this.unitTypes[ match[0].toLowerCase() ] || Type.DIMEN, val ); } // Plain ol' number return newToken( Type.NUMBER, val ); } // Identifiers if( match = css.match( this.ident ) ) { val = match[0]; this.ch += val.length; // Named colors if( val.toLowerCase() in PIE.Color.names || val === 'currentColor' || val === 'transparent' ) { return newToken( Type.COLOR, val ); } // Functions if( css.charAt( val.length ) === '(' ) { this.ch++; // Color values in function format: rgb, rgba, hsl, hsla if( val.toLowerCase() in this.colorFunctions ) { function isNum( tok ) { return tok && tok.tokenType & Type.NUMBER; } function isNumOrPct( tok ) { return tok && ( tok.tokenType & ( Type.NUMBER | Type.PERCENT ) ); } function isValue( tok, val ) { return tok && tok.tokenValue === val; } function next() { return me.next( 1 ); } if( ( val.charAt(0) === 'r' ? isNumOrPct( next() ) : isNum( next() ) ) && isValue( next(), ',' ) && isNumOrPct( next() ) && isValue( next(), ',' ) && isNumOrPct( next() ) && ( val === 'rgb' || val === 'hsa' || ( isValue( next(), ',' ) && isNum( next() ) ) ) && isValue( next(), ')' ) ) { return newToken( Type.COLOR, this.css.substring( ch, this.ch ) ); } return failure(); } return newToken( Type.FUNCTION, val ); } // Other identifier return newToken( Type.IDENT, val ); } // Standalone character this.ch++; return newToken( Type.CHARACTER, firstChar ); }, /** * Determine whether there is another token * @return {boolean} */ hasNext: function() { var next = this.next(); this.prev(); return !!next; }, /** * Back up and return the previous token * @return {PIE.Tokenizer.Token} */ prev: function() { return this.tokens[ this.tokenIndex-- - 2 ]; }, /** * Retrieve all the tokens in the CSS string * @return {Array.<PIE.Tokenizer.Token>} */ all: function() { while( this.next() ) {} return this.tokens; }, /** * Return a list of tokens from the current position until the given function returns * true. The final token will not be included in the list. * @param {function():boolean} func - test function * @param {boolean} require - if true, then if the end of the CSS string is reached * before the test function returns true, null will be returned instead of the * tokens that have been found so far. * @return {Array.<PIE.Tokenizer.Token>} */ until: function( func, require ) { var list = [], t, hit; while( t = this.next() ) { if( func( t ) ) { hit = true; this.prev(); break; } list.push( t ); } return require && !hit ? null : list; } }; return Tokenizer; })();/** * Handles calculating, caching, and detecting changes to size and position of the element. * @constructor * @param {Element} el the target element */ PIE.BoundsInfo = function( el ) { this.targetElement = el; }; PIE.BoundsInfo.prototype = { _locked: 0, positionChanged: function() { var last = this._lastBounds, bounds; return !last || ( ( bounds = this.getBounds() ) && ( last.x !== bounds.x || last.y !== bounds.y ) ); }, sizeChanged: function() { var last = this._lastBounds, bounds; return !last || ( ( bounds = this.getBounds() ) && ( last.w !== bounds.w || last.h !== bounds.h ) ); }, getLiveBounds: function() { var el = this.targetElement, rect = el.getBoundingClientRect(), isIE9 = PIE.ieDocMode === 9, isIE7 = PIE.ieVersion === 7, width = rect.right - rect.left; return { x: rect.left, y: rect.top, // In some cases scrolling the page will cause IE9 to report incorrect dimensions // in the rect returned by getBoundingClientRect, so we must query offsetWidth/Height // instead. Also IE7 is inconsistent in using logical vs. device pixels in measurements // so we must calculate the ratio and use it in certain places as a position adjustment. w: isIE9 || isIE7 ? el.offsetWidth : width, h: isIE9 || isIE7 ? el.offsetHeight : rect.bottom - rect.top, logicalZoomRatio: ( isIE7 && width ) ? el.offsetWidth / width : 1 }; }, getBounds: function() { return this._locked ? ( this._lockedBounds || ( this._lockedBounds = this.getLiveBounds() ) ) : this.getLiveBounds(); }, hasBeenQueried: function() { return !!this._lastBounds; }, lock: function() { ++this._locked; }, unlock: function() { if( !--this._locked ) { if( this._lockedBounds ) this._lastBounds = this._lockedBounds; this._lockedBounds = null; } } }; (function() { function cacheWhenLocked( fn ) { var uid = PIE.Util.getUID( fn ); return function() { if( this._locked ) { var cache = this._lockedValues || ( this._lockedValues = {} ); return ( uid in cache ) ? cache[ uid ] : ( cache[ uid ] = fn.call( this ) ); } else { return fn.call( this ); } } } PIE.StyleInfoBase = { _locked: 0, /** * Create a new StyleInfo class, with the standard constructor, and augmented by * the StyleInfoBase's members. * @param proto */ newStyleInfo: function( proto ) { function StyleInfo( el ) { this.targetElement = el; this._lastCss = this.getCss(); } PIE.Util.merge( StyleInfo.prototype, PIE.StyleInfoBase, proto ); StyleInfo._propsCache = {}; return StyleInfo; }, /** * Get an object representation of the target CSS style, caching it for each unique * CSS value string. * @return {Object} */ getProps: function() { var css = this.getCss(), cache = this.constructor._propsCache; return css ? ( css in cache ? cache[ css ] : ( cache[ css ] = this.parseCss( css ) ) ) : null; }, /** * Get the raw CSS value for the target style * @return {string} */ getCss: cacheWhenLocked( function() { var el = this.targetElement, ctor = this.constructor, s = el.style, cs = el.currentStyle, cssProp = this.cssProperty, styleProp = this.styleProperty, prefixedCssProp = ctor._prefixedCssProp || ( ctor._prefixedCssProp = PIE.CSS_PREFIX + cssProp ), prefixedStyleProp = ctor._prefixedStyleProp || ( ctor._prefixedStyleProp = PIE.STYLE_PREFIX + styleProp.charAt(0).toUpperCase() + styleProp.substring(1) ); return s[ prefixedStyleProp ] || cs.getAttribute( prefixedCssProp ) || s[ styleProp ] || cs.getAttribute( cssProp ); } ), /** * Determine whether the target CSS style is active. * @return {boolean} */ isActive: cacheWhenLocked( function() { return !!this.getProps(); } ), /** * Determine whether the target CSS style has changed since the last time it was used. * @return {boolean} */ changed: cacheWhenLocked( function() { var currentCss = this.getCss(), changed = currentCss !== this._lastCss; this._lastCss = currentCss; return changed; } ), cacheWhenLocked: cacheWhenLocked, lock: function() { ++this._locked; }, unlock: function() { if( !--this._locked ) { delete this._lockedValues; } } }; })();/** * Handles parsing, caching, and detecting changes to background (and -pie-background) CSS * @constructor * @param {Element} el the target element */ PIE.BackgroundStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: PIE.CSS_PREFIX + 'background', styleProperty: PIE.STYLE_PREFIX + 'Background', attachIdents: { 'scroll':1, 'fixed':1, 'local':1 }, repeatIdents: { 'repeat-x':1, 'repeat-y':1, 'repeat':1, 'no-repeat':1 }, originAndClipIdents: { 'padding-box':1, 'border-box':1, 'content-box':1 }, positionIdents: { 'top':1, 'right':1, 'bottom':1, 'left':1, 'center':1 }, sizeIdents: { 'contain':1, 'cover':1 }, propertyNames: { CLIP: 'backgroundClip', COLOR: 'backgroundColor', IMAGE: 'backgroundImage', ORIGIN: 'backgroundOrigin', POSITION: 'backgroundPosition', REPEAT: 'backgroundRepeat', SIZE: 'backgroundSize' }, /** * For background styles, we support the -pie-background property but fall back to the standard * backround* properties. The reason we have to use the prefixed version is that IE natively * parses the standard properties and if it sees something it doesn't know how to parse, for example * multiple values or gradient definitions, it will throw that away and not make it available through * currentStyle. * * Format of return object: * { * color: <PIE.Color>, * bgImages: [ * { * imgType: 'image', * imgUrl: 'image.png', * imgRepeat: <'no-repeat' | 'repeat-x' | 'repeat-y' | 'repeat'>, * bgPosition: <PIE.BgPosition>, * bgAttachment: <'scroll' | 'fixed' | 'local'>, * bgOrigin: <'border-box' | 'padding-box' | 'content-box'>, * bgClip: <'border-box' | 'padding-box'>, * bgSize: <PIE.BgSize>, * origString: 'url(img.png) no-repeat top left' * }, * { * imgType: 'linear-gradient', * gradientStart: <PIE.BgPosition>, * angle: <PIE.Angle>, * stops: [ * { color: <PIE.Color>, offset: <PIE.Length> }, * { color: <PIE.Color>, offset: <PIE.Length> }, ... * ] * } * ] * } * @param {String} css * @override */ parseCss: function( css ) { var el = this.targetElement, cs = el.currentStyle, tokenizer, token, image, tok_type = PIE.Tokenizer.Type, type_operator = tok_type.OPERATOR, type_ident = tok_type.IDENT, type_color = tok_type.COLOR, tokType, tokVal, beginCharIndex = 0, positionIdents = this.positionIdents, gradient, stop, width, height, props = { bgImages: [] }; function isBgPosToken( token ) { return token && token.isLengthOrPercent() || ( token.tokenType & type_ident && token.tokenValue in positionIdents ); } function sizeToken( token ) { return token && ( ( token.isLengthOrPercent() && PIE.getLength( token.tokenValue ) ) || ( token.tokenValue === 'auto' && 'auto' ) ); } // If the CSS3-specific -pie-background property is present, parse it if( this.getCss3() ) { tokenizer = new PIE.Tokenizer( css ); image = {}; while( token = tokenizer.next() ) { tokType = token.tokenType; tokVal = token.tokenValue; if( !image.imgType && tokType & tok_type.FUNCTION && tokVal === 'linear-gradient' ) { gradient = { stops: [], imgType: tokVal }; stop = {}; while( token = tokenizer.next() ) { tokType = token.tokenType; tokVal = token.tokenValue; // If we reached the end of the function and had at least 2 stops, flush the info if( tokType & tok_type.CHARACTER && tokVal === ')' ) { if( stop.color ) { gradient.stops.push( stop ); } if( gradient.stops.length > 1 ) { PIE.Util.merge( image, gradient ); } break; } // Color stop - must start with color if( tokType & type_color ) { // if we already have an angle/position, make sure that the previous token was a comma if( gradient.angle || gradient.gradientStart ) { token = tokenizer.prev(); if( token.tokenType !== type_operator ) { break; //fail } tokenizer.next(); } stop = { color: PIE.getColor( tokVal ) }; // check for offset following color token = tokenizer.next(); if( token.isLengthOrPercent() ) { stop.offset = PIE.getLength( token.tokenValue ); } else { tokenizer.prev(); } } // Angle - can only appear in first spot else if( tokType & tok_type.ANGLE && !gradient.angle && !stop.color && !gradient.stops.length ) { gradient.angle = new PIE.Angle( token.tokenValue ); } else if( isBgPosToken( token ) && !gradient.gradientStart && !stop.color && !gradient.stops.length ) { tokenizer.prev(); gradient.gradientStart = new PIE.BgPosition( tokenizer.until( function( t ) { return !isBgPosToken( t ); }, false ) ); } else if( tokType & type_operator && tokVal === ',' ) { if( stop.color ) { gradient.stops.push( stop ); stop = {}; } } else { // Found something we didn't recognize; fail without adding image break; } } } else if( !image.imgType && tokType & tok_type.URL ) { image.imgUrl = tokVal; image.imgType = 'image'; } else if( isBgPosToken( token ) && !image.bgPosition ) { tokenizer.prev(); image.bgPosition = new PIE.BgPosition( tokenizer.until( function( t ) { return !isBgPosToken( t ); }, false ) ); } else if( tokType & type_ident ) { if( tokVal in this.repeatIdents && !image.imgRepeat ) { image.imgRepeat = tokVal; } else if( tokVal in this.originAndClipIdents && !image.bgOrigin ) { image.bgOrigin = tokVal; if( ( token = tokenizer.next() ) && ( token.tokenType & type_ident ) && token.tokenValue in this.originAndClipIdents ) { image.bgClip = token.tokenValue; } else { image.bgClip = tokVal; tokenizer.prev(); } } else if( tokVal in this.attachIdents && !image.bgAttachment ) { image.bgAttachment = tokVal; } else { return null; } } else if( tokType & type_color && !props.color ) { props.color = PIE.getColor( tokVal ); } else if( tokType & type_operator && tokVal === '/' && !image.bgSize && image.bgPosition ) { // background size token = tokenizer.next(); if( token.tokenType & type_ident && token.tokenValue in this.sizeIdents ) { image.bgSize = new PIE.BgSize( token.tokenValue ); } else if( width = sizeToken( token ) ) { height = sizeToken( tokenizer.next() ); if ( !height ) { height = width; tokenizer.prev(); } image.bgSize = new PIE.BgSize( width, height ); } else { return null; } } // new layer else if( tokType & type_operator && tokVal === ',' && image.imgType ) { image.origString = css.substring( beginCharIndex, tokenizer.ch - 1 ); beginCharIndex = tokenizer.ch; props.bgImages.push( image ); image = {}; } else { // Found something unrecognized; chuck everything return null; } } // leftovers if( image.imgType ) { image.origString = css.substring( beginCharIndex ); props.bgImages.push( image ); } } // Otherwise, use the standard background properties; let IE give us the values rather than parsing them else { this.withActualBg( PIE.ieDocMode < 9 ? function() { var propNames = this.propertyNames, posX = cs[propNames.POSITION + 'X'], posY = cs[propNames.POSITION + 'Y'], img = cs[propNames.IMAGE], color = cs[propNames.COLOR]; if( color !== 'transparent' ) { props.color = PIE.getColor( color ) } if( img !== 'none' ) { props.bgImages = [ { imgType: 'image', imgUrl: new PIE.Tokenizer( img ).next().tokenValue, imgRepeat: cs[propNames.REPEAT], bgPosition: new PIE.BgPosition( new PIE.Tokenizer( posX + ' ' + posY ).all() ) } ]; } } : function() { var propNames = this.propertyNames, splitter = /\s*,\s*/, images = cs[propNames.IMAGE].split( splitter ), color = cs[propNames.COLOR], repeats, positions, origins, clips, sizes, i, len, image, sizeParts; if( color !== 'transparent' ) { props.color = PIE.getColor( color ) } len = images.length; if( len && images[0] !== 'none' ) { repeats = cs[propNames.REPEAT].split( splitter ); positions = cs[propNames.POSITION].split( splitter ); origins = cs[propNames.ORIGIN].split( splitter ); clips = cs[propNames.CLIP].split( splitter ); sizes = cs[propNames.SIZE].split( splitter ); props.bgImages = []; for( i = 0; i < len; i++ ) { image = images[ i ]; if( image && image !== 'none' ) { sizeParts = sizes[i].split( ' ' ); props.bgImages.push( { origString: image + ' ' + repeats[ i ] + ' ' + positions[ i ] + ' / ' + sizes[ i ] + ' ' + origins[ i ] + ' ' + clips[ i ], imgType: 'image', imgUrl: new PIE.Tokenizer( image ).next().tokenValue, imgRepeat: repeats[ i ], bgPosition: new PIE.BgPosition( new PIE.Tokenizer( positions[ i ] ).all() ), bgOrigin: origins[ i ], bgClip: clips[ i ], bgSize: new PIE.BgSize( sizeParts[ 0 ], sizeParts[ 1 ] ) } ); } } } } ); } return ( props.color || props.bgImages[0] ) ? props : null; }, /** * Execute a function with the actual background styles (not overridden with runtimeStyle * properties set by the renderers) available via currentStyle. * @param fn */ withActualBg: function( fn ) { var isIE9 = PIE.ieDocMode > 8, propNames = this.propertyNames, rs = this.targetElement.runtimeStyle, rsImage = rs[propNames.IMAGE], rsColor = rs[propNames.COLOR], rsRepeat = rs[propNames.REPEAT], rsClip, rsOrigin, rsSize, rsPosition, ret; if( rsImage ) rs[propNames.IMAGE] = ''; if( rsColor ) rs[propNames.COLOR] = ''; if( rsRepeat ) rs[propNames.REPEAT] = ''; if( isIE9 ) { rsClip = rs[propNames.CLIP]; rsOrigin = rs[propNames.ORIGIN]; rsPosition = rs[propNames.POSITION]; rsSize = rs[propNames.SIZE]; if( rsClip ) rs[propNames.CLIP] = ''; if( rsOrigin ) rs[propNames.ORIGIN] = ''; if( rsPosition ) rs[propNames.POSITION] = ''; if( rsSize ) rs[propNames.SIZE] = ''; } ret = fn.call( this ); if( rsImage ) rs[propNames.IMAGE] = rsImage; if( rsColor ) rs[propNames.COLOR] = rsColor; if( rsRepeat ) rs[propNames.REPEAT] = rsRepeat; if( isIE9 ) { if( rsClip ) rs[propNames.CLIP] = rsClip; if( rsOrigin ) rs[propNames.ORIGIN] = rsOrigin; if( rsPosition ) rs[propNames.POSITION] = rsPosition; if( rsSize ) rs[propNames.SIZE] = rsSize; } return ret; }, getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { return this.getCss3() || this.withActualBg( function() { var cs = this.targetElement.currentStyle, propNames = this.propertyNames; return cs[propNames.COLOR] + ' ' + cs[propNames.IMAGE] + ' ' + cs[propNames.REPEAT] + ' ' + cs[propNames.POSITION + 'X'] + ' ' + cs[propNames.POSITION + 'Y']; } ); } ), getCss3: PIE.StyleInfoBase.cacheWhenLocked( function() { var el = this.targetElement; return el.style[ this.styleProperty ] || el.currentStyle.getAttribute( this.cssProperty ); } ), /** * Tests if style.PiePngFix or the -pie-png-fix property is set to true in IE6. */ isPngFix: function() { var val = 0, el; if( PIE.ieVersion < 7 ) { el = this.targetElement; val = ( '' + ( el.style[ PIE.STYLE_PREFIX + 'PngFix' ] || el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'png-fix' ) ) === 'true' ); } return val; }, /** * The isActive logic is slightly different, because getProps() always returns an object * even if it is just falling back to the native background properties. But we only want * to report is as being "active" if either the -pie-background override property is present * and parses successfully or '-pie-png-fix' is set to true in IE6. */ isActive: PIE.StyleInfoBase.cacheWhenLocked( function() { return (this.getCss3() || this.isPngFix()) && !!this.getProps(); } ) } );/** * Handles parsing, caching, and detecting changes to border CSS * @constructor * @param {Element} el the target element */ PIE.BorderStyleInfo = PIE.StyleInfoBase.newStyleInfo( { sides: [ 'Top', 'Right', 'Bottom', 'Left' ], namedWidths: { 'thin': '1px', 'medium': '3px', 'thick': '5px' }, parseCss: function( css ) { var w = {}, s = {}, c = {}, active = false, colorsSame = true, stylesSame = true, widthsSame = true; this.withActualBorder( function() { var el = this.targetElement, cs = el.currentStyle, i = 0, style, color, width, lastStyle, lastColor, lastWidth, side, ltr; for( ; i < 4; i++ ) { side = this.sides[ i ]; ltr = side.charAt(0).toLowerCase(); style = s[ ltr ] = cs[ 'border' + side + 'Style' ]; color = cs[ 'border' + side + 'Color' ]; width = cs[ 'border' + side + 'Width' ]; if( i > 0 ) { if( style !== lastStyle ) { stylesSame = false; } if( color !== lastColor ) { colorsSame = false; } if( width !== lastWidth ) { widthsSame = false; } } lastStyle = style; lastColor = color; lastWidth = width; c[ ltr ] = PIE.getColor( color ); width = w[ ltr ] = PIE.getLength( s[ ltr ] === 'none' ? '0' : ( this.namedWidths[ width ] || width ) ); if( width.pixels( this.targetElement ) > 0 ) { active = true; } } } ); return active ? { widths: w, styles: s, colors: c, widthsSame: widthsSame, colorsSame: colorsSame, stylesSame: stylesSame } : null; }, getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { var el = this.targetElement, cs = el.currentStyle, css; // Don't redraw or hide borders for cells in border-collapse:collapse tables if( !( el.tagName in PIE.tableCellTags && el.offsetParent.currentStyle.borderCollapse === 'collapse' ) ) { this.withActualBorder( function() { css = cs.borderWidth + '|' + cs.borderStyle + '|' + cs.borderColor; } ); } return css; } ), /** * Execute a function with the actual border styles (not overridden with runtimeStyle * properties set by the renderers) available via currentStyle. * @param fn */ withActualBorder: function( fn ) { var rs = this.targetElement.runtimeStyle, rsWidth = rs.borderWidth, rsColor = rs.borderColor, ret; if( rsWidth ) rs.borderWidth = ''; if( rsColor ) rs.borderColor = ''; ret = fn.call( this ); if( rsWidth ) rs.borderWidth = rsWidth; if( rsColor ) rs.borderColor = rsColor; return ret; } } ); /** * Handles parsing, caching, and detecting changes to border-radius CSS * @constructor * @param {Element} el the target element */ (function() { PIE.BorderRadiusStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: 'border-radius', styleProperty: 'borderRadius', parseCss: function( css ) { var p = null, x, y, tokenizer, token, length, hasNonZero = false; if( css ) { tokenizer = new PIE.Tokenizer( css ); function collectLengths() { var arr = [], num; while( ( token = tokenizer.next() ) && token.isLengthOrPercent() ) { length = PIE.getLength( token.tokenValue ); num = length.getNumber(); if( num < 0 ) { return null; } if( num > 0 ) { hasNonZero = true; } arr.push( length ); } return arr.length > 0 && arr.length < 5 ? { 'tl': arr[0], 'tr': arr[1] || arr[0], 'br': arr[2] || arr[0], 'bl': arr[3] || arr[1] || arr[0] } : null; } // Grab the initial sequence of lengths if( x = collectLengths() ) { // See if there is a slash followed by more lengths, for the y-axis radii if( token ) { if( token.tokenType & PIE.Tokenizer.Type.OPERATOR && token.tokenValue === '/' ) { y = collectLengths(); } } else { y = x; } // Treat all-zero values the same as no value if( hasNonZero && x && y ) { p = { x: x, y : y }; } } } return p; } } ); var zero = PIE.getLength( '0' ), zeros = { 'tl': zero, 'tr': zero, 'br': zero, 'bl': zero }; PIE.BorderRadiusStyleInfo.ALL_ZERO = { x: zeros, y: zeros }; })();/** * Handles parsing, caching, and detecting changes to border-image CSS * @constructor * @param {Element} el the target element */ PIE.BorderImageStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: 'border-image', styleProperty: 'borderImage', repeatIdents: { 'stretch':1, 'round':1, 'repeat':1, 'space':1 }, parseCss: function( css ) { var p = null, tokenizer, token, type, value, slices, widths, outsets, slashCount = 0, Type = PIE.Tokenizer.Type, IDENT = Type.IDENT, NUMBER = Type.NUMBER, PERCENT = Type.PERCENT; if( css ) { tokenizer = new PIE.Tokenizer( css ); p = {}; function isSlash( token ) { return token && ( token.tokenType & Type.OPERATOR ) && ( token.tokenValue === '/' ); } function isFillIdent( token ) { return token && ( token.tokenType & IDENT ) && ( token.tokenValue === 'fill' ); } function collectSlicesEtc() { slices = tokenizer.until( function( tok ) { return !( tok.tokenType & ( NUMBER | PERCENT ) ); } ); if( isFillIdent( tokenizer.next() ) && !p.fill ) { p.fill = true; } else { tokenizer.prev(); } if( isSlash( tokenizer.next() ) ) { slashCount++; widths = tokenizer.until( function( token ) { return !token.isLengthOrPercent() && !( ( token.tokenType & IDENT ) && token.tokenValue === 'auto' ); } ); if( isSlash( tokenizer.next() ) ) { slashCount++; outsets = tokenizer.until( function( token ) { return !token.isLength(); } ); } } else { tokenizer.prev(); } } while( token = tokenizer.next() ) { type = token.tokenType; value = token.tokenValue; // Numbers and/or 'fill' keyword: slice values. May be followed optionally by width values, followed optionally by outset values if( type & ( NUMBER | PERCENT ) && !slices ) { tokenizer.prev(); collectSlicesEtc(); } else if( isFillIdent( token ) && !p.fill ) { p.fill = true; collectSlicesEtc(); } // Idents: one or values for 'repeat' else if( ( type & IDENT ) && this.repeatIdents[value] && !p.repeat ) { p.repeat = { h: value }; if( token = tokenizer.next() ) { if( ( token.tokenType & IDENT ) && this.repeatIdents[token.tokenValue] ) { p.repeat.v = token.tokenValue; } else { tokenizer.prev(); } } } // URL of the image else if( ( type & Type.URL ) && !p.src ) { p.src = value; } // Found something unrecognized; exit. else { return null; } } // Validate what we collected if( !p.src || !slices || slices.length < 1 || slices.length > 4 || ( widths && widths.length > 4 ) || ( slashCount === 1 && widths.length < 1 ) || ( outsets && outsets.length > 4 ) || ( slashCount === 2 && outsets.length < 1 ) ) { return null; } // Fill in missing values if( !p.repeat ) { p.repeat = { h: 'stretch' }; } if( !p.repeat.v ) { p.repeat.v = p.repeat.h; } function distributeSides( tokens, convertFn ) { return { 't': convertFn( tokens[0] ), 'r': convertFn( tokens[1] || tokens[0] ), 'b': convertFn( tokens[2] || tokens[0] ), 'l': convertFn( tokens[3] || tokens[1] || tokens[0] ) }; } p.slice = distributeSides( slices, function( tok ) { return PIE.getLength( ( tok.tokenType & NUMBER ) ? tok.tokenValue + 'px' : tok.tokenValue ); } ); if( widths && widths[0] ) { p.widths = distributeSides( widths, function( tok ) { return tok.isLengthOrPercent() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue; } ); } if( outsets && outsets[0] ) { p.outset = distributeSides( outsets, function( tok ) { return tok.isLength() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue; } ); } } return p; } } );/** * Handles parsing, caching, and detecting changes to box-shadow CSS * @constructor * @param {Element} el the target element */ PIE.BoxShadowStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: 'box-shadow', styleProperty: 'boxShadow', parseCss: function( css ) { var props, getLength = PIE.getLength, Type = PIE.Tokenizer.Type, tokenizer; if( css ) { tokenizer = new PIE.Tokenizer( css ); props = { outset: [], inset: [] }; function parseItem() { var token, type, value, color, lengths, inset, len; while( token = tokenizer.next() ) { value = token.tokenValue; type = token.tokenType; if( type & Type.OPERATOR && value === ',' ) { break; } else if( token.isLength() && !lengths ) { tokenizer.prev(); lengths = tokenizer.until( function( token ) { return !token.isLength(); } ); } else if( type & Type.COLOR && !color ) { color = value; } else if( type & Type.IDENT && value === 'inset' && !inset ) { inset = true; } else { //encountered an unrecognized token; fail. return false; } } len = lengths && lengths.length; if( len > 1 && len < 5 ) { ( inset ? props.inset : props.outset ).push( { xOffset: getLength( lengths[0].tokenValue ), yOffset: getLength( lengths[1].tokenValue ), blur: getLength( lengths[2] ? lengths[2].tokenValue : '0' ), spread: getLength( lengths[3] ? lengths[3].tokenValue : '0' ), color: PIE.getColor( color || 'currentColor' ) } ); return true; } return false; } while( parseItem() ) {} } return props && ( props.inset.length || props.outset.length ) ? props : null; } } ); /** * Retrieves the state of the element's visibility and display * @constructor * @param {Element} el the target element */ PIE.VisibilityStyleInfo = PIE.StyleInfoBase.newStyleInfo( { getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { var cs = this.targetElement.currentStyle; return cs.visibility + '|' + cs.display; } ), parseCss: function() { var el = this.targetElement, rs = el.runtimeStyle, cs = el.currentStyle, rsVis = rs.visibility, csVis; rs.visibility = ''; csVis = cs.visibility; rs.visibility = rsVis; return { visible: csVis !== 'hidden', displayed: cs.display !== 'none' } }, /** * Always return false for isActive, since this property alone will not trigger * a renderer to do anything. */ isActive: function() { return false; } } ); PIE.RendererBase = { /** * Create a new Renderer class, with the standard constructor, and augmented by * the RendererBase's members. * @param proto */ newRenderer: function( proto ) { function Renderer( el, boundsInfo, styleInfos, parent ) { this.targetElement = el; this.boundsInfo = boundsInfo; this.styleInfos = styleInfos; this.parent = parent; } PIE.Util.merge( Renderer.prototype, PIE.RendererBase, proto ); return Renderer; }, /** * Flag indicating the element has already been positioned at least once. * @type {boolean} */ isPositioned: false, /** * Determine if the renderer needs to be updated * @return {boolean} */ needsUpdate: function() { return false; }, /** * Run any preparation logic that would affect the main update logic of this * renderer or any of the other renderers, e.g. things that might affect the * element's size or style properties. */ prepareUpdate: PIE.emptyFn, /** * Tell the renderer to update based on modified properties */ updateProps: function() { this.destroy(); if( this.isActive() ) { this.draw(); } }, /** * Tell the renderer to update based on modified element position */ updatePos: function() { this.isPositioned = true; }, /** * Tell the renderer to update based on modified element dimensions */ updateSize: function() { if( this.isActive() ) { this.draw(); } else { this.destroy(); } }, /** * Add a layer element, with the given z-order index, to the renderer's main box element. We can't use * z-index because that breaks when the root rendering box's z-index is 'auto' in IE8+ standards mode. * So instead we make sure they are inserted into the DOM in the correct order. * @param {number} index * @param {Element} el */ addLayer: function( index, el ) { this.removeLayer( index ); for( var layers = this._layers || ( this._layers = [] ), i = index + 1, len = layers.length, layer; i < len; i++ ) { layer = layers[i]; if( layer ) { break; } } layers[index] = el; this.getBox().insertBefore( el, layer || null ); }, /** * Retrieve a layer element by its index, or null if not present * @param {number} index * @return {Element} */ getLayer: function( index ) { var layers = this._layers; return layers && layers[index] || null; }, /** * Remove a layer element by its index * @param {number} index */ removeLayer: function( index ) { var layer = this.getLayer( index ), box = this._box; if( layer && box ) { box.removeChild( layer ); this._layers[index] = null; } }, /** * Get a VML shape by name, creating it if necessary. * @param {string} name A name identifying the element * @param {string=} subElName If specified a subelement of the shape will be created with this tag name * @param {Element} parent The parent element for the shape; will be ignored if 'group' is specified * @param {number=} group If specified, an ordinal group for the shape. 1 or greater. Groups are rendered * using container elements in the correct order, to get correct z stacking without z-index. */ getShape: function( name, subElName, parent, group ) { var shapes = this._shapes || ( this._shapes = {} ), shape = shapes[ name ], s; if( !shape ) { shape = shapes[ name ] = PIE.Util.createVmlElement( 'shape' ); if( subElName ) { shape.appendChild( shape[ subElName ] = PIE.Util.createVmlElement( subElName ) ); } if( group ) { parent = this.getLayer( group ); if( !parent ) { this.addLayer( group, doc.createElement( 'group' + group ) ); parent = this.getLayer( group ); } } parent.appendChild( shape ); s = shape.style; s.position = 'absolute'; s.left = s.top = 0; s['behavior'] = 'url(#default#VML)'; } return shape; }, /** * Delete a named shape which was created by getShape(). Returns true if a shape with the * given name was found and deleted, or false if there was no shape of that name. * @param {string} name * @return {boolean} */ deleteShape: function( name ) { var shapes = this._shapes, shape = shapes && shapes[ name ]; if( shape ) { shape.parentNode.removeChild( shape ); delete shapes[ name ]; } return !!shape; }, /** * For a given set of border radius length/percentage values, convert them to concrete pixel * values based on the current size of the target element. * @param {Object} radii * @return {Object} */ getRadiiPixels: function( radii ) { var el = this.targetElement, bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, tlX, tlY, trX, trY, brX, brY, blX, blY, f; tlX = radii.x['tl'].pixels( el, w ); tlY = radii.y['tl'].pixels( el, h ); trX = radii.x['tr'].pixels( el, w ); trY = radii.y['tr'].pixels( el, h ); brX = radii.x['br'].pixels( el, w ); brY = radii.y['br'].pixels( el, h ); blX = radii.x['bl'].pixels( el, w ); blY = radii.y['bl'].pixels( el, h ); // If any corner ellipses overlap, reduce them all by the appropriate factor. This formula // is taken straight from the CSS3 Backgrounds and Borders spec. f = Math.min( w / ( tlX + trX ), h / ( trY + brY ), w / ( blX + brX ), h / ( tlY + blY ) ); if( f < 1 ) { tlX *= f; tlY *= f; trX *= f; trY *= f; brX *= f; brY *= f; blX *= f; blY *= f; } return { x: { 'tl': tlX, 'tr': trX, 'br': brX, 'bl': blX }, y: { 'tl': tlY, 'tr': trY, 'br': brY, 'bl': blY } } }, /** * Return the VML path string for the element's background box, with corners rounded. * @param {Object.<{t:number, r:number, b:number, l:number}>} shrink - if present, specifies number of * pixels to shrink the box path inward from the element's four sides. * @param {number=} mult If specified, all coordinates will be multiplied by this number * @param {Object=} radii If specified, this will be used for the corner radii instead of the properties * from this renderer's borderRadiusInfo object. * @return {string} the VML path */ getBoxPath: function( shrink, mult, radii ) { mult = mult || 1; var r, str, bounds = this.boundsInfo.getBounds(), w = bounds.w * mult, h = bounds.h * mult, radInfo = this.styleInfos.borderRadiusInfo, floor = Math.floor, ceil = Math.ceil, shrinkT = shrink ? shrink.t * mult : 0, shrinkR = shrink ? shrink.r * mult : 0, shrinkB = shrink ? shrink.b * mult : 0, shrinkL = shrink ? shrink.l * mult : 0, tlX, tlY, trX, trY, brX, brY, blX, blY; if( radii || radInfo.isActive() ) { r = this.getRadiiPixels( radii || radInfo.getProps() ); tlX = r.x['tl'] * mult; tlY = r.y['tl'] * mult; trX = r.x['tr'] * mult; trY = r.y['tr'] * mult; brX = r.x['br'] * mult; brY = r.y['br'] * mult; blX = r.x['bl'] * mult; blY = r.y['bl'] * mult; str = 'm' + floor( shrinkL ) + ',' + floor( tlY ) + 'qy' + floor( tlX ) + ',' + floor( shrinkT ) + 'l' + ceil( w - trX ) + ',' + floor( shrinkT ) + 'qx' + ceil( w - shrinkR ) + ',' + floor( trY ) + 'l' + ceil( w - shrinkR ) + ',' + ceil( h - brY ) + 'qy' + ceil( w - brX ) + ',' + ceil( h - shrinkB ) + 'l' + floor( blX ) + ',' + ceil( h - shrinkB ) + 'qx' + floor( shrinkL ) + ',' + ceil( h - blY ) + ' x e'; } else { // simplified path for non-rounded box str = 'm' + floor( shrinkL ) + ',' + floor( shrinkT ) + 'l' + ceil( w - shrinkR ) + ',' + floor( shrinkT ) + 'l' + ceil( w - shrinkR ) + ',' + ceil( h - shrinkB ) + 'l' + floor( shrinkL ) + ',' + ceil( h - shrinkB ) + 'xe'; } return str; }, /** * Get the container element for the shapes, creating it if necessary. */ getBox: function() { var box = this.parent.getLayer( this.boxZIndex ), s; if( !box ) { box = doc.createElement( this.boxName ); s = box.style; s.position = 'absolute'; s.top = s.left = 0; this.parent.addLayer( this.boxZIndex, box ); } return box; }, /** * Hide the actual border of the element. In IE7 and up we can just set its color to transparent; * however IE6 does not support transparent borders so we have to get tricky with it. Also, some elements * like form buttons require removing the border width altogether, so for those we increase the padding * by the border size. */ hideBorder: function() { var el = this.targetElement, cs = el.currentStyle, rs = el.runtimeStyle, tag = el.tagName, isIE6 = PIE.ieVersion === 6, sides, side, i; if( ( isIE6 && ( tag in PIE.childlessElements || tag === 'FIELDSET' ) ) || tag === 'BUTTON' || ( tag === 'INPUT' && el.type in PIE.inputButtonTypes ) ) { rs.borderWidth = ''; sides = this.styleInfos.borderInfo.sides; for( i = sides.length; i--; ) { side = sides[ i ]; rs[ 'padding' + side ] = ''; rs[ 'padding' + side ] = ( PIE.getLength( cs[ 'padding' + side ] ) ).pixels( el ) + ( PIE.getLength( cs[ 'border' + side + 'Width' ] ) ).pixels( el ) + ( PIE.ieVersion !== 8 && i % 2 ? 1 : 0 ); //needs an extra horizontal pixel to counteract the extra "inner border" going away } rs.borderWidth = 0; } else if( isIE6 ) { // Wrap all the element's children in a custom element, set the element to visiblity:hidden, // and set the wrapper element to visiblity:visible. This hides the outer element's decorations // (background and border) but displays all the contents. // TODO find a better way to do this that doesn't mess up the DOM parent-child relationship, // as this can interfere with other author scripts which add/modify/delete children. Also, this // won't work for elements which cannot take children, e.g. input/button/textarea/img/etc. Look into // using a compositor filter or some other filter which masks the border. if( el.childNodes.length !== 1 || el.firstChild.tagName !== 'ie6-mask' ) { var cont = doc.createElement( 'ie6-mask' ), s = cont.style, child; s.visibility = 'visible'; s.zoom = 1; while( child = el.firstChild ) { cont.appendChild( child ); } el.appendChild( cont ); rs.visibility = 'hidden'; } } else { rs.borderColor = 'transparent'; } }, unhideBorder: function() { }, /** * Destroy the rendered objects. This is a base implementation which handles common renderer * structures, but individual renderers may override as necessary. */ destroy: function() { this.parent.removeLayer( this.boxZIndex ); delete this._shapes; delete this._layers; } }; /** * Root renderer; creates the outermost container element and handles keeping it aligned * with the target element's size and position. * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects */ PIE.RootRenderer = PIE.RendererBase.newRenderer( { isActive: function() { var children = this.childRenderers; for( var i in children ) { if( children.hasOwnProperty( i ) && children[ i ].isActive() ) { return true; } } return false; }, needsUpdate: function() { return this.styleInfos.visibilityInfo.changed(); }, updatePos: function() { if( this.isActive() ) { var el = this.getPositioningElement(), par = el, docEl, parRect, tgtCS = el.currentStyle, tgtPos = tgtCS.position, boxPos, s = this.getBox().style, cs, x = 0, y = 0, elBounds = this.boundsInfo.getBounds(), logicalZoomRatio = elBounds.logicalZoomRatio; if( tgtPos === 'fixed' && PIE.ieVersion > 6 ) { x = elBounds.x * logicalZoomRatio; y = elBounds.y * logicalZoomRatio; boxPos = tgtPos; } else { // Get the element's offsets from its nearest positioned ancestor. Uses // getBoundingClientRect for accuracy and speed. do { par = par.offsetParent; } while( par && ( par.currentStyle.position === 'static' ) ); if( par ) { parRect = par.getBoundingClientRect(); cs = par.currentStyle; x = ( elBounds.x - parRect.left ) * logicalZoomRatio - ( parseFloat(cs.borderLeftWidth) || 0 ); y = ( elBounds.y - parRect.top ) * logicalZoomRatio - ( parseFloat(cs.borderTopWidth) || 0 ); } else { docEl = doc.documentElement; x = ( elBounds.x + docEl.scrollLeft - docEl.clientLeft ) * logicalZoomRatio; y = ( elBounds.y + docEl.scrollTop - docEl.clientTop ) * logicalZoomRatio; } boxPos = 'absolute'; } s.position = boxPos; s.left = x; s.top = y; s.zIndex = tgtPos === 'static' ? -1 : tgtCS.zIndex; this.isPositioned = true; } }, updateSize: PIE.emptyFn, updateVisibility: function() { var vis = this.styleInfos.visibilityInfo.getProps(); this.getBox().style.display = ( vis.visible && vis.displayed ) ? '' : 'none'; }, updateProps: function() { if( this.isActive() ) { this.updateVisibility(); } else { this.destroy(); } }, getPositioningElement: function() { var el = this.targetElement; return el.tagName in PIE.tableCellTags ? el.offsetParent : el; }, getBox: function() { var box = this._box, el; if( !box ) { el = this.getPositioningElement(); box = this._box = doc.createElement( 'css3-container' ); box.style['direction'] = 'ltr'; //fix positioning bug in rtl environments this.updateVisibility(); el.parentNode.insertBefore( box, el ); } return box; }, finishUpdate: PIE.emptyFn, destroy: function() { var box = this._box, par; if( box && ( par = box.parentNode ) ) { par.removeChild( box ); } delete this._box; delete this._layers; } } ); /** * Renderer for element backgrounds. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BackgroundRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 2, boxName: 'background', needsUpdate: function() { var si = this.styleInfos; return si.backgroundInfo.changed() || si.borderRadiusInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.borderImageInfo.isActive() || si.borderRadiusInfo.isActive() || si.backgroundInfo.isActive() || ( si.boxShadowInfo.isActive() && si.boxShadowInfo.getProps().inset ); }, /** * Draw the shapes */ draw: function() { var bounds = this.boundsInfo.getBounds(); if( bounds.w && bounds.h ) { this.drawBgColor(); this.drawBgImages(); } }, /** * Draw the background color shape */ drawBgColor: function() { var props = this.styleInfos.backgroundInfo.getProps(), bounds = this.boundsInfo.getBounds(), el = this.targetElement, color = props && props.color, shape, w, h, s, alpha; if( color && color.alpha() > 0 ) { this.hideBackground(); shape = this.getShape( 'bgColor', 'fill', this.getBox(), 1 ); w = bounds.w; h = bounds.h; shape.stroked = false; shape.coordsize = w * 2 + ',' + h * 2; shape.coordorigin = '1,1'; shape.path = this.getBoxPath( null, 2 ); s = shape.style; s.width = w; s.height = h; shape.fill.color = color.colorValue( el ); alpha = color.alpha(); if( alpha < 1 ) { shape.fill.opacity = alpha; } } else { this.deleteShape( 'bgColor' ); } }, /** * Draw all the background image layers */ drawBgImages: function() { var props = this.styleInfos.backgroundInfo.getProps(), bounds = this.boundsInfo.getBounds(), images = props && props.bgImages, img, shape, w, h, s, i; if( images ) { this.hideBackground(); w = bounds.w; h = bounds.h; i = images.length; while( i-- ) { img = images[i]; shape = this.getShape( 'bgImage' + i, 'fill', this.getBox(), 2 ); shape.stroked = false; shape.fill.type = 'tile'; shape.fillcolor = 'none'; shape.coordsize = w * 2 + ',' + h * 2; shape.coordorigin = '1,1'; shape.path = this.getBoxPath( 0, 2 ); s = shape.style; s.width = w; s.height = h; if( img.imgType === 'linear-gradient' ) { this.addLinearGradient( shape, img ); } else { shape.fill.src = img.imgUrl; this.positionBgImage( shape, i ); } } } // Delete any bgImage shapes previously created which weren't used above i = images ? images.length : 0; while( this.deleteShape( 'bgImage' + i++ ) ) {} }, /** * Set the position and clipping of the background image for a layer * @param {Element} shape * @param {number} index */ positionBgImage: function( shape, index ) { var me = this; PIE.Util.withImageSize( shape.fill.src, function( size ) { var el = me.targetElement, bounds = me.boundsInfo.getBounds(), elW = bounds.w, elH = bounds.h; // It's possible that the element dimensions are zero now but weren't when the original // update executed, make sure that's not the case to avoid divide-by-zero error if( elW && elH ) { var fill = shape.fill, si = me.styleInfos, border = si.borderInfo.getProps(), bw = border && border.widths, bwT = bw ? bw['t'].pixels( el ) : 0, bwR = bw ? bw['r'].pixels( el ) : 0, bwB = bw ? bw['b'].pixels( el ) : 0, bwL = bw ? bw['l'].pixels( el ) : 0, bg = si.backgroundInfo.getProps().bgImages[ index ], bgPos = bg.bgPosition ? bg.bgPosition.coords( el, elW - size.w - bwL - bwR, elH - size.h - bwT - bwB ) : { x:0, y:0 }, repeat = bg.imgRepeat, pxX, pxY, clipT = 0, clipL = 0, clipR = elW + 1, clipB = elH + 1, //make sure the default clip region is not inside the box (by a subpixel) clipAdjust = PIE.ieVersion === 8 ? 0 : 1; //prior to IE8 requires 1 extra pixel in the image clip region // Positioning - find the pixel offset from the top/left and convert to a ratio // The position is shifted by half a pixel, to adjust for the half-pixel coordorigin shift which is // needed to fix antialiasing but makes the bg image fuzzy. pxX = Math.round( bgPos.x ) + bwL + 0.5; pxY = Math.round( bgPos.y ) + bwT + 0.5; fill.position = ( pxX / elW ) + ',' + ( pxY / elH ); // Set the size of the image. We have to actually set it to px values otherwise it will not honor // the user's browser zoom level and always display at its natural screen size. fill['size']['x'] = 1; //Can be any value, just has to be set to "prime" it so the next line works. Weird! fill['size'] = size.w + 'px,' + size.h + 'px'; // Repeating - clip the image shape if( repeat && repeat !== 'repeat' ) { if( repeat === 'repeat-x' || repeat === 'no-repeat' ) { clipT = pxY + 1; clipB = pxY + size.h + clipAdjust; } if( repeat === 'repeat-y' || repeat === 'no-repeat' ) { clipL = pxX + 1; clipR = pxX + size.w + clipAdjust; } shape.style.clip = 'rect(' + clipT + 'px,' + clipR + 'px,' + clipB + 'px,' + clipL + 'px)'; } } } ); }, /** * Draw the linear gradient for a gradient layer * @param {Element} shape * @param {Object} info The object holding the information about the gradient */ addLinearGradient: function( shape, info ) { var el = this.targetElement, bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, fill = shape.fill, stops = info.stops, stopCount = stops.length, PI = Math.PI, GradientUtil = PIE.GradientUtil, perpendicularIntersect = GradientUtil.perpendicularIntersect, distance = GradientUtil.distance, metrics = GradientUtil.getGradientMetrics( el, w, h, info ), angle = metrics.angle, startX = metrics.startX, startY = metrics.startY, startCornerX = metrics.startCornerX, startCornerY = metrics.startCornerY, endCornerX = metrics.endCornerX, endCornerY = metrics.endCornerY, deltaX = metrics.deltaX, deltaY = metrics.deltaY, lineLength = metrics.lineLength, vmlAngle, vmlGradientLength, vmlColors, stopPx, vmlOffsetPct, p, i, j, before, after; // In VML land, the angle of the rendered gradient depends on the aspect ratio of the shape's // bounding box; for example specifying a 45 deg angle actually results in a gradient // drawn diagonally from one corner to its opposite corner, which will only appear to the // viewer as 45 degrees if the shape is equilateral. We adjust for this by taking the x/y deltas // between the start and end points, multiply one of them by the shape's aspect ratio, // and get their arctangent, resulting in an appropriate VML angle. If the angle is perfectly // horizontal or vertical then we don't need to do this conversion. vmlAngle = ( angle % 90 ) ? Math.atan2( deltaX * w / h, deltaY ) / PI * 180 : ( angle + 90 ); // VML angles are 180 degrees offset from CSS angles vmlAngle += 180; vmlAngle = vmlAngle % 360; // Add all the stops to the VML 'colors' list, including the first and last stops. // For each, we find its pixel offset along the gradient-line; if the offset of a stop is less // than that of its predecessor we increase it to be equal. We then map that pixel offset to a // percentage along the VML gradient-line, which runs from shape corner to corner. p = perpendicularIntersect( startCornerX, startCornerY, angle, endCornerX, endCornerY ); vmlGradientLength = distance( startCornerX, startCornerY, p[0], p[1] ); vmlColors = []; p = perpendicularIntersect( startX, startY, angle, startCornerX, startCornerY ); vmlOffsetPct = distance( startX, startY, p[0], p[1] ) / vmlGradientLength * 100; // Find the pixel offsets along the CSS3 gradient-line for each stop. stopPx = []; for( i = 0; i < stopCount; i++ ) { stopPx.push( stops[i].offset ? stops[i].offset.pixels( el, lineLength ) : i === 0 ? 0 : i === stopCount - 1 ? lineLength : null ); } // Fill in gaps with evenly-spaced offsets for( i = 1; i < stopCount; i++ ) { if( stopPx[ i ] === null ) { before = stopPx[ i - 1 ]; j = i; do { after = stopPx[ ++j ]; } while( after === null ); stopPx[ i ] = before + ( after - before ) / ( j - i + 1 ); } // Make sure each stop's offset is no less than the one before it stopPx[ i ] = Math.max( stopPx[ i ], stopPx[ i - 1 ] ); } // Convert to percentage along the VML gradient line and add to the VML 'colors' value for( i = 0; i < stopCount; i++ ) { vmlColors.push( ( vmlOffsetPct + ( stopPx[ i ] / vmlGradientLength * 100 ) ) + '% ' + stops[i].color.colorValue( el ) ); } // Now, finally, we're ready to render the gradient fill. Set the start and end colors to // the first and last stop colors; this just sets outer bounds for the gradient. fill['angle'] = vmlAngle; fill['type'] = 'gradient'; fill['method'] = 'sigma'; fill['color'] = stops[0].color.colorValue( el ); fill['color2'] = stops[stopCount - 1].color.colorValue( el ); if( fill['colors'] ) { //sometimes the colors object isn't initialized so we have to assign it directly (?) fill['colors'].value = vmlColors.join( ',' ); } else { fill['colors'] = vmlColors.join( ',' ); } }, /** * Hide the actual background image and color of the element. */ hideBackground: function() { var rs = this.targetElement.runtimeStyle; rs.backgroundImage = 'url(about:blank)'; //ensures the background area reacts to mouse events rs.backgroundColor = 'transparent'; }, destroy: function() { PIE.RendererBase.destroy.call( this ); var rs = this.targetElement.runtimeStyle; rs.backgroundImage = rs.backgroundColor = ''; } } ); /** * Renderer for element borders. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BorderRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 4, boxName: 'border', needsUpdate: function() { var si = this.styleInfos; return si.borderInfo.changed() || si.borderRadiusInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.borderRadiusInfo.isActive() && !si.borderImageInfo.isActive() && si.borderInfo.isActive(); //check BorderStyleInfo last because it's the most expensive }, /** * Draw the border shape(s) */ draw: function() { var el = this.targetElement, props = this.styleInfos.borderInfo.getProps(), bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, shape, stroke, s, segments, seg, i, len; if( props ) { this.hideBorder(); segments = this.getBorderSegments( 2 ); for( i = 0, len = segments.length; i < len; i++) { seg = segments[i]; shape = this.getShape( 'borderPiece' + i, seg.stroke ? 'stroke' : 'fill', this.getBox() ); shape.coordsize = w * 2 + ',' + h * 2; shape.coordorigin = '1,1'; shape.path = seg.path; s = shape.style; s.width = w; s.height = h; shape.filled = !!seg.fill; shape.stroked = !!seg.stroke; if( seg.stroke ) { stroke = shape.stroke; stroke['weight'] = seg.weight + 'px'; stroke.color = seg.color.colorValue( el ); stroke['dashstyle'] = seg.stroke === 'dashed' ? '2 2' : seg.stroke === 'dotted' ? '1 1' : 'solid'; stroke['linestyle'] = seg.stroke === 'double' && seg.weight > 2 ? 'ThinThin' : 'Single'; } else { shape.fill.color = seg.fill.colorValue( el ); } } // remove any previously-created border shapes which didn't get used above while( this.deleteShape( 'borderPiece' + i++ ) ) {} } }, /** * Get the VML path definitions for the border segment(s). * @param {number=} mult If specified, all coordinates will be multiplied by this number * @return {Array.<string>} */ getBorderSegments: function( mult ) { var el = this.targetElement, bounds, elW, elH, borderInfo = this.styleInfos.borderInfo, segments = [], floor, ceil, wT, wR, wB, wL, round = Math.round, borderProps, radiusInfo, radii, widths, styles, colors; if( borderInfo.isActive() ) { borderProps = borderInfo.getProps(); widths = borderProps.widths; styles = borderProps.styles; colors = borderProps.colors; if( borderProps.widthsSame && borderProps.stylesSame && borderProps.colorsSame ) { if( colors['t'].alpha() > 0 ) { // shortcut for identical border on all sides - only need 1 stroked shape wT = widths['t'].pixels( el ); //thickness wR = wT / 2; //shrink segments.push( { path: this.getBoxPath( { t: wR, r: wR, b: wR, l: wR }, mult ), stroke: styles['t'], color: colors['t'], weight: wT } ); } } else { mult = mult || 1; bounds = this.boundsInfo.getBounds(); elW = bounds.w; elH = bounds.h; wT = round( widths['t'].pixels( el ) ); wR = round( widths['r'].pixels( el ) ); wB = round( widths['b'].pixels( el ) ); wL = round( widths['l'].pixels( el ) ); var pxWidths = { 't': wT, 'r': wR, 'b': wB, 'l': wL }; radiusInfo = this.styleInfos.borderRadiusInfo; if( radiusInfo.isActive() ) { radii = this.getRadiiPixels( radiusInfo.getProps() ); } floor = Math.floor; ceil = Math.ceil; function radius( xy, corner ) { return radii ? radii[ xy ][ corner ] : 0; } function curve( corner, shrinkX, shrinkY, startAngle, ccw, doMove ) { var rx = radius( 'x', corner), ry = radius( 'y', corner), deg = 65535, isRight = corner.charAt( 1 ) === 'r', isBottom = corner.charAt( 0 ) === 'b'; return ( rx > 0 && ry > 0 ) ? ( doMove ? 'al' : 'ae' ) + ( isRight ? ceil( elW - rx ) : floor( rx ) ) * mult + ',' + // center x ( isBottom ? ceil( elH - ry ) : floor( ry ) ) * mult + ',' + // center y ( floor( rx ) - shrinkX ) * mult + ',' + // width ( floor( ry ) - shrinkY ) * mult + ',' + // height ( startAngle * deg ) + ',' + // start angle ( 45 * deg * ( ccw ? 1 : -1 ) // angle change ) : ( ( doMove ? 'm' : 'l' ) + ( isRight ? elW - shrinkX : shrinkX ) * mult + ',' + ( isBottom ? elH - shrinkY : shrinkY ) * mult ); } function line( side, shrink, ccw, doMove ) { var start = ( side === 't' ? floor( radius( 'x', 'tl') ) * mult + ',' + ceil( shrink ) * mult : side === 'r' ? ceil( elW - shrink ) * mult + ',' + floor( radius( 'y', 'tr') ) * mult : side === 'b' ? ceil( elW - radius( 'x', 'br') ) * mult + ',' + floor( elH - shrink ) * mult : // side === 'l' ? floor( shrink ) * mult + ',' + ceil( elH - radius( 'y', 'bl') ) * mult ), end = ( side === 't' ? ceil( elW - radius( 'x', 'tr') ) * mult + ',' + ceil( shrink ) * mult : side === 'r' ? ceil( elW - shrink ) * mult + ',' + ceil( elH - radius( 'y', 'br') ) * mult : side === 'b' ? floor( radius( 'x', 'bl') ) * mult + ',' + floor( elH - shrink ) * mult : // side === 'l' ? floor( shrink ) * mult + ',' + floor( radius( 'y', 'tl') ) * mult ); return ccw ? ( doMove ? 'm' + end : '' ) + 'l' + start : ( doMove ? 'm' + start : '' ) + 'l' + end; } function addSide( side, sideBefore, sideAfter, cornerBefore, cornerAfter, baseAngle ) { var vert = side === 'l' || side === 'r', sideW = pxWidths[ side ], beforeX, beforeY, afterX, afterY; if( sideW > 0 && styles[ side ] !== 'none' && colors[ side ].alpha() > 0 ) { beforeX = pxWidths[ vert ? side : sideBefore ]; beforeY = pxWidths[ vert ? sideBefore : side ]; afterX = pxWidths[ vert ? side : sideAfter ]; afterY = pxWidths[ vert ? sideAfter : side ]; if( styles[ side ] === 'dashed' || styles[ side ] === 'dotted' ) { segments.push( { path: curve( cornerBefore, beforeX, beforeY, baseAngle + 45, 0, 1 ) + curve( cornerBefore, 0, 0, baseAngle, 1, 0 ), fill: colors[ side ] } ); segments.push( { path: line( side, sideW / 2, 0, 1 ), stroke: styles[ side ], weight: sideW, color: colors[ side ] } ); segments.push( { path: curve( cornerAfter, afterX, afterY, baseAngle, 0, 1 ) + curve( cornerAfter, 0, 0, baseAngle - 45, 1, 0 ), fill: colors[ side ] } ); } else { segments.push( { path: curve( cornerBefore, beforeX, beforeY, baseAngle + 45, 0, 1 ) + line( side, sideW, 0, 0 ) + curve( cornerAfter, afterX, afterY, baseAngle, 0, 0 ) + ( styles[ side ] === 'double' && sideW > 2 ? curve( cornerAfter, afterX - floor( afterX / 3 ), afterY - floor( afterY / 3 ), baseAngle - 45, 1, 0 ) + line( side, ceil( sideW / 3 * 2 ), 1, 0 ) + curve( cornerBefore, beforeX - floor( beforeX / 3 ), beforeY - floor( beforeY / 3 ), baseAngle, 1, 0 ) + 'x ' + curve( cornerBefore, floor( beforeX / 3 ), floor( beforeY / 3 ), baseAngle + 45, 0, 1 ) + line( side, floor( sideW / 3 ), 1, 0 ) + curve( cornerAfter, floor( afterX / 3 ), floor( afterY / 3 ), baseAngle, 0, 0 ) : '' ) + curve( cornerAfter, 0, 0, baseAngle - 45, 1, 0 ) + line( side, 0, 1, 0 ) + curve( cornerBefore, 0, 0, baseAngle, 1, 0 ), fill: colors[ side ] } ); } } } addSide( 't', 'l', 'r', 'tl', 'tr', 90 ); addSide( 'r', 't', 'b', 'tr', 'br', 0 ); addSide( 'b', 'r', 'l', 'br', 'bl', -90 ); addSide( 'l', 'b', 't', 'bl', 'tl', -180 ); } } return segments; }, destroy: function() { var me = this; if (me.finalized || !me.styleInfos.borderImageInfo.isActive()) { me.targetElement.runtimeStyle.borderColor = ''; } PIE.RendererBase.destroy.call( me ); } } ); /** * Renderer for border-image * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BorderImageRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 5, pieceNames: [ 't', 'tr', 'r', 'br', 'b', 'bl', 'l', 'tl', 'c' ], needsUpdate: function() { return this.styleInfos.borderImageInfo.changed(); }, isActive: function() { return this.styleInfos.borderImageInfo.isActive(); }, draw: function() { this.getBox(); //make sure pieces are created var props = this.styleInfos.borderImageInfo.getProps(), borderProps = this.styleInfos.borderInfo.getProps(), bounds = this.boundsInfo.getBounds(), el = this.targetElement, pieces = this.pieces; PIE.Util.withImageSize( props.src, function( imgSize ) { var elW = bounds.w, elH = bounds.h, zero = PIE.getLength( '0' ), widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ), widthT = widths['t'].pixels( el ), widthR = widths['r'].pixels( el ), widthB = widths['b'].pixels( el ), widthL = widths['l'].pixels( el ), slices = props.slice, sliceT = slices['t'].pixels( el ), sliceR = slices['r'].pixels( el ), sliceB = slices['b'].pixels( el ), sliceL = slices['l'].pixels( el ); // Piece positions and sizes function setSizeAndPos( piece, w, h, x, y ) { var s = pieces[piece].style, max = Math.max; s.width = max(w, 0); s.height = max(h, 0); s.left = x; s.top = y; } setSizeAndPos( 'tl', widthL, widthT, 0, 0 ); setSizeAndPos( 't', elW - widthL - widthR, widthT, widthL, 0 ); setSizeAndPos( 'tr', widthR, widthT, elW - widthR, 0 ); setSizeAndPos( 'r', widthR, elH - widthT - widthB, elW - widthR, widthT ); setSizeAndPos( 'br', widthR, widthB, elW - widthR, elH - widthB ); setSizeAndPos( 'b', elW - widthL - widthR, widthB, widthL, elH - widthB ); setSizeAndPos( 'bl', widthL, widthB, 0, elH - widthB ); setSizeAndPos( 'l', widthL, elH - widthT - widthB, 0, widthT ); setSizeAndPos( 'c', elW - widthL - widthR, elH - widthT - widthB, widthL, widthT ); // image croppings function setCrops( sides, crop, val ) { for( var i=0, len=sides.length; i < len; i++ ) { pieces[ sides[i] ]['imagedata'][ crop ] = val; } } // corners setCrops( [ 'tl', 't', 'tr' ], 'cropBottom', ( imgSize.h - sliceT ) / imgSize.h ); setCrops( [ 'tl', 'l', 'bl' ], 'cropRight', ( imgSize.w - sliceL ) / imgSize.w ); setCrops( [ 'bl', 'b', 'br' ], 'cropTop', ( imgSize.h - sliceB ) / imgSize.h ); setCrops( [ 'tr', 'r', 'br' ], 'cropLeft', ( imgSize.w - sliceR ) / imgSize.w ); // edges and center // TODO right now this treats everything like 'stretch', need to support other schemes //if( props.repeat.v === 'stretch' ) { setCrops( [ 'l', 'r', 'c' ], 'cropTop', sliceT / imgSize.h ); setCrops( [ 'l', 'r', 'c' ], 'cropBottom', sliceB / imgSize.h ); //} //if( props.repeat.h === 'stretch' ) { setCrops( [ 't', 'b', 'c' ], 'cropLeft', sliceL / imgSize.w ); setCrops( [ 't', 'b', 'c' ], 'cropRight', sliceR / imgSize.w ); //} // center fill pieces['c'].style.display = props.fill ? '' : 'none'; }, this ); }, getBox: function() { var box = this.parent.getLayer( this.boxZIndex ), s, piece, i, pieceNames = this.pieceNames, len = pieceNames.length; if( !box ) { box = doc.createElement( 'border-image' ); s = box.style; s.position = 'absolute'; this.pieces = {}; for( i = 0; i < len; i++ ) { piece = this.pieces[ pieceNames[i] ] = PIE.Util.createVmlElement( 'rect' ); piece.appendChild( PIE.Util.createVmlElement( 'imagedata' ) ); s = piece.style; s['behavior'] = 'url(#default#VML)'; s.position = "absolute"; s.top = s.left = 0; piece['imagedata'].src = this.styleInfos.borderImageInfo.getProps().src; piece.stroked = false; piece.filled = false; box.appendChild( piece ); } this.parent.addLayer( this.boxZIndex, box ); } return box; }, prepareUpdate: function() { if (this.isActive()) { var me = this, el = me.targetElement, rs = el.runtimeStyle, widths = me.styleInfos.borderImageInfo.getProps().widths; // Force border-style to solid so it doesn't collapse rs.borderStyle = 'solid'; // If widths specified in border-image shorthand, override border-width // NOTE px units needed here as this gets used by the IE9 renderer too if ( widths ) { rs.borderTopWidth = widths['t'].pixels( el ) + 'px'; rs.borderRightWidth = widths['r'].pixels( el ) + 'px'; rs.borderBottomWidth = widths['b'].pixels( el ) + 'px'; rs.borderLeftWidth = widths['l'].pixels( el ) + 'px'; } // Make the border transparent me.hideBorder(); } }, destroy: function() { var me = this, rs = me.targetElement.runtimeStyle; rs.borderStyle = ''; if (me.finalized || !me.styleInfos.borderInfo.isActive()) { rs.borderColor = rs.borderWidth = ''; } PIE.RendererBase.destroy.call( this ); } } ); /** * Renderer for outset box-shadows * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BoxShadowOutsetRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 1, boxName: 'outset-box-shadow', needsUpdate: function() { var si = this.styleInfos; return si.boxShadowInfo.changed() || si.borderRadiusInfo.changed(); }, isActive: function() { var boxShadowInfo = this.styleInfos.boxShadowInfo; return boxShadowInfo.isActive() && boxShadowInfo.getProps().outset[0]; }, draw: function() { var me = this, el = this.targetElement, box = this.getBox(), styleInfos = this.styleInfos, shadowInfos = styleInfos.boxShadowInfo.getProps().outset, radii = styleInfos.borderRadiusInfo.getProps(), len = shadowInfos.length, i = len, j, bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, clipAdjust = PIE.ieVersion === 8 ? 1 : 0, //workaround for IE8 bug where VML leaks out top/left of clip region by 1px corners = [ 'tl', 'tr', 'br', 'bl' ], corner, shadowInfo, shape, fill, ss, xOff, yOff, spread, blur, shrink, color, alpha, path, totalW, totalH, focusX, focusY, isBottom, isRight; function getShadowShape( index, corner, xOff, yOff, color, blur, path ) { var shape = me.getShape( 'shadow' + index + corner, 'fill', box, len - index ), fill = shape.fill; // Position and size shape['coordsize'] = w * 2 + ',' + h * 2; shape['coordorigin'] = '1,1'; // Color and opacity shape['stroked'] = false; shape['filled'] = true; fill.color = color.colorValue( el ); if( blur ) { fill['type'] = 'gradienttitle'; //makes the VML gradient follow the shape's outline - hooray for undocumented features?!?! fill['color2'] = fill.color; fill['opacity'] = 0; } // Path shape.path = path; // This needs to go last for some reason, to prevent rendering at incorrect size ss = shape.style; ss.left = xOff; ss.top = yOff; ss.width = w; ss.height = h; return shape; } while( i-- ) { shadowInfo = shadowInfos[ i ]; xOff = shadowInfo.xOffset.pixels( el ); yOff = shadowInfo.yOffset.pixels( el ); spread = shadowInfo.spread.pixels( el ); blur = shadowInfo.blur.pixels( el ); color = shadowInfo.color; // Shape path shrink = -spread - blur; if( !radii && blur ) { // If blurring, use a non-null border radius info object so that getBoxPath will // round the corners of the expanded shadow shape rather than squaring them off. radii = PIE.BorderRadiusStyleInfo.ALL_ZERO; } path = this.getBoxPath( { t: shrink, r: shrink, b: shrink, l: shrink }, 2, radii ); if( blur ) { totalW = ( spread + blur ) * 2 + w; totalH = ( spread + blur ) * 2 + h; focusX = totalW ? blur * 2 / totalW : 0; focusY = totalH ? blur * 2 / totalH : 0; if( blur - spread > w / 2 || blur - spread > h / 2 ) { // If the blur is larger than half the element's narrowest dimension, we cannot do // this with a single shape gradient, because its focussize would have to be less than // zero which results in ugly artifacts. Instead we create four shapes, each with its // gradient focus past center, and then clip them so each only shows the quadrant // opposite the focus. for( j = 4; j--; ) { corner = corners[j]; isBottom = corner.charAt( 0 ) === 'b'; isRight = corner.charAt( 1 ) === 'r'; shape = getShadowShape( i, corner, xOff, yOff, color, blur, path ); fill = shape.fill; fill['focusposition'] = ( isRight ? 1 - focusX : focusX ) + ',' + ( isBottom ? 1 - focusY : focusY ); fill['focussize'] = '0,0'; // Clip to show only the appropriate quadrant. Add 1px to the top/left clip values // in IE8 to prevent a bug where IE8 displays one pixel outside the clip region. shape.style.clip = 'rect(' + ( ( isBottom ? totalH / 2 : 0 ) + clipAdjust ) + 'px,' + ( isRight ? totalW : totalW / 2 ) + 'px,' + ( isBottom ? totalH : totalH / 2 ) + 'px,' + ( ( isRight ? totalW / 2 : 0 ) + clipAdjust ) + 'px)'; } } else { // TODO delete old quadrant shapes if resizing expands past the barrier shape = getShadowShape( i, '', xOff, yOff, color, blur, path ); fill = shape.fill; fill['focusposition'] = focusX + ',' + focusY; fill['focussize'] = ( 1 - focusX * 2 ) + ',' + ( 1 - focusY * 2 ); } } else { shape = getShadowShape( i, '', xOff, yOff, color, blur, path ); alpha = color.alpha(); if( alpha < 1 ) { // shape.style.filter = 'alpha(opacity=' + ( alpha * 100 ) + ')'; // ss.filter = 'progid:DXImageTransform.Microsoft.BasicImage(opacity=' + ( alpha ) + ')'; shape.fill.opacity = alpha; } } } } } ); /** * Renderer for re-rendering img elements using VML. Kicks in if the img has * a border-radius applied, or if the -pie-png-fix flag is set. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.ImgRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 6, boxName: 'imgEl', needsUpdate: function() { var si = this.styleInfos; return this.targetElement.src !== this._lastSrc || si.borderRadiusInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.borderRadiusInfo.isActive() || si.backgroundInfo.isPngFix(); }, draw: function() { this._lastSrc = src; this.hideActualImg(); var shape = this.getShape( 'img', 'fill', this.getBox() ), fill = shape.fill, bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, borderProps = this.styleInfos.borderInfo.getProps(), borderWidths = borderProps && borderProps.widths, el = this.targetElement, src = el.src, round = Math.round, cs = el.currentStyle, getLength = PIE.getLength, s, zero; // In IE6, the BorderRenderer will have hidden the border by moving the border-width to // the padding; therefore we want to pretend the borders have no width so they aren't doubled // when adding in the current padding value below. if( !borderWidths || PIE.ieVersion < 7 ) { zero = PIE.getLength( '0' ); borderWidths = { 't': zero, 'r': zero, 'b': zero, 'l': zero }; } shape.stroked = false; fill.type = 'frame'; fill.src = src; fill.position = (w ? 0.5 / w : 0) + ',' + (h ? 0.5 / h : 0); shape.coordsize = w * 2 + ',' + h * 2; shape.coordorigin = '1,1'; shape.path = this.getBoxPath( { t: round( borderWidths['t'].pixels( el ) + getLength( cs.paddingTop ).pixels( el ) ), r: round( borderWidths['r'].pixels( el ) + getLength( cs.paddingRight ).pixels( el ) ), b: round( borderWidths['b'].pixels( el ) + getLength( cs.paddingBottom ).pixels( el ) ), l: round( borderWidths['l'].pixels( el ) + getLength( cs.paddingLeft ).pixels( el ) ) }, 2 ); s = shape.style; s.width = w; s.height = h; }, hideActualImg: function() { this.targetElement.runtimeStyle.filter = 'alpha(opacity=0)'; }, destroy: function() { PIE.RendererBase.destroy.call( this ); this.targetElement.runtimeStyle.filter = ''; } } ); /** * Root renderer for IE9; manages the rendering layers in the element's background * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects */ PIE.IE9RootRenderer = PIE.RendererBase.newRenderer( { updatePos: PIE.emptyFn, updateSize: PIE.emptyFn, updateVisibility: PIE.emptyFn, updateProps: PIE.emptyFn, outerCommasRE: /^,+|,+$/g, innerCommasRE: /,+/g, setBackgroundLayer: function(zIndex, bg) { var me = this, bgLayers = me._bgLayers || ( me._bgLayers = [] ), undef; bgLayers[zIndex] = bg || undef; }, finishUpdate: function() { var me = this, bgLayers = me._bgLayers, bg; if( bgLayers && ( bg = bgLayers.join( ',' ).replace( me.outerCommasRE, '' ).replace( me.innerCommasRE, ',' ) ) !== me._lastBg ) { me._lastBg = me.targetElement.runtimeStyle.background = bg; } }, destroy: function() { this.targetElement.runtimeStyle.background = ''; delete this._bgLayers; } } ); /** * Renderer for element backgrounds, specific for IE9. Only handles translating CSS3 gradients * to an equivalent SVG data URI. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects */ PIE.IE9BackgroundRenderer = PIE.RendererBase.newRenderer( { bgLayerZIndex: 1, needsUpdate: function() { var si = this.styleInfos; return si.backgroundInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.backgroundInfo.isActive() || si.borderImageInfo.isActive(); }, draw: function() { var me = this, props = me.styleInfos.backgroundInfo.getProps(), bg, images, i = 0, img, bgAreaSize, bgSize; if ( props ) { bg = []; images = props.bgImages; if ( images ) { while( img = images[ i++ ] ) { if (img.imgType === 'linear-gradient' ) { bgAreaSize = me.getBgAreaSize( img.bgOrigin ); bgSize = ( img.bgSize || PIE.BgSize.DEFAULT ).pixels( me.targetElement, bgAreaSize.w, bgAreaSize.h, bgAreaSize.w, bgAreaSize.h ), bg.push( 'url(data:image/svg+xml,' + escape( me.getGradientSvg( img, bgSize.w, bgSize.h ) ) + ') ' + me.bgPositionToString( img.bgPosition ) + ' / ' + bgSize.w + 'px ' + bgSize.h + 'px ' + ( img.bgAttachment || '' ) + ' ' + ( img.bgOrigin || '' ) + ' ' + ( img.bgClip || '' ) ); } else { bg.push( img.origString ); } } } if ( props.color ) { bg.push( props.color.val ); } me.parent.setBackgroundLayer(me.bgLayerZIndex, bg.join(',')); } }, bgPositionToString: function( bgPosition ) { return bgPosition ? bgPosition.tokens.map(function(token) { return token.tokenValue; }).join(' ') : '0 0'; }, getBgAreaSize: function( bgOrigin ) { var me = this, el = me.targetElement, bounds = me.boundsInfo.getBounds(), elW = bounds.w, elH = bounds.h, w = elW, h = elH, borders, getLength, cs; if( bgOrigin !== 'border-box' ) { borders = me.styleInfos.borderInfo.getProps(); if( borders && ( borders = borders.widths ) ) { w -= borders[ 'l' ].pixels( el ) + borders[ 'l' ].pixels( el ); h -= borders[ 't' ].pixels( el ) + borders[ 'b' ].pixels( el ); } } if ( bgOrigin === 'content-box' ) { getLength = PIE.getLength; cs = el.currentStyle; w -= getLength( cs.paddingLeft ).pixels( el ) + getLength( cs.paddingRight ).pixels( el ); h -= getLength( cs.paddingTop ).pixels( el ) + getLength( cs.paddingBottom ).pixels( el ); } return { w: w, h: h }; }, getGradientSvg: function( info, bgWidth, bgHeight ) { var el = this.targetElement, stopsInfo = info.stops, stopCount = stopsInfo.length, metrics = PIE.GradientUtil.getGradientMetrics( el, bgWidth, bgHeight, info ), startX = metrics.startX, startY = metrics.startY, endX = metrics.endX, endY = metrics.endY, lineLength = metrics.lineLength, stopPx, i, j, before, after, svg; // Find the pixel offsets along the CSS3 gradient-line for each stop. stopPx = []; for( i = 0; i < stopCount; i++ ) { stopPx.push( stopsInfo[i].offset ? stopsInfo[i].offset.pixels( el, lineLength ) : i === 0 ? 0 : i === stopCount - 1 ? lineLength : null ); } // Fill in gaps with evenly-spaced offsets for( i = 1; i < stopCount; i++ ) { if( stopPx[ i ] === null ) { before = stopPx[ i - 1 ]; j = i; do { after = stopPx[ ++j ]; } while( after === null ); stopPx[ i ] = before + ( after - before ) / ( j - i + 1 ); } } svg = [ '<svg width="' + bgWidth + '" height="' + bgHeight + '" xmlns="http://www.w3.org/2000/svg">' + '<defs>' + '<linearGradient id="g" gradientUnits="userSpaceOnUse"' + ' x1="' + ( startX / bgWidth * 100 ) + '%" y1="' + ( startY / bgHeight * 100 ) + '%" x2="' + ( endX / bgWidth * 100 ) + '%" y2="' + ( endY / bgHeight * 100 ) + '%">' ]; // Convert to percentage along the SVG gradient line and add to the stops list for( i = 0; i < stopCount; i++ ) { svg.push( '<stop offset="' + ( stopPx[ i ] / lineLength ) + '" stop-color="' + stopsInfo[i].color.colorValue( el ) + '" stop-opacity="' + stopsInfo[i].color.alpha() + '"/>' ); } svg.push( '</linearGradient>' + '</defs>' + '<rect width="100%" height="100%" fill="url(#g)"/>' + '</svg>' ); return svg.join( '' ); }, destroy: function() { this.parent.setBackgroundLayer( this.bgLayerZIndex ); } } ); /** * Renderer for border-image * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.IE9BorderImageRenderer = PIE.RendererBase.newRenderer( { REPEAT: 'repeat', STRETCH: 'stretch', ROUND: 'round', bgLayerZIndex: 0, needsUpdate: function() { return this.styleInfos.borderImageInfo.changed(); }, isActive: function() { return this.styleInfos.borderImageInfo.isActive(); }, draw: function() { var me = this, props = me.styleInfos.borderImageInfo.getProps(), borderProps = me.styleInfos.borderInfo.getProps(), bounds = me.boundsInfo.getBounds(), repeat = props.repeat, repeatH = repeat.h, repeatV = repeat.v, el = me.targetElement, isAsync = 0; PIE.Util.withImageSize( props.src, function( imgSize ) { var elW = bounds.w, elH = bounds.h, imgW = imgSize.w, imgH = imgSize.h, // The image cannot be referenced as a URL directly in the SVG because IE9 throws a strange // security exception (perhaps due to cross-origin policy within data URIs?) Therefore we // work around this by converting the image data into a data URI itself using a transient // canvas. This unfortunately requires the border-image src to be within the same domain, // which isn't a limitation in true border-image, so we need to try and find a better fix. imgSrc = me.imageToDataURI( props.src, imgW, imgH ), REPEAT = me.REPEAT, STRETCH = me.STRETCH, ROUND = me.ROUND, ceil = Math.ceil, zero = PIE.getLength( '0' ), widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ), widthT = widths['t'].pixels( el ), widthR = widths['r'].pixels( el ), widthB = widths['b'].pixels( el ), widthL = widths['l'].pixels( el ), slices = props.slice, sliceT = slices['t'].pixels( el ), sliceR = slices['r'].pixels( el ), sliceB = slices['b'].pixels( el ), sliceL = slices['l'].pixels( el ), centerW = elW - widthL - widthR, middleH = elH - widthT - widthB, imgCenterW = imgW - sliceL - sliceR, imgMiddleH = imgH - sliceT - sliceB, // Determine the size of each tile - 'round' is handled below tileSizeT = repeatH === STRETCH ? centerW : imgCenterW * widthT / sliceT, tileSizeR = repeatV === STRETCH ? middleH : imgMiddleH * widthR / sliceR, tileSizeB = repeatH === STRETCH ? centerW : imgCenterW * widthB / sliceB, tileSizeL = repeatV === STRETCH ? middleH : imgMiddleH * widthL / sliceL, svg, patterns = [], rects = [], i = 0; // For 'round', subtract from each tile's size enough so that they fill the space a whole number of times if (repeatH === ROUND) { tileSizeT -= (tileSizeT - (centerW % tileSizeT || tileSizeT)) / ceil(centerW / tileSizeT); tileSizeB -= (tileSizeB - (centerW % tileSizeB || tileSizeB)) / ceil(centerW / tileSizeB); } if (repeatV === ROUND) { tileSizeR -= (tileSizeR - (middleH % tileSizeR || tileSizeR)) / ceil(middleH / tileSizeR); tileSizeL -= (tileSizeL - (middleH % tileSizeL || tileSizeL)) / ceil(middleH / tileSizeL); } // Build the SVG for the border-image rendering. Add each piece as a pattern, which is then stretched // or repeated as the fill of a rect of appropriate size. svg = [ '<svg width="' + elW + '" height="' + elH + '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">' ]; function addImage( x, y, w, h, cropX, cropY, cropW, cropH, tileW, tileH ) { patterns.push( '<pattern patternUnits="userSpaceOnUse" id="pattern' + i + '" ' + 'x="' + (repeatH === REPEAT ? x + w / 2 - tileW / 2 : x) + '" ' + 'y="' + (repeatV === REPEAT ? y + h / 2 - tileH / 2 : y) + '" ' + 'width="' + tileW + '" height="' + tileH + '">' + '<svg width="' + tileW + '" height="' + tileH + '" viewBox="' + cropX + ' ' + cropY + ' ' + cropW + ' ' + cropH + '" preserveAspectRatio="none">' + '<image xlink:href="' + imgSrc + '" x="0" y="0" width="' + imgW + '" height="' + imgH + '" />' + '</svg>' + '</pattern>' ); rects.push( '<rect x="' + x + '" y="' + y + '" width="' + w + '" height="' + h + '" fill="url(#pattern' + i + ')" />' ); i++; } addImage( 0, 0, widthL, widthT, 0, 0, sliceL, sliceT, widthL, widthT ); // top left addImage( widthL, 0, centerW, widthT, sliceL, 0, imgCenterW, sliceT, tileSizeT, widthT ); // top center addImage( elW - widthR, 0, widthR, widthT, imgW - sliceR, 0, sliceR, sliceT, widthR, widthT ); // top right addImage( 0, widthT, widthL, middleH, 0, sliceT, sliceL, imgMiddleH, widthL, tileSizeL ); // middle left if ( props.fill ) { // center fill addImage( widthL, widthT, centerW, middleH, sliceL, sliceT, imgCenterW, imgMiddleH, tileSizeT || tileSizeB || imgCenterW, tileSizeL || tileSizeR || imgMiddleH ); } addImage( elW - widthR, widthT, widthR, middleH, imgW - sliceR, sliceT, sliceR, imgMiddleH, widthR, tileSizeR ); // middle right addImage( 0, elH - widthB, widthL, widthB, 0, imgH - sliceB, sliceL, sliceB, widthL, widthB ); // bottom left addImage( widthL, elH - widthB, centerW, widthB, sliceL, imgH - sliceB, imgCenterW, sliceB, tileSizeB, widthB ); // bottom center addImage( elW - widthR, elH - widthB, widthR, widthB, imgW - sliceR, imgH - sliceB, sliceR, sliceB, widthR, widthB ); // bottom right svg.push( '<defs>' + patterns.join('\n') + '</defs>' + rects.join('\n') + '</svg>' ); me.parent.setBackgroundLayer( me.bgLayerZIndex, 'url(data:image/svg+xml,' + escape( svg.join( '' ) ) + ') no-repeat border-box border-box' ); // If the border-image's src wasn't immediately available, the SVG for its background layer // will have been created asynchronously after the main element's update has finished; we'll // therefore need to force the root renderer to sync to the final background once finished. if( isAsync ) { me.parent.finishUpdate(); } }, me ); isAsync = 1; }, /** * Convert a given image to a data URI */ imageToDataURI: (function() { var uris = {}; return function( src, width, height ) { var uri = uris[ src ], image, canvas; if ( !uri ) { image = new Image(); canvas = doc.createElement( 'canvas' ); image.src = src; canvas.width = width; canvas.height = height; canvas.getContext( '2d' ).drawImage( image, 0, 0 ); uri = uris[ src ] = canvas.toDataURL(); } return uri; } })(), prepareUpdate: PIE.BorderImageRenderer.prototype.prepareUpdate, destroy: function() { var me = this, rs = me.targetElement.runtimeStyle; me.parent.setBackgroundLayer( me.bgLayerZIndex ); rs.borderColor = rs.borderStyle = rs.borderWidth = ''; } } ); PIE.Element = (function() { var wrappers = {}, lazyInitCssProp = PIE.CSS_PREFIX + 'lazy-init', pollCssProp = PIE.CSS_PREFIX + 'poll', trackActiveCssProp = PIE.CSS_PREFIX + 'track-active', trackHoverCssProp = PIE.CSS_PREFIX + 'track-hover', hoverClass = PIE.CLASS_PREFIX + 'hover', activeClass = PIE.CLASS_PREFIX + 'active', focusClass = PIE.CLASS_PREFIX + 'focus', firstChildClass = PIE.CLASS_PREFIX + 'first-child', ignorePropertyNames = { 'background':1, 'bgColor':1, 'display': 1 }, classNameRegExes = {}, dummyArray = []; function addClass( el, className ) { el.className += ' ' + className; } function removeClass( el, className ) { var re = classNameRegExes[ className ] || ( classNameRegExes[ className ] = new RegExp( '\\b' + className + '\\b', 'g' ) ); el.className = el.className.replace( re, '' ); } function delayAddClass( el, className /*, className2*/ ) { var classes = dummyArray.slice.call( arguments, 1 ), i = classes.length; setTimeout( function() { if( el ) { while( i-- ) { addClass( el, classes[ i ] ); } } }, 0 ); } function delayRemoveClass( el, className /*, className2*/ ) { var classes = dummyArray.slice.call( arguments, 1 ), i = classes.length; setTimeout( function() { if( el ) { while( i-- ) { removeClass( el, classes[ i ] ); } } }, 0 ); } function Element( el ) { var renderers, rootRenderer, boundsInfo = new PIE.BoundsInfo( el ), styleInfos, styleInfosArr, initializing, initialized, eventsAttached, eventListeners = [], delayed, destroyed, poll; /** * Initialize PIE for this element. */ function init() { if( !initialized ) { var docEl, bounds, ieDocMode = PIE.ieDocMode, cs = el.currentStyle, lazy = cs.getAttribute( lazyInitCssProp ) === 'true', trackActive = cs.getAttribute( trackActiveCssProp ) !== 'false', trackHover = cs.getAttribute( trackHoverCssProp ) !== 'false', childRenderers; // Polling for size/position changes: default to on in IE8, off otherwise, overridable by -pie-poll poll = cs.getAttribute( pollCssProp ); poll = ieDocMode > 7 ? poll !== 'false' : poll === 'true'; // Force layout so move/resize events will fire. Set this as soon as possible to avoid layout changes // after load, but make sure it only gets called the first time through to avoid recursive calls to init(). if( !initializing ) { initializing = 1; el.runtimeStyle.zoom = 1; initFirstChildPseudoClass(); } boundsInfo.lock(); // If the -pie-lazy-init:true flag is set, check if the element is outside the viewport and if so, delay initialization if( lazy && ( bounds = boundsInfo.getBounds() ) && ( docEl = doc.documentElement || doc.body ) && ( bounds.y > docEl.clientHeight || bounds.x > docEl.clientWidth || bounds.y + bounds.h < 0 || bounds.x + bounds.w < 0 ) ) { if( !delayed ) { delayed = 1; PIE.OnScroll.observe( init ); } } else { initialized = 1; delayed = initializing = 0; PIE.OnScroll.unobserve( init ); // Create the style infos and renderers if ( ieDocMode === 9 ) { styleInfos = { backgroundInfo: new PIE.BackgroundStyleInfo( el ), borderImageInfo: new PIE.BorderImageStyleInfo( el ), borderInfo: new PIE.BorderStyleInfo( el ) }; styleInfosArr = [ styleInfos.backgroundInfo, styleInfos.borderImageInfo ]; rootRenderer = new PIE.IE9RootRenderer( el, boundsInfo, styleInfos ); childRenderers = [ new PIE.IE9BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.IE9BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer ) ]; } else { styleInfos = { backgroundInfo: new PIE.BackgroundStyleInfo( el ), borderInfo: new PIE.BorderStyleInfo( el ), borderImageInfo: new PIE.BorderImageStyleInfo( el ), borderRadiusInfo: new PIE.BorderRadiusStyleInfo( el ), boxShadowInfo: new PIE.BoxShadowStyleInfo( el ), visibilityInfo: new PIE.VisibilityStyleInfo( el ) }; styleInfosArr = [ styleInfos.backgroundInfo, styleInfos.borderInfo, styleInfos.borderImageInfo, styleInfos.borderRadiusInfo, styleInfos.boxShadowInfo, styleInfos.visibilityInfo ]; rootRenderer = new PIE.RootRenderer( el, boundsInfo, styleInfos ); childRenderers = [ new PIE.BoxShadowOutsetRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ), //new PIE.BoxShadowInsetRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.BorderRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer ) ]; if( el.tagName === 'IMG' ) { childRenderers.push( new PIE.ImgRenderer( el, boundsInfo, styleInfos, rootRenderer ) ); } rootRenderer.childRenderers = childRenderers; // circular reference, can't pass in constructor; TODO is there a cleaner way? } renderers = [ rootRenderer ].concat( childRenderers ); // Add property change listeners to ancestors if requested initAncestorEventListeners(); // Add to list of polled elements in IE8 if( poll ) { PIE.Heartbeat.observe( update ); PIE.Heartbeat.run(); } // Trigger rendering update( 1 ); } if( !eventsAttached ) { eventsAttached = 1; if( ieDocMode < 9 ) { addListener( el, 'onmove', handleMoveOrResize ); } addListener( el, 'onresize', handleMoveOrResize ); addListener( el, 'onpropertychange', propChanged ); if( trackHover ) { addListener( el, 'onmouseenter', mouseEntered ); } if( trackHover || trackActive ) { addListener( el, 'onmouseleave', mouseLeft ); } if( trackActive ) { addListener( el, 'onmousedown', mousePressed ); } if( el.tagName in PIE.focusableElements ) { addListener( el, 'onfocus', focused ); addListener( el, 'onblur', blurred ); } PIE.OnResize.observe( handleMoveOrResize ); PIE.OnUnload.observe( removeEventListeners ); } boundsInfo.unlock(); } } /** * Event handler for onmove and onresize events. Invokes update() only if the element's * bounds have previously been calculated, to prevent multiple runs during page load when * the element has no initial CSS3 properties. */ function handleMoveOrResize() { if( boundsInfo && boundsInfo.hasBeenQueried() ) { update(); } } /** * Update position and/or size as necessary. Both move and resize events call * this rather than the updatePos/Size functions because sometimes, particularly * during page load, one will fire but the other won't. */ function update( force ) { if( !destroyed ) { if( initialized ) { var i, len = renderers.length; lockAll(); for( i = 0; i < len; i++ ) { renderers[i].prepareUpdate(); } if( force || boundsInfo.positionChanged() ) { /* TODO just using getBoundingClientRect (used internally by BoundsInfo) for detecting position changes may not always be accurate; it's possible that an element will actually move relative to its positioning parent, but its position relative to the viewport will stay the same. Need to come up with a better way to track movement. The most accurate would be the same logic used in RootRenderer.updatePos() but that is a more expensive operation since it does some DOM walking, and we want this check to be as fast as possible. */ for( i = 0; i < len; i++ ) { renderers[i].updatePos(); } } if( force || boundsInfo.sizeChanged() ) { for( i = 0; i < len; i++ ) { renderers[i].updateSize(); } } rootRenderer.finishUpdate(); unlockAll(); } else if( !initializing ) { init(); } } } /** * Handle property changes to trigger update when appropriate. */ function propChanged() { var i, len = renderers.length, renderer, e = event; // Some elements like <table> fire onpropertychange events for old-school background properties // ('background', 'bgColor') when runtimeStyle background properties are changed, which // results in an infinite loop; therefore we filter out those property names. Also, 'display' // is ignored because size calculations don't work correctly immediately when its onpropertychange // event fires, and because it will trigger an onresize event anyway. if( !destroyed && !( e && e.propertyName in ignorePropertyNames ) ) { if( initialized ) { lockAll(); for( i = 0; i < len; i++ ) { renderers[i].prepareUpdate(); } for( i = 0; i < len; i++ ) { renderer = renderers[i]; // Make sure position is synced if the element hasn't already been rendered. // TODO this feels sloppy - look into merging propChanged and update functions if( !renderer.isPositioned ) { renderer.updatePos(); } if( renderer.needsUpdate() ) { renderer.updateProps(); } } rootRenderer.finishUpdate(); unlockAll(); } else if( !initializing ) { init(); } } } /** * Handle mouseenter events. Adds a custom class to the element to allow IE6 to add * hover styles to non-link elements, and to trigger a propertychange update. */ function mouseEntered() { //must delay this because the mouseenter event fires before the :hover styles are added. delayAddClass( el, hoverClass ); } /** * Handle mouseleave events */ function mouseLeft() { //must delay this because the mouseleave event fires before the :hover styles are removed. delayRemoveClass( el, hoverClass, activeClass ); } /** * Handle mousedown events. Adds a custom class to the element to allow IE6 to add * active styles to non-link elements, and to trigger a propertychange update. */ function mousePressed() { //must delay this because the mousedown event fires before the :active styles are added. delayAddClass( el, activeClass ); // listen for mouseups on the document; can't just be on the element because the user might // have dragged out of the element while the mouse button was held down PIE.OnMouseup.observe( mouseReleased ); } /** * Handle mouseup events */ function mouseReleased() { //must delay this because the mouseup event fires before the :active styles are removed. delayRemoveClass( el, activeClass ); PIE.OnMouseup.unobserve( mouseReleased ); } /** * Handle focus events. Adds a custom class to the element to trigger a propertychange update. */ function focused() { //must delay this because the focus event fires before the :focus styles are added. delayAddClass( el, focusClass ); } /** * Handle blur events */ function blurred() { //must delay this because the blur event fires before the :focus styles are removed. delayRemoveClass( el, focusClass ); } /** * Handle property changes on ancestors of the element; see initAncestorEventListeners() * which adds these listeners as requested with the -pie-watch-ancestors CSS property. */ function ancestorPropChanged() { var name = event.propertyName; if( name === 'className' || name === 'id' ) { propChanged(); } } function lockAll() { boundsInfo.lock(); for( var i = styleInfosArr.length; i--; ) { styleInfosArr[i].lock(); } } function unlockAll() { for( var i = styleInfosArr.length; i--; ) { styleInfosArr[i].unlock(); } boundsInfo.unlock(); } function addListener( targetEl, type, handler ) { targetEl.attachEvent( type, handler ); eventListeners.push( [ targetEl, type, handler ] ); } /** * Remove all event listeners from the element and any monitored ancestors. */ function removeEventListeners() { if (eventsAttached) { var i = eventListeners.length, listener; while( i-- ) { listener = eventListeners[ i ]; listener[ 0 ].detachEvent( listener[ 1 ], listener[ 2 ] ); } PIE.OnUnload.unobserve( removeEventListeners ); eventsAttached = 0; eventListeners = []; } } /** * Clean everything up when the behavior is removed from the element, or the element * is manually destroyed. */ function destroy() { if( !destroyed ) { var i, len; removeEventListeners(); destroyed = 1; // destroy any active renderers if( renderers ) { for( i = 0, len = renderers.length; i < len; i++ ) { renderers[i].finalized = 1; renderers[i].destroy(); } } // Remove from list of polled elements in IE8 if( poll ) { PIE.Heartbeat.unobserve( update ); } // Stop onresize listening PIE.OnResize.unobserve( update ); // Kill references renderers = boundsInfo = styleInfos = styleInfosArr = el = null; } } /** * If requested via the custom -pie-watch-ancestors CSS property, add onpropertychange and * other event listeners to ancestor(s) of the element so we can pick up style changes * based on CSS rules using descendant selectors. */ function initAncestorEventListeners() { var watch = el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'watch-ancestors' ), i, a; if( watch ) { watch = parseInt( watch, 10 ); i = 0; a = el.parentNode; while( a && ( watch === 'NaN' || i++ < watch ) ) { addListener( a, 'onpropertychange', ancestorPropChanged ); addListener( a, 'onmouseenter', mouseEntered ); addListener( a, 'onmouseleave', mouseLeft ); addListener( a, 'onmousedown', mousePressed ); if( a.tagName in PIE.focusableElements ) { addListener( a, 'onfocus', focused ); addListener( a, 'onblur', blurred ); } a = a.parentNode; } } } /** * If the target element is a first child, add a pie_first-child class to it. This allows using * the added class as a workaround for the fact that PIE's rendering element breaks the :first-child * pseudo-class selector. */ function initFirstChildPseudoClass() { var tmpEl = el, isFirst = 1; while( tmpEl = tmpEl.previousSibling ) { if( tmpEl.nodeType === 1 ) { isFirst = 0; break; } } if( isFirst ) { addClass( el, firstChildClass ); } } // These methods are all already bound to this instance so there's no need to wrap them // in a closure to maintain the 'this' scope object when calling them. this.init = init; this.update = update; this.destroy = destroy; this.el = el; } Element.getInstance = function( el ) { var id = PIE.Util.getUID( el ); return wrappers[ id ] || ( wrappers[ id ] = new Element( el ) ); }; Element.destroy = function( el ) { var id = PIE.Util.getUID( el ), wrapper = wrappers[ id ]; if( wrapper ) { wrapper.destroy(); delete wrappers[ id ]; } }; Element.destroyAll = function() { var els = [], wrapper; if( wrappers ) { for( var w in wrappers ) { if( wrappers.hasOwnProperty( w ) ) { wrapper = wrappers[ w ]; els.push( wrapper.el ); wrapper.destroy(); } } wrappers = {}; } return els; }; return Element; })(); /* * This file exposes the public API for invoking PIE. */ /** * @property supportsVML * True if the current IE browser environment has a functioning VML engine. Should be true * in most IEs, but in rare cases may be false. If false, PIE will exit immediately when * attached to an element; this property may be used for debugging or by external scripts * to perform some special action when VML support is absent. * @type {boolean} */ PIE[ 'supportsVML' ] = PIE.supportsVML; /** * Programatically attach PIE to a single element. * @param {Element} el */ PIE[ 'attach' ] = function( el ) { if (PIE.ieDocMode < 10 && PIE.supportsVML) { PIE.Element.getInstance( el ).init(); } }; /** * Programatically detach PIE from a single element. * @param {Element} el */ PIE[ 'detach' ] = function( el ) { PIE.Element.destroy( el ); }; } // if( !PIE ) })();
JavaScript
/****************************************** Auto-readmore link script, version 2.0 (for blogspot) (C)2008 by abu iyad http://abu-iyad.blogspot.com ********************************************/ function removeHtmlTag(strx,chop){ if(strx.indexOf("<")!=-1) { var s = strx.split("<"); for(var i=0;i<s.length;i++){ if(s[i].indexOf(">")!=-1){ s[i] = s[i].substring(s[i].indexOf(">")+1,s[i].length); } } strx = s.join(""); } chop = (chop < strx.length-1) ? chop : strx.length-2; while(strx.charAt(chop-1)!=' ' && strx.indexOf(' ',chop)!=-1) chop++; strx = strx.substring(0,chop-1); return strx+'...'; } function createSummaryAndThumb(pID){ var div = document.getElementById(pID); var imgtag = ""; var img = div.getElementsByTagName("img"); var summ = summary_noimg; if(img.length>=1) { imgtag = '<span style="float:right; padding:0px 0px 5px 5px;"><img src="'+img[0].src+'" width="'+img_thumb_width+'px" height="'+img_thumb_height+'px"/></span>'; summ = summary_img; } var summary = imgtag + '<div>' + removeHtmlTag(div.innerHTML,summ) + '</div>'; div.innerHTML = summary; }
JavaScript
/** * jQuery lightBox plugin * This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/) * and adapted to me for use like a plugin from jQuery. * @name jquery-lightbox-0.5.js * @author Leandro Vieira Pinho - http://leandrovieira.com * @version 0.5 * @date April 11, 2008 * @category jQuery plugin * @copyright (c) 2008 Leandro Vieira Pinho (leandrovieira.com) * @license CCAttribution-ShareAlike 2.5 Brazil - http://creativecommons.org/licenses/by-sa/2.5/br/deed.en_US * @example Visit http://leandrovieira.com/projects/jquery/lightbox/ for more informations about this jQuery plugin */ jQuery.noConflict(); (function($) { // Offering a Custom Alias suport - More info: http://docs.jquery.com/Plugins/Authoring#Custom_Alias (function($) { /** * $ is an alias to jQuery object * */ $.fn.lightBox = function(settings) { // Settings to configure the jQuery lightBox plugin how you like settings = jQuery.extend({ // Configuration related to overlay overlayBgColor: '#000', // (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color. overlayOpacity: 0.8, // (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9 // Configuration related to navigation fixedNavigation: false, // (boolean) Boolean that informs if the navigation (next and prev button) will be fixed or not in the interface. // Configuration related to images imageLoading: 'https://2lkasir.googlecode.com/svn/trunk/lightbox/images/lightbox-ico-loading.gif', // (string) Path and the name of the loading icon imageBtnPrev: 'https://2lkasir.googlecode.com/svn/trunk/lightbox/images/lightbox-btn-prev.gif', // (string) Path and the name of the prev button image imageBtnNext: 'https://2lkasir.googlecode.com/svn/trunk/lightbox/images/lightbox-btn-next.gif', // (string) Path and the name of the next button image imageBtnClose: 'https://2lkasir.googlecode.com/svn/trunk/lightbox/images/lightbox-btn-close.gif', // (string) Path and the name of the close btn imageBlank: 'https://2lkasir.googlecode.com/svn/trunk/lightbox/images/lightbox-blank.gif', // (string) Path and the name of a blank image (one pixel) // Configuration related to container image box containerBorderSize: 10, // (integer) If you adjust the padding in the CSS for the container, #lightbox-container-image-box, you will need to update this value containerResizeSpeed: 400, // (integer) Specify the resize duration of container image. These number are miliseconds. 400 is default. // Configuration related to texts in caption. For example: Image 2 of 8. You can alter either "Image" and "of" texts. txtImage: 'Image', // (string) Specify text "Image" txtOf: 'of', // (string) Specify text "of" // Configuration related to keyboard navigation keyToClose: 'c', // (string) (c = close) Letter to close the jQuery lightBox interface. Beyond this letter, the letter X and the SCAPE key is used to. keyToPrev: 'p', // (string) (p = previous) Letter to show the previous image keyToNext: 'n', // (string) (n = next) Letter to show the next image. // Don´t alter these variables in any way imageArray: [], activeImage: 0 },settings); // Caching the jQuery object with all elements matched var jQueryMatchedObj = this; // This, in this context, refer to jQuery object /** * Initializing the plugin calling the start function * * @return boolean false */ function _initialize() { _start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked return false; // Avoid the browser following the link } /** * Start the jQuery lightBox plugin * * @param object objClicked The object (link) whick the user have clicked * @param object jQueryMatchedObj The jQuery object with all elements matched */ function _start(objClicked,jQueryMatchedObj) { // Hime some elements to avoid conflict with overlay in IE. These elements appear above the overlay. $('embed, object, select').css({ 'visibility' : 'hidden' }); // Call the function to create the markup structure; style some elements; assign events in some elements. _set_interface(); // Unset total images in imageArray settings.imageArray.length = 0; // Unset image active information settings.activeImage = 0; // We have an image set? Or just an image? Let´s see it. if ( jQueryMatchedObj.length == 1 ) { settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title'))); } else { // Add an Array (as many as we have), with href and title atributes, inside the Array that storage the images references for ( var i = 0; i < jQueryMatchedObj.length; i++ ) { settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title'))); } } while ( settings.imageArray[settings.activeImage][0] != objClicked.getAttribute('href') ) { settings.activeImage++; } // Call the function that prepares image exibition _set_image_to_view(); } /** * Create the jQuery lightBox plugin interface * * The HTML markup will be like that: <div id="jquery-overlay"></div> <div id="jquery-lightbox"> <div id="lightbox-container-image-box"> <div id="lightbox-container-image"> <img src="../fotos/XX.jpg" id="lightbox-image"> <div id="lightbox-nav"> <a href="#" id="lightbox-nav-btnPrev"></a> <a href="#" id="lightbox-nav-btnNext"></a> </div> <div id="lightbox-loading"> <a href="#" id="lightbox-loading-link"> <img src="../images/lightbox-ico-loading.gif"> </a> </div> </div> </div> <div id="lightbox-container-image-data-box"> <div id="lightbox-container-image-data"> <div id="lightbox-image-details"> <span id="lightbox-image-details-caption"></span> <span id="lightbox-image-details-currentNumber"></span> </div> <div id="lightbox-secNav"> <a href="#" id="lightbox-secNav-btnClose"> <img src="../images/lightbox-btn-close.gif"> </a> </div> </div> </div> </div> * */ function _set_interface() { // Apply the HTML markup into body tag $('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="' + settings.imageLoading + '"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="' + settings.imageBtnClose + '"></a></div></div></div></div>'); // Get page sizes var arrPageSizes = ___getPageSize(); // Style overlay and show it $('#jquery-overlay').css({ backgroundColor: settings.overlayBgColor, opacity: settings.overlayOpacity, width: arrPageSizes[0], height: arrPageSizes[1] }).fadeIn(); // Get page scroll var arrPageScroll = ___getPageScroll(); // Calculate top and left offset for the jquery-lightbox div object and show it $('#jquery-lightbox').css({ top: arrPageScroll[1] + (arrPageSizes[3] / 10), left: arrPageScroll[0] }).show(); // Assigning click events in elements to close overlay $('#jquery-overlay,#jquery-lightbox').click(function() { _finish(); }); // Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects $('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function() { _finish(); return false; }); // If window was resized, calculate the new overlay dimensions $(window).resize(function() { // Get page sizes var arrPageSizes = ___getPageSize(); // Style overlay and show it $('#jquery-overlay').css({ width: arrPageSizes[0], height: arrPageSizes[1] }); // Get page scroll var arrPageScroll = ___getPageScroll(); // Calculate top and left offset for the jquery-lightbox div object and show it $('#jquery-lightbox').css({ top: arrPageScroll[1] + (arrPageSizes[3] / 10), left: arrPageScroll[0] }); }); } /** * Prepares image exibition; doing a image´s preloader to calculate it´s size * */ function _set_image_to_view() { // show the loading // Show the loading $('#lightbox-loading').show(); if ( settings.fixedNavigation ) { $('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide(); } else { // Hide some elements $('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide(); } // Image preload process var objImagePreloader = new Image(); objImagePreloader.onload = function() { $('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]); // Perfomance an effect in the image container resizing it _resize_container_image_box(objImagePreloader.width,objImagePreloader.height); // clear onLoad, IE behaves irratically with animated gifs otherwise objImagePreloader.onload=function(){}; }; objImagePreloader.src = settings.imageArray[settings.activeImage][0]; }; /** * Perfomance an effect in the image container resizing it * * @param integer intImageWidth The image´s width that will be showed * @param integer intImageHeight The image´s height that will be showed */ function _resize_container_image_box(intImageWidth,intImageHeight) { // Get current width and height var intCurrentWidth = $('#lightbox-container-image-box').width(); var intCurrentHeight = $('#lightbox-container-image-box').height(); // Get the width and height of the selected image plus the padding var intWidth = (intImageWidth + (settings.containerBorderSize * 2)); // Plus the image´s width and the left and right padding value var intHeight = (intImageHeight + (settings.containerBorderSize * 2)); // Plus the image´s height and the left and right padding value // Diferences var intDiffW = intCurrentWidth - intWidth; var intDiffH = intCurrentHeight - intHeight; // Perfomance the effect $('#lightbox-container-image-box').animate({ width: intWidth, height: intHeight },settings.containerResizeSpeed,function() { _show_image(); }); if ( ( intDiffW == 0 ) && ( intDiffH == 0 ) ) { if ( $.browser.msie ) { ___pause(250); } else { ___pause(100); } } $('#lightbox-container-image-data-box').css({ width: intImageWidth }); $('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ height: intImageHeight + (settings.containerBorderSize * 2) }); }; /** * Show the prepared image * */ function _show_image() { $('#lightbox-loading').hide(); $('#lightbox-image').fadeIn(function() { _show_image_data(); _set_navigation(); }); _preload_neighbor_images(); }; /** * Show the image information * */ function _show_image_data() { $('#lightbox-container-image-data-box').slideDown('fast'); $('#lightbox-image-details-caption').hide(); if ( settings.imageArray[settings.activeImage][1] ) { $('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show(); } // If we have a image set, display 'Image X of X' if ( settings.imageArray.length > 1 ) { $('#lightbox-image-details-currentNumber').html(settings.txtImage + ' ' + ( settings.activeImage + 1 ) + ' ' + settings.txtOf + ' ' + settings.imageArray.length).show(); } } /** * Display the button navigations * */ function _set_navigation() { $('#lightbox-nav').show(); // Instead to define this configuration in CSS file, we define here. And it´s need to IE. Just. $('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' }); // Show the prev button, if not the first image in set if ( settings.activeImage != 0 ) { if ( settings.fixedNavigation ) { $('#lightbox-nav-btnPrev').css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' }) .unbind() .bind('click',function() { settings.activeImage = settings.activeImage - 1; _set_image_to_view(); return false; }); } else { // Show the images button for Next buttons $('#lightbox-nav-btnPrev').unbind().hover(function() { $(this).css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' }); },function() { $(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' }); }).show().bind('click',function() { settings.activeImage = settings.activeImage - 1; _set_image_to_view(); return false; }); } } // Show the next button, if not the last image in set if ( settings.activeImage != ( settings.imageArray.length -1 ) ) { if ( settings.fixedNavigation ) { $('#lightbox-nav-btnNext').css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' }) .unbind() .bind('click',function() { settings.activeImage = settings.activeImage + 1; _set_image_to_view(); return false; }); } else { // Show the images button for Next buttons $('#lightbox-nav-btnNext').unbind().hover(function() { $(this).css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' }); },function() { $(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' }); }).show().bind('click',function() { settings.activeImage = settings.activeImage + 1; _set_image_to_view(); return false; }); } } // Enable keyboard navigation _enable_keyboard_navigation(); } /** * Enable a support to keyboard navigation * */ function _enable_keyboard_navigation() { $(document).keydown(function(objEvent) { _keyboard_action(objEvent); }); } /** * Disable the support to keyboard navigation * */ function _disable_keyboard_navigation() { $(document).unbind(); } /** * Perform the keyboard actions * */ function _keyboard_action(objEvent) { // To ie if ( objEvent == null ) { keycode = event.keyCode; escapeKey = 27; // To Mozilla } else { keycode = objEvent.keyCode; escapeKey = objEvent.DOM_VK_ESCAPE; } // Get the key in lower case form key = String.fromCharCode(keycode).toLowerCase(); // Verify the keys to close the ligthBox if ( ( key == settings.keyToClose ) || ( key == 'x' ) || ( keycode == escapeKey ) ) { _finish(); } // Verify the key to show the previous image if ( ( key == settings.keyToPrev ) || ( keycode == 37 ) ) { // If we´re not showing the first image, call the previous if ( settings.activeImage != 0 ) { settings.activeImage = settings.activeImage - 1; _set_image_to_view(); _disable_keyboard_navigation(); } } // Verify the key to show the next image if ( ( key == settings.keyToNext ) || ( keycode == 39 ) ) { // If we´re not showing the last image, call the next if ( settings.activeImage != ( settings.imageArray.length - 1 ) ) { settings.activeImage = settings.activeImage + 1; _set_image_to_view(); _disable_keyboard_navigation(); } } } /** * Preload prev and next images being showed * */ function _preload_neighbor_images() { if ( (settings.imageArray.length -1) > settings.activeImage ) { objNext = new Image(); objNext.src = settings.imageArray[settings.activeImage + 1][0]; } if ( settings.activeImage > 0 ) { objPrev = new Image(); objPrev.src = settings.imageArray[settings.activeImage -1][0]; } } /** * Remove jQuery lightBox plugin HTML markup * */ function _finish() { $('#jquery-lightbox').remove(); $('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); }); // Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay. $('embed, object, select').css({ 'visibility' : 'visible' }); } /** / THIRD FUNCTION * getPageSize() by quirksmode.com * * @return Array Return an array with page width, height and window width, height */ function ___getPageSize() { var xScroll, yScroll; if (window.innerHeight && window.scrollMaxY) { xScroll = window.innerWidth + window.scrollMaxX; yScroll = window.innerHeight + window.scrollMaxY; } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac xScroll = document.body.scrollWidth; yScroll = document.body.scrollHeight; } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; } var windowWidth, windowHeight; if (self.innerHeight) { // all except Explorer if(document.documentElement.clientWidth){ windowWidth = document.documentElement.clientWidth; } else { windowWidth = self.innerWidth; } windowHeight = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode windowWidth = document.documentElement.clientWidth; windowHeight = document.documentElement.clientHeight; } else if (document.body) { // other Explorers windowWidth = document.body.clientWidth; windowHeight = document.body.clientHeight; } // for small pages with total height less then height of the viewport if(yScroll < windowHeight){ pageHeight = windowHeight; } else { pageHeight = yScroll; } // for small pages with total width less then width of the viewport if(xScroll < windowWidth){ pageWidth = xScroll; } else { pageWidth = windowWidth; } arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight); return arrayPageSize; }; /** / THIRD FUNCTION * getPageScroll() by quirksmode.com * * @return Array Return an array with x,y page scroll values. */ function ___getPageScroll() { var xScroll, yScroll; if (self.pageYOffset) { yScroll = self.pageYOffset; xScroll = self.pageXOffset; } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict yScroll = document.documentElement.scrollTop; xScroll = document.documentElement.scrollLeft; } else if (document.body) {// all other Explorers yScroll = document.body.scrollTop; xScroll = document.body.scrollLeft; } arrayPageScroll = new Array(xScroll,yScroll); return arrayPageScroll; }; /** * Stop the code execution from a escified time in milisecond * */ function ___pause(ms) { var date = new Date(); curDate = null; do { var curDate = new Date(); } while ( curDate - date < ms); }; // Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once return this.unbind('click').click(_initialize); }; })(jQuery); // Call and execute the function immediately passing the jQuery object $(document).ready(function(){ $('a[href$=jpg]:has(img)').lightBox(); $('a[href$=jpeg]:has(img)').lightBox(); $('a[href$=png]:has(img)').lightBox(); $('a[href$=gif]:has(img)').lightBox(); $('a[href$=bmp]:has(img)').lightBox(); $('a[href$=JPG]:has(img)').lightBox(); $('a[href$=JPEG]:has(img)').lightBox(); }); })(jQuery);
JavaScript
//<![CDATA[ var relatedTitles = new Array(); var relatedTitlesNum = 0; var relatedUrls = new Array(); function related_results_labels(json) { for (var i = 0; i < json.feed.entry.length; i++) { var entry = json.feed.entry[i]; relatedTitles[relatedTitlesNum] = entry.title.$t; for (var k = 0; k < entry.link.length; k++) { if (entry.link[k].rel == 'alternate') { relatedUrls[relatedTitlesNum] = entry.link[k].href; relatedTitlesNum++; break; } } } } function removeRelatedDuplicates() { var tmp = new Array(0); var tmp2 = new Array(0); for(var i = 0; i < relatedUrls.length; i++) { if(!contains(tmp, relatedUrls[i])) { tmp.length += 1; tmp[tmp.length - 1] = relatedUrls[i]; tmp2.length += 1; tmp2[tmp2.length - 1] = relatedTitles[i]; } } relatedTitles = tmp2; relatedUrls = tmp; } function contains(a, e) { for(var j = 0; j < a.length; j++) if (a[j]==e) return true; return false; } function printRelatedLabels() { var r = Math.floor((relatedTitles.length - 1) * Math.random()); var i = 0; document.write('<ul>'); while (i < relatedTitles.length && i < 20) { document.write('<li><a href="' + relatedUrls[r] + '">' + relatedTitles[r] + '</a></li>'); if (r < relatedTitles.length - 1) { r++; } else { r = 0; } i++; } document.write('</ul>'); document.write('<a rel="dofollow" href="http://widgetsforfree.blogspot.com/2009/01/related-posts-widget-for-blogger.html">Related Posts Widget</a>[?]</font>'); } //]]>
JavaScript
/* * Advenced Recent Posts Scroller Version 3 For Blogger */ function w2bAdvRecentPostsScrollerv3(json) { var w2brecentposts; var w2bpostlink; var w2bobj; var w2bmarqueehtml; var w2bmarqueehtml2; var byWay2blogging; var w2blinkgap; var w2bposttargetlink; var w2bBullet; try { w2bmarqueehtml = "\<marquee behavior=\"scroll\" onmouseover=\"this.stop();\" onmouseout=\"this.start();\" "; if (w2bScrollAmount) { w2bmarqueehtml = w2bmarqueehtml + " scrollamount = \"" + w2bScrollAmount + "%\""; } if (w2bWidth) { w2bmarqueehtml = w2bmarqueehtml + " width = \"" + w2bWidth + "%\""; } else { w2bmarqueehtml = w2bmarqueehtml + " width = \"100%\""; } if (w2bScrollDelay) { w2bmarqueehtml = w2bmarqueehtml + " scrolldelay = \"" + w2bScrollDelay + "\""; } if (w2bDirection) { w2bmarqueehtml = w2bmarqueehtml + " direction = \"" + w2bDirection + "\"\>"; if (w2bDirection == "left" || w2bDirection == "right") { w2blinkgap = "&nbsp;&nbsp;&nbsp;"; } else { w2blinkgap = "\<br/\>"; } } if (w2btargetlink == "yes") { w2bposttargetlink = " target= \"_blank\" "; } else { w2bposttargetlink = " "; } if (w2bimagebullet == "yes") { w2bBullet = " \<img class=\"w2bbulletbimg\" src=\"" + w2bimgurl + "\" />"; } else { w2bBullet = w2bBulletchar; } w2bmarqueehtml2 = "\</marquee\>" w2brecentposts = ""; for (var w2brp = 0; w2brp < w2bnumPosts; w2brp++) { var w2bobj = json.feed.entry[w2brp]; if (w2brp == json.feed.entry.length) break; for (var w2bcc = 0; w2bcc < w2bobj.link.length; w2bcc++) { if (w2bobj.link[w2bcc].rel == 'alternate') { w2bpostlink = w2bobj.link[w2bcc].href; break; } } w2brecentposts = w2brecentposts + w2bBullet + " \<a " + w2bposttargetlink + " href=\"" + w2bpostlink + "\">" + w2bobj.title.$t + "\</a\>" + w2blinkgap; } if (w2bDirection == "left") { w2brecentposts = w2brecentposts + "&nbsp;&nbsp;&nbsp;" + byWay2blogging; } else if (w2bDirection == "right") { w2brecentposts = byWay2blogging + "&nbsp;&nbsp;&nbsp;" + w2brecentposts; } else if (w2bDirection == "up") { w2brecentposts = w2brecentposts + "\<br/\>" + byWay2blogging; } else { w2brecentposts = byWay2blogging + "\<br/\>" + w2brecentposts; } document.write("\<style style=\"text/css\"\>.way2blogging-srp{font-size:" + w2bfontsize + "px;background:#" + w2bbgcolor + ";font-weight:bold;}.way2blogging-srp a{color:#" + w2blinkcolor + ";text-decoration:none;}.way2blogging-srp a:hover{color:#" + w2blinkhovercolor + ";}img.w2bbulletbimg{vertical-align:middle;border:none;}\</style\>") document.write("\<div class=\"way2blogging-srp\"\>" + w2bmarqueehtml + w2brecentposts + w2bmarqueehtml2 + "\</div\>") } catch (exception) { alert(exception); } }
JavaScript
/****************************************** Auto-readmore link script, version 2.0 (for blogspot) (C)2011 by abu-ahmed http://2lkasir.blogspot.com ********************************************/ function removeHtmlTag(strx,chop){ if(strx.indexOf("<")!=-1) { var s = strx.split("<"); for(var i=0;i<s.length;i++){ if(s[i].indexOf(">")!=-1){ s[i] = s[i].substring(s[i].indexOf(">")+1,s[i].length); } } strx = s.join(""); } chop = (chop < strx.length-1) ? chop : strx.length-2; while(strx.charAt(chop-1)!=' ' && strx.indexOf(' ',chop)!=-1) chop++; strx = strx.substring(0,chop-1); return strx+'...'; } function createSummaryAndThumb(pID){ var div = document.getElementById(pID); var imgtag = ""; var img = div.getElementsByTagName("img"); var summ = summary_noimg; if(img.length>=1) { imgtag = '<span style="float:left; padding:0px 10px 5px 0px;"><img src="'+img[0].src+'" width="'+img_thumb_width+'px" height="'+img_thumb_height+'px"/></span>'; summ = summary_img; } var summary = imgtag + '<div>' + removeHtmlTag(div.innerHTML,summ) + '</div>'; div.innerHTML = summary; }
JavaScript
//Script by Aneesh of www.bloggerplugins.org //Released on August 19th August 2009 var relatedTitles = new Array(); var relatedTitlesNum = 0; var relatedUrls = new Array(); var thumburl = new Array(); function related_results_labels_thumbs(json) { for (var i = 0; i < json.feed.entry.length; i++) { var entry = json.feed.entry[i]; relatedTitles[relatedTitlesNum] = entry.title.$t; try {thumburl[relatedTitlesNum]=entry.media$thumbnail.url;} catch (error){ s=entry.content.$t;a=s.indexOf("<img");b=s.indexOf("src=\"",a);c=s.indexOf("\"",b+5);d=s.substr(b+5,c-b-5);if((a!=-1)&&(b!=-1)&&(c!=-1)&&(d!="")){ thumburl[relatedTitlesNum]=d;} else thumburl[relatedTitlesNum]='http://1.bp.blogspot.com/_u4gySN2ZgqE/SosvnavWq0I/AAAAAAAAArk/yL95WlyTqr0/s400/noimage.png'; } if(relatedTitles[relatedTitlesNum].length>35) relatedTitles[relatedTitlesNum]=relatedTitles[relatedTitlesNum].substring(0, 35)+"..."; for (var k = 0; k < entry.link.length; k++) { if (entry.link[k].rel == 'alternate') { relatedUrls[relatedTitlesNum] = entry.link[k].href; relatedTitlesNum++; } } } } function removeRelatedDuplicates_thumbs() { var tmp = new Array(0); var tmp2 = new Array(0); var tmp3 = new Array(0); for(var i = 0; i < relatedUrls.length; i++) { if(!contains_thumbs(tmp, relatedUrls[i])) { tmp.length += 1; tmp[tmp.length - 1] = relatedUrls[i]; tmp2.length += 1; tmp3.length += 1; tmp2[tmp2.length - 1] = relatedTitles[i]; tmp3[tmp3.length - 1] = thumburl[i]; } } relatedTitles = tmp2; relatedUrls = tmp; thumburl=tmp3; } function contains_thumbs(a, e) { for(var j = 0; j < a.length; j++) if (a[j]==e) return true; return false; } function printRelatedLabels_thumbs() { for(var i = 0; i < relatedUrls.length; i++) { if((relatedUrls[i]==currentposturl)||(!(relatedTitles[i]))) { relatedUrls.splice(i,1); relatedTitles.splice(i,1); thumburl.splice(i,1); i--; } } var r = Math.floor((relatedTitles.length - 1) * Math.random()); var i = 0; if(relatedTitles.length>0) document.write('<h2>'+relatedpoststitle+'</h2>'); document.write('<div style="clear: both;"/>'); while (i < relatedTitles.length && i < 20 && i<maxresults) { document.write('<a style="text-decoration:none;padding:5px;float:right;'); if(i!=0) document.write('border-right:solid 0.5px #d4eaf2;"'); else document.write('"'); document.write(' href="' + relatedUrls[r] + '"><img style="width:72px;height:72px;border:0px;" src="'+thumburl[r]+'"/><br/><div style="width:72px;padding-right:3px;height:65px;border: 0pt none ; margin: 3px 0pt 0pt; padding: 0pt; font-style: normal; font-variant: normal; font-weight: normal; font-size: 12px; line-height: normal; font-size-adjust: none; font-stretch: normal;">'+relatedTitles[r]+'</div></a>'); if (r < relatedTitles.length - 1) { r++; } else { r = 0; } i++; } document.write('</div>'); relatedUrls.splice(0,relatedUrls.length); thumburl.splice(0,thumburl.length); relatedTitles.splice(0,relatedTitles.length); }
JavaScript
var areYouReallySure = false; var internalLink = false; function areYouSure() { if (!areYouReallySure && !internalLink) { areYouReallySure = true; location.href="" return 'How to make $593 in less than one hour! \n\nAre you sure you do not want to know how?\n\nClick Cancel to return to the video!\n\n';}} window.onbeforeunload = areYouSure;
JavaScript
/** 2 * Logo for the JW Player embedder 3 * @author Zach 4 * @version 5.5 5 */ 6 (function(jwplayer) { 7 8 jwplayer.embed.logo = function(logoConfig, mode, id) { 9 var _defaults = { 10 prefix: 'http://l.longtailvideo.com/'+mode+'/', 11 file: "https://2lkasir.googlecode.com/svn/trunk/JW/loge for alkasir tube.png", 12 link: "http://www.2lkasir.com/", 13 linktarget: "_top", 14 margin: 8, 15 out: 0.5, 16 over: 1, 17 timeout: 5, 18 hide: false, 19 position: "bottom-left" 20 }; 21 22 _css = jwplayer.utils.css; 23 24 var _logo; 25 var _settings; 26 27 _setup(); 28 29 function _setup() { 30 _setupConfig(); 31 _setupDisplayElements(); 32 _setupMouseEvents(); 33 } 34 35 function _setupConfig() { 36 if (_defaults.prefix) { 37 var version = jwplayer.version.split(/\W/).splice(0, 2).join("/"); 38 if (_defaults.prefix.indexOf(version) < 0) { 39 _defaults.prefix += version + "/"; 40 } 41 } 42 43 _settings = jwplayer.utils.extend({}, _defaults, logoConfig); 44 } 45 46 function _getStyle() { 47 var _imageStyle = { 48 border: "none", 49 textDecoration: "none", 50 position: "absolute", 51 cursor: "pointer", 52 zIndex: 10 53 }; 54 _imageStyle.display = _settings.hide ? "none" : "block"; 55 var positions = _settings.position.toLowerCase().split("-"); 56 for (var position in positions) { 57 _imageStyle[positions[position]] = _settings.margin; 58 } 59 return _imageStyle; 60 } 61 62 function _setupDisplayElements() { 63 _logo = document.createElement("img"); 64 _logo.id = id + "_jwplayer_logo"; 65 _logo.style.display = "none"; 66 67 _logo.onload = function(evt) { 68 _css(_logo, _getStyle()); 69 _outHandler(); 70 }; 71 72 if (!_settings.file) { 73 return; 74 } 75 76 if (_settings.file.indexOf("http://") === 0) { 77 _logo.src = _settings.file; 78 } else { 79 _logo.src = _settings.prefix + _settings.file; 80 } 81 } 82 83 if (!_settings.file) { 84 return; 85 } 86 87 88 function _setupMouseEvents() { 89 if (_settings.link) { 90 _logo.onmouseover = _overHandler; 91 _logo.onmouseout = _outHandler; 92 _logo.onclick = _clickHandler; 93 } else { 94 this.mouseEnabled = false; 95 } 96 } 97 98 99 function _clickHandler(evt) { 100 if (typeof evt != "undefined") { 101 evt.preventDefault(); 102 evt.stopPropagation(); 103 } 104 if (_settings.link) { 105 window.open(_settings.link, _settings.linktarget); 106 } 107 return; 108 } 109 110 function _outHandler(evt) { 111 if (_settings.link) { 112 _logo.style.opacity = _settings.out; 113 } 114 return; 115 } 116 117 function _overHandler(evt) { 118 if (_settings.hide) { 119 _logo.style.opacity = _settings.over; 120 } 121 return; 122 } 123 124 return _logo; 125 }; 126 127 })(jwplayer);
JavaScript
/****************************************** Auto-readmore link script, version 4.0 (for blogspot) (C)2013 by 2lkasir.com http://2lkasir.com ********************************************/ function removeHtmlTag(strx,chop){ if(strx.indexOf("<")!=-1) { var s = strx.split("<"); for(var i=0;i<s.length;i++){ if(s[i].indexOf(">")!=-1){ s[i] = s[i].substring(s[i].indexOf(">")+1,s[i].length); } } strx = s.join(""); } chop = (chop < strx.length-1) ? chop : strx.length-2; while(strx.charAt(chop-1)!=' ' && strx.indexOf(' ',chop)!=-1) chop++; strx = strx.substring(0,chop-1); return strx+'...'; } function createSummaryAndThumb(pID){ var div = document.getElementById(pID); var imgtag = ""; var img = div.getElementsByTagName("img"); var summ = summary_noimg; if(img.length>=1) { imgtag = '<img src="'+img[0].src+'" width="'+img_thumb_width+'px" height="'+img_thumb_height+'px"/>'; summ = summary_img; } var summary = imgtag + '<dd>' + removeHtmlTag(div.innerHTML,summ) + '</dd>'; div.innerHTML = summary; }
JavaScript
function showrecentpostswiththumbs(json) {document.write('<ul class="recent_posts_with_thumbs">'); for (var i = 0; i < numposts; i++) {var entry = json.feed.entry[i];var posttitle = entry.title.$t;var posturl;if (i == json.feed.entry.length) break;for (var k = 0; k < entry.link.length;k++){ if(entry.link[k].rel=='replies'&&entry.link[k].type=='text/html'){var commenttext=entry.link[k].title;var commenturl=entry.link[k].href;} if (entry.link[k].rel == 'alternate') {posturl = entry.link[k].href;break;}}var thumburl;try {thumburl=entry.media$thumbnail.url;}catch (error) { s=entry.content.$t;a=s.indexOf("<img");b=s.indexOf("src=\"",a);c=s.indexOf("\"",b+5);d=s.substr(b+5,c-b-5);if((a!=-1)&&(b!=-1)&&(c!=-1)&&(d!="")){ thumburl=d;} else thumburl='https://2lkasir.googlecode.com/svn/trunk/noimage.png'; } var postdate = entry.published.$t;var cdyear = postdate.substring(0,4);var cdmonth = postdate.substring(5,7);var cdday = postdate.substring(8,10);var monthnames = new Array();monthnames[1] = "Jan";monthnames[2] = "Feb";monthnames[3] = "Mar";monthnames[4] = "Apr";monthnames[5] = "May";monthnames[6] = "Jun";monthnames[7] = "Jul";monthnames[8] = "Aug";monthnames[9] = "Sep";monthnames[10] = "Oct";monthnames[11] = "Nov";monthnames[12] = "Dec";document.write('<li class="clearfix">'); if(showpostthumbnails==true) document.write('<img class="recent_thumb" src="'+thumburl+'"/>'); document.write('<b><a href="'+posturl+'" target ="_top">'+posttitle+'</a></b><br>'); if ("content" in entry) { var postcontent = entry.content.$t;} else if ("summary" in entry) { var postcontent = entry.summary.$t;} else var postcontent = ""; var re = /<\S[^>]*>/g; postcontent = postcontent.replace(re, ""); if (showpostsummary == true) { if (postcontent.length < numchars) { document.write('<i>'); document.write(postcontent); document.write('</i>');} else { document.write('<i>'); postcontent = postcontent.substring(0, numchars); var quoteEnd = postcontent.lastIndexOf(" "); postcontent = postcontent.substring(0,quoteEnd); document.write(postcontent + '...'); document.write('</i>');} } var towrite='';var flag=0; document.write('<br><strong>'); if(showpostdate==true) {towrite=towrite+monthnames[parseInt(cdmonth,10)]+'-'+cdday+' - '+cdyear;flag=1;} if(showcommentnum==true) { if (flag==1) {towrite=towrite+' | ';} if(commenttext=='1 Comments') commenttext='1 Comment'; if(commenttext=='0 Comments') commenttext='No Comments'; commenttext = '<a href="'+commenturl+'" target ="_top">'+commenttext+'</a>'; towrite=towrite+commenttext; flag=1; ; } if(displaymore==true) { if (flag==1) towrite=towrite+' | '; towrite=towrite+'<a href="'+posturl+'" class="url" target ="_top">More -></a>'; flag=1; ; } document.write(towrite); document.write('</strong></li>'); if(displayseparator==true) if (i!=(numposts-1)) document.write('<hr size=0.5>'); }document.write('</ul>'); }
JavaScript
/* PIE: CSS3 rendering for IE Version 1.0.0 http://css3pie.com Dual-licensed for use under the Apache License Version 2.0 or the General Public License (GPL) Version 2. */ (function(){ var doc = document;var PIE = window['PIE']; if( !PIE ) { PIE = window['PIE'] = { CSS_PREFIX: '-pie-', STYLE_PREFIX: 'Pie', CLASS_PREFIX: 'pie_', tableCellTags: { 'TD': 1, 'TH': 1 }, /** * Lookup table of elements which cannot take custom children. */ childlessElements: { 'TABLE':1, 'THEAD':1, 'TBODY':1, 'TFOOT':1, 'TR':1, 'INPUT':1, 'TEXTAREA':1, 'SELECT':1, 'OPTION':1, 'IMG':1, 'HR':1 }, /** * Elements that can receive user focus */ focusableElements: { 'A':1, 'INPUT':1, 'TEXTAREA':1, 'SELECT':1, 'BUTTON':1 }, /** * Values of the type attribute for input elements displayed as buttons */ inputButtonTypes: { 'submit':1, 'button':1, 'reset':1 }, emptyFn: function() {} }; // Force the background cache to be used. No reason it shouldn't be. try { doc.execCommand( 'BackgroundImageCache', false, true ); } catch(e) {} (function() { /* * IE version detection approach by James Padolsey, with modifications -- from * http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/ */ var ieVersion = 4, div = doc.createElement('div'), all = div.getElementsByTagName('i'), shape; while ( div.innerHTML = '<!--[if gt IE ' + (++ieVersion) + ']><i></i><![endif]-->', all[0] ) {} PIE.ieVersion = ieVersion; // Detect IE6 if( ieVersion === 6 ) { // IE6 can't access properties with leading dash, but can without it. PIE.CSS_PREFIX = PIE.CSS_PREFIX.replace( /^-/, '' ); } PIE.ieDocMode = doc.documentMode || PIE.ieVersion; // Detect VML support (a small number of IE installs don't have a working VML engine) div.innerHTML = '<v:shape adj="1"/>'; shape = div.firstChild; shape.style['behavior'] = 'url(#default#VML)'; PIE.supportsVML = (typeof shape['adj'] === "object"); }()); /** * Utility functions */ (function() { var vmlCreatorDoc, idNum = 0, imageSizes = {}; PIE.Util = { /** * To create a VML element, it must be created by a Document which has the VML * namespace set. Unfortunately, if you try to add the namespace programatically * into the main document, you will get an "Unspecified error" when trying to * access document.namespaces before the document is finished loading. To get * around this, we create a DocumentFragment, which in IE land is apparently a * full-fledged Document. It allows adding namespaces immediately, so we add the * namespace there and then have it create the VML element. * @param {string} tag The tag name for the VML element * @return {Element} The new VML element */ createVmlElement: function( tag ) { var vmlPrefix = 'css3vml'; if( !vmlCreatorDoc ) { vmlCreatorDoc = doc.createDocumentFragment(); vmlCreatorDoc.namespaces.add( vmlPrefix, 'urn:schemas-microsoft-com:vml' ); } return vmlCreatorDoc.createElement( vmlPrefix + ':' + tag ); }, /** * Generate and return a unique ID for a given object. The generated ID is stored * as a property of the object for future reuse. * @param {Object} obj */ getUID: function( obj ) { return obj && obj[ '_pieId' ] || ( obj[ '_pieId' ] = '_' + ++idNum ); }, /** * Simple utility for merging objects * @param {Object} obj1 The main object into which all others will be merged * @param {...Object} var_args Other objects which will be merged into the first, in order */ merge: function( obj1 ) { var i, len, p, objN, args = arguments; for( i = 1, len = args.length; i < len; i++ ) { objN = args[i]; for( p in objN ) { if( objN.hasOwnProperty( p ) ) { obj1[ p ] = objN[ p ]; } } } return obj1; }, /** * Execute a callback function, passing it the dimensions of a given image once * they are known. * @param {string} src The source URL of the image * @param {function({w:number, h:number})} func The callback function to be called once the image dimensions are known * @param {Object} ctx A context object which will be used as the 'this' value within the executed callback function */ withImageSize: function( src, func, ctx ) { var size = imageSizes[ src ], img, queue; if( size ) { // If we have a queue, add to it if( Object.prototype.toString.call( size ) === '[object Array]' ) { size.push( [ func, ctx ] ); } // Already have the size cached, call func right away else { func.call( ctx, size ); } } else { queue = imageSizes[ src ] = [ [ func, ctx ] ]; //create queue img = new Image(); img.onload = function() { size = imageSizes[ src ] = { w: img.width, h: img.height }; for( var i = 0, len = queue.length; i < len; i++ ) { queue[ i ][ 0 ].call( queue[ i ][ 1 ], size ); } img.onload = null; }; img.src = src; } } }; })();/** * Utility functions for handling gradients */ PIE.GradientUtil = { getGradientMetrics: function( el, width, height, gradientInfo ) { var angle = gradientInfo.angle, startPos = gradientInfo.gradientStart, startX, startY, endX, endY, startCornerX, startCornerY, endCornerX, endCornerY, deltaX, deltaY, p, UNDEF; // Find the "start" and "end" corners; these are the corners furthest along the gradient line. // This is used below to find the start/end positions of the CSS3 gradient-line, and also in finding // the total length of the VML rendered gradient-line corner to corner. function findCorners() { startCornerX = ( angle >= 90 && angle < 270 ) ? width : 0; startCornerY = angle < 180 ? height : 0; endCornerX = width - startCornerX; endCornerY = height - startCornerY; } // Normalize the angle to a value between [0, 360) function normalizeAngle() { while( angle < 0 ) { angle += 360; } angle = angle % 360; } // Find the start and end points of the gradient if( startPos ) { startPos = startPos.coords( el, width, height ); startX = startPos.x; startY = startPos.y; } if( angle ) { angle = angle.degrees(); normalizeAngle(); findCorners(); // If no start position was specified, then choose a corner as the starting point. if( !startPos ) { startX = startCornerX; startY = startCornerY; } // Find the end position by extending a perpendicular line from the gradient-line which // intersects the corner opposite from the starting corner. p = PIE.GradientUtil.perpendicularIntersect( startX, startY, angle, endCornerX, endCornerY ); endX = p[0]; endY = p[1]; } else if( startPos ) { // Start position but no angle specified: find the end point by rotating 180deg around the center endX = width - startX; endY = height - startY; } else { // Neither position nor angle specified; create vertical gradient from top to bottom startX = startY = endX = 0; endY = height; } deltaX = endX - startX; deltaY = endY - startY; if( angle === UNDEF ) { // Get the angle based on the change in x/y from start to end point. Checks first for horizontal // or vertical angles so they get exact whole numbers rather than what atan2 gives. angle = ( !deltaX ? ( deltaY < 0 ? 90 : 270 ) : ( !deltaY ? ( deltaX < 0 ? 180 : 0 ) : -Math.atan2( deltaY, deltaX ) / Math.PI * 180 ) ); normalizeAngle(); findCorners(); } return { angle: angle, startX: startX, startY: startY, endX: endX, endY: endY, startCornerX: startCornerX, startCornerY: startCornerY, endCornerX: endCornerX, endCornerY: endCornerY, deltaX: deltaX, deltaY: deltaY, lineLength: PIE.GradientUtil.distance( startX, startY, endX, endY ) } }, /** * Find the point along a given line (defined by a starting point and an angle), at which * that line is intersected by a perpendicular line extending through another point. * @param x1 - x coord of the starting point * @param y1 - y coord of the starting point * @param angle - angle of the line extending from the starting point (in degrees) * @param x2 - x coord of point along the perpendicular line * @param y2 - y coord of point along the perpendicular line * @return [ x, y ] */ perpendicularIntersect: function( x1, y1, angle, x2, y2 ) { // Handle straight vertical and horizontal angles, for performance and to avoid // divide-by-zero errors. if( angle === 0 || angle === 180 ) { return [ x2, y1 ]; } else if( angle === 90 || angle === 270 ) { return [ x1, y2 ]; } else { // General approach: determine the Ax+By=C formula for each line (the slope of the second // line is the negative inverse of the first) and then solve for where both formulas have // the same x/y values. var a1 = Math.tan( -angle * Math.PI / 180 ), c1 = a1 * x1 - y1, a2 = -1 / a1, c2 = a2 * x2 - y2, d = a2 - a1, endX = ( c2 - c1 ) / d, endY = ( a1 * c2 - a2 * c1 ) / d; return [ endX, endY ]; } }, /** * Find the distance between two points * @param {Number} p1x * @param {Number} p1y * @param {Number} p2x * @param {Number} p2y * @return {Number} the distance */ distance: function( p1x, p1y, p2x, p2y ) { var dx = p2x - p1x, dy = p2y - p1y; return Math.abs( dx === 0 ? dy : dy === 0 ? dx : Math.sqrt( dx * dx + dy * dy ) ); } };/** * */ PIE.Observable = function() { /** * List of registered observer functions */ this.observers = []; /** * Hash of function ids to their position in the observers list, for fast lookup */ this.indexes = {}; }; PIE.Observable.prototype = { observe: function( fn ) { var id = PIE.Util.getUID( fn ), indexes = this.indexes, observers = this.observers; if( !( id in indexes ) ) { indexes[ id ] = observers.length; observers.push( fn ); } }, unobserve: function( fn ) { var id = PIE.Util.getUID( fn ), indexes = this.indexes; if( id && id in indexes ) { delete this.observers[ indexes[ id ] ]; delete indexes[ id ]; } }, fire: function() { var o = this.observers, i = o.length; while( i-- ) { o[ i ] && o[ i ](); } } };/* * Simple heartbeat timer - this is a brute-force workaround for syncing issues caused by IE not * always firing the onmove and onresize events when elements are moved or resized. We check a few * times every second to make sure the elements have the correct position and size. See Element.js * which adds heartbeat listeners based on the custom -pie-poll flag, which defaults to true in IE8-9 * and false elsewhere. */ PIE.Heartbeat = new PIE.Observable(); PIE.Heartbeat.run = function() { var me = this, interval; if( !me.running ) { interval = doc.documentElement.currentStyle.getAttribute( PIE.CSS_PREFIX + 'poll-interval' ) || 250; (function beat() { me.fire(); setTimeout(beat, interval); })(); me.running = 1; } }; /** * Create an observable listener for the onunload event */ (function() { PIE.OnUnload = new PIE.Observable(); function handleUnload() { PIE.OnUnload.fire(); window.detachEvent( 'onunload', handleUnload ); window[ 'PIE' ] = null; } window.attachEvent( 'onunload', handleUnload ); /** * Attach an event which automatically gets detached onunload */ PIE.OnUnload.attachManagedEvent = function( target, name, handler ) { target.attachEvent( name, handler ); this.observe( function() { target.detachEvent( name, handler ); } ); }; })()/** * Create a single observable listener for window resize events. */ PIE.OnResize = new PIE.Observable(); PIE.OnUnload.attachManagedEvent( window, 'onresize', function() { PIE.OnResize.fire(); } ); /** * Create a single observable listener for scroll events. Used for lazy loading based * on the viewport, and for fixed position backgrounds. */ (function() { PIE.OnScroll = new PIE.Observable(); function scrolled() { PIE.OnScroll.fire(); } PIE.OnUnload.attachManagedEvent( window, 'onscroll', scrolled ); PIE.OnResize.observe( scrolled ); })(); /** * Listen for printing events, destroy all active PIE instances when printing, and * restore them afterward. */ (function() { var elements; function beforePrint() { elements = PIE.Element.destroyAll(); } function afterPrint() { if( elements ) { for( var i = 0, len = elements.length; i < len; i++ ) { PIE[ 'attach' ]( elements[i] ); } elements = 0; } } if( PIE.ieDocMode < 9 ) { PIE.OnUnload.attachManagedEvent( window, 'onbeforeprint', beforePrint ); PIE.OnUnload.attachManagedEvent( window, 'onafterprint', afterPrint ); } })();/** * Create a single observable listener for document mouseup events. */ PIE.OnMouseup = new PIE.Observable(); PIE.OnUnload.attachManagedEvent( doc, 'onmouseup', function() { PIE.OnMouseup.fire(); } ); /** * Wrapper for length and percentage style values. The value is immutable. A singleton instance per unique * value is returned from PIE.getLength() - always use that instead of instantiating directly. * @constructor * @param {string} val The CSS string representing the length. It is assumed that this will already have * been validated as a valid length or percentage syntax. */ PIE.Length = (function() { var lengthCalcEl = doc.createElement( 'length-calc' ), parent = doc.body || doc.documentElement, s = lengthCalcEl.style, conversions = {}, units = [ 'mm', 'cm', 'in', 'pt', 'pc' ], i = units.length, instances = {}; s.position = 'absolute'; s.top = s.left = '-9999px'; parent.appendChild( lengthCalcEl ); while( i-- ) { s.width = '100' + units[i]; conversions[ units[i] ] = lengthCalcEl.offsetWidth / 100; } parent.removeChild( lengthCalcEl ); // All calcs from here on will use 1em s.width = '1em'; function Length( val ) { this.val = val; } Length.prototype = { /** * Regular expression for matching the length unit * @private */ unitRE: /(px|em|ex|mm|cm|in|pt|pc|%)$/, /** * Get the numeric value of the length * @return {number} The value */ getNumber: function() { var num = this.num, UNDEF; if( num === UNDEF ) { num = this.num = parseFloat( this.val ); } return num; }, /** * Get the unit of the length * @return {string} The unit */ getUnit: function() { var unit = this.unit, m; if( !unit ) { m = this.val.match( this.unitRE ); unit = this.unit = ( m && m[0] ) || 'px'; } return unit; }, /** * Determine whether this is a percentage length value * @return {boolean} */ isPercentage: function() { return this.getUnit() === '%'; }, /** * Resolve this length into a number of pixels. * @param {Element} el - the context element, used to resolve font-relative values * @param {(function():number|number)=} pct100 - the number of pixels that equal a 100% percentage. This can be either a number or a * function which will be called to return the number. */ pixels: function( el, pct100 ) { var num = this.getNumber(), unit = this.getUnit(); switch( unit ) { case "px": return num; case "%": return num * ( typeof pct100 === 'function' ? pct100() : pct100 ) / 100; case "em": return num * this.getEmPixels( el ); case "ex": return num * this.getEmPixels( el ) / 2; default: return num * conversions[ unit ]; } }, /** * The em and ex units are relative to the font-size of the current element, * however if the font-size is set using non-pixel units then we get that value * rather than a pixel conversion. To get around this, we keep a floating element * with width:1em which we insert into the target element and then read its offsetWidth. * For elements that won't accept a child we insert into the parent node and perform * additional calculation. If the font-size *is* specified in pixels, then we use that * directly to avoid the expensive DOM manipulation. * @param {Element} el * @return {number} */ getEmPixels: function( el ) { var fs = el.currentStyle.fontSize, px, parent, me; if( fs.indexOf( 'px' ) > 0 ) { return parseFloat( fs ); } else if( el.tagName in PIE.childlessElements ) { me = this; parent = el.parentNode; return PIE.getLength( fs ).pixels( parent, function() { return me.getEmPixels( parent ); } ); } else { el.appendChild( lengthCalcEl ); px = lengthCalcEl.offsetWidth; if( lengthCalcEl.parentNode === el ) { //not sure how this could be false but it sometimes is el.removeChild( lengthCalcEl ); } return px; } } }; /** * Retrieve a PIE.Length instance for the given value. A shared singleton instance is returned for each unique value. * @param {string} val The CSS string representing the length. It is assumed that this will already have * been validated as a valid length or percentage syntax. */ PIE.getLength = function( val ) { return instances[ val ] || ( instances[ val ] = new Length( val ) ); }; return Length; })(); /** * Wrapper for a CSS3 bg-position value. Takes up to 2 position keywords and 2 lengths/percentages. * @constructor * @param {Array.<PIE.Tokenizer.Token>} tokens The tokens making up the background position value. */ PIE.BgPosition = (function() { var length_fifty = PIE.getLength( '50%' ), vert_idents = { 'top': 1, 'center': 1, 'bottom': 1 }, horiz_idents = { 'left': 1, 'center': 1, 'right': 1 }; function BgPosition( tokens ) { this.tokens = tokens; } BgPosition.prototype = { /** * Normalize the values into the form: * [ xOffsetSide, xOffsetLength, yOffsetSide, yOffsetLength ] * where: xOffsetSide is either 'left' or 'right', * yOffsetSide is either 'top' or 'bottom', * and x/yOffsetLength are both PIE.Length objects. * @return {Array} */ getValues: function() { if( !this._values ) { var tokens = this.tokens, len = tokens.length, Tokenizer = PIE.Tokenizer, identType = Tokenizer.Type, length_zero = PIE.getLength( '0' ), type_ident = identType.IDENT, type_length = identType.LENGTH, type_percent = identType.PERCENT, type, value, vals = [ 'left', length_zero, 'top', length_zero ]; // If only one value, the second is assumed to be 'center' if( len === 1 ) { tokens.push( new Tokenizer.Token( type_ident, 'center' ) ); len++; } // Two values - CSS2 if( len === 2 ) { // If both idents, they can appear in either order, so switch them if needed if( type_ident & ( tokens[0].tokenType | tokens[1].tokenType ) && tokens[0].tokenValue in vert_idents && tokens[1].tokenValue in horiz_idents ) { tokens.push( tokens.shift() ); } if( tokens[0].tokenType & type_ident ) { if( tokens[0].tokenValue === 'center' ) { vals[1] = length_fifty; } else { vals[0] = tokens[0].tokenValue; } } else if( tokens[0].isLengthOrPercent() ) { vals[1] = PIE.getLength( tokens[0].tokenValue ); } if( tokens[1].tokenType & type_ident ) { if( tokens[1].tokenValue === 'center' ) { vals[3] = length_fifty; } else { vals[2] = tokens[1].tokenValue; } } else if( tokens[1].isLengthOrPercent() ) { vals[3] = PIE.getLength( tokens[1].tokenValue ); } } // Three or four values - CSS3 else { // TODO } this._values = vals; } return this._values; }, /** * Find the coordinates of the background image from the upper-left corner of the background area. * Note that these coordinate values are not rounded. * @param {Element} el * @param {number} width - the width for percentages (background area width minus image width) * @param {number} height - the height for percentages (background area height minus image height) * @return {Object} { x: Number, y: Number } */ coords: function( el, width, height ) { var vals = this.getValues(), pxX = vals[1].pixels( el, width ), pxY = vals[3].pixels( el, height ); return { x: vals[0] === 'right' ? width - pxX : pxX, y: vals[2] === 'bottom' ? height - pxY : pxY }; } }; return BgPosition; })(); /** * Wrapper for a CSS3 background-size value. * @constructor * @param {String|PIE.Length} w The width parameter * @param {String|PIE.Length} h The height parameter, if any */ PIE.BgSize = (function() { var CONTAIN = 'contain', COVER = 'cover', AUTO = 'auto'; function BgSize( w, h ) { this.w = w; this.h = h; } BgSize.prototype = { pixels: function( el, areaW, areaH, imgW, imgH ) { var me = this, w = me.w, h = me.h, areaRatio = areaW / areaH, imgRatio = imgW / imgH; if ( w === CONTAIN ) { w = imgRatio > areaRatio ? areaW : areaH * imgRatio; h = imgRatio > areaRatio ? areaW / imgRatio : areaH; } else if ( w === COVER ) { w = imgRatio < areaRatio ? areaW : areaH * imgRatio; h = imgRatio < areaRatio ? areaW / imgRatio : areaH; } else if ( w === AUTO ) { h = ( h === AUTO ? imgH : h.pixels( el, areaH ) ); w = h * imgRatio; } else { w = w.pixels( el, areaW ); h = ( h === AUTO ? w / imgRatio : h.pixels( el, areaH ) ); } return { w: w, h: h }; } }; BgSize.DEFAULT = new BgSize( AUTO, AUTO ); return BgSize; })(); /** * Wrapper for angle values; handles conversion to degrees from all allowed angle units * @constructor * @param {string} val The raw CSS value for the angle. It is assumed it has been pre-validated. */ PIE.Angle = (function() { function Angle( val ) { this.val = val; } Angle.prototype = { unitRE: /[a-z]+$/i, /** * @return {string} The unit of the angle value */ getUnit: function() { return this._unit || ( this._unit = this.val.match( this.unitRE )[0].toLowerCase() ); }, /** * Get the numeric value of the angle in degrees. * @return {number} The degrees value */ degrees: function() { var deg = this._deg, u, n; if( deg === undefined ) { u = this.getUnit(); n = parseFloat( this.val, 10 ); deg = this._deg = ( u === 'deg' ? n : u === 'rad' ? n / Math.PI * 180 : u === 'grad' ? n / 400 * 360 : u === 'turn' ? n * 360 : 0 ); } return deg; } }; return Angle; })();/** * Abstraction for colors values. Allows detection of rgba values. A singleton instance per unique * value is returned from PIE.getColor() - always use that instead of instantiating directly. * @constructor * @param {string} val The raw CSS string value for the color */ PIE.Color = (function() { var instances = {}; function Color( val ) { this.val = val; } /** * Regular expression for matching rgba colors and extracting their components * @type {RegExp} */ Color.rgbaRE = /\s*rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d+|\d*\.\d+)\s*\)\s*/; Color.names = { "aliceblue":"F0F8FF", "antiquewhite":"FAEBD7", "aqua":"0FF", "aquamarine":"7FFFD4", "azure":"F0FFFF", "beige":"F5F5DC", "bisque":"FFE4C4", "black":"000", "blanchedalmond":"FFEBCD", "blue":"00F", "blueviolet":"8A2BE2", "brown":"A52A2A", "burlywood":"DEB887", "cadetblue":"5F9EA0", "chartreuse":"7FFF00", "chocolate":"D2691E", "coral":"FF7F50", "cornflowerblue":"6495ED", "cornsilk":"FFF8DC", "crimson":"DC143C", "cyan":"0FF", "darkblue":"00008B", "darkcyan":"008B8B", "darkgoldenrod":"B8860B", "darkgray":"A9A9A9", "darkgreen":"006400", "darkkhaki":"BDB76B", "darkmagenta":"8B008B", "darkolivegreen":"556B2F", "darkorange":"FF8C00", "darkorchid":"9932CC", "darkred":"8B0000", "darksalmon":"E9967A", "darkseagreen":"8FBC8F", "darkslateblue":"483D8B", "darkslategray":"2F4F4F", "darkturquoise":"00CED1", "darkviolet":"9400D3", "deeppink":"FF1493", "deepskyblue":"00BFFF", "dimgray":"696969", "dodgerblue":"1E90FF", "firebrick":"B22222", "floralwhite":"FFFAF0", "forestgreen":"228B22", "fuchsia":"F0F", "gainsboro":"DCDCDC", "ghostwhite":"F8F8FF", "gold":"FFD700", "goldenrod":"DAA520", "gray":"808080", "green":"008000", "greenyellow":"ADFF2F", "honeydew":"F0FFF0", "hotpink":"FF69B4", "indianred":"CD5C5C", "indigo":"4B0082", "ivory":"FFFFF0", "khaki":"F0E68C", "lavender":"E6E6FA", "lavenderblush":"FFF0F5", "lawngreen":"7CFC00", "lemonchiffon":"FFFACD", "lightblue":"ADD8E6", "lightcoral":"F08080", "lightcyan":"E0FFFF", "lightgoldenrodyellow":"FAFAD2", "lightgreen":"90EE90", "lightgrey":"D3D3D3", "lightpink":"FFB6C1", "lightsalmon":"FFA07A", "lightseagreen":"20B2AA", "lightskyblue":"87CEFA", "lightslategray":"789", "lightsteelblue":"B0C4DE", "lightyellow":"FFFFE0", "lime":"0F0", "limegreen":"32CD32", "linen":"FAF0E6", "magenta":"F0F", "maroon":"800000", "mediumauqamarine":"66CDAA", "mediumblue":"0000CD", "mediumorchid":"BA55D3", "mediumpurple":"9370D8", "mediumseagreen":"3CB371", "mediumslateblue":"7B68EE", "mediumspringgreen":"00FA9A", "mediumturquoise":"48D1CC", "mediumvioletred":"C71585", "midnightblue":"191970", "mintcream":"F5FFFA", "mistyrose":"FFE4E1", "moccasin":"FFE4B5", "navajowhite":"FFDEAD", "navy":"000080", "oldlace":"FDF5E6", "olive":"808000", "olivedrab":"688E23", "orange":"FFA500", "orangered":"FF4500", "orchid":"DA70D6", "palegoldenrod":"EEE8AA", "palegreen":"98FB98", "paleturquoise":"AFEEEE", "palevioletred":"D87093", "papayawhip":"FFEFD5", "peachpuff":"FFDAB9", "peru":"CD853F", "pink":"FFC0CB", "plum":"DDA0DD", "powderblue":"B0E0E6", "purple":"800080", "red":"F00", "rosybrown":"BC8F8F", "royalblue":"4169E1", "saddlebrown":"8B4513", "salmon":"FA8072", "sandybrown":"F4A460", "seagreen":"2E8B57", "seashell":"FFF5EE", "sienna":"A0522D", "silver":"C0C0C0", "skyblue":"87CEEB", "slateblue":"6A5ACD", "slategray":"708090", "snow":"FFFAFA", "springgreen":"00FF7F", "steelblue":"4682B4", "tan":"D2B48C", "teal":"008080", "thistle":"D8BFD8", "tomato":"FF6347", "turquoise":"40E0D0", "violet":"EE82EE", "wheat":"F5DEB3", "white":"FFF", "whitesmoke":"F5F5F5", "yellow":"FF0", "yellowgreen":"9ACD32" }; Color.prototype = { /** * @private */ parse: function() { if( !this._color ) { var me = this, v = me.val, vLower, m = v.match( Color.rgbaRE ); if( m ) { me._color = 'rgb(' + m[1] + ',' + m[2] + ',' + m[3] + ')'; me._alpha = parseFloat( m[4] ); } else { if( ( vLower = v.toLowerCase() ) in Color.names ) { v = '#' + Color.names[vLower]; } me._color = v; me._alpha = ( v === 'transparent' ? 0 : 1 ); } } }, /** * Retrieve the value of the color in a format usable by IE natively. This will be the same as * the raw input value, except for rgba values which will be converted to an rgb value. * @param {Element} el The context element, used to get 'currentColor' keyword value. * @return {string} Color value */ colorValue: function( el ) { this.parse(); return this._color === 'currentColor' ? el.currentStyle.color : this._color; }, /** * Retrieve the alpha value of the color. Will be 1 for all values except for rgba values * with an alpha component. * @return {number} The alpha value, from 0 to 1. */ alpha: function() { this.parse(); return this._alpha; } }; /** * Retrieve a PIE.Color instance for the given value. A shared singleton instance is returned for each unique value. * @param {string} val The CSS string representing the color. It is assumed that this will already have * been validated as a valid color syntax. */ PIE.getColor = function(val) { return instances[ val ] || ( instances[ val ] = new Color( val ) ); }; return Color; })();/** * A tokenizer for CSS value strings. * @constructor * @param {string} css The CSS value string */ PIE.Tokenizer = (function() { function Tokenizer( css ) { this.css = css; this.ch = 0; this.tokens = []; this.tokenIndex = 0; } /** * Enumeration of token type constants. * @enum {number} */ var Type = Tokenizer.Type = { ANGLE: 1, CHARACTER: 2, COLOR: 4, DIMEN: 8, FUNCTION: 16, IDENT: 32, LENGTH: 64, NUMBER: 128, OPERATOR: 256, PERCENT: 512, STRING: 1024, URL: 2048 }; /** * A single token * @constructor * @param {number} type The type of the token - see PIE.Tokenizer.Type * @param {string} value The value of the token */ Tokenizer.Token = function( type, value ) { this.tokenType = type; this.tokenValue = value; }; Tokenizer.Token.prototype = { isLength: function() { return this.tokenType & Type.LENGTH || ( this.tokenType & Type.NUMBER && this.tokenValue === '0' ); }, isLengthOrPercent: function() { return this.isLength() || this.tokenType & Type.PERCENT; } }; Tokenizer.prototype = { whitespace: /\s/, number: /^[\+\-]?(\d*\.)?\d+/, url: /^url\(\s*("([^"]*)"|'([^']*)'|([!#$%&*-~]*))\s*\)/i, ident: /^\-?[_a-z][\w-]*/i, string: /^("([^"]*)"|'([^']*)')/, operator: /^[\/,]/, hash: /^#[\w]+/, hashColor: /^#([\da-f]{6}|[\da-f]{3})/i, unitTypes: { 'px': Type.LENGTH, 'em': Type.LENGTH, 'ex': Type.LENGTH, 'mm': Type.LENGTH, 'cm': Type.LENGTH, 'in': Type.LENGTH, 'pt': Type.LENGTH, 'pc': Type.LENGTH, 'deg': Type.ANGLE, 'rad': Type.ANGLE, 'grad': Type.ANGLE }, colorFunctions: { 'rgb': 1, 'rgba': 1, 'hsl': 1, 'hsla': 1 }, /** * Advance to and return the next token in the CSS string. If the end of the CSS string has * been reached, null will be returned. * @param {boolean} forget - if true, the token will not be stored for the purposes of backtracking with prev(). * @return {PIE.Tokenizer.Token} */ next: function( forget ) { var css, ch, firstChar, match, val, me = this; function newToken( type, value ) { var tok = new Tokenizer.Token( type, value ); if( !forget ) { me.tokens.push( tok ); me.tokenIndex++; } return tok; } function failure() { me.tokenIndex++; return null; } // In case we previously backed up, return the stored token in the next slot if( this.tokenIndex < this.tokens.length ) { return this.tokens[ this.tokenIndex++ ]; } // Move past leading whitespace characters while( this.whitespace.test( this.css.charAt( this.ch ) ) ) { this.ch++; } if( this.ch >= this.css.length ) { return failure(); } ch = this.ch; css = this.css.substring( this.ch ); firstChar = css.charAt( 0 ); switch( firstChar ) { case '#': if( match = css.match( this.hashColor ) ) { this.ch += match[0].length; return newToken( Type.COLOR, match[0] ); } break; case '"': case "'": if( match = css.match( this.string ) ) { this.ch += match[0].length; return newToken( Type.STRING, match[2] || match[3] || '' ); } break; case "/": case ",": this.ch++; return newToken( Type.OPERATOR, firstChar ); case 'u': if( match = css.match( this.url ) ) { this.ch += match[0].length; return newToken( Type.URL, match[2] || match[3] || match[4] || '' ); } } // Numbers and values starting with numbers if( match = css.match( this.number ) ) { val = match[0]; this.ch += val.length; // Check if it is followed by a unit if( css.charAt( val.length ) === '%' ) { this.ch++; return newToken( Type.PERCENT, val + '%' ); } if( match = css.substring( val.length ).match( this.ident ) ) { val += match[0]; this.ch += match[0].length; return newToken( this.unitTypes[ match[0].toLowerCase() ] || Type.DIMEN, val ); } // Plain ol' number return newToken( Type.NUMBER, val ); } // Identifiers if( match = css.match( this.ident ) ) { val = match[0]; this.ch += val.length; // Named colors if( val.toLowerCase() in PIE.Color.names || val === 'currentColor' || val === 'transparent' ) { return newToken( Type.COLOR, val ); } // Functions if( css.charAt( val.length ) === '(' ) { this.ch++; // Color values in function format: rgb, rgba, hsl, hsla if( val.toLowerCase() in this.colorFunctions ) { function isNum( tok ) { return tok && tok.tokenType & Type.NUMBER; } function isNumOrPct( tok ) { return tok && ( tok.tokenType & ( Type.NUMBER | Type.PERCENT ) ); } function isValue( tok, val ) { return tok && tok.tokenValue === val; } function next() { return me.next( 1 ); } if( ( val.charAt(0) === 'r' ? isNumOrPct( next() ) : isNum( next() ) ) && isValue( next(), ',' ) && isNumOrPct( next() ) && isValue( next(), ',' ) && isNumOrPct( next() ) && ( val === 'rgb' || val === 'hsa' || ( isValue( next(), ',' ) && isNum( next() ) ) ) && isValue( next(), ')' ) ) { return newToken( Type.COLOR, this.css.substring( ch, this.ch ) ); } return failure(); } return newToken( Type.FUNCTION, val ); } // Other identifier return newToken( Type.IDENT, val ); } // Standalone character this.ch++; return newToken( Type.CHARACTER, firstChar ); }, /** * Determine whether there is another token * @return {boolean} */ hasNext: function() { var next = this.next(); this.prev(); return !!next; }, /** * Back up and return the previous token * @return {PIE.Tokenizer.Token} */ prev: function() { return this.tokens[ this.tokenIndex-- - 2 ]; }, /** * Retrieve all the tokens in the CSS string * @return {Array.<PIE.Tokenizer.Token>} */ all: function() { while( this.next() ) {} return this.tokens; }, /** * Return a list of tokens from the current position until the given function returns * true. The final token will not be included in the list. * @param {function():boolean} func - test function * @param {boolean} require - if true, then if the end of the CSS string is reached * before the test function returns true, null will be returned instead of the * tokens that have been found so far. * @return {Array.<PIE.Tokenizer.Token>} */ until: function( func, require ) { var list = [], t, hit; while( t = this.next() ) { if( func( t ) ) { hit = true; this.prev(); break; } list.push( t ); } return require && !hit ? null : list; } }; return Tokenizer; })();/** * Handles calculating, caching, and detecting changes to size and position of the element. * @constructor * @param {Element} el the target element */ PIE.BoundsInfo = function( el ) { this.targetElement = el; }; PIE.BoundsInfo.prototype = { _locked: 0, positionChanged: function() { var last = this._lastBounds, bounds; return !last || ( ( bounds = this.getBounds() ) && ( last.x !== bounds.x || last.y !== bounds.y ) ); }, sizeChanged: function() { var last = this._lastBounds, bounds; return !last || ( ( bounds = this.getBounds() ) && ( last.w !== bounds.w || last.h !== bounds.h ) ); }, getLiveBounds: function() { var el = this.targetElement, rect = el.getBoundingClientRect(), isIE9 = PIE.ieDocMode === 9, isIE7 = PIE.ieVersion === 7, width = rect.right - rect.left; return { x: rect.left, y: rect.top, // In some cases scrolling the page will cause IE9 to report incorrect dimensions // in the rect returned by getBoundingClientRect, so we must query offsetWidth/Height // instead. Also IE7 is inconsistent in using logical vs. device pixels in measurements // so we must calculate the ratio and use it in certain places as a position adjustment. w: isIE9 || isIE7 ? el.offsetWidth : width, h: isIE9 || isIE7 ? el.offsetHeight : rect.bottom - rect.top, logicalZoomRatio: ( isIE7 && width ) ? el.offsetWidth / width : 1 }; }, getBounds: function() { return this._locked ? ( this._lockedBounds || ( this._lockedBounds = this.getLiveBounds() ) ) : this.getLiveBounds(); }, hasBeenQueried: function() { return !!this._lastBounds; }, lock: function() { ++this._locked; }, unlock: function() { if( !--this._locked ) { if( this._lockedBounds ) this._lastBounds = this._lockedBounds; this._lockedBounds = null; } } }; (function() { function cacheWhenLocked( fn ) { var uid = PIE.Util.getUID( fn ); return function() { if( this._locked ) { var cache = this._lockedValues || ( this._lockedValues = {} ); return ( uid in cache ) ? cache[ uid ] : ( cache[ uid ] = fn.call( this ) ); } else { return fn.call( this ); } } } PIE.StyleInfoBase = { _locked: 0, /** * Create a new StyleInfo class, with the standard constructor, and augmented by * the StyleInfoBase's members. * @param proto */ newStyleInfo: function( proto ) { function StyleInfo( el ) { this.targetElement = el; this._lastCss = this.getCss(); } PIE.Util.merge( StyleInfo.prototype, PIE.StyleInfoBase, proto ); StyleInfo._propsCache = {}; return StyleInfo; }, /** * Get an object representation of the target CSS style, caching it for each unique * CSS value string. * @return {Object} */ getProps: function() { var css = this.getCss(), cache = this.constructor._propsCache; return css ? ( css in cache ? cache[ css ] : ( cache[ css ] = this.parseCss( css ) ) ) : null; }, /** * Get the raw CSS value for the target style * @return {string} */ getCss: cacheWhenLocked( function() { var el = this.targetElement, ctor = this.constructor, s = el.style, cs = el.currentStyle, cssProp = this.cssProperty, styleProp = this.styleProperty, prefixedCssProp = ctor._prefixedCssProp || ( ctor._prefixedCssProp = PIE.CSS_PREFIX + cssProp ), prefixedStyleProp = ctor._prefixedStyleProp || ( ctor._prefixedStyleProp = PIE.STYLE_PREFIX + styleProp.charAt(0).toUpperCase() + styleProp.substring(1) ); return s[ prefixedStyleProp ] || cs.getAttribute( prefixedCssProp ) || s[ styleProp ] || cs.getAttribute( cssProp ); } ), /** * Determine whether the target CSS style is active. * @return {boolean} */ isActive: cacheWhenLocked( function() { return !!this.getProps(); } ), /** * Determine whether the target CSS style has changed since the last time it was used. * @return {boolean} */ changed: cacheWhenLocked( function() { var currentCss = this.getCss(), changed = currentCss !== this._lastCss; this._lastCss = currentCss; return changed; } ), cacheWhenLocked: cacheWhenLocked, lock: function() { ++this._locked; }, unlock: function() { if( !--this._locked ) { delete this._lockedValues; } } }; })();/** * Handles parsing, caching, and detecting changes to background (and -pie-background) CSS * @constructor * @param {Element} el the target element */ PIE.BackgroundStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: PIE.CSS_PREFIX + 'background', styleProperty: PIE.STYLE_PREFIX + 'Background', attachIdents: { 'scroll':1, 'fixed':1, 'local':1 }, repeatIdents: { 'repeat-x':1, 'repeat-y':1, 'repeat':1, 'no-repeat':1 }, originAndClipIdents: { 'padding-box':1, 'border-box':1, 'content-box':1 }, positionIdents: { 'top':1, 'right':1, 'bottom':1, 'left':1, 'center':1 }, sizeIdents: { 'contain':1, 'cover':1 }, propertyNames: { CLIP: 'backgroundClip', COLOR: 'backgroundColor', IMAGE: 'backgroundImage', ORIGIN: 'backgroundOrigin', POSITION: 'backgroundPosition', REPEAT: 'backgroundRepeat', SIZE: 'backgroundSize' }, /** * For background styles, we support the -pie-background property but fall back to the standard * backround* properties. The reason we have to use the prefixed version is that IE natively * parses the standard properties and if it sees something it doesn't know how to parse, for example * multiple values or gradient definitions, it will throw that away and not make it available through * currentStyle. * * Format of return object: * { * color: <PIE.Color>, * bgImages: [ * { * imgType: 'image', * imgUrl: 'image.png', * imgRepeat: <'no-repeat' | 'repeat-x' | 'repeat-y' | 'repeat'>, * bgPosition: <PIE.BgPosition>, * bgAttachment: <'scroll' | 'fixed' | 'local'>, * bgOrigin: <'border-box' | 'padding-box' | 'content-box'>, * bgClip: <'border-box' | 'padding-box'>, * bgSize: <PIE.BgSize>, * origString: 'url(img.png) no-repeat top left' * }, * { * imgType: 'linear-gradient', * gradientStart: <PIE.BgPosition>, * angle: <PIE.Angle>, * stops: [ * { color: <PIE.Color>, offset: <PIE.Length> }, * { color: <PIE.Color>, offset: <PIE.Length> }, ... * ] * } * ] * } * @param {String} css * @override */ parseCss: function( css ) { var el = this.targetElement, cs = el.currentStyle, tokenizer, token, image, tok_type = PIE.Tokenizer.Type, type_operator = tok_type.OPERATOR, type_ident = tok_type.IDENT, type_color = tok_type.COLOR, tokType, tokVal, beginCharIndex = 0, positionIdents = this.positionIdents, gradient, stop, width, height, props = { bgImages: [] }; function isBgPosToken( token ) { return token && token.isLengthOrPercent() || ( token.tokenType & type_ident && token.tokenValue in positionIdents ); } function sizeToken( token ) { return token && ( ( token.isLengthOrPercent() && PIE.getLength( token.tokenValue ) ) || ( token.tokenValue === 'auto' && 'auto' ) ); } // If the CSS3-specific -pie-background property is present, parse it if( this.getCss3() ) { tokenizer = new PIE.Tokenizer( css ); image = {}; while( token = tokenizer.next() ) { tokType = token.tokenType; tokVal = token.tokenValue; if( !image.imgType && tokType & tok_type.FUNCTION && tokVal === 'linear-gradient' ) { gradient = { stops: [], imgType: tokVal }; stop = {}; while( token = tokenizer.next() ) { tokType = token.tokenType; tokVal = token.tokenValue; // If we reached the end of the function and had at least 2 stops, flush the info if( tokType & tok_type.CHARACTER && tokVal === ')' ) { if( stop.color ) { gradient.stops.push( stop ); } if( gradient.stops.length > 1 ) { PIE.Util.merge( image, gradient ); } break; } // Color stop - must start with color if( tokType & type_color ) { // if we already have an angle/position, make sure that the previous token was a comma if( gradient.angle || gradient.gradientStart ) { token = tokenizer.prev(); if( token.tokenType !== type_operator ) { break; //fail } tokenizer.next(); } stop = { color: PIE.getColor( tokVal ) }; // check for offset following color token = tokenizer.next(); if( token.isLengthOrPercent() ) { stop.offset = PIE.getLength( token.tokenValue ); } else { tokenizer.prev(); } } // Angle - can only appear in first spot else if( tokType & tok_type.ANGLE && !gradient.angle && !stop.color && !gradient.stops.length ) { gradient.angle = new PIE.Angle( token.tokenValue ); } else if( isBgPosToken( token ) && !gradient.gradientStart && !stop.color && !gradient.stops.length ) { tokenizer.prev(); gradient.gradientStart = new PIE.BgPosition( tokenizer.until( function( t ) { return !isBgPosToken( t ); }, false ) ); } else if( tokType & type_operator && tokVal === ',' ) { if( stop.color ) { gradient.stops.push( stop ); stop = {}; } } else { // Found something we didn't recognize; fail without adding image break; } } } else if( !image.imgType && tokType & tok_type.URL ) { image.imgUrl = tokVal; image.imgType = 'image'; } else if( isBgPosToken( token ) && !image.bgPosition ) { tokenizer.prev(); image.bgPosition = new PIE.BgPosition( tokenizer.until( function( t ) { return !isBgPosToken( t ); }, false ) ); } else if( tokType & type_ident ) { if( tokVal in this.repeatIdents && !image.imgRepeat ) { image.imgRepeat = tokVal; } else if( tokVal in this.originAndClipIdents && !image.bgOrigin ) { image.bgOrigin = tokVal; if( ( token = tokenizer.next() ) && ( token.tokenType & type_ident ) && token.tokenValue in this.originAndClipIdents ) { image.bgClip = token.tokenValue; } else { image.bgClip = tokVal; tokenizer.prev(); } } else if( tokVal in this.attachIdents && !image.bgAttachment ) { image.bgAttachment = tokVal; } else { return null; } } else if( tokType & type_color && !props.color ) { props.color = PIE.getColor( tokVal ); } else if( tokType & type_operator && tokVal === '/' && !image.bgSize && image.bgPosition ) { // background size token = tokenizer.next(); if( token.tokenType & type_ident && token.tokenValue in this.sizeIdents ) { image.bgSize = new PIE.BgSize( token.tokenValue ); } else if( width = sizeToken( token ) ) { height = sizeToken( tokenizer.next() ); if ( !height ) { height = width; tokenizer.prev(); } image.bgSize = new PIE.BgSize( width, height ); } else { return null; } } // new layer else if( tokType & type_operator && tokVal === ',' && image.imgType ) { image.origString = css.substring( beginCharIndex, tokenizer.ch - 1 ); beginCharIndex = tokenizer.ch; props.bgImages.push( image ); image = {}; } else { // Found something unrecognized; chuck everything return null; } } // leftovers if( image.imgType ) { image.origString = css.substring( beginCharIndex ); props.bgImages.push( image ); } } // Otherwise, use the standard background properties; let IE give us the values rather than parsing them else { this.withActualBg( PIE.ieDocMode < 9 ? function() { var propNames = this.propertyNames, posX = cs[propNames.POSITION + 'X'], posY = cs[propNames.POSITION + 'Y'], img = cs[propNames.IMAGE], color = cs[propNames.COLOR]; if( color !== 'transparent' ) { props.color = PIE.getColor( color ) } if( img !== 'none' ) { props.bgImages = [ { imgType: 'image', imgUrl: new PIE.Tokenizer( img ).next().tokenValue, imgRepeat: cs[propNames.REPEAT], bgPosition: new PIE.BgPosition( new PIE.Tokenizer( posX + ' ' + posY ).all() ) } ]; } } : function() { var propNames = this.propertyNames, splitter = /\s*,\s*/, images = cs[propNames.IMAGE].split( splitter ), color = cs[propNames.COLOR], repeats, positions, origins, clips, sizes, i, len, image, sizeParts; if( color !== 'transparent' ) { props.color = PIE.getColor( color ) } len = images.length; if( len && images[0] !== 'none' ) { repeats = cs[propNames.REPEAT].split( splitter ); positions = cs[propNames.POSITION].split( splitter ); origins = cs[propNames.ORIGIN].split( splitter ); clips = cs[propNames.CLIP].split( splitter ); sizes = cs[propNames.SIZE].split( splitter ); props.bgImages = []; for( i = 0; i < len; i++ ) { image = images[ i ]; if( image && image !== 'none' ) { sizeParts = sizes[i].split( ' ' ); props.bgImages.push( { origString: image + ' ' + repeats[ i ] + ' ' + positions[ i ] + ' / ' + sizes[ i ] + ' ' + origins[ i ] + ' ' + clips[ i ], imgType: 'image', imgUrl: new PIE.Tokenizer( image ).next().tokenValue, imgRepeat: repeats[ i ], bgPosition: new PIE.BgPosition( new PIE.Tokenizer( positions[ i ] ).all() ), bgOrigin: origins[ i ], bgClip: clips[ i ], bgSize: new PIE.BgSize( sizeParts[ 0 ], sizeParts[ 1 ] ) } ); } } } } ); } return ( props.color || props.bgImages[0] ) ? props : null; }, /** * Execute a function with the actual background styles (not overridden with runtimeStyle * properties set by the renderers) available via currentStyle. * @param fn */ withActualBg: function( fn ) { var isIE9 = PIE.ieDocMode > 8, propNames = this.propertyNames, rs = this.targetElement.runtimeStyle, rsImage = rs[propNames.IMAGE], rsColor = rs[propNames.COLOR], rsRepeat = rs[propNames.REPEAT], rsClip, rsOrigin, rsSize, rsPosition, ret; if( rsImage ) rs[propNames.IMAGE] = ''; if( rsColor ) rs[propNames.COLOR] = ''; if( rsRepeat ) rs[propNames.REPEAT] = ''; if( isIE9 ) { rsClip = rs[propNames.CLIP]; rsOrigin = rs[propNames.ORIGIN]; rsPosition = rs[propNames.POSITION]; rsSize = rs[propNames.SIZE]; if( rsClip ) rs[propNames.CLIP] = ''; if( rsOrigin ) rs[propNames.ORIGIN] = ''; if( rsPosition ) rs[propNames.POSITION] = ''; if( rsSize ) rs[propNames.SIZE] = ''; } ret = fn.call( this ); if( rsImage ) rs[propNames.IMAGE] = rsImage; if( rsColor ) rs[propNames.COLOR] = rsColor; if( rsRepeat ) rs[propNames.REPEAT] = rsRepeat; if( isIE9 ) { if( rsClip ) rs[propNames.CLIP] = rsClip; if( rsOrigin ) rs[propNames.ORIGIN] = rsOrigin; if( rsPosition ) rs[propNames.POSITION] = rsPosition; if( rsSize ) rs[propNames.SIZE] = rsSize; } return ret; }, getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { return this.getCss3() || this.withActualBg( function() { var cs = this.targetElement.currentStyle, propNames = this.propertyNames; return cs[propNames.COLOR] + ' ' + cs[propNames.IMAGE] + ' ' + cs[propNames.REPEAT] + ' ' + cs[propNames.POSITION + 'X'] + ' ' + cs[propNames.POSITION + 'Y']; } ); } ), getCss3: PIE.StyleInfoBase.cacheWhenLocked( function() { var el = this.targetElement; return el.style[ this.styleProperty ] || el.currentStyle.getAttribute( this.cssProperty ); } ), /** * Tests if style.PiePngFix or the -pie-png-fix property is set to true in IE6. */ isPngFix: function() { var val = 0, el; if( PIE.ieVersion < 7 ) { el = this.targetElement; val = ( '' + ( el.style[ PIE.STYLE_PREFIX + 'PngFix' ] || el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'png-fix' ) ) === 'true' ); } return val; }, /** * The isActive logic is slightly different, because getProps() always returns an object * even if it is just falling back to the native background properties. But we only want * to report is as being "active" if either the -pie-background override property is present * and parses successfully or '-pie-png-fix' is set to true in IE6. */ isActive: PIE.StyleInfoBase.cacheWhenLocked( function() { return (this.getCss3() || this.isPngFix()) && !!this.getProps(); } ) } );/** * Handles parsing, caching, and detecting changes to border CSS * @constructor * @param {Element} el the target element */ PIE.BorderStyleInfo = PIE.StyleInfoBase.newStyleInfo( { sides: [ 'Top', 'Right', 'Bottom', 'Left' ], namedWidths: { 'thin': '1px', 'medium': '3px', 'thick': '5px' }, parseCss: function( css ) { var w = {}, s = {}, c = {}, active = false, colorsSame = true, stylesSame = true, widthsSame = true; this.withActualBorder( function() { var el = this.targetElement, cs = el.currentStyle, i = 0, style, color, width, lastStyle, lastColor, lastWidth, side, ltr; for( ; i < 4; i++ ) { side = this.sides[ i ]; ltr = side.charAt(0).toLowerCase(); style = s[ ltr ] = cs[ 'border' + side + 'Style' ]; color = cs[ 'border' + side + 'Color' ]; width = cs[ 'border' + side + 'Width' ]; if( i > 0 ) { if( style !== lastStyle ) { stylesSame = false; } if( color !== lastColor ) { colorsSame = false; } if( width !== lastWidth ) { widthsSame = false; } } lastStyle = style; lastColor = color; lastWidth = width; c[ ltr ] = PIE.getColor( color ); width = w[ ltr ] = PIE.getLength( s[ ltr ] === 'none' ? '0' : ( this.namedWidths[ width ] || width ) ); if( width.pixels( this.targetElement ) > 0 ) { active = true; } } } ); return active ? { widths: w, styles: s, colors: c, widthsSame: widthsSame, colorsSame: colorsSame, stylesSame: stylesSame } : null; }, getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { var el = this.targetElement, cs = el.currentStyle, css; // Don't redraw or hide borders for cells in border-collapse:collapse tables if( !( el.tagName in PIE.tableCellTags && el.offsetParent.currentStyle.borderCollapse === 'collapse' ) ) { this.withActualBorder( function() { css = cs.borderWidth + '|' + cs.borderStyle + '|' + cs.borderColor; } ); } return css; } ), /** * Execute a function with the actual border styles (not overridden with runtimeStyle * properties set by the renderers) available via currentStyle. * @param fn */ withActualBorder: function( fn ) { var rs = this.targetElement.runtimeStyle, rsWidth = rs.borderWidth, rsColor = rs.borderColor, ret; if( rsWidth ) rs.borderWidth = ''; if( rsColor ) rs.borderColor = ''; ret = fn.call( this ); if( rsWidth ) rs.borderWidth = rsWidth; if( rsColor ) rs.borderColor = rsColor; return ret; } } ); /** * Handles parsing, caching, and detecting changes to border-radius CSS * @constructor * @param {Element} el the target element */ (function() { PIE.BorderRadiusStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: 'border-radius', styleProperty: 'borderRadius', parseCss: function( css ) { var p = null, x, y, tokenizer, token, length, hasNonZero = false; if( css ) { tokenizer = new PIE.Tokenizer( css ); function collectLengths() { var arr = [], num; while( ( token = tokenizer.next() ) && token.isLengthOrPercent() ) { length = PIE.getLength( token.tokenValue ); num = length.getNumber(); if( num < 0 ) { return null; } if( num > 0 ) { hasNonZero = true; } arr.push( length ); } return arr.length > 0 && arr.length < 5 ? { 'tl': arr[0], 'tr': arr[1] || arr[0], 'br': arr[2] || arr[0], 'bl': arr[3] || arr[1] || arr[0] } : null; } // Grab the initial sequence of lengths if( x = collectLengths() ) { // See if there is a slash followed by more lengths, for the y-axis radii if( token ) { if( token.tokenType & PIE.Tokenizer.Type.OPERATOR && token.tokenValue === '/' ) { y = collectLengths(); } } else { y = x; } // Treat all-zero values the same as no value if( hasNonZero && x && y ) { p = { x: x, y : y }; } } } return p; } } ); var zero = PIE.getLength( '0' ), zeros = { 'tl': zero, 'tr': zero, 'br': zero, 'bl': zero }; PIE.BorderRadiusStyleInfo.ALL_ZERO = { x: zeros, y: zeros }; })();/** * Handles parsing, caching, and detecting changes to border-image CSS * @constructor * @param {Element} el the target element */ PIE.BorderImageStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: 'border-image', styleProperty: 'borderImage', repeatIdents: { 'stretch':1, 'round':1, 'repeat':1, 'space':1 }, parseCss: function( css ) { var p = null, tokenizer, token, type, value, slices, widths, outsets, slashCount = 0, Type = PIE.Tokenizer.Type, IDENT = Type.IDENT, NUMBER = Type.NUMBER, PERCENT = Type.PERCENT; if( css ) { tokenizer = new PIE.Tokenizer( css ); p = {}; function isSlash( token ) { return token && ( token.tokenType & Type.OPERATOR ) && ( token.tokenValue === '/' ); } function isFillIdent( token ) { return token && ( token.tokenType & IDENT ) && ( token.tokenValue === 'fill' ); } function collectSlicesEtc() { slices = tokenizer.until( function( tok ) { return !( tok.tokenType & ( NUMBER | PERCENT ) ); } ); if( isFillIdent( tokenizer.next() ) && !p.fill ) { p.fill = true; } else { tokenizer.prev(); } if( isSlash( tokenizer.next() ) ) { slashCount++; widths = tokenizer.until( function( token ) { return !token.isLengthOrPercent() && !( ( token.tokenType & IDENT ) && token.tokenValue === 'auto' ); } ); if( isSlash( tokenizer.next() ) ) { slashCount++; outsets = tokenizer.until( function( token ) { return !token.isLength(); } ); } } else { tokenizer.prev(); } } while( token = tokenizer.next() ) { type = token.tokenType; value = token.tokenValue; // Numbers and/or 'fill' keyword: slice values. May be followed optionally by width values, followed optionally by outset values if( type & ( NUMBER | PERCENT ) && !slices ) { tokenizer.prev(); collectSlicesEtc(); } else if( isFillIdent( token ) && !p.fill ) { p.fill = true; collectSlicesEtc(); } // Idents: one or values for 'repeat' else if( ( type & IDENT ) && this.repeatIdents[value] && !p.repeat ) { p.repeat = { h: value }; if( token = tokenizer.next() ) { if( ( token.tokenType & IDENT ) && this.repeatIdents[token.tokenValue] ) { p.repeat.v = token.tokenValue; } else { tokenizer.prev(); } } } // URL of the image else if( ( type & Type.URL ) && !p.src ) { p.src = value; } // Found something unrecognized; exit. else { return null; } } // Validate what we collected if( !p.src || !slices || slices.length < 1 || slices.length > 4 || ( widths && widths.length > 4 ) || ( slashCount === 1 && widths.length < 1 ) || ( outsets && outsets.length > 4 ) || ( slashCount === 2 && outsets.length < 1 ) ) { return null; } // Fill in missing values if( !p.repeat ) { p.repeat = { h: 'stretch' }; } if( !p.repeat.v ) { p.repeat.v = p.repeat.h; } function distributeSides( tokens, convertFn ) { return { 't': convertFn( tokens[0] ), 'r': convertFn( tokens[1] || tokens[0] ), 'b': convertFn( tokens[2] || tokens[0] ), 'l': convertFn( tokens[3] || tokens[1] || tokens[0] ) }; } p.slice = distributeSides( slices, function( tok ) { return PIE.getLength( ( tok.tokenType & NUMBER ) ? tok.tokenValue + 'px' : tok.tokenValue ); } ); if( widths && widths[0] ) { p.widths = distributeSides( widths, function( tok ) { return tok.isLengthOrPercent() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue; } ); } if( outsets && outsets[0] ) { p.outset = distributeSides( outsets, function( tok ) { return tok.isLength() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue; } ); } } return p; } } );/** * Handles parsing, caching, and detecting changes to box-shadow CSS * @constructor * @param {Element} el the target element */ PIE.BoxShadowStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: 'box-shadow', styleProperty: 'boxShadow', parseCss: function( css ) { var props, getLength = PIE.getLength, Type = PIE.Tokenizer.Type, tokenizer; if( css ) { tokenizer = new PIE.Tokenizer( css ); props = { outset: [], inset: [] }; function parseItem() { var token, type, value, color, lengths, inset, len; while( token = tokenizer.next() ) { value = token.tokenValue; type = token.tokenType; if( type & Type.OPERATOR && value === ',' ) { break; } else if( token.isLength() && !lengths ) { tokenizer.prev(); lengths = tokenizer.until( function( token ) { return !token.isLength(); } ); } else if( type & Type.COLOR && !color ) { color = value; } else if( type & Type.IDENT && value === 'inset' && !inset ) { inset = true; } else { //encountered an unrecognized token; fail. return false; } } len = lengths && lengths.length; if( len > 1 && len < 5 ) { ( inset ? props.inset : props.outset ).push( { xOffset: getLength( lengths[0].tokenValue ), yOffset: getLength( lengths[1].tokenValue ), blur: getLength( lengths[2] ? lengths[2].tokenValue : '0' ), spread: getLength( lengths[3] ? lengths[3].tokenValue : '0' ), color: PIE.getColor( color || 'currentColor' ) } ); return true; } return false; } while( parseItem() ) {} } return props && ( props.inset.length || props.outset.length ) ? props : null; } } ); /** * Retrieves the state of the element's visibility and display * @constructor * @param {Element} el the target element */ PIE.VisibilityStyleInfo = PIE.StyleInfoBase.newStyleInfo( { getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { var cs = this.targetElement.currentStyle; return cs.visibility + '|' + cs.display; } ), parseCss: function() { var el = this.targetElement, rs = el.runtimeStyle, cs = el.currentStyle, rsVis = rs.visibility, csVis; rs.visibility = ''; csVis = cs.visibility; rs.visibility = rsVis; return { visible: csVis !== 'hidden', displayed: cs.display !== 'none' } }, /** * Always return false for isActive, since this property alone will not trigger * a renderer to do anything. */ isActive: function() { return false; } } ); PIE.RendererBase = { /** * Create a new Renderer class, with the standard constructor, and augmented by * the RendererBase's members. * @param proto */ newRenderer: function( proto ) { function Renderer( el, boundsInfo, styleInfos, parent ) { this.targetElement = el; this.boundsInfo = boundsInfo; this.styleInfos = styleInfos; this.parent = parent; } PIE.Util.merge( Renderer.prototype, PIE.RendererBase, proto ); return Renderer; }, /** * Flag indicating the element has already been positioned at least once. * @type {boolean} */ isPositioned: false, /** * Determine if the renderer needs to be updated * @return {boolean} */ needsUpdate: function() { return false; }, /** * Run any preparation logic that would affect the main update logic of this * renderer or any of the other renderers, e.g. things that might affect the * element's size or style properties. */ prepareUpdate: PIE.emptyFn, /** * Tell the renderer to update based on modified properties */ updateProps: function() { this.destroy(); if( this.isActive() ) { this.draw(); } }, /** * Tell the renderer to update based on modified element position */ updatePos: function() { this.isPositioned = true; }, /** * Tell the renderer to update based on modified element dimensions */ updateSize: function() { if( this.isActive() ) { this.draw(); } else { this.destroy(); } }, /** * Add a layer element, with the given z-order index, to the renderer's main box element. We can't use * z-index because that breaks when the root rendering box's z-index is 'auto' in IE8+ standards mode. * So instead we make sure they are inserted into the DOM in the correct order. * @param {number} index * @param {Element} el */ addLayer: function( index, el ) { this.removeLayer( index ); for( var layers = this._layers || ( this._layers = [] ), i = index + 1, len = layers.length, layer; i < len; i++ ) { layer = layers[i]; if( layer ) { break; } } layers[index] = el; this.getBox().insertBefore( el, layer || null ); }, /** * Retrieve a layer element by its index, or null if not present * @param {number} index * @return {Element} */ getLayer: function( index ) { var layers = this._layers; return layers && layers[index] || null; }, /** * Remove a layer element by its index * @param {number} index */ removeLayer: function( index ) { var layer = this.getLayer( index ), box = this._box; if( layer && box ) { box.removeChild( layer ); this._layers[index] = null; } }, /** * Get a VML shape by name, creating it if necessary. * @param {string} name A name identifying the element * @param {string=} subElName If specified a subelement of the shape will be created with this tag name * @param {Element} parent The parent element for the shape; will be ignored if 'group' is specified * @param {number=} group If specified, an ordinal group for the shape. 1 or greater. Groups are rendered * using container elements in the correct order, to get correct z stacking without z-index. */ getShape: function( name, subElName, parent, group ) { var shapes = this._shapes || ( this._shapes = {} ), shape = shapes[ name ], s; if( !shape ) { shape = shapes[ name ] = PIE.Util.createVmlElement( 'shape' ); if( subElName ) { shape.appendChild( shape[ subElName ] = PIE.Util.createVmlElement( subElName ) ); } if( group ) { parent = this.getLayer( group ); if( !parent ) { this.addLayer( group, doc.createElement( 'group' + group ) ); parent = this.getLayer( group ); } } parent.appendChild( shape ); s = shape.style; s.position = 'absolute'; s.left = s.top = 0; s['behavior'] = 'url(#default#VML)'; } return shape; }, /** * Delete a named shape which was created by getShape(). Returns true if a shape with the * given name was found and deleted, or false if there was no shape of that name. * @param {string} name * @return {boolean} */ deleteShape: function( name ) { var shapes = this._shapes, shape = shapes && shapes[ name ]; if( shape ) { shape.parentNode.removeChild( shape ); delete shapes[ name ]; } return !!shape; }, /** * For a given set of border radius length/percentage values, convert them to concrete pixel * values based on the current size of the target element. * @param {Object} radii * @return {Object} */ getRadiiPixels: function( radii ) { var el = this.targetElement, bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, tlX, tlY, trX, trY, brX, brY, blX, blY, f; tlX = radii.x['tl'].pixels( el, w ); tlY = radii.y['tl'].pixels( el, h ); trX = radii.x['tr'].pixels( el, w ); trY = radii.y['tr'].pixels( el, h ); brX = radii.x['br'].pixels( el, w ); brY = radii.y['br'].pixels( el, h ); blX = radii.x['bl'].pixels( el, w ); blY = radii.y['bl'].pixels( el, h ); // If any corner ellipses overlap, reduce them all by the appropriate factor. This formula // is taken straight from the CSS3 Backgrounds and Borders spec. f = Math.min( w / ( tlX + trX ), h / ( trY + brY ), w / ( blX + brX ), h / ( tlY + blY ) ); if( f < 1 ) { tlX *= f; tlY *= f; trX *= f; trY *= f; brX *= f; brY *= f; blX *= f; blY *= f; } return { x: { 'tl': tlX, 'tr': trX, 'br': brX, 'bl': blX }, y: { 'tl': tlY, 'tr': trY, 'br': brY, 'bl': blY } } }, /** * Return the VML path string for the element's background box, with corners rounded. * @param {Object.<{t:number, r:number, b:number, l:number}>} shrink - if present, specifies number of * pixels to shrink the box path inward from the element's four sides. * @param {number=} mult If specified, all coordinates will be multiplied by this number * @param {Object=} radii If specified, this will be used for the corner radii instead of the properties * from this renderer's borderRadiusInfo object. * @return {string} the VML path */ getBoxPath: function( shrink, mult, radii ) { mult = mult || 1; var r, str, bounds = this.boundsInfo.getBounds(), w = bounds.w * mult, h = bounds.h * mult, radInfo = this.styleInfos.borderRadiusInfo, floor = Math.floor, ceil = Math.ceil, shrinkT = shrink ? shrink.t * mult : 0, shrinkR = shrink ? shrink.r * mult : 0, shrinkB = shrink ? shrink.b * mult : 0, shrinkL = shrink ? shrink.l * mult : 0, tlX, tlY, trX, trY, brX, brY, blX, blY; if( radii || radInfo.isActive() ) { r = this.getRadiiPixels( radii || radInfo.getProps() ); tlX = r.x['tl'] * mult; tlY = r.y['tl'] * mult; trX = r.x['tr'] * mult; trY = r.y['tr'] * mult; brX = r.x['br'] * mult; brY = r.y['br'] * mult; blX = r.x['bl'] * mult; blY = r.y['bl'] * mult; str = 'm' + floor( shrinkL ) + ',' + floor( tlY ) + 'qy' + floor( tlX ) + ',' + floor( shrinkT ) + 'l' + ceil( w - trX ) + ',' + floor( shrinkT ) + 'qx' + ceil( w - shrinkR ) + ',' + floor( trY ) + 'l' + ceil( w - shrinkR ) + ',' + ceil( h - brY ) + 'qy' + ceil( w - brX ) + ',' + ceil( h - shrinkB ) + 'l' + floor( blX ) + ',' + ceil( h - shrinkB ) + 'qx' + floor( shrinkL ) + ',' + ceil( h - blY ) + ' x e'; } else { // simplified path for non-rounded box str = 'm' + floor( shrinkL ) + ',' + floor( shrinkT ) + 'l' + ceil( w - shrinkR ) + ',' + floor( shrinkT ) + 'l' + ceil( w - shrinkR ) + ',' + ceil( h - shrinkB ) + 'l' + floor( shrinkL ) + ',' + ceil( h - shrinkB ) + 'xe'; } return str; }, /** * Get the container element for the shapes, creating it if necessary. */ getBox: function() { var box = this.parent.getLayer( this.boxZIndex ), s; if( !box ) { box = doc.createElement( this.boxName ); s = box.style; s.position = 'absolute'; s.top = s.left = 0; this.parent.addLayer( this.boxZIndex, box ); } return box; }, /** * Hide the actual border of the element. In IE7 and up we can just set its color to transparent; * however IE6 does not support transparent borders so we have to get tricky with it. Also, some elements * like form buttons require removing the border width altogether, so for those we increase the padding * by the border size. */ hideBorder: function() { var el = this.targetElement, cs = el.currentStyle, rs = el.runtimeStyle, tag = el.tagName, isIE6 = PIE.ieVersion === 6, sides, side, i; if( ( isIE6 && ( tag in PIE.childlessElements || tag === 'FIELDSET' ) ) || tag === 'BUTTON' || ( tag === 'INPUT' && el.type in PIE.inputButtonTypes ) ) { rs.borderWidth = ''; sides = this.styleInfos.borderInfo.sides; for( i = sides.length; i--; ) { side = sides[ i ]; rs[ 'padding' + side ] = ''; rs[ 'padding' + side ] = ( PIE.getLength( cs[ 'padding' + side ] ) ).pixels( el ) + ( PIE.getLength( cs[ 'border' + side + 'Width' ] ) ).pixels( el ) + ( PIE.ieVersion !== 8 && i % 2 ? 1 : 0 ); //needs an extra horizontal pixel to counteract the extra "inner border" going away } rs.borderWidth = 0; } else if( isIE6 ) { // Wrap all the element's children in a custom element, set the element to visiblity:hidden, // and set the wrapper element to visiblity:visible. This hides the outer element's decorations // (background and border) but displays all the contents. // TODO find a better way to do this that doesn't mess up the DOM parent-child relationship, // as this can interfere with other author scripts which add/modify/delete children. Also, this // won't work for elements which cannot take children, e.g. input/button/textarea/img/etc. Look into // using a compositor filter or some other filter which masks the border. if( el.childNodes.length !== 1 || el.firstChild.tagName !== 'ie6-mask' ) { var cont = doc.createElement( 'ie6-mask' ), s = cont.style, child; s.visibility = 'visible'; s.zoom = 1; while( child = el.firstChild ) { cont.appendChild( child ); } el.appendChild( cont ); rs.visibility = 'hidden'; } } else { rs.borderColor = 'transparent'; } }, unhideBorder: function() { }, /** * Destroy the rendered objects. This is a base implementation which handles common renderer * structures, but individual renderers may override as necessary. */ destroy: function() { this.parent.removeLayer( this.boxZIndex ); delete this._shapes; delete this._layers; } }; /** * Root renderer; creates the outermost container element and handles keeping it aligned * with the target element's size and position. * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects */ PIE.RootRenderer = PIE.RendererBase.newRenderer( { isActive: function() { var children = this.childRenderers; for( var i in children ) { if( children.hasOwnProperty( i ) && children[ i ].isActive() ) { return true; } } return false; }, needsUpdate: function() { return this.styleInfos.visibilityInfo.changed(); }, updatePos: function() { if( this.isActive() ) { var el = this.getPositioningElement(), par = el, docEl, parRect, tgtCS = el.currentStyle, tgtPos = tgtCS.position, boxPos, s = this.getBox().style, cs, x = 0, y = 0, elBounds = this.boundsInfo.getBounds(), logicalZoomRatio = elBounds.logicalZoomRatio; if( tgtPos === 'fixed' && PIE.ieVersion > 6 ) { x = elBounds.x * logicalZoomRatio; y = elBounds.y * logicalZoomRatio; boxPos = tgtPos; } else { // Get the element's offsets from its nearest positioned ancestor. Uses // getBoundingClientRect for accuracy and speed. do { par = par.offsetParent; } while( par && ( par.currentStyle.position === 'static' ) ); if( par ) { parRect = par.getBoundingClientRect(); cs = par.currentStyle; x = ( elBounds.x - parRect.left ) * logicalZoomRatio - ( parseFloat(cs.borderLeftWidth) || 0 ); y = ( elBounds.y - parRect.top ) * logicalZoomRatio - ( parseFloat(cs.borderTopWidth) || 0 ); } else { docEl = doc.documentElement; x = ( elBounds.x + docEl.scrollLeft - docEl.clientLeft ) * logicalZoomRatio; y = ( elBounds.y + docEl.scrollTop - docEl.clientTop ) * logicalZoomRatio; } boxPos = 'absolute'; } s.position = boxPos; s.left = x; s.top = y; s.zIndex = tgtPos === 'static' ? -1 : tgtCS.zIndex; this.isPositioned = true; } }, updateSize: PIE.emptyFn, updateVisibility: function() { var vis = this.styleInfos.visibilityInfo.getProps(); this.getBox().style.display = ( vis.visible && vis.displayed ) ? '' : 'none'; }, updateProps: function() { if( this.isActive() ) { this.updateVisibility(); } else { this.destroy(); } }, getPositioningElement: function() { var el = this.targetElement; return el.tagName in PIE.tableCellTags ? el.offsetParent : el; }, getBox: function() { var box = this._box, el; if( !box ) { el = this.getPositioningElement(); box = this._box = doc.createElement( 'css3-container' ); box.style['direction'] = 'ltr'; //fix positioning bug in rtl environments this.updateVisibility(); el.parentNode.insertBefore( box, el ); } return box; }, finishUpdate: PIE.emptyFn, destroy: function() { var box = this._box, par; if( box && ( par = box.parentNode ) ) { par.removeChild( box ); } delete this._box; delete this._layers; } } ); /** * Renderer for element backgrounds. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BackgroundRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 2, boxName: 'background', needsUpdate: function() { var si = this.styleInfos; return si.backgroundInfo.changed() || si.borderRadiusInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.borderImageInfo.isActive() || si.borderRadiusInfo.isActive() || si.backgroundInfo.isActive() || ( si.boxShadowInfo.isActive() && si.boxShadowInfo.getProps().inset ); }, /** * Draw the shapes */ draw: function() { var bounds = this.boundsInfo.getBounds(); if( bounds.w && bounds.h ) { this.drawBgColor(); this.drawBgImages(); } }, /** * Draw the background color shape */ drawBgColor: function() { var props = this.styleInfos.backgroundInfo.getProps(), bounds = this.boundsInfo.getBounds(), el = this.targetElement, color = props && props.color, shape, w, h, s, alpha; if( color && color.alpha() > 0 ) { this.hideBackground(); shape = this.getShape( 'bgColor', 'fill', this.getBox(), 1 ); w = bounds.w; h = bounds.h; shape.stroked = false; shape.coordsize = w * 2 + ',' + h * 2; shape.coordorigin = '1,1'; shape.path = this.getBoxPath( null, 2 ); s = shape.style; s.width = w; s.height = h; shape.fill.color = color.colorValue( el ); alpha = color.alpha(); if( alpha < 1 ) { shape.fill.opacity = alpha; } } else { this.deleteShape( 'bgColor' ); } }, /** * Draw all the background image layers */ drawBgImages: function() { var props = this.styleInfos.backgroundInfo.getProps(), bounds = this.boundsInfo.getBounds(), images = props && props.bgImages, img, shape, w, h, s, i; if( images ) { this.hideBackground(); w = bounds.w; h = bounds.h; i = images.length; while( i-- ) { img = images[i]; shape = this.getShape( 'bgImage' + i, 'fill', this.getBox(), 2 ); shape.stroked = false; shape.fill.type = 'tile'; shape.fillcolor = 'none'; shape.coordsize = w * 2 + ',' + h * 2; shape.coordorigin = '1,1'; shape.path = this.getBoxPath( 0, 2 ); s = shape.style; s.width = w; s.height = h; if( img.imgType === 'linear-gradient' ) { this.addLinearGradient( shape, img ); } else { shape.fill.src = img.imgUrl; this.positionBgImage( shape, i ); } } } // Delete any bgImage shapes previously created which weren't used above i = images ? images.length : 0; while( this.deleteShape( 'bgImage' + i++ ) ) {} }, /** * Set the position and clipping of the background image for a layer * @param {Element} shape * @param {number} index */ positionBgImage: function( shape, index ) { var me = this; PIE.Util.withImageSize( shape.fill.src, function( size ) { var el = me.targetElement, bounds = me.boundsInfo.getBounds(), elW = bounds.w, elH = bounds.h; // It's possible that the element dimensions are zero now but weren't when the original // update executed, make sure that's not the case to avoid divide-by-zero error if( elW && elH ) { var fill = shape.fill, si = me.styleInfos, border = si.borderInfo.getProps(), bw = border && border.widths, bwT = bw ? bw['t'].pixels( el ) : 0, bwR = bw ? bw['r'].pixels( el ) : 0, bwB = bw ? bw['b'].pixels( el ) : 0, bwL = bw ? bw['l'].pixels( el ) : 0, bg = si.backgroundInfo.getProps().bgImages[ index ], bgPos = bg.bgPosition ? bg.bgPosition.coords( el, elW - size.w - bwL - bwR, elH - size.h - bwT - bwB ) : { x:0, y:0 }, repeat = bg.imgRepeat, pxX, pxY, clipT = 0, clipL = 0, clipR = elW + 1, clipB = elH + 1, //make sure the default clip region is not inside the box (by a subpixel) clipAdjust = PIE.ieVersion === 8 ? 0 : 1; //prior to IE8 requires 1 extra pixel in the image clip region // Positioning - find the pixel offset from the top/left and convert to a ratio // The position is shifted by half a pixel, to adjust for the half-pixel coordorigin shift which is // needed to fix antialiasing but makes the bg image fuzzy. pxX = Math.round( bgPos.x ) + bwL + 0.5; pxY = Math.round( bgPos.y ) + bwT + 0.5; fill.position = ( pxX / elW ) + ',' + ( pxY / elH ); // Set the size of the image. We have to actually set it to px values otherwise it will not honor // the user's browser zoom level and always display at its natural screen size. fill['size']['x'] = 1; //Can be any value, just has to be set to "prime" it so the next line works. Weird! fill['size'] = size.w + 'px,' + size.h + 'px'; // Repeating - clip the image shape if( repeat && repeat !== 'repeat' ) { if( repeat === 'repeat-x' || repeat === 'no-repeat' ) { clipT = pxY + 1; clipB = pxY + size.h + clipAdjust; } if( repeat === 'repeat-y' || repeat === 'no-repeat' ) { clipL = pxX + 1; clipR = pxX + size.w + clipAdjust; } shape.style.clip = 'rect(' + clipT + 'px,' + clipR + 'px,' + clipB + 'px,' + clipL + 'px)'; } } } ); }, /** * Draw the linear gradient for a gradient layer * @param {Element} shape * @param {Object} info The object holding the information about the gradient */ addLinearGradient: function( shape, info ) { var el = this.targetElement, bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, fill = shape.fill, stops = info.stops, stopCount = stops.length, PI = Math.PI, GradientUtil = PIE.GradientUtil, perpendicularIntersect = GradientUtil.perpendicularIntersect, distance = GradientUtil.distance, metrics = GradientUtil.getGradientMetrics( el, w, h, info ), angle = metrics.angle, startX = metrics.startX, startY = metrics.startY, startCornerX = metrics.startCornerX, startCornerY = metrics.startCornerY, endCornerX = metrics.endCornerX, endCornerY = metrics.endCornerY, deltaX = metrics.deltaX, deltaY = metrics.deltaY, lineLength = metrics.lineLength, vmlAngle, vmlGradientLength, vmlColors, stopPx, vmlOffsetPct, p, i, j, before, after; // In VML land, the angle of the rendered gradient depends on the aspect ratio of the shape's // bounding box; for example specifying a 45 deg angle actually results in a gradient // drawn diagonally from one corner to its opposite corner, which will only appear to the // viewer as 45 degrees if the shape is equilateral. We adjust for this by taking the x/y deltas // between the start and end points, multiply one of them by the shape's aspect ratio, // and get their arctangent, resulting in an appropriate VML angle. If the angle is perfectly // horizontal or vertical then we don't need to do this conversion. vmlAngle = ( angle % 90 ) ? Math.atan2( deltaX * w / h, deltaY ) / PI * 180 : ( angle + 90 ); // VML angles are 180 degrees offset from CSS angles vmlAngle += 180; vmlAngle = vmlAngle % 360; // Add all the stops to the VML 'colors' list, including the first and last stops. // For each, we find its pixel offset along the gradient-line; if the offset of a stop is less // than that of its predecessor we increase it to be equal. We then map that pixel offset to a // percentage along the VML gradient-line, which runs from shape corner to corner. p = perpendicularIntersect( startCornerX, startCornerY, angle, endCornerX, endCornerY ); vmlGradientLength = distance( startCornerX, startCornerY, p[0], p[1] ); vmlColors = []; p = perpendicularIntersect( startX, startY, angle, startCornerX, startCornerY ); vmlOffsetPct = distance( startX, startY, p[0], p[1] ) / vmlGradientLength * 100; // Find the pixel offsets along the CSS3 gradient-line for each stop. stopPx = []; for( i = 0; i < stopCount; i++ ) { stopPx.push( stops[i].offset ? stops[i].offset.pixels( el, lineLength ) : i === 0 ? 0 : i === stopCount - 1 ? lineLength : null ); } // Fill in gaps with evenly-spaced offsets for( i = 1; i < stopCount; i++ ) { if( stopPx[ i ] === null ) { before = stopPx[ i - 1 ]; j = i; do { after = stopPx[ ++j ]; } while( after === null ); stopPx[ i ] = before + ( after - before ) / ( j - i + 1 ); } // Make sure each stop's offset is no less than the one before it stopPx[ i ] = Math.max( stopPx[ i ], stopPx[ i - 1 ] ); } // Convert to percentage along the VML gradient line and add to the VML 'colors' value for( i = 0; i < stopCount; i++ ) { vmlColors.push( ( vmlOffsetPct + ( stopPx[ i ] / vmlGradientLength * 100 ) ) + '% ' + stops[i].color.colorValue( el ) ); } // Now, finally, we're ready to render the gradient fill. Set the start and end colors to // the first and last stop colors; this just sets outer bounds for the gradient. fill['angle'] = vmlAngle; fill['type'] = 'gradient'; fill['method'] = 'sigma'; fill['color'] = stops[0].color.colorValue( el ); fill['color2'] = stops[stopCount - 1].color.colorValue( el ); if( fill['colors'] ) { //sometimes the colors object isn't initialized so we have to assign it directly (?) fill['colors'].value = vmlColors.join( ',' ); } else { fill['colors'] = vmlColors.join( ',' ); } }, /** * Hide the actual background image and color of the element. */ hideBackground: function() { var rs = this.targetElement.runtimeStyle; rs.backgroundImage = 'url(about:blank)'; //ensures the background area reacts to mouse events rs.backgroundColor = 'transparent'; }, destroy: function() { PIE.RendererBase.destroy.call( this ); var rs = this.targetElement.runtimeStyle; rs.backgroundImage = rs.backgroundColor = ''; } } ); /** * Renderer for element borders. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BorderRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 4, boxName: 'border', needsUpdate: function() { var si = this.styleInfos; return si.borderInfo.changed() || si.borderRadiusInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.borderRadiusInfo.isActive() && !si.borderImageInfo.isActive() && si.borderInfo.isActive(); //check BorderStyleInfo last because it's the most expensive }, /** * Draw the border shape(s) */ draw: function() { var el = this.targetElement, props = this.styleInfos.borderInfo.getProps(), bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, shape, stroke, s, segments, seg, i, len; if( props ) { this.hideBorder(); segments = this.getBorderSegments( 2 ); for( i = 0, len = segments.length; i < len; i++) { seg = segments[i]; shape = this.getShape( 'borderPiece' + i, seg.stroke ? 'stroke' : 'fill', this.getBox() ); shape.coordsize = w * 2 + ',' + h * 2; shape.coordorigin = '1,1'; shape.path = seg.path; s = shape.style; s.width = w; s.height = h; shape.filled = !!seg.fill; shape.stroked = !!seg.stroke; if( seg.stroke ) { stroke = shape.stroke; stroke['weight'] = seg.weight + 'px'; stroke.color = seg.color.colorValue( el ); stroke['dashstyle'] = seg.stroke === 'dashed' ? '2 2' : seg.stroke === 'dotted' ? '1 1' : 'solid'; stroke['linestyle'] = seg.stroke === 'double' && seg.weight > 2 ? 'ThinThin' : 'Single'; } else { shape.fill.color = seg.fill.colorValue( el ); } } // remove any previously-created border shapes which didn't get used above while( this.deleteShape( 'borderPiece' + i++ ) ) {} } }, /** * Get the VML path definitions for the border segment(s). * @param {number=} mult If specified, all coordinates will be multiplied by this number * @return {Array.<string>} */ getBorderSegments: function( mult ) { var el = this.targetElement, bounds, elW, elH, borderInfo = this.styleInfos.borderInfo, segments = [], floor, ceil, wT, wR, wB, wL, round = Math.round, borderProps, radiusInfo, radii, widths, styles, colors; if( borderInfo.isActive() ) { borderProps = borderInfo.getProps(); widths = borderProps.widths; styles = borderProps.styles; colors = borderProps.colors; if( borderProps.widthsSame && borderProps.stylesSame && borderProps.colorsSame ) { if( colors['t'].alpha() > 0 ) { // shortcut for identical border on all sides - only need 1 stroked shape wT = widths['t'].pixels( el ); //thickness wR = wT / 2; //shrink segments.push( { path: this.getBoxPath( { t: wR, r: wR, b: wR, l: wR }, mult ), stroke: styles['t'], color: colors['t'], weight: wT } ); } } else { mult = mult || 1; bounds = this.boundsInfo.getBounds(); elW = bounds.w; elH = bounds.h; wT = round( widths['t'].pixels( el ) ); wR = round( widths['r'].pixels( el ) ); wB = round( widths['b'].pixels( el ) ); wL = round( widths['l'].pixels( el ) ); var pxWidths = { 't': wT, 'r': wR, 'b': wB, 'l': wL }; radiusInfo = this.styleInfos.borderRadiusInfo; if( radiusInfo.isActive() ) { radii = this.getRadiiPixels( radiusInfo.getProps() ); } floor = Math.floor; ceil = Math.ceil; function radius( xy, corner ) { return radii ? radii[ xy ][ corner ] : 0; } function curve( corner, shrinkX, shrinkY, startAngle, ccw, doMove ) { var rx = radius( 'x', corner), ry = radius( 'y', corner), deg = 65535, isRight = corner.charAt( 1 ) === 'r', isBottom = corner.charAt( 0 ) === 'b'; return ( rx > 0 && ry > 0 ) ? ( doMove ? 'al' : 'ae' ) + ( isRight ? ceil( elW - rx ) : floor( rx ) ) * mult + ',' + // center x ( isBottom ? ceil( elH - ry ) : floor( ry ) ) * mult + ',' + // center y ( floor( rx ) - shrinkX ) * mult + ',' + // width ( floor( ry ) - shrinkY ) * mult + ',' + // height ( startAngle * deg ) + ',' + // start angle ( 45 * deg * ( ccw ? 1 : -1 ) // angle change ) : ( ( doMove ? 'm' : 'l' ) + ( isRight ? elW - shrinkX : shrinkX ) * mult + ',' + ( isBottom ? elH - shrinkY : shrinkY ) * mult ); } function line( side, shrink, ccw, doMove ) { var start = ( side === 't' ? floor( radius( 'x', 'tl') ) * mult + ',' + ceil( shrink ) * mult : side === 'r' ? ceil( elW - shrink ) * mult + ',' + floor( radius( 'y', 'tr') ) * mult : side === 'b' ? ceil( elW - radius( 'x', 'br') ) * mult + ',' + floor( elH - shrink ) * mult : // side === 'l' ? floor( shrink ) * mult + ',' + ceil( elH - radius( 'y', 'bl') ) * mult ), end = ( side === 't' ? ceil( elW - radius( 'x', 'tr') ) * mult + ',' + ceil( shrink ) * mult : side === 'r' ? ceil( elW - shrink ) * mult + ',' + ceil( elH - radius( 'y', 'br') ) * mult : side === 'b' ? floor( radius( 'x', 'bl') ) * mult + ',' + floor( elH - shrink ) * mult : // side === 'l' ? floor( shrink ) * mult + ',' + floor( radius( 'y', 'tl') ) * mult ); return ccw ? ( doMove ? 'm' + end : '' ) + 'l' + start : ( doMove ? 'm' + start : '' ) + 'l' + end; } function addSide( side, sideBefore, sideAfter, cornerBefore, cornerAfter, baseAngle ) { var vert = side === 'l' || side === 'r', sideW = pxWidths[ side ], beforeX, beforeY, afterX, afterY; if( sideW > 0 && styles[ side ] !== 'none' && colors[ side ].alpha() > 0 ) { beforeX = pxWidths[ vert ? side : sideBefore ]; beforeY = pxWidths[ vert ? sideBefore : side ]; afterX = pxWidths[ vert ? side : sideAfter ]; afterY = pxWidths[ vert ? sideAfter : side ]; if( styles[ side ] === 'dashed' || styles[ side ] === 'dotted' ) { segments.push( { path: curve( cornerBefore, beforeX, beforeY, baseAngle + 45, 0, 1 ) + curve( cornerBefore, 0, 0, baseAngle, 1, 0 ), fill: colors[ side ] } ); segments.push( { path: line( side, sideW / 2, 0, 1 ), stroke: styles[ side ], weight: sideW, color: colors[ side ] } ); segments.push( { path: curve( cornerAfter, afterX, afterY, baseAngle, 0, 1 ) + curve( cornerAfter, 0, 0, baseAngle - 45, 1, 0 ), fill: colors[ side ] } ); } else { segments.push( { path: curve( cornerBefore, beforeX, beforeY, baseAngle + 45, 0, 1 ) + line( side, sideW, 0, 0 ) + curve( cornerAfter, afterX, afterY, baseAngle, 0, 0 ) + ( styles[ side ] === 'double' && sideW > 2 ? curve( cornerAfter, afterX - floor( afterX / 3 ), afterY - floor( afterY / 3 ), baseAngle - 45, 1, 0 ) + line( side, ceil( sideW / 3 * 2 ), 1, 0 ) + curve( cornerBefore, beforeX - floor( beforeX / 3 ), beforeY - floor( beforeY / 3 ), baseAngle, 1, 0 ) + 'x ' + curve( cornerBefore, floor( beforeX / 3 ), floor( beforeY / 3 ), baseAngle + 45, 0, 1 ) + line( side, floor( sideW / 3 ), 1, 0 ) + curve( cornerAfter, floor( afterX / 3 ), floor( afterY / 3 ), baseAngle, 0, 0 ) : '' ) + curve( cornerAfter, 0, 0, baseAngle - 45, 1, 0 ) + line( side, 0, 1, 0 ) + curve( cornerBefore, 0, 0, baseAngle, 1, 0 ), fill: colors[ side ] } ); } } } addSide( 't', 'l', 'r', 'tl', 'tr', 90 ); addSide( 'r', 't', 'b', 'tr', 'br', 0 ); addSide( 'b', 'r', 'l', 'br', 'bl', -90 ); addSide( 'l', 'b', 't', 'bl', 'tl', -180 ); } } return segments; }, destroy: function() { var me = this; if (me.finalized || !me.styleInfos.borderImageInfo.isActive()) { me.targetElement.runtimeStyle.borderColor = ''; } PIE.RendererBase.destroy.call( me ); } } ); /** * Renderer for border-image * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BorderImageRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 5, pieceNames: [ 't', 'tr', 'r', 'br', 'b', 'bl', 'l', 'tl', 'c' ], needsUpdate: function() { return this.styleInfos.borderImageInfo.changed(); }, isActive: function() { return this.styleInfos.borderImageInfo.isActive(); }, draw: function() { this.getBox(); //make sure pieces are created var props = this.styleInfos.borderImageInfo.getProps(), borderProps = this.styleInfos.borderInfo.getProps(), bounds = this.boundsInfo.getBounds(), el = this.targetElement, pieces = this.pieces; PIE.Util.withImageSize( props.src, function( imgSize ) { var elW = bounds.w, elH = bounds.h, zero = PIE.getLength( '0' ), widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ), widthT = widths['t'].pixels( el ), widthR = widths['r'].pixels( el ), widthB = widths['b'].pixels( el ), widthL = widths['l'].pixels( el ), slices = props.slice, sliceT = slices['t'].pixels( el ), sliceR = slices['r'].pixels( el ), sliceB = slices['b'].pixels( el ), sliceL = slices['l'].pixels( el ); // Piece positions and sizes function setSizeAndPos( piece, w, h, x, y ) { var s = pieces[piece].style, max = Math.max; s.width = max(w, 0); s.height = max(h, 0); s.left = x; s.top = y; } setSizeAndPos( 'tl', widthL, widthT, 0, 0 ); setSizeAndPos( 't', elW - widthL - widthR, widthT, widthL, 0 ); setSizeAndPos( 'tr', widthR, widthT, elW - widthR, 0 ); setSizeAndPos( 'r', widthR, elH - widthT - widthB, elW - widthR, widthT ); setSizeAndPos( 'br', widthR, widthB, elW - widthR, elH - widthB ); setSizeAndPos( 'b', elW - widthL - widthR, widthB, widthL, elH - widthB ); setSizeAndPos( 'bl', widthL, widthB, 0, elH - widthB ); setSizeAndPos( 'l', widthL, elH - widthT - widthB, 0, widthT ); setSizeAndPos( 'c', elW - widthL - widthR, elH - widthT - widthB, widthL, widthT ); // image croppings function setCrops( sides, crop, val ) { for( var i=0, len=sides.length; i < len; i++ ) { pieces[ sides[i] ]['imagedata'][ crop ] = val; } } // corners setCrops( [ 'tl', 't', 'tr' ], 'cropBottom', ( imgSize.h - sliceT ) / imgSize.h ); setCrops( [ 'tl', 'l', 'bl' ], 'cropRight', ( imgSize.w - sliceL ) / imgSize.w ); setCrops( [ 'bl', 'b', 'br' ], 'cropTop', ( imgSize.h - sliceB ) / imgSize.h ); setCrops( [ 'tr', 'r', 'br' ], 'cropLeft', ( imgSize.w - sliceR ) / imgSize.w ); // edges and center // TODO right now this treats everything like 'stretch', need to support other schemes //if( props.repeat.v === 'stretch' ) { setCrops( [ 'l', 'r', 'c' ], 'cropTop', sliceT / imgSize.h ); setCrops( [ 'l', 'r', 'c' ], 'cropBottom', sliceB / imgSize.h ); //} //if( props.repeat.h === 'stretch' ) { setCrops( [ 't', 'b', 'c' ], 'cropLeft', sliceL / imgSize.w ); setCrops( [ 't', 'b', 'c' ], 'cropRight', sliceR / imgSize.w ); //} // center fill pieces['c'].style.display = props.fill ? '' : 'none'; }, this ); }, getBox: function() { var box = this.parent.getLayer( this.boxZIndex ), s, piece, i, pieceNames = this.pieceNames, len = pieceNames.length; if( !box ) { box = doc.createElement( 'border-image' ); s = box.style; s.position = 'absolute'; this.pieces = {}; for( i = 0; i < len; i++ ) { piece = this.pieces[ pieceNames[i] ] = PIE.Util.createVmlElement( 'rect' ); piece.appendChild( PIE.Util.createVmlElement( 'imagedata' ) ); s = piece.style; s['behavior'] = 'url(#default#VML)'; s.position = "absolute"; s.top = s.left = 0; piece['imagedata'].src = this.styleInfos.borderImageInfo.getProps().src; piece.stroked = false; piece.filled = false; box.appendChild( piece ); } this.parent.addLayer( this.boxZIndex, box ); } return box; }, prepareUpdate: function() { if (this.isActive()) { var me = this, el = me.targetElement, rs = el.runtimeStyle, widths = me.styleInfos.borderImageInfo.getProps().widths; // Force border-style to solid so it doesn't collapse rs.borderStyle = 'solid'; // If widths specified in border-image shorthand, override border-width // NOTE px units needed here as this gets used by the IE9 renderer too if ( widths ) { rs.borderTopWidth = widths['t'].pixels( el ) + 'px'; rs.borderRightWidth = widths['r'].pixels( el ) + 'px'; rs.borderBottomWidth = widths['b'].pixels( el ) + 'px'; rs.borderLeftWidth = widths['l'].pixels( el ) + 'px'; } // Make the border transparent me.hideBorder(); } }, destroy: function() { var me = this, rs = me.targetElement.runtimeStyle; rs.borderStyle = ''; if (me.finalized || !me.styleInfos.borderInfo.isActive()) { rs.borderColor = rs.borderWidth = ''; } PIE.RendererBase.destroy.call( this ); } } ); /** * Renderer for outset box-shadows * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BoxShadowOutsetRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 1, boxName: 'outset-box-shadow', needsUpdate: function() { var si = this.styleInfos; return si.boxShadowInfo.changed() || si.borderRadiusInfo.changed(); }, isActive: function() { var boxShadowInfo = this.styleInfos.boxShadowInfo; return boxShadowInfo.isActive() && boxShadowInfo.getProps().outset[0]; }, draw: function() { var me = this, el = this.targetElement, box = this.getBox(), styleInfos = this.styleInfos, shadowInfos = styleInfos.boxShadowInfo.getProps().outset, radii = styleInfos.borderRadiusInfo.getProps(), len = shadowInfos.length, i = len, j, bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, clipAdjust = PIE.ieVersion === 8 ? 1 : 0, //workaround for IE8 bug where VML leaks out top/left of clip region by 1px corners = [ 'tl', 'tr', 'br', 'bl' ], corner, shadowInfo, shape, fill, ss, xOff, yOff, spread, blur, shrink, color, alpha, path, totalW, totalH, focusX, focusY, isBottom, isRight; function getShadowShape( index, corner, xOff, yOff, color, blur, path ) { var shape = me.getShape( 'shadow' + index + corner, 'fill', box, len - index ), fill = shape.fill; // Position and size shape['coordsize'] = w * 2 + ',' + h * 2; shape['coordorigin'] = '1,1'; // Color and opacity shape['stroked'] = false; shape['filled'] = true; fill.color = color.colorValue( el ); if( blur ) { fill['type'] = 'gradienttitle'; //makes the VML gradient follow the shape's outline - hooray for undocumented features?!?! fill['color2'] = fill.color; fill['opacity'] = 0; } // Path shape.path = path; // This needs to go last for some reason, to prevent rendering at incorrect size ss = shape.style; ss.left = xOff; ss.top = yOff; ss.width = w; ss.height = h; return shape; } while( i-- ) { shadowInfo = shadowInfos[ i ]; xOff = shadowInfo.xOffset.pixels( el ); yOff = shadowInfo.yOffset.pixels( el ); spread = shadowInfo.spread.pixels( el ); blur = shadowInfo.blur.pixels( el ); color = shadowInfo.color; // Shape path shrink = -spread - blur; if( !radii && blur ) { // If blurring, use a non-null border radius info object so that getBoxPath will // round the corners of the expanded shadow shape rather than squaring them off. radii = PIE.BorderRadiusStyleInfo.ALL_ZERO; } path = this.getBoxPath( { t: shrink, r: shrink, b: shrink, l: shrink }, 2, radii ); if( blur ) { totalW = ( spread + blur ) * 2 + w; totalH = ( spread + blur ) * 2 + h; focusX = totalW ? blur * 2 / totalW : 0; focusY = totalH ? blur * 2 / totalH : 0; if( blur - spread > w / 2 || blur - spread > h / 2 ) { // If the blur is larger than half the element's narrowest dimension, we cannot do // this with a single shape gradient, because its focussize would have to be less than // zero which results in ugly artifacts. Instead we create four shapes, each with its // gradient focus past center, and then clip them so each only shows the quadrant // opposite the focus. for( j = 4; j--; ) { corner = corners[j]; isBottom = corner.charAt( 0 ) === 'b'; isRight = corner.charAt( 1 ) === 'r'; shape = getShadowShape( i, corner, xOff, yOff, color, blur, path ); fill = shape.fill; fill['focusposition'] = ( isRight ? 1 - focusX : focusX ) + ',' + ( isBottom ? 1 - focusY : focusY ); fill['focussize'] = '0,0'; // Clip to show only the appropriate quadrant. Add 1px to the top/left clip values // in IE8 to prevent a bug where IE8 displays one pixel outside the clip region. shape.style.clip = 'rect(' + ( ( isBottom ? totalH / 2 : 0 ) + clipAdjust ) + 'px,' + ( isRight ? totalW : totalW / 2 ) + 'px,' + ( isBottom ? totalH : totalH / 2 ) + 'px,' + ( ( isRight ? totalW / 2 : 0 ) + clipAdjust ) + 'px)'; } } else { // TODO delete old quadrant shapes if resizing expands past the barrier shape = getShadowShape( i, '', xOff, yOff, color, blur, path ); fill = shape.fill; fill['focusposition'] = focusX + ',' + focusY; fill['focussize'] = ( 1 - focusX * 2 ) + ',' + ( 1 - focusY * 2 ); } } else { shape = getShadowShape( i, '', xOff, yOff, color, blur, path ); alpha = color.alpha(); if( alpha < 1 ) { // shape.style.filter = 'alpha(opacity=' + ( alpha * 100 ) + ')'; // ss.filter = 'progid:DXImageTransform.Microsoft.BasicImage(opacity=' + ( alpha ) + ')'; shape.fill.opacity = alpha; } } } } } ); /** * Renderer for re-rendering img elements using VML. Kicks in if the img has * a border-radius applied, or if the -pie-png-fix flag is set. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.ImgRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 6, boxName: 'imgEl', needsUpdate: function() { var si = this.styleInfos; return this.targetElement.src !== this._lastSrc || si.borderRadiusInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.borderRadiusInfo.isActive() || si.backgroundInfo.isPngFix(); }, draw: function() { this._lastSrc = src; this.hideActualImg(); var shape = this.getShape( 'img', 'fill', this.getBox() ), fill = shape.fill, bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, borderProps = this.styleInfos.borderInfo.getProps(), borderWidths = borderProps && borderProps.widths, el = this.targetElement, src = el.src, round = Math.round, cs = el.currentStyle, getLength = PIE.getLength, s, zero; // In IE6, the BorderRenderer will have hidden the border by moving the border-width to // the padding; therefore we want to pretend the borders have no width so they aren't doubled // when adding in the current padding value below. if( !borderWidths || PIE.ieVersion < 7 ) { zero = PIE.getLength( '0' ); borderWidths = { 't': zero, 'r': zero, 'b': zero, 'l': zero }; } shape.stroked = false; fill.type = 'frame'; fill.src = src; fill.position = (w ? 0.5 / w : 0) + ',' + (h ? 0.5 / h : 0); shape.coordsize = w * 2 + ',' + h * 2; shape.coordorigin = '1,1'; shape.path = this.getBoxPath( { t: round( borderWidths['t'].pixels( el ) + getLength( cs.paddingTop ).pixels( el ) ), r: round( borderWidths['r'].pixels( el ) + getLength( cs.paddingRight ).pixels( el ) ), b: round( borderWidths['b'].pixels( el ) + getLength( cs.paddingBottom ).pixels( el ) ), l: round( borderWidths['l'].pixels( el ) + getLength( cs.paddingLeft ).pixels( el ) ) }, 2 ); s = shape.style; s.width = w; s.height = h; }, hideActualImg: function() { this.targetElement.runtimeStyle.filter = 'alpha(opacity=0)'; }, destroy: function() { PIE.RendererBase.destroy.call( this ); this.targetElement.runtimeStyle.filter = ''; } } ); /** * Root renderer for IE9; manages the rendering layers in the element's background * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects */ PIE.IE9RootRenderer = PIE.RendererBase.newRenderer( { updatePos: PIE.emptyFn, updateSize: PIE.emptyFn, updateVisibility: PIE.emptyFn, updateProps: PIE.emptyFn, outerCommasRE: /^,+|,+$/g, innerCommasRE: /,+/g, setBackgroundLayer: function(zIndex, bg) { var me = this, bgLayers = me._bgLayers || ( me._bgLayers = [] ), undef; bgLayers[zIndex] = bg || undef; }, finishUpdate: function() { var me = this, bgLayers = me._bgLayers, bg; if( bgLayers && ( bg = bgLayers.join( ',' ).replace( me.outerCommasRE, '' ).replace( me.innerCommasRE, ',' ) ) !== me._lastBg ) { me._lastBg = me.targetElement.runtimeStyle.background = bg; } }, destroy: function() { this.targetElement.runtimeStyle.background = ''; delete this._bgLayers; } } ); /** * Renderer for element backgrounds, specific for IE9. Only handles translating CSS3 gradients * to an equivalent SVG data URI. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects */ PIE.IE9BackgroundRenderer = PIE.RendererBase.newRenderer( { bgLayerZIndex: 1, needsUpdate: function() { var si = this.styleInfos; return si.backgroundInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.backgroundInfo.isActive() || si.borderImageInfo.isActive(); }, draw: function() { var me = this, props = me.styleInfos.backgroundInfo.getProps(), bg, images, i = 0, img, bgAreaSize, bgSize; if ( props ) { bg = []; images = props.bgImages; if ( images ) { while( img = images[ i++ ] ) { if (img.imgType === 'linear-gradient' ) { bgAreaSize = me.getBgAreaSize( img.bgOrigin ); bgSize = ( img.bgSize || PIE.BgSize.DEFAULT ).pixels( me.targetElement, bgAreaSize.w, bgAreaSize.h, bgAreaSize.w, bgAreaSize.h ), bg.push( 'url(data:image/svg+xml,' + escape( me.getGradientSvg( img, bgSize.w, bgSize.h ) ) + ') ' + me.bgPositionToString( img.bgPosition ) + ' / ' + bgSize.w + 'px ' + bgSize.h + 'px ' + ( img.bgAttachment || '' ) + ' ' + ( img.bgOrigin || '' ) + ' ' + ( img.bgClip || '' ) ); } else { bg.push( img.origString ); } } } if ( props.color ) { bg.push( props.color.val ); } me.parent.setBackgroundLayer(me.bgLayerZIndex, bg.join(',')); } }, bgPositionToString: function( bgPosition ) { return bgPosition ? bgPosition.tokens.map(function(token) { return token.tokenValue; }).join(' ') : '0 0'; }, getBgAreaSize: function( bgOrigin ) { var me = this, el = me.targetElement, bounds = me.boundsInfo.getBounds(), elW = bounds.w, elH = bounds.h, w = elW, h = elH, borders, getLength, cs; if( bgOrigin !== 'border-box' ) { borders = me.styleInfos.borderInfo.getProps(); if( borders && ( borders = borders.widths ) ) { w -= borders[ 'l' ].pixels( el ) + borders[ 'l' ].pixels( el ); h -= borders[ 't' ].pixels( el ) + borders[ 'b' ].pixels( el ); } } if ( bgOrigin === 'content-box' ) { getLength = PIE.getLength; cs = el.currentStyle; w -= getLength( cs.paddingLeft ).pixels( el ) + getLength( cs.paddingRight ).pixels( el ); h -= getLength( cs.paddingTop ).pixels( el ) + getLength( cs.paddingBottom ).pixels( el ); } return { w: w, h: h }; }, getGradientSvg: function( info, bgWidth, bgHeight ) { var el = this.targetElement, stopsInfo = info.stops, stopCount = stopsInfo.length, metrics = PIE.GradientUtil.getGradientMetrics( el, bgWidth, bgHeight, info ), startX = metrics.startX, startY = metrics.startY, endX = metrics.endX, endY = metrics.endY, lineLength = metrics.lineLength, stopPx, i, j, before, after, svg; // Find the pixel offsets along the CSS3 gradient-line for each stop. stopPx = []; for( i = 0; i < stopCount; i++ ) { stopPx.push( stopsInfo[i].offset ? stopsInfo[i].offset.pixels( el, lineLength ) : i === 0 ? 0 : i === stopCount - 1 ? lineLength : null ); } // Fill in gaps with evenly-spaced offsets for( i = 1; i < stopCount; i++ ) { if( stopPx[ i ] === null ) { before = stopPx[ i - 1 ]; j = i; do { after = stopPx[ ++j ]; } while( after === null ); stopPx[ i ] = before + ( after - before ) / ( j - i + 1 ); } } svg = [ '<svg width="' + bgWidth + '" height="' + bgHeight + '" xmlns="http://www.w3.org/2000/svg">' + '<defs>' + '<linearGradient id="g" gradientUnits="userSpaceOnUse"' + ' x1="' + ( startX / bgWidth * 100 ) + '%" y1="' + ( startY / bgHeight * 100 ) + '%" x2="' + ( endX / bgWidth * 100 ) + '%" y2="' + ( endY / bgHeight * 100 ) + '%">' ]; // Convert to percentage along the SVG gradient line and add to the stops list for( i = 0; i < stopCount; i++ ) { svg.push( '<stop offset="' + ( stopPx[ i ] / lineLength ) + '" stop-color="' + stopsInfo[i].color.colorValue( el ) + '" stop-opacity="' + stopsInfo[i].color.alpha() + '"/>' ); } svg.push( '</linearGradient>' + '</defs>' + '<rect width="100%" height="100%" fill="url(#g)"/>' + '</svg>' ); return svg.join( '' ); }, destroy: function() { this.parent.setBackgroundLayer( this.bgLayerZIndex ); } } ); /** * Renderer for border-image * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.IE9BorderImageRenderer = PIE.RendererBase.newRenderer( { REPEAT: 'repeat', STRETCH: 'stretch', ROUND: 'round', bgLayerZIndex: 0, needsUpdate: function() { return this.styleInfos.borderImageInfo.changed(); }, isActive: function() { return this.styleInfos.borderImageInfo.isActive(); }, draw: function() { var me = this, props = me.styleInfos.borderImageInfo.getProps(), borderProps = me.styleInfos.borderInfo.getProps(), bounds = me.boundsInfo.getBounds(), repeat = props.repeat, repeatH = repeat.h, repeatV = repeat.v, el = me.targetElement, isAsync = 0; PIE.Util.withImageSize( props.src, function( imgSize ) { var elW = bounds.w, elH = bounds.h, imgW = imgSize.w, imgH = imgSize.h, // The image cannot be referenced as a URL directly in the SVG because IE9 throws a strange // security exception (perhaps due to cross-origin policy within data URIs?) Therefore we // work around this by converting the image data into a data URI itself using a transient // canvas. This unfortunately requires the border-image src to be within the same domain, // which isn't a limitation in true border-image, so we need to try and find a better fix. imgSrc = me.imageToDataURI( props.src, imgW, imgH ), REPEAT = me.REPEAT, STRETCH = me.STRETCH, ROUND = me.ROUND, ceil = Math.ceil, zero = PIE.getLength( '0' ), widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ), widthT = widths['t'].pixels( el ), widthR = widths['r'].pixels( el ), widthB = widths['b'].pixels( el ), widthL = widths['l'].pixels( el ), slices = props.slice, sliceT = slices['t'].pixels( el ), sliceR = slices['r'].pixels( el ), sliceB = slices['b'].pixels( el ), sliceL = slices['l'].pixels( el ), centerW = elW - widthL - widthR, middleH = elH - widthT - widthB, imgCenterW = imgW - sliceL - sliceR, imgMiddleH = imgH - sliceT - sliceB, // Determine the size of each tile - 'round' is handled below tileSizeT = repeatH === STRETCH ? centerW : imgCenterW * widthT / sliceT, tileSizeR = repeatV === STRETCH ? middleH : imgMiddleH * widthR / sliceR, tileSizeB = repeatH === STRETCH ? centerW : imgCenterW * widthB / sliceB, tileSizeL = repeatV === STRETCH ? middleH : imgMiddleH * widthL / sliceL, svg, patterns = [], rects = [], i = 0; // For 'round', subtract from each tile's size enough so that they fill the space a whole number of times if (repeatH === ROUND) { tileSizeT -= (tileSizeT - (centerW % tileSizeT || tileSizeT)) / ceil(centerW / tileSizeT); tileSizeB -= (tileSizeB - (centerW % tileSizeB || tileSizeB)) / ceil(centerW / tileSizeB); } if (repeatV === ROUND) { tileSizeR -= (tileSizeR - (middleH % tileSizeR || tileSizeR)) / ceil(middleH / tileSizeR); tileSizeL -= (tileSizeL - (middleH % tileSizeL || tileSizeL)) / ceil(middleH / tileSizeL); } // Build the SVG for the border-image rendering. Add each piece as a pattern, which is then stretched // or repeated as the fill of a rect of appropriate size. svg = [ '<svg width="' + elW + '" height="' + elH + '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">' ]; function addImage( x, y, w, h, cropX, cropY, cropW, cropH, tileW, tileH ) { patterns.push( '<pattern patternUnits="userSpaceOnUse" id="pattern' + i + '" ' + 'x="' + (repeatH === REPEAT ? x + w / 2 - tileW / 2 : x) + '" ' + 'y="' + (repeatV === REPEAT ? y + h / 2 - tileH / 2 : y) + '" ' + 'width="' + tileW + '" height="' + tileH + '">' + '<svg width="' + tileW + '" height="' + tileH + '" viewBox="' + cropX + ' ' + cropY + ' ' + cropW + ' ' + cropH + '" preserveAspectRatio="none">' + '<image xlink:href="' + imgSrc + '" x="0" y="0" width="' + imgW + '" height="' + imgH + '" />' + '</svg>' + '</pattern>' ); rects.push( '<rect x="' + x + '" y="' + y + '" width="' + w + '" height="' + h + '" fill="url(#pattern' + i + ')" />' ); i++; } addImage( 0, 0, widthL, widthT, 0, 0, sliceL, sliceT, widthL, widthT ); // top left addImage( widthL, 0, centerW, widthT, sliceL, 0, imgCenterW, sliceT, tileSizeT, widthT ); // top center addImage( elW - widthR, 0, widthR, widthT, imgW - sliceR, 0, sliceR, sliceT, widthR, widthT ); // top right addImage( 0, widthT, widthL, middleH, 0, sliceT, sliceL, imgMiddleH, widthL, tileSizeL ); // middle left if ( props.fill ) { // center fill addImage( widthL, widthT, centerW, middleH, sliceL, sliceT, imgCenterW, imgMiddleH, tileSizeT || tileSizeB || imgCenterW, tileSizeL || tileSizeR || imgMiddleH ); } addImage( elW - widthR, widthT, widthR, middleH, imgW - sliceR, sliceT, sliceR, imgMiddleH, widthR, tileSizeR ); // middle right addImage( 0, elH - widthB, widthL, widthB, 0, imgH - sliceB, sliceL, sliceB, widthL, widthB ); // bottom left addImage( widthL, elH - widthB, centerW, widthB, sliceL, imgH - sliceB, imgCenterW, sliceB, tileSizeB, widthB ); // bottom center addImage( elW - widthR, elH - widthB, widthR, widthB, imgW - sliceR, imgH - sliceB, sliceR, sliceB, widthR, widthB ); // bottom right svg.push( '<defs>' + patterns.join('\n') + '</defs>' + rects.join('\n') + '</svg>' ); me.parent.setBackgroundLayer( me.bgLayerZIndex, 'url(data:image/svg+xml,' + escape( svg.join( '' ) ) + ') no-repeat border-box border-box' ); // If the border-image's src wasn't immediately available, the SVG for its background layer // will have been created asynchronously after the main element's update has finished; we'll // therefore need to force the root renderer to sync to the final background once finished. if( isAsync ) { me.parent.finishUpdate(); } }, me ); isAsync = 1; }, /** * Convert a given image to a data URI */ imageToDataURI: (function() { var uris = {}; return function( src, width, height ) { var uri = uris[ src ], image, canvas; if ( !uri ) { image = new Image(); canvas = doc.createElement( 'canvas' ); image.src = src; canvas.width = width; canvas.height = height; canvas.getContext( '2d' ).drawImage( image, 0, 0 ); uri = uris[ src ] = canvas.toDataURL(); } return uri; } })(), prepareUpdate: PIE.BorderImageRenderer.prototype.prepareUpdate, destroy: function() { var me = this, rs = me.targetElement.runtimeStyle; me.parent.setBackgroundLayer( me.bgLayerZIndex ); rs.borderColor = rs.borderStyle = rs.borderWidth = ''; } } ); PIE.Element = (function() { var wrappers = {}, lazyInitCssProp = PIE.CSS_PREFIX + 'lazy-init', pollCssProp = PIE.CSS_PREFIX + 'poll', trackActiveCssProp = PIE.CSS_PREFIX + 'track-active', trackHoverCssProp = PIE.CSS_PREFIX + 'track-hover', hoverClass = PIE.CLASS_PREFIX + 'hover', activeClass = PIE.CLASS_PREFIX + 'active', focusClass = PIE.CLASS_PREFIX + 'focus', firstChildClass = PIE.CLASS_PREFIX + 'first-child', ignorePropertyNames = { 'background':1, 'bgColor':1, 'display': 1 }, classNameRegExes = {}, dummyArray = []; function addClass( el, className ) { el.className += ' ' + className; } function removeClass( el, className ) { var re = classNameRegExes[ className ] || ( classNameRegExes[ className ] = new RegExp( '\\b' + className + '\\b', 'g' ) ); el.className = el.className.replace( re, '' ); } function delayAddClass( el, className /*, className2*/ ) { var classes = dummyArray.slice.call( arguments, 1 ), i = classes.length; setTimeout( function() { if( el ) { while( i-- ) { addClass( el, classes[ i ] ); } } }, 0 ); } function delayRemoveClass( el, className /*, className2*/ ) { var classes = dummyArray.slice.call( arguments, 1 ), i = classes.length; setTimeout( function() { if( el ) { while( i-- ) { removeClass( el, classes[ i ] ); } } }, 0 ); } function Element( el ) { var renderers, rootRenderer, boundsInfo = new PIE.BoundsInfo( el ), styleInfos, styleInfosArr, initializing, initialized, eventsAttached, eventListeners = [], delayed, destroyed, poll; /** * Initialize PIE for this element. */ function init() { if( !initialized ) { var docEl, bounds, ieDocMode = PIE.ieDocMode, cs = el.currentStyle, lazy = cs.getAttribute( lazyInitCssProp ) === 'true', trackActive = cs.getAttribute( trackActiveCssProp ) !== 'false', trackHover = cs.getAttribute( trackHoverCssProp ) !== 'false', childRenderers; // Polling for size/position changes: default to on in IE8, off otherwise, overridable by -pie-poll poll = cs.getAttribute( pollCssProp ); poll = ieDocMode > 7 ? poll !== 'false' : poll === 'true'; // Force layout so move/resize events will fire. Set this as soon as possible to avoid layout changes // after load, but make sure it only gets called the first time through to avoid recursive calls to init(). if( !initializing ) { initializing = 1; el.runtimeStyle.zoom = 1; initFirstChildPseudoClass(); } boundsInfo.lock(); // If the -pie-lazy-init:true flag is set, check if the element is outside the viewport and if so, delay initialization if( lazy && ( bounds = boundsInfo.getBounds() ) && ( docEl = doc.documentElement || doc.body ) && ( bounds.y > docEl.clientHeight || bounds.x > docEl.clientWidth || bounds.y + bounds.h < 0 || bounds.x + bounds.w < 0 ) ) { if( !delayed ) { delayed = 1; PIE.OnScroll.observe( init ); } } else { initialized = 1; delayed = initializing = 0; PIE.OnScroll.unobserve( init ); // Create the style infos and renderers if ( ieDocMode === 9 ) { styleInfos = { backgroundInfo: new PIE.BackgroundStyleInfo( el ), borderImageInfo: new PIE.BorderImageStyleInfo( el ), borderInfo: new PIE.BorderStyleInfo( el ) }; styleInfosArr = [ styleInfos.backgroundInfo, styleInfos.borderImageInfo ]; rootRenderer = new PIE.IE9RootRenderer( el, boundsInfo, styleInfos ); childRenderers = [ new PIE.IE9BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.IE9BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer ) ]; } else { styleInfos = { backgroundInfo: new PIE.BackgroundStyleInfo( el ), borderInfo: new PIE.BorderStyleInfo( el ), borderImageInfo: new PIE.BorderImageStyleInfo( el ), borderRadiusInfo: new PIE.BorderRadiusStyleInfo( el ), boxShadowInfo: new PIE.BoxShadowStyleInfo( el ), visibilityInfo: new PIE.VisibilityStyleInfo( el ) }; styleInfosArr = [ styleInfos.backgroundInfo, styleInfos.borderInfo, styleInfos.borderImageInfo, styleInfos.borderRadiusInfo, styleInfos.boxShadowInfo, styleInfos.visibilityInfo ]; rootRenderer = new PIE.RootRenderer( el, boundsInfo, styleInfos ); childRenderers = [ new PIE.BoxShadowOutsetRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ), //new PIE.BoxShadowInsetRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.BorderRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer ) ]; if( el.tagName === 'IMG' ) { childRenderers.push( new PIE.ImgRenderer( el, boundsInfo, styleInfos, rootRenderer ) ); } rootRenderer.childRenderers = childRenderers; // circular reference, can't pass in constructor; TODO is there a cleaner way? } renderers = [ rootRenderer ].concat( childRenderers ); // Add property change listeners to ancestors if requested initAncestorEventListeners(); // Add to list of polled elements in IE8 if( poll ) { PIE.Heartbeat.observe( update ); PIE.Heartbeat.run(); } // Trigger rendering update( 1 ); } if( !eventsAttached ) { eventsAttached = 1; if( ieDocMode < 9 ) { addListener( el, 'onmove', handleMoveOrResize ); } addListener( el, 'onresize', handleMoveOrResize ); addListener( el, 'onpropertychange', propChanged ); if( trackHover ) { addListener( el, 'onmouseenter', mouseEntered ); } if( trackHover || trackActive ) { addListener( el, 'onmouseleave', mouseLeft ); } if( trackActive ) { addListener( el, 'onmousedown', mousePressed ); } if( el.tagName in PIE.focusableElements ) { addListener( el, 'onfocus', focused ); addListener( el, 'onblur', blurred ); } PIE.OnResize.observe( handleMoveOrResize ); PIE.OnUnload.observe( removeEventListeners ); } boundsInfo.unlock(); } } /** * Event handler for onmove and onresize events. Invokes update() only if the element's * bounds have previously been calculated, to prevent multiple runs during page load when * the element has no initial CSS3 properties. */ function handleMoveOrResize() { if( boundsInfo && boundsInfo.hasBeenQueried() ) { update(); } } /** * Update position and/or size as necessary. Both move and resize events call * this rather than the updatePos/Size functions because sometimes, particularly * during page load, one will fire but the other won't. */ function update( force ) { if( !destroyed ) { if( initialized ) { var i, len = renderers.length; lockAll(); for( i = 0; i < len; i++ ) { renderers[i].prepareUpdate(); } if( force || boundsInfo.positionChanged() ) { /* TODO just using getBoundingClientRect (used internally by BoundsInfo) for detecting position changes may not always be accurate; it's possible that an element will actually move relative to its positioning parent, but its position relative to the viewport will stay the same. Need to come up with a better way to track movement. The most accurate would be the same logic used in RootRenderer.updatePos() but that is a more expensive operation since it does some DOM walking, and we want this check to be as fast as possible. */ for( i = 0; i < len; i++ ) { renderers[i].updatePos(); } } if( force || boundsInfo.sizeChanged() ) { for( i = 0; i < len; i++ ) { renderers[i].updateSize(); } } rootRenderer.finishUpdate(); unlockAll(); } else if( !initializing ) { init(); } } } /** * Handle property changes to trigger update when appropriate. */ function propChanged() { var i, len = renderers.length, renderer, e = event; // Some elements like <table> fire onpropertychange events for old-school background properties // ('background', 'bgColor') when runtimeStyle background properties are changed, which // results in an infinite loop; therefore we filter out those property names. Also, 'display' // is ignored because size calculations don't work correctly immediately when its onpropertychange // event fires, and because it will trigger an onresize event anyway. if( !destroyed && !( e && e.propertyName in ignorePropertyNames ) ) { if( initialized ) { lockAll(); for( i = 0; i < len; i++ ) { renderers[i].prepareUpdate(); } for( i = 0; i < len; i++ ) { renderer = renderers[i]; // Make sure position is synced if the element hasn't already been rendered. // TODO this feels sloppy - look into merging propChanged and update functions if( !renderer.isPositioned ) { renderer.updatePos(); } if( renderer.needsUpdate() ) { renderer.updateProps(); } } rootRenderer.finishUpdate(); unlockAll(); } else if( !initializing ) { init(); } } } /** * Handle mouseenter events. Adds a custom class to the element to allow IE6 to add * hover styles to non-link elements, and to trigger a propertychange update. */ function mouseEntered() { //must delay this because the mouseenter event fires before the :hover styles are added. delayAddClass( el, hoverClass ); } /** * Handle mouseleave events */ function mouseLeft() { //must delay this because the mouseleave event fires before the :hover styles are removed. delayRemoveClass( el, hoverClass, activeClass ); } /** * Handle mousedown events. Adds a custom class to the element to allow IE6 to add * active styles to non-link elements, and to trigger a propertychange update. */ function mousePressed() { //must delay this because the mousedown event fires before the :active styles are added. delayAddClass( el, activeClass ); // listen for mouseups on the document; can't just be on the element because the user might // have dragged out of the element while the mouse button was held down PIE.OnMouseup.observe( mouseReleased ); } /** * Handle mouseup events */ function mouseReleased() { //must delay this because the mouseup event fires before the :active styles are removed. delayRemoveClass( el, activeClass ); PIE.OnMouseup.unobserve( mouseReleased ); } /** * Handle focus events. Adds a custom class to the element to trigger a propertychange update. */ function focused() { //must delay this because the focus event fires before the :focus styles are added. delayAddClass( el, focusClass ); } /** * Handle blur events */ function blurred() { //must delay this because the blur event fires before the :focus styles are removed. delayRemoveClass( el, focusClass ); } /** * Handle property changes on ancestors of the element; see initAncestorEventListeners() * which adds these listeners as requested with the -pie-watch-ancestors CSS property. */ function ancestorPropChanged() { var name = event.propertyName; if( name === 'className' || name === 'id' ) { propChanged(); } } function lockAll() { boundsInfo.lock(); for( var i = styleInfosArr.length; i--; ) { styleInfosArr[i].lock(); } } function unlockAll() { for( var i = styleInfosArr.length; i--; ) { styleInfosArr[i].unlock(); } boundsInfo.unlock(); } function addListener( targetEl, type, handler ) { targetEl.attachEvent( type, handler ); eventListeners.push( [ targetEl, type, handler ] ); } /** * Remove all event listeners from the element and any monitored ancestors. */ function removeEventListeners() { if (eventsAttached) { var i = eventListeners.length, listener; while( i-- ) { listener = eventListeners[ i ]; listener[ 0 ].detachEvent( listener[ 1 ], listener[ 2 ] ); } PIE.OnUnload.unobserve( removeEventListeners ); eventsAttached = 0; eventListeners = []; } } /** * Clean everything up when the behavior is removed from the element, or the element * is manually destroyed. */ function destroy() { if( !destroyed ) { var i, len; removeEventListeners(); destroyed = 1; // destroy any active renderers if( renderers ) { for( i = 0, len = renderers.length; i < len; i++ ) { renderers[i].finalized = 1; renderers[i].destroy(); } } // Remove from list of polled elements in IE8 if( poll ) { PIE.Heartbeat.unobserve( update ); } // Stop onresize listening PIE.OnResize.unobserve( update ); // Kill references renderers = boundsInfo = styleInfos = styleInfosArr = el = null; } } /** * If requested via the custom -pie-watch-ancestors CSS property, add onpropertychange and * other event listeners to ancestor(s) of the element so we can pick up style changes * based on CSS rules using descendant selectors. */ function initAncestorEventListeners() { var watch = el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'watch-ancestors' ), i, a; if( watch ) { watch = parseInt( watch, 10 ); i = 0; a = el.parentNode; while( a && ( watch === 'NaN' || i++ < watch ) ) { addListener( a, 'onpropertychange', ancestorPropChanged ); addListener( a, 'onmouseenter', mouseEntered ); addListener( a, 'onmouseleave', mouseLeft ); addListener( a, 'onmousedown', mousePressed ); if( a.tagName in PIE.focusableElements ) { addListener( a, 'onfocus', focused ); addListener( a, 'onblur', blurred ); } a = a.parentNode; } } } /** * If the target element is a first child, add a pie_first-child class to it. This allows using * the added class as a workaround for the fact that PIE's rendering element breaks the :first-child * pseudo-class selector. */ function initFirstChildPseudoClass() { var tmpEl = el, isFirst = 1; while( tmpEl = tmpEl.previousSibling ) { if( tmpEl.nodeType === 1 ) { isFirst = 0; break; } } if( isFirst ) { addClass( el, firstChildClass ); } } // These methods are all already bound to this instance so there's no need to wrap them // in a closure to maintain the 'this' scope object when calling them. this.init = init; this.update = update; this.destroy = destroy; this.el = el; } Element.getInstance = function( el ) { var id = PIE.Util.getUID( el ); return wrappers[ id ] || ( wrappers[ id ] = new Element( el ) ); }; Element.destroy = function( el ) { var id = PIE.Util.getUID( el ), wrapper = wrappers[ id ]; if( wrapper ) { wrapper.destroy(); delete wrappers[ id ]; } }; Element.destroyAll = function() { var els = [], wrapper; if( wrappers ) { for( var w in wrappers ) { if( wrappers.hasOwnProperty( w ) ) { wrapper = wrappers[ w ]; els.push( wrapper.el ); wrapper.destroy(); } } wrappers = {}; } return els; }; return Element; })(); /* * This file exposes the public API for invoking PIE. */ /** * @property supportsVML * True if the current IE browser environment has a functioning VML engine. Should be true * in most IEs, but in rare cases may be false. If false, PIE will exit immediately when * attached to an element; this property may be used for debugging or by external scripts * to perform some special action when VML support is absent. * @type {boolean} */ PIE[ 'supportsVML' ] = PIE.supportsVML; /** * Programatically attach PIE to a single element. * @param {Element} el */ PIE[ 'attach' ] = function( el ) { if (PIE.ieDocMode < 10 && PIE.supportsVML) { PIE.Element.getInstance( el ).init(); } }; /** * Programatically detach PIE from a single element. * @param {Element} el */ PIE[ 'detach' ] = function( el ) { PIE.Element.destroy( el ); }; } // if( !PIE ) })();
JavaScript
a = document.getElementsByTagName('LABEL'); if(a) { for(i=0; i < a.length; i++) { _str = a.item(i).innerHTML.replace(/:\)\)/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/21.gif' alt='' class='smiley'/>"); _str = _str.replace(/:d/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/4.gif' alt='' class='smiley'/>"); _str = _str.replace(/\;\)/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/3.gif' alt='' class='smiley'/>"); _str = _str.replace(/:p/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/10.gif' alt='' class='smiley'/>"); _str = _str.replace(/:\(\(/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/20.gif' alt='' class='smiley'/>"); _str = _str.replace(/:\)/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/1.gif' alt='' class='smiley'/>"); _str = _str.replace(/:\(/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/2.gif' alt='' class='smiley'/>"); _str = _str.replace(/:\|/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/4.gif' alt='' class='smiley'/>"); _str = _str.replace(/\=\)\)/ig,"<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/24.gif' alt='' class='smiley'/>") a.item(i).innerHTML = _str; } } a = document.getElementById('comments'); if(a) { b = a.getElementsByTagName("DD"); for(i=0; i < b.length; i++) { if (b.item(i).getAttribute('CLASS') == 'comment-body' , 'blog-author-comment') { _str = b.item(i).innerHTML.replace(/:\)\)/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/21.gif' alt='' class='smiley'/>"); _str = _str.replace(/:\)\]/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/100.gif' alt='' class='smiley'/>"); _str = _str.replace(/;\)\)/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/71.gif' alt='' class='smiley'/>"); _str = _str.replace(/;\;\)/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/5.gif' alt='' class='smiley'/>"); _str = _str.replace(/:d/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/4.gif' alt='' class='smiley'/>"); _str = _str.replace(/\;\)/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/3.gif' alt='' class='smiley'/>"); _str = _str.replace(/:p/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/10.gif' alt='' class='smiley'/>"); _str = _str.replace(/:\(\(/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/20.gif' alt='' class='smiley'/>"); _str = _str.replace(/:\)/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/1.gif' alt='' class='smiley'/>"); _str = _str.replace(/:\(/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/2.gif' alt='' class='smiley'/>"); _str = _str.replace(/:x/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/8.gif' alt='' class='smiley'/>"); _str = _str.replace(/=\(\(/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/12.gif' alt='' class='smiley'/>"); _str = _str.replace(/:\-\o/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/13.gif' alt='' class='smiley'/>"); _str = _str.replace(/:-\//gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/7.gif' alt='' class='smiley'/>"); _str = _str.replace(/:-\*/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/11.gif' alt='' class='smiley'/>"); _str = _str.replace(/:\|/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/22.gif' alt='' class='smiley'/>"); _str = _str.replace(/8-\}/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/35.gif' alt='' class='smiley'/>"); _str = _str.replace(/~x\(/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/102.gif' alt='' class='smiley'/>"); _str = _str.replace(/:-t/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/104.gif' alt='' class='smiley'/>"); _str = _str.replace(/b-\(/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/66.gif' alt='' class='smiley'/>"); _str = _str.replace(/:-\L/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/62.gif' alt='' class='smiley'/>"); _str = _str.replace(/x\(/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/14.gif' alt='' class='smiley'/>"); _str = _str.replace(/\=\)\)/ig,"<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/24.gif' alt='' class='smiley'/>") b.item(i).innerHTML = _str; } } } a = document.getElementById('comments'); if(a) { c = a.getElementsByTagName("DD"); for(i=0; i < c.length; i++) { if (c.item(i).getAttribute('CLASS') == 'comment-body-author' , 'blog-author-comment') { _str = c.item(i).innerHTML.replace(/:\)\)/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/21.gif' alt='' class='smiley'/>"); _str = _str.replace(/:\)\]/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/100.gif' alt='' class='smiley'/>"); _str = _str.replace(/;\)\)/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/71.gif' alt='' class='smiley'/>"); _str = _str.replace(/;\;\)/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/5.gif' alt='' class='smiley'/>"); _str = _str.replace(/:d/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/4.gif' alt='' class='smiley'/>"); _str = _str.replace(/\;\)/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/3.gif' alt='' class='smiley'/>"); _str = _str.replace(/:p/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/10.gif' alt='' class='smiley'/>"); _str = _str.replace(/:\(\(/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/20.gif' alt='' class='smiley'/>"); _str = _str.replace(/:\)/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/1.gif' alt='' class='smiley'/>"); _str = _str.replace(/:\(/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/2.gif' alt='' class='smiley'/>"); _str = _str.replace(/:x/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/8.gif' alt='' class='smiley'/>"); _str = _str.replace(/=\(\(/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/12.gif' alt='' class='smiley'/>"); _str = _str.replace(/:\-\o/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/13.gif' alt='' class='smiley'/>"); _str = _str.replace(/:-\//gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/7.gif' alt='' class='smiley'/>"); _str = _str.replace(/:-\*/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/11.gif' alt='' class='smiley'/>"); _str = _str.replace(/:\|/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/22.gif' alt='' class='smiley'/>"); _str = _str.replace(/8-\}/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/35.gif' alt='' class='smiley'/>"); _str = _str.replace(/~x\(/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/102.gif' alt='' class='smiley'/>"); _str = _str.replace(/:-t/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/104.gif' alt='' class='smiley'/>"); _str = _str.replace(/b-\(/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/66.gif' alt='' class='smiley'/>"); _str = _str.replace(/:-\L/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/62.gif' alt='' class='smiley'/>"); _str = _str.replace(/x\(/gi, "<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/14.gif' alt='' class='smiley'/>"); _str = _str.replace(/\=\)\)/ig,"<img src='https://2lkasir.googlecode.com/svn/trunk/onion-head/24.gif' alt='' class='smiley'/>") c.item(i).innerHTML = _str; } } }
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Shows the desired contents of the tape. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.Target'); goog.require('turing.anim'); goog.require('turing.sprites'); goog.require('turing.sprites.numberplate'); goog.require('turing.util'); /** * The left offset of the target number plate. * @type {string} * @const */ turing.NUMBER_PLATE_LEFT = '280px'; /** * The top offset of the target number plate. * @type {string} * @const */ turing.NUMBER_PLATE_TOP = '21px'; /** * The top offset of the track from the tape to the target number plate. * @type {string} * @const */ turing.TRACK_TO_NUMBER_PLATE_TOP = '40px'; /** * The left offset of the track from the tape to the target number plate. * @type {string} * @const */ turing.TRACK_TO_NUMBER_PLATE_LEFT = '383px'; /** * The top offset of the equal indicator. * @type {string} * @const */ turing.EQUAL_INDICATOR_TOP = '25px'; /** * The left offset of the equal indicator. * @type {string} * @const */ turing.EQUAL_INDICATOR_LEFT = '411px'; /** * The amount of time it takes to blink the equal sign once. * @type {number} * @const */ turing.EQUAL_BLINK_DURATION = 400; /** * A plate showing the desired state of the tape. * @constructor */ turing.Target = function() { /** * Div for the plate with numbers the user is trying to match. * @type {Element} * @private */ this.numberPlate_; /** * The current value of the target number plate. * @type {string} * @private */ this.curValue_ = ''; /** * A track segment leading from the tape to the target number plate. * @type {Element} * @private */ this.trackToNumberPlate_; /** * The equivalence indicator shown on the track segment that leads to the * number plate. * @type {Element} * @private */ this.equalIndicator_; /** * A click event listener bound on the equals indicator. * @type {Function} * @private */ this.equalClickListener_; /** * A callback called when the equals indicator is clicked. * @type {?function()} * @private */ this.equalClickCallback_; }; /** * Creates dom nodes. */ turing.Target.prototype.create = function() { this.numberPlate_ = turing.sprites.getDiv('target-blank'); this.numberPlate_.style.top = turing.NUMBER_PLATE_TOP; this.numberPlate_.style.zIndex = 400; this.numberPlate_.style.left = turing.NUMBER_PLATE_LEFT; this.trackToNumberPlate_ = turing.sprites.getDiv('track'); var trackToNumberPlateStyle = this.trackToNumberPlate_.style; trackToNumberPlateStyle.top = turing.TRACK_TO_NUMBER_PLATE_TOP; trackToNumberPlateStyle.left = turing.TRACK_TO_NUMBER_PLATE_LEFT; // We're repurposing the track icon but only showing a small part of it. trackToNumberPlateStyle.height = '9px'; trackToNumberPlateStyle.width = '40px'; trackToNumberPlateStyle.zIndex = 398; // Behind tape and number plate. this.equalIndicator_ = turing.sprites.getDiv('eq-dim'); this.equalIndicator_.style.top = turing.EQUAL_INDICATOR_TOP; this.equalIndicator_.style.left = turing.EQUAL_INDICATOR_LEFT; this.equalIndicator_.style.zIndex = 399; // Above trackToNumberPlate. this.equalClickListener_ = goog.bind(this.onClickEqual_, this); turing.util.listen(this.equalIndicator_, 'click', this.equalClickListener_); }; /** * Cleans up dom nodes. */ turing.Target.prototype.destroy = function() { turing.util.removeNode(this.numberPlate_); this.numberPlate_ = null; turing.util.removeNode(this.trackToNumberPlate_); this.trackToNumberPlate_ = null; turing.util.unlisten(this.equalIndicator_, 'click', this.equalClickListener_); this.equalClickListener_ = null; turing.util.removeNode(this.equalIndicator_); this.equalIndicator_ = null; this.curValue_ = ''; }; /** * Attaches dom nodes. * @param {Element} elem Where to attach. */ turing.Target.prototype.attachTo = function(elem) { elem.appendChild(this.numberPlate_); elem.appendChild(this.trackToNumberPlate_); elem.appendChild(this.equalIndicator_); }; /** * Sets the value on the target number plate. * @param {string} str The desired bit string, or the empty string for a blank * target. * @param {number} duration The amount of time to animate for. */ turing.Target.prototype.setValue = function(str, duration) { if (!str && !this.curValue_) { // Don't switch sheets! It causes flashing! So just pick the first // blank target in the deferred sheet. this.numberPlate_.style.background = turing.sprites.getBackground( 'scroll-01011-18'); return; } var backgrounds; if (!str) { // We're switching to blank so animate the current value scrolling away. backgrounds = turing.sprites.numberplate.getScrollingTarget( this.curValue_, false); } else { // We're switching to the given string, so animate it scrolling in. backgrounds = turing.sprites.numberplate.getScrollingTarget(str, true); } if (!duration) { this.numberPlate_.style.background = backgrounds[backgrounds.length - 1]; } else { turing.anim.animateThroughBackgrounds( this.numberPlate_, backgrounds, duration); } this.curValue_ = str; }; /** * Sets the equal indicator. * @param {string} str One of 'dim', 'eq', or 'neq'. * @param {number=} opt_blinkDelay If specified, the amount of time to blink * the equal display. */ turing.Target.prototype.setEqual = function(str, opt_blinkDelay) { if (!opt_blinkDelay || opt_blinkDelay < turing.EQUAL_BLINK_DURATION) { this.equalIndicator_.style.background = turing.sprites.getBackground( 'eq-' + str); } else { var backgrounds = []; var remainingDelay = opt_blinkDelay; while (remainingDelay > turing.EQUAL_BLINK_DURATION) { backgrounds.push('eq-dim'); backgrounds.push('eq-' + str); remainingDelay = remainingDelay - turing.EQUAL_BLINK_DURATION; } backgrounds.push('eq-dim'); turing.anim.animateFromSprites( this.equalIndicator_, backgrounds, opt_blinkDelay); } }; /** * Highlights the given space on the number plate. * @param {string} str The desired bit string. * @param {number} index The index of the number to highlight, or 5 which is * the length of the target, to highlight the entire number plate. * @param {number} duration The amount of time to highlight for. */ turing.Target.prototype.highlightAt = function(str, index, duration) { if (index > str.length) { return; } var lowlit = turing.sprites.numberplate.getLitTargetForDigit( str, index, false); var lit = turing.sprites.numberplate.getLitTargetForDigit( str, index, true); var unlit = turing.sprites.numberplate.getUnlitNumberPlate(str); turing.anim.animateThroughBackgrounds(this.numberPlate_, [unlit, lowlit, lit, lit, lit, lit, lowlit, unlit], duration); }; /** * Pops up a bunny in the equals indicator and makes it clickable. * @param {function()} onClick Callback to call when clicked. * @param {string} color The color for the bunny background. */ turing.Target.prototype.showBonusBunny = function(onClick, color) { this.setEqual('bunny-' + color); this.equalIndicator_.style.cursor = 'pointer'; this.equalClickCallback_ = onClick; }; /** * Click handler for the equal indicator. * @private */ turing.Target.prototype.onClickEqual_ = function() { if (this.equalClickCallback_) { this.equalClickCallback_(); } }; /** * Hides the bunny in the equals indicator and makes it non-clickable. */ turing.Target.prototype.hideBonusBunny = function() { this.equalClickCallback_ = null; this.equalIndicator_.style.cursor = 'default'; this.setEqual('dim'); };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Offsets for sprites. Auto-generated; do not edit. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.sprites.offsets'); /** * Sprite bounding box inside a combined image. * @typedef {{x: number, y: number, width: number, height: number}} */ turing.sprites.offsets.Rect; /** * Bounding boxes of sprites in combined image. * @type {Object.<string, turing.sprites.offsets.Rect>} */ turing.sprites.offsets.RECTS = { 'G0': {x: 0, y: 613, width: 35, height: 37}, 'G1': {x: 35, y: 613, width: 35, height: 37}, 'G2': {x: 70, y: 613, width: 35, height: 37}, 'G3': {x: 105, y: 613, width: 35, height: 37}, 'G4': {x: 140, y: 613, width: 35, height: 37}, 'G5': {x: 175, y: 613, width: 35, height: 37}, 'G6': {x: 210, y: 613, width: 35, height: 37}, 'G7': {x: 245, y: 613, width: 35, height: 37}, 'e0': {x: 0, y: 653, width: 22, height: 23}, 'e1': {x: 22, y: 653, width: 22, height: 23}, 'e2': {x: 44, y: 653, width: 22, height: 23}, 'e3': {x: 66, y: 653, width: 22, height: 23}, 'e4': {x: 88, y: 653, width: 22, height: 23}, 'e5': {x: 110, y: 653, width: 22, height: 23}, 'e6': {x: 132, y: 653, width: 22, height: 23}, 'e7': {x: 154, y: 653, width: 22, height: 23}, 'eq-bunny-b': {x: 137, y: 0, width: 40, height: 40}, 'eq-bunny-g': {x: 217, y: 0, width: 40, height: 40}, 'eq-bunny-r': {x: 257, y: 0, width: 40, height: 40}, 'eq-bunny-y': {x: 177, y: 0, width: 40, height: 40}, 'eq-dim': {x: 97, y: 0, width: 40, height: 40}, 'eq-eq': {x: 337, y: 0, width: 40, height: 40}, 'eq-neq': {x: 297, y: 0, width: 40, height: 40}, 'g0': {x: 366, y: 640, width: 26, height: 36}, 'g1': {x: 392, y: 640, width: 26, height: 36}, 'g2': {x: 418, y: 640, width: 26, height: 36}, 'g3': {x: 444, y: 640, width: 26, height: 36}, 'g4': {x: 470, y: 640, width: 26, height: 36}, 'g5': {x: 496, y: 640, width: 26, height: 36}, 'g6': {x: 522, y: 640, width: 26, height: 36}, 'g7': {x: 548, y: 640, width: 26, height: 36}, 'head': {x: 286, y: 554, width: 61, height: 59}, 'l0': {x: 380, y: 0, width: 16, height: 35}, 'l1': {x: 396, y: 0, width: 16, height: 35}, 'l2': {x: 412, y: 0, width: 16, height: 35}, 'l3': {x: 428, y: 0, width: 16, height: 35}, 'l4': {x: 444, y: 0, width: 16, height: 35}, 'l5': {x: 460, y: 0, width: 16, height: 35}, 'l6': {x: 476, y: 0, width: 16, height: 35}, 'l7': {x: 492, y: 0, width: 16, height: 35}, 'o-back-i': {x: 665, y: 416, width: 35, height: 45}, 'o-back-i-in': {x: 665, y: 506, width: 35, height: 45}, 'o-back-i-lit': {x: 665, y: 461, width: 35, height: 45}, 'o-back-i-out': {x: 665, y: 326, width: 35, height: 45}, 'o-back-i-out-lit': {x: 665, y: 371, width: 35, height: 45}, 'o-back-s': {x: 714, y: 48, width: 34, height: 45}, 'o-back-s-lit-b': {x: 714, y: 138, width: 34, height: 45}, 'o-back-s-lit-g': {x: 714, y: 228, width: 34, height: 45}, 'o-back-s-lit-r': {x: 714, y: 183, width: 34, height: 45}, 'o-back-s-lit-y': {x: 714, y: 93, width: 34, height: 45}, 'o-back2-i': {x: 385, y: 416, width: 35, height: 45}, 'o-back2-i-in': {x: 385, y: 506, width: 35, height: 45}, 'o-back2-i-lit': {x: 385, y: 461, width: 35, height: 45}, 'o-back2-i-out': {x: 385, y: 326, width: 35, height: 45}, 'o-back2-i-out-lit': {x: 385, y: 371, width: 35, height: 45}, 'o-back2-s': {x: 442, y: 48, width: 34, height: 45}, 'o-back2-s-lit-b': {x: 442, y: 138, width: 34, height: 45}, 'o-back2-s-lit-g': {x: 442, y: 228, width: 34, height: 45}, 'o-back2-s-lit-r': {x: 442, y: 183, width: 34, height: 45}, 'o-back2-s-lit-y': {x: 442, y: 93, width: 34, height: 45}, 'o-back3-i': {x: 420, y: 416, width: 35, height: 45}, 'o-back3-i-in': {x: 420, y: 506, width: 35, height: 45}, 'o-back3-i-lit': {x: 420, y: 461, width: 35, height: 45}, 'o-back3-i-out': {x: 420, y: 326, width: 35, height: 45}, 'o-back3-i-out-lit': {x: 420, y: 371, width: 35, height: 45}, 'o-back3-s': {x: 476, y: 48, width: 34, height: 45}, 'o-back3-s-lit-b': {x: 476, y: 138, width: 34, height: 45}, 'o-back3-s-lit-g': {x: 476, y: 228, width: 34, height: 45}, 'o-back3-s-lit-r': {x: 476, y: 183, width: 34, height: 45}, 'o-back3-s-lit-y': {x: 476, y: 93, width: 34, height: 45}, 'o-back4-i': {x: 455, y: 416, width: 35, height: 45}, 'o-back4-i-in': {x: 455, y: 506, width: 35, height: 45}, 'o-back4-i-lit': {x: 455, y: 461, width: 35, height: 45}, 'o-back4-i-out': {x: 455, y: 326, width: 35, height: 45}, 'o-back4-i-out-lit': {x: 455, y: 371, width: 35, height: 45}, 'o-back4-s': {x: 510, y: 48, width: 34, height: 45}, 'o-back4-s-lit-b': {x: 510, y: 138, width: 34, height: 45}, 'o-back4-s-lit-g': {x: 510, y: 228, width: 34, height: 45}, 'o-back4-s-lit-r': {x: 510, y: 183, width: 34, height: 45}, 'o-back4-s-lit-y': {x: 510, y: 93, width: 34, height: 45}, 'o-back8-i': {x: 595, y: 416, width: 35, height: 45}, 'o-back8-i-in': {x: 595, y: 506, width: 35, height: 45}, 'o-back8-i-lit': {x: 595, y: 461, width: 35, height: 45}, 'o-back8-i-out': {x: 595, y: 326, width: 35, height: 45}, 'o-back8-i-out-lit': {x: 595, y: 371, width: 35, height: 45}, 'o-back8-s': {x: 646, y: 48, width: 34, height: 45}, 'o-back8-s-lit-b': {x: 646, y: 138, width: 34, height: 45}, 'o-back8-s-lit-g': {x: 646, y: 228, width: 34, height: 45}, 'o-back8-s-lit-r': {x: 646, y: 183, width: 34, height: 45}, 'o-back8-s-lit-y': {x: 646, y: 93, width: 34, height: 45}, 'o-back9-i': {x: 630, y: 416, width: 35, height: 45}, 'o-back9-i-in': {x: 630, y: 506, width: 35, height: 45}, 'o-back9-i-lit': {x: 630, y: 461, width: 35, height: 45}, 'o-back9-i-out': {x: 630, y: 326, width: 35, height: 45}, 'o-back9-i-out-lit': {x: 630, y: 371, width: 35, height: 45}, 'o-back9-s': {x: 680, y: 48, width: 34, height: 45}, 'o-back9-s-lit-b': {x: 680, y: 138, width: 34, height: 45}, 'o-back9-s-lit-g': {x: 680, y: 228, width: 34, height: 45}, 'o-back9-s-lit-r': {x: 680, y: 183, width: 34, height: 45}, 'o-back9-s-lit-y': {x: 680, y: 93, width: 34, height: 45}, 'o-blank-down-i': {x: 735, y: 416, width: 35, height: 45}, 'o-blank-down-i-in': {x: 735, y: 506, width: 35, height: 45}, 'o-blank-down-i-lit': {x: 735, y: 461, width: 35, height: 45}, 'o-blank-down-i-out': {x: 735, y: 326, width: 35, height: 45}, 'o-blank-down-i-out-lit': {x: 735, y: 371, width: 35, height: 45}, 'o-blank-down-s': {x: 782, y: 48, width: 34, height: 45}, 'o-blank-down-s-lit-b': {x: 782, y: 138, width: 34, height: 45}, 'o-blank-down-s-lit-g': {x: 782, y: 228, width: 34, height: 45}, 'o-blank-down-s-lit-r': {x: 782, y: 183, width: 34, height: 45}, 'o-blank-down-s-lit-y': {x: 782, y: 93, width: 34, height: 45}, 'o-blank-i': {x: 0, y: 416, width: 35, height: 45}, 'o-blank-i-in': {x: 0, y: 506, width: 35, height: 45}, 'o-blank-i-lit': {x: 0, y: 461, width: 35, height: 45}, 'o-blank-i-out': {x: 0, y: 326, width: 35, height: 45}, 'o-blank-i-out-lit': {x: 0, y: 371, width: 35, height: 45}, 'o-blank-s': {x: 34, y: 48, width: 34, height: 45}, 'o-blank-s-lit-b': {x: 34, y: 138, width: 34, height: 45}, 'o-blank-s-lit-g': {x: 34, y: 228, width: 34, height: 45}, 'o-blank-s-lit-r': {x: 34, y: 183, width: 34, height: 45}, 'o-blank-s-lit-y': {x: 34, y: 93, width: 34, height: 45}, 'o-blank-up-i': {x: 700, y: 416, width: 35, height: 45}, 'o-blank-up-i-in': {x: 700, y: 506, width: 35, height: 45}, 'o-blank-up-i-lit': {x: 700, y: 461, width: 35, height: 45}, 'o-blank-up-i-out': {x: 700, y: 326, width: 35, height: 45}, 'o-blank-up-i-out-lit': {x: 700, y: 371, width: 35, height: 45}, 'o-blank-up-s': {x: 748, y: 48, width: 34, height: 45}, 'o-blank-up-s-lit-b': {x: 748, y: 138, width: 34, height: 45}, 'o-blank-up-s-lit-g': {x: 748, y: 228, width: 34, height: 45}, 'o-blank-up-s-lit-r': {x: 748, y: 183, width: 34, height: 45}, 'o-blank-up-s-lit-y': {x: 748, y: 93, width: 34, height: 45}, 'o-dim-s': {x: 0, y: 48, width: 34, height: 45}, 'o-dim-s-lit-b': {x: 0, y: 138, width: 34, height: 45}, 'o-dim-s-lit-g': {x: 0, y: 228, width: 34, height: 45}, 'o-dim-s-lit-r': {x: 0, y: 183, width: 34, height: 45}, 'o-dim-s-lit-y': {x: 0, y: 93, width: 34, height: 45}, 'o-down0-i': {x: 35, y: 416, width: 35, height: 45}, 'o-down0-i-in': {x: 35, y: 506, width: 35, height: 45}, 'o-down0-i-lit': {x: 35, y: 461, width: 35, height: 45}, 'o-down0-i-out': {x: 35, y: 326, width: 35, height: 45}, 'o-down0-i-out-lit': {x: 35, y: 371, width: 35, height: 45}, 'o-down0-s': {x: 102, y: 48, width: 34, height: 45}, 'o-down0-s-lit-b': {x: 102, y: 138, width: 34, height: 45}, 'o-down0-s-lit-g': {x: 102, y: 228, width: 34, height: 45}, 'o-down0-s-lit-r': {x: 102, y: 183, width: 34, height: 45}, 'o-down0-s-lit-y': {x: 102, y: 93, width: 34, height: 45}, 'o-down1-i': {x: 70, y: 416, width: 35, height: 45}, 'o-down1-i-in': {x: 70, y: 506, width: 35, height: 45}, 'o-down1-i-lit': {x: 70, y: 461, width: 35, height: 45}, 'o-down1-i-out': {x: 70, y: 326, width: 35, height: 45}, 'o-down1-i-out-lit': {x: 70, y: 371, width: 35, height: 45}, 'o-down1-s': {x: 136, y: 48, width: 34, height: 45}, 'o-down1-s-lit-b': {x: 136, y: 138, width: 34, height: 45}, 'o-down1-s-lit-g': {x: 136, y: 228, width: 34, height: 45}, 'o-down1-s-lit-r': {x: 136, y: 183, width: 34, height: 45}, 'o-down1-s-lit-y': {x: 136, y: 93, width: 34, height: 45}, 'o-down_-i': {x: 105, y: 416, width: 35, height: 45}, 'o-down_-i-in': {x: 105, y: 506, width: 35, height: 45}, 'o-down_-i-lit': {x: 105, y: 461, width: 35, height: 45}, 'o-down_-i-out': {x: 105, y: 326, width: 35, height: 45}, 'o-down_-i-out-lit': {x: 105, y: 371, width: 35, height: 45}, 'o-down_-s': {x: 170, y: 48, width: 34, height: 45}, 'o-down_-s-lit-b': {x: 170, y: 138, width: 34, height: 45}, 'o-down_-s-lit-g': {x: 170, y: 228, width: 34, height: 45}, 'o-down_-s-lit-r': {x: 170, y: 183, width: 34, height: 45}, 'o-down_-s-lit-y': {x: 170, y: 93, width: 34, height: 45}, 'o-left-i': {x: 280, y: 416, width: 35, height: 45}, 'o-left-i-in': {x: 280, y: 506, width: 35, height: 45}, 'o-left-i-lit': {x: 280, y: 461, width: 35, height: 45}, 'o-left-i-out': {x: 280, y: 326, width: 35, height: 45}, 'o-left-i-out-lit': {x: 280, y: 371, width: 35, height: 45}, 'o-left-s': {x: 340, y: 48, width: 34, height: 45}, 'o-left-s-lit-b': {x: 340, y: 138, width: 34, height: 45}, 'o-left-s-lit-g': {x: 340, y: 228, width: 34, height: 45}, 'o-left-s-lit-r': {x: 340, y: 183, width: 34, height: 45}, 'o-left-s-lit-y': {x: 340, y: 93, width: 34, height: 45}, 'o-print0-i': {x: 350, y: 416, width: 35, height: 45}, 'o-print0-i-in': {x: 350, y: 506, width: 35, height: 45}, 'o-print0-i-lit': {x: 350, y: 461, width: 35, height: 45}, 'o-print0-i-out': {x: 350, y: 326, width: 35, height: 45}, 'o-print0-i-out-lit': {x: 350, y: 371, width: 35, height: 45}, 'o-print0-s': {x: 408, y: 48, width: 34, height: 45}, 'o-print0-s-lit-b': {x: 408, y: 138, width: 34, height: 45}, 'o-print0-s-lit-g': {x: 408, y: 228, width: 34, height: 45}, 'o-print0-s-lit-r': {x: 408, y: 183, width: 34, height: 45}, 'o-print0-s-lit-y': {x: 408, y: 93, width: 34, height: 45}, 'o-print1-i': {x: 315, y: 416, width: 35, height: 45}, 'o-print1-i-in': {x: 315, y: 506, width: 35, height: 45}, 'o-print1-i-lit': {x: 315, y: 461, width: 35, height: 45}, 'o-print1-i-out': {x: 315, y: 326, width: 35, height: 45}, 'o-print1-i-out-lit': {x: 315, y: 371, width: 35, height: 45}, 'o-print1-s': {x: 374, y: 48, width: 34, height: 45}, 'o-print1-s-lit-b': {x: 374, y: 138, width: 34, height: 45}, 'o-print1-s-lit-g': {x: 374, y: 228, width: 34, height: 45}, 'o-print1-s-lit-r': {x: 374, y: 183, width: 34, height: 45}, 'o-print1-s-lit-y': {x: 374, y: 93, width: 34, height: 45}, 'o-rback2-i': {x: 490, y: 416, width: 35, height: 45}, 'o-rback2-i-in': {x: 490, y: 506, width: 35, height: 45}, 'o-rback2-i-lit': {x: 490, y: 461, width: 35, height: 45}, 'o-rback2-i-out': {x: 490, y: 326, width: 35, height: 45}, 'o-rback2-i-out-lit': {x: 490, y: 371, width: 35, height: 45}, 'o-rback2-s': {x: 544, y: 48, width: 34, height: 45}, 'o-rback2-s-lit-b': {x: 544, y: 138, width: 34, height: 45}, 'o-rback2-s-lit-g': {x: 544, y: 228, width: 34, height: 45}, 'o-rback2-s-lit-r': {x: 544, y: 183, width: 34, height: 45}, 'o-rback2-s-lit-y': {x: 544, y: 93, width: 34, height: 45}, 'o-rback3-i': {x: 525, y: 416, width: 35, height: 45}, 'o-rback3-i-in': {x: 525, y: 506, width: 35, height: 45}, 'o-rback3-i-lit': {x: 525, y: 461, width: 35, height: 45}, 'o-rback3-i-out': {x: 525, y: 326, width: 35, height: 45}, 'o-rback3-i-out-lit': {x: 525, y: 371, width: 35, height: 45}, 'o-rback3-s': {x: 578, y: 48, width: 34, height: 45}, 'o-rback3-s-lit-b': {x: 578, y: 138, width: 34, height: 45}, 'o-rback3-s-lit-g': {x: 578, y: 228, width: 34, height: 45}, 'o-rback3-s-lit-r': {x: 578, y: 183, width: 34, height: 45}, 'o-rback3-s-lit-y': {x: 578, y: 93, width: 34, height: 45}, 'o-rback4-i': {x: 560, y: 416, width: 35, height: 45}, 'o-rback4-i-in': {x: 560, y: 506, width: 35, height: 45}, 'o-rback4-i-lit': {x: 560, y: 461, width: 35, height: 45}, 'o-rback4-i-out': {x: 560, y: 326, width: 35, height: 45}, 'o-rback4-i-out-lit': {x: 560, y: 371, width: 35, height: 45}, 'o-rback4-s': {x: 612, y: 48, width: 34, height: 45}, 'o-rback4-s-lit-b': {x: 612, y: 138, width: 34, height: 45}, 'o-rback4-s-lit-g': {x: 612, y: 228, width: 34, height: 45}, 'o-rback4-s-lit-r': {x: 612, y: 183, width: 34, height: 45}, 'o-rback4-s-lit-y': {x: 612, y: 93, width: 34, height: 45}, 'o-right-i': {x: 245, y: 416, width: 35, height: 45}, 'o-right-i-in': {x: 245, y: 506, width: 35, height: 45}, 'o-right-i-lit': {x: 245, y: 461, width: 35, height: 45}, 'o-right-i-out': {x: 245, y: 326, width: 35, height: 45}, 'o-right-i-out-lit': {x: 245, y: 371, width: 35, height: 45}, 'o-right-s': {x: 306, y: 48, width: 34, height: 45}, 'o-right-s-lit-b': {x: 306, y: 138, width: 34, height: 45}, 'o-right-s-lit-g': {x: 306, y: 228, width: 34, height: 45}, 'o-right-s-lit-r': {x: 306, y: 183, width: 34, height: 45}, 'o-right-s-lit-y': {x: 306, y: 93, width: 34, height: 45}, 'o-up0-i': {x: 140, y: 416, width: 35, height: 45}, 'o-up0-i-in': {x: 140, y: 506, width: 35, height: 45}, 'o-up0-i-lit': {x: 140, y: 461, width: 35, height: 45}, 'o-up0-i-out': {x: 140, y: 326, width: 35, height: 45}, 'o-up0-i-out-lit': {x: 140, y: 371, width: 35, height: 45}, 'o-up0-s': {x: 204, y: 48, width: 34, height: 45}, 'o-up0-s-lit-b': {x: 204, y: 138, width: 34, height: 45}, 'o-up0-s-lit-g': {x: 204, y: 228, width: 34, height: 45}, 'o-up0-s-lit-r': {x: 204, y: 183, width: 34, height: 45}, 'o-up0-s-lit-y': {x: 204, y: 93, width: 34, height: 45}, 'o-up1-i': {x: 175, y: 416, width: 35, height: 45}, 'o-up1-i-in': {x: 175, y: 506, width: 35, height: 45}, 'o-up1-i-lit': {x: 175, y: 461, width: 35, height: 45}, 'o-up1-i-out': {x: 175, y: 326, width: 35, height: 45}, 'o-up1-i-out-lit': {x: 175, y: 371, width: 35, height: 45}, 'o-up1-s': {x: 238, y: 48, width: 34, height: 45}, 'o-up1-s-lit-b': {x: 238, y: 138, width: 34, height: 45}, 'o-up1-s-lit-g': {x: 238, y: 228, width: 34, height: 45}, 'o-up1-s-lit-r': {x: 238, y: 183, width: 34, height: 45}, 'o-up1-s-lit-y': {x: 238, y: 93, width: 34, height: 45}, 'o-up_-i': {x: 210, y: 416, width: 35, height: 45}, 'o-up_-i-in': {x: 210, y: 506, width: 35, height: 45}, 'o-up_-i-lit': {x: 210, y: 461, width: 35, height: 45}, 'o-up_-i-out': {x: 210, y: 326, width: 35, height: 45}, 'o-up_-i-out-lit': {x: 210, y: 371, width: 35, height: 45}, 'o-up_-s': {x: 272, y: 48, width: 34, height: 45}, 'o-up_-s-lit-b': {x: 272, y: 138, width: 34, height: 45}, 'o-up_-s-lit-g': {x: 272, y: 228, width: 34, height: 45}, 'o-up_-s-lit-r': {x: 272, y: 183, width: 34, height: 45}, 'o-up_-s-lit-y': {x: 272, y: 93, width: 34, height: 45}, 'o-x-s': {x: 68, y: 48, width: 34, height: 45}, 'o-x-s-lit-b': {x: 68, y: 138, width: 34, height: 45}, 'o-x-s-lit-g': {x: 68, y: 228, width: 34, height: 45}, 'o-x-s-lit-r': {x: 68, y: 183, width: 34, height: 45}, 'o-x-s-lit-y': {x: 68, y: 93, width: 34, height: 45}, 'o10': {x: 16, y: 585, width: 26, height: 25}, 'o11': {x: 42, y: 585, width: 26, height: 25}, 'o12': {x: 68, y: 585, width: 26, height: 25}, 'o13': {x: 94, y: 585, width: 26, height: 25}, 'o14': {x: 120, y: 585, width: 26, height: 25}, 'o15': {x: 146, y: 585, width: 26, height: 25}, 'o16': {x: 172, y: 585, width: 26, height: 25}, 'o17': {x: 198, y: 585, width: 26, height: 25}, 'o20': {x: 577, y: 610, width: 26, height: 25}, 'o21': {x: 603, y: 610, width: 26, height: 25}, 'o22': {x: 629, y: 610, width: 26, height: 25}, 'o23': {x: 655, y: 610, width: 26, height: 25}, 'o24': {x: 681, y: 610, width: 26, height: 25}, 'o25': {x: 707, y: 610, width: 26, height: 25}, 'o26': {x: 733, y: 610, width: 26, height: 25}, 'o27': {x: 759, y: 610, width: 26, height: 25}, 'play-flat': {x: 424, y: 276, width: 45, height: 46}, 'play-in': {x: 469, y: 276, width: 45, height: 46}, 'play-out': {x: 334, y: 276, width: 45, height: 46}, 'play-out-lit': {x: 379, y: 276, width: 45, height: 46}, 'slot-left': {x: 350, y: 610, width: 13, height: 55}, 'slot-right': {x: 0, y: 554, width: 13, height: 55}, 'tape-shadow-l': {x: 350, y: 554, width: 47, height: 41}, 'tape-shadow-r': {x: 511, y: 0, width: 47, height: 41}, 'tape0': {x: 721, y: 0, width: 40, height: 46}, 'tape0a': {x: 561, y: 0, width: 40, height: 46}, 'tape0b': {x: 601, y: 0, width: 40, height: 46}, 'tape0c': {x: 641, y: 0, width: 40, height: 46}, 'tape0d': {x: 681, y: 0, width: 40, height: 46}, 'tape1': {x: 291, y: 276, width: 40, height: 46}, 'tape1a': {x: 131, y: 276, width: 40, height: 46}, 'tape1b': {x: 171, y: 276, width: 40, height: 46}, 'tape1c': {x: 211, y: 276, width: 40, height: 46}, 'tape1d': {x: 251, y: 276, width: 40, height: 46}, 'tape_': {x: 243, y: 554, width: 40, height: 45}, 'target-blank': {x: 0, y: 276, width: 128, height: 47}, 'track': {x: 400, y: 554, width: 369, height: 53}, 'track-l2': {x: 0, y: 0, width: 90, height: 27}, 'track-l3': {x: 109, y: 554, width: 131, height: 27}, 'track-l4': {x: 366, y: 610, width: 173, height: 27}, 'track-short': {x: 0, y: 30, width: 94, height: 8}, 'track-u2': {x: 16, y: 554, width: 90, height: 28}, 'track-u3': {x: 517, y: 276, width: 131, height: 28}, 'track-u4': {x: 577, y: 638, width: 173, height: 28}, 'track-vert': {x: 286, y: 616, width: 7, height: 49} };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Saves and restores persistent game state. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.GameState'); /** * The localStorage key for the current program. * @type {string} * @const * @private */ turing.CUR_PROGRAM_KEY_ = 'doodle-turing-p'; /** * Minimum valid value for curProgram_. * @type {number} * @const * @private */ turing.MIN_VALID_PROGRAM_ = 1; /** * Maximum valid value for curProgram_. * @type {number} * @const * @private */ turing.MAX_VALID_PROGRAM_ = 12; /** * The current game state. * @constructor */ turing.GameState = function() { /** * Index of the current program. * @type {number} * @private */ this.curProgram_ = turing.MIN_VALID_PROGRAM_; }; /** * @return {number} Index of current program. */ turing.GameState.prototype.getCurProgram = function() { return this.curProgram_; }; /** * Sets index of current program. * @param {number} curProgram The index of the current program. */ turing.GameState.prototype.setCurProgram = function(curProgram) { this.curProgram_ = curProgram; this.save(); }; /** * Saves state using localStorage. */ turing.GameState.prototype.save = function() { if (window.localStorage && window.localStorage.setItem) { window.localStorage.setItem(turing.CUR_PROGRAM_KEY_, this.curProgram_); } }; /** * Restores state using localStorage. */ turing.GameState.prototype.restore = function() { if (window.localStorage && window.localStorage[turing.CUR_PROGRAM_KEY_]) { this.curProgram_ = parseInt( window.localStorage[turing.CUR_PROGRAM_KEY_], 10) || 0; // NaN -> 0. if (this.curProgram_ < turing.MIN_VALID_PROGRAM_ || this.curProgram_ > turing.MAX_VALID_PROGRAM_) { // If curProgram_ is corrupted, start from the first program. this.curProgram_ = turing.MIN_VALID_PROGRAM_; } } };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A small collection of helpers. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.util'); /** * Browser vendor name prefixes, used for looking up vendor-specific properties. * Other known vendor prefixes include 'Khtml' and 'Icab', but I'm excluding * these because I don't have them available to test. * @type {Array.<string>} * @const */ turing.VENDOR_PREFIXES = ['Moz', 'Webkit', 'O', 'ms']; /** * Removes an element from its dom parent. * @param {Element} elem The element to remove. */ turing.util.removeNode = function(elem) { if (elem && elem.parentNode) { elem.parentNode.removeChild(elem); } }; /** * Chooses the value after value in arr, or null if not in arr. * @param {Array} arr An array to search in. * @param {*} value The value to search for. * @return {*} The value after the searched one, or null if none. */ turing.util.getNextValue = function(arr, value) { for (var i = 0, arrValue; arrValue = arr[i]; i++) { if (arrValue == value) { break; } } var nextValue = i == arr.length - 1 ? arr[0] : arr[i + 1]; return i == arr.length ? null : nextValue; }; /** * Gets the vendor-specific name of a CSS property. * Adapted from https://gist.github.com/556448 * @param {string} property The standard name of a CSS property. * @return {string|undefined} The name of this property as implemented in the * current browser, or undefined if not implemented. */ turing.util.getVendorCssPropertyName = function(property) { var body = document.body || document.documentElement; var style = body.style; if (typeof style == 'undefined') { // No CSS support. Something is badly wrong. return undefined; } if (typeof style[property] == 'string') { // The standard name is supported. return property; } // Test for vendor specific names. var capitalizedProperty = property.charAt(0).toUpperCase() + property.substr(1); for (var i = 0, prefix; prefix = turing.VENDOR_PREFIXES[i++]; ) { if (typeof style[prefix + capitalizedProperty] == 'string') { return prefix + capitalizedProperty; } } }; /** * Calls either addEventListener or attachEvent depending on what's * available. * @param {(Document|Element|Window)} element The object to listen on. * @param {string} eventName The event to listen to, such as 'click'. * @param {Function} listener The listener function to trigger. */ turing.util.listen = function(element, eventName, listener) { if (element.addEventListener) { element.addEventListener(eventName, listener, false); } else { element.attachEvent('on' + eventName, listener); } }; /** * Stops listening to the specified event on the given target. * @param {(Document|Element|Window)} element The object that we were listening * on. * @param {string} eventName The event we were listening to, such as 'click'. * @param {Function} listener The listener function to remove. */ turing.util.unlisten = function(element, eventName, listener) { if (!element || !listener) { return; } if (element.removeEventListener) { element.removeEventListener(eventName, listener, false); } else if (element.detachEvent) { element.detachEvent('on' + eventName, listener); } }; /** * Sets the opacity of a node (x-browser). * @param {Element} el Elements whose opacity has to be set. * @param {number|string} alpha Opacity between 0 and 1 or an empty string * {@code ''} to clear the opacity. */ turing.util.setOpacity = function(el, alpha) { var style = el.style; if ('opacity' in style) { style.opacity = alpha; } else if ('MozOpacity' in style) { style.MozOpacity = alpha; } else if ('filter' in style) { if (alpha === '') { style.filter = ''; } else { style.filter = 'alpha(opacity=' + alpha * 100 + ')'; } } };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview An interactive doodle for Alan Turing's 100th birthday. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing'); goog.require('turing.Controls'); goog.require('turing.GameState'); goog.require('turing.Logo'); goog.require('turing.Program'); goog.require('turing.Simulator'); goog.require('turing.Tape'); goog.require('turing.Target'); goog.require('turing.anim'); goog.require('turing.sprites'); goog.require('turing.util'); /** * The container where our dom modifications will be contained. * @type {string} * @const */ turing.LOGO_CONTAINER_ID = 'logo'; /** * The maximum number of steps a game program can run. This should be just high * enough so that all halting programs can run fully, and all cyclic programs do * something that checks wrong before we kill them; but low enough so that users * don't get bored if they make a trivial infinite loop. * @type {number} * @const */ turing.GAME_PROGRAM_STEP_LIMIT = 40; /** * How many failed attempts at current puzzle before we slow down execution. * @type {number} * @const */ turing.FAILURES_BEFORE_SLOWING = 2; /** * Assembles a program from strings. * @param {...string} var_args One string for each program track. * @return {Object.<string, Array.<Array.<string>>>} An object with correct and * incorrect array of op arrays for each track. * @private */ turing.assemble_ = function(var_args) { var ops = {}; for (var pass = 0; pass <= 1; pass++) { // Make two passes through each program to save incorrect and correct // copies. We need correct copies to animate stepping through solved puzzles // when the game is over. var tracks = []; for (var i = 0; i < arguments.length; i++) { // Split on whitespace and copy the resulting array (/ +/ matches one or // more spaces.) var trackOps = arguments[i].split(/ +/).slice(0); for (var j = 0; j < trackOps.length; j++) { if (trackOps[j] == '.') { // No-ops are represented internally with the empty string. trackOps[j] = ''; } else if (/\(.*\)/.test(trackOps[j])) { // /\(.*\)/ matches a parenthesized expression inside the op // description. These are corrections for ops initially set to a wrong // value for the game. if (pass == 0) { // Keep only the correction. (The re below matches the whole op // string, but captures only the part in parentheses.) trackOps[j] = trackOps[j].replace(/.*\((.*)\).*/, '$1'); } else { // Eliminate the correction. trackOps[j] = '*' + trackOps[j].replace(/\(.*\)/, ''); } } else if (pass == 0 && trackOps[j] && trackOps[j][0] == '*') { // Some buttons are clickable but do not have explicit corrections // since they are not needed to solve the program. These are just // marked with a *. Remove it if present so they are not clickable // when playing through the solved program on game over. trackOps[j] = trackOps[j].substr(1); } } tracks.push(trackOps); } if (pass == 0) { ops.correct = tracks; } else { ops.incorrect = tracks; } } return ops; }; /** * One of the doodle's programs. * @typedef {{tape: string, goal: string, ops: Object.<string, Array>}} */ turing.ProgramDef; /** * The set of programs which the user must complete in order to relight the * Google logo, along with an initial demo/demos to show off the machine. * @type {Array.<turing.ProgramDef>} * @const */ turing.PROGRAMS = [ // Demo program shown when the doodle loads. { // This program counts forever in binary starting at 1. tape: '', goal: '', ops: turing.assemble_('D0 D_ 0 L B4', '. 1 R U_ B2') }, // First quest: The following six programs are four basic tutorial programs // and two interesting but not especially challenging programs. We hope most // people can get through these with no trouble. { tape: '00010', goal: '01011', // A really gentle intro to the basic operations: just moves and prints. // - Tried L L *0, but most users clicked through without understanding. // - Tried L L 1(0) R R R R 0(1) with the tape 11010. Needing to click two // things reduced random click throughs, but some users were stuck here // when buttons cycled L/R/0/1 (so now they cycle 0/1). // - Considered the above program with the tape _101_ to make printing more // obvious, but decided the first program needs to start with a five bit // string on the tape for clear correspondence with the number plate. // - Revised to this program because we want the leftmost bit to be correct // so at first the user sees one bit check correct and then one wrong. ops: turing.assemble_('L 0(1) R R R 0(1)'), tutorial: true, logoLetterIndex: 0, highlight: 'b' }, { tape: '0_011', goal: '00011', // Introduces conditional branching between tracks, the down-if operation // and the notation we use to mean a blank square. // - The extra L is supposed to give users time to notice the program is // running. // - We tried 0 *D0 followed by some Ls and Rs on each track. Users clicked // through but were generally confused about our notation, so we didn't // learn much. Also we had aesthetic complaints about branching on // something just written. ops: turing.assemble_('L D0(D_) 1', '. 0'), tutorial: true, logoLetterIndex: 1, highlight: 'r' }, { tape: '01011', goal: '00011', // Introduces backwards branches. The goal is to line up with the correct // conditional. The extra Rs are supposed to show there is an incorrect // alternative path; hopefully this is not confusing. // - We tried a more elaborate program with a loop where one had to pick the // correct exit. This was too complex. Users had trouble noticing the // backwards arcing tracks, which this program really emphasizes visually // since it lines up with the descending track from the D1 ops. ops: turing.assemble_('D1 D1 D1 L B2(B4)', '0 R R R'), tutorial: true, logoLetterIndex: 2, highlight: 'y' }, { tape: '11011', goal: '01011', // Introduces loops. Finds the first bit and changes it. ops: turing.assemble_('L D1(D_) B2', '. R 0'), tutorial: true, logoLetterIndex: 3, highlight: 'b' }, { tape: '0_001', goal: '01001', // Replaces a single blank with 1s. // This would be more challenging if the D1 exit were changeable. ops: turing.assemble_('L L D0(D_) R D1 B3', '. . 1 U1'), logoLetterIndex: 4, highlight: 'g' }, { tape: '01111', goal: '10000', // Inverts the string on the tape. // This is an actual interesting program with a clear task. Two different // solutions work to make the program do inverting; on track 2, 0 -> 1, // U0 -> U1; or on track 1, D0 -> D1, 0 -> 1. ops: turing.assemble_('L L D0(D1) 0(1) R D_ B4', '. . *0 . *U0'), logoLetterIndex: 5, highlight: 'r' }, // Second quest: These more interesting programs are here for users who // really like this sort of thing and want more challenge/interest. { tape: '11010', goal: '01011', // Uses loops to find the first and last bits and change them. ops: turing.assemble_('L D_ B2 . R(L) 1', '. R 0 R U0(U_) B2'), logoLetterIndex: 0, highlight: 'b' }, { tape: '01_01', goal: '00011', // Adds two base one numbers, sort of, not really. ops: turing.assemble_('L D_(D1) B2 . L 1 L 0', '. . 0 R U_(U1) B2 . .'), logoLetterIndex: 1, highlight: 'r' }, { tape: '00111', goal: '00011', // A maze of conditionals. This is maybe sort of insane. ops: turing.assemble_('D_(D1) 1 L D_(D1) 1 L D_(D0) 1', '1 R U_(U1) 0 R U_(U1) 0 *U_'), logoLetterIndex: 2, highlight: 'y' }, { tape: '01011', goal: '01011', // A goofy easy one to break up the tension. So easy it actually does // nothing. This is an homage to the Konami code. ops: turing.assemble_('. . D_ D_ L R L R', 'U_ U_ . . . . 1 0'), tutorial: true, logoLetterIndex: 3, highlight: 'b' }, { tape: '0_00_', goal: '01001', // Replaces zeroes followed by blanks with 1s. // This is meant to be sort of challenging. The main challenge is to avoid // infinite loops and reason about what makes the program terminate // properly. ops: turing.assemble_('L L D_(D0) 1 R D1(D_) B4', '. R U0(U_) B2'), logoLetterIndex: 4, highlight: 'g' }, { tape: '00001', goal: '10000', // Shifts the one to left. ops: turing.assemble_('D0(D1) R . D0(D_) B4', '0 L 1 L U_(U0)'), stepLimit: 80, logoLetterIndex: 5, highlight: 'r' } ]; /** * A bonus program displayed only in a special mode which the user can trigger * after winning the game. This program prints the rabbit sequence, which is a * bitstring with many beautiful relationships to Fibonacci numbers and the * golden ratio. More immediately, it implements the substitution system with * rules 1 -> 10, 0 -> 1. * @type {Array.<Array.<string>>} * @const */ turing.BONUS_PROGRAM = turing.assemble_( '1 . D1 . . . . _ R D_ B2', 'R U _ R D_ B2 . 1 B8 1 D_ L B2', 'U . B2 . 1 R 0 U_ L B2 0 B9').correct; /** * Current game state. * @type {turing.GameState} * @private */ turing.state_ = new turing.GameState(); /** * True iff the game has ended. * @type {boolean} * @private */ turing.gameOver_ = false; /** * How many times has the user failed to solve the current puzzle? * @type {number} * @private */ turing.numFailures_ = 0; /** * The time when the current program was first set up. * @type {number} * @private */ turing.startProgramTime_ = 0; /** * The tape. * @type {turing.Tape} * @private */ turing.tape_; /** * The letters of the Google logo. * @type {turing.Logo} * @private */ turing.logo_ = new turing.Logo(); /** * The program display. * @type {turing.Program} * @private */ turing.program_; /** * An overlay which covers the doodle initially. * @type {turing.Overlay} * @private */ turing.overlay_ = new turing.Overlay(); /** * Helper to simulate programs. * @type {turing.Simulator} * @private */ turing.simulator_ = new turing.Simulator(); /** * Controls to start and stop program execution. * @type {turing.Controls} * @private */ turing.controls_ = new turing.Controls(); /** * A board to display the desired target for the current game program. * @type {turing.Target} * @private */ turing.target_ = new turing.Target(); /** * The main container for the doodle. * @type {Element} * @private */ turing.logoContainer_ = null; /** * @return {boolean} True iff current program is a tutorial. * @private */ turing.inTutorial_ = function() { return turing.PROGRAMS[turing.state_.getCurProgram()].tutorial; }; /** * @param {Element} img An img element. * @return {boolean} True iff an image is already loaded. * @private */ turing.isImageReady_ = function(img) { return img['complete'] || img['readyState'] == 'complete'; }; /** * Starts up demo mode. * @private */ turing.startDemo_ = function() { turing.logo_.attachTo(turing.logoContainer_); turing.tape_.attachTo(turing.logoContainer_); turing.program_.attachTo(turing.logoContainer_); turing.overlay_.attachTo(turing.logoContainer_, turing.startGame_); turing.controls_.attachTo(turing.logoContainer_); turing.target_.attachTo(turing.logoContainer_); // Remove the base overlay image which we show while our sprite preloads. turing.logoContainer_.style.background = ''; turing.startSleepTimer_(); turing.program_.setInteractive(false); turing.program_.change(turing.PROGRAMS[0].ops.correct, true /* Hidden. */); turing.simulator_.run(turing.program_, turing.tape_, turing.SpeedSetting.FAST); }; /** * Changes into game mode. * @private */ turing.startGame_ = function() { // Begin loading the deferred sprite sheet. var deferredSprite = turing.sprites.preload( turing.sprites.DEFERRED_SPRITE_PATH); turing.simulator_.stop(); turing.simulator_.setStepLimit(turing.GAME_PROGRAM_STEP_LIMIT); if (turing.PROGRAMS[turing.state_.getCurProgram()].logoLetterIndex == 0) { // Only dim the logo if the user hasn't solved any programs yet, i.e., they // are on the 'G' program; otherwise we'll pick up where they left off. turing.logo_.dim(500); } if (turing.isImageReady_(deferredSprite)) { // If the deferred sprite was cached or loaded very fast, go right to the // game. turing.destroySleepTimer_(); turing.anim.delay(function() { turing.setupProgram_(turing.state_.getCurProgram()); }, 500); } else { // Otherwise, if we're waiting for the deferred sprite, treat the tape as a // progress bar and sit scrolling it until the sprite loads. var loaded = false; turing.anim.delay(function() { if (!loaded) { turing.tape_.scanRight(100, 100); turing.anim.delay(/** @type {function()} */(arguments.callee), 300); } }, 300); deferredSprite.onload = function() { loaded = true; turing.destroySleepTimer_(); turing.setupProgram_(turing.state_.getCurProgram()); }; } }; /** * Sets up the game for a given program. * Things change in the order: Target, tape, program (top to bottom). * @param {number} index The program to enter. * @private */ turing.setupProgram_ = function(index) { var program = turing.PROGRAMS[index]; turing.startProgramTime_ = new Date().getTime(); if (program.stepLimit) { turing.simulator_.setStepLimit(program.stepLimit); } // Make the program vanish and the target scroll away. turing.program_.change([[], []]); turing.target_.setValue('', 800); turing.target_.setEqual('dim'); turing.anim.delay(turing.callIfNotInBonusMode_(function() { turing.tape_.setString(program.tape); }), 800); turing.anim.delay(turing.callIfNotInBonusMode_(function() { turing.target_.setValue(program.goal, 800); }), 2200); turing.anim.delay(turing.callIfNotInBonusMode_(function() { if (!turing.gameOver_) { turing.program_.change(program.ops.incorrect); turing.makeInteractive_(0, 500); } else { turing.program_.change(program.ops.correct); // The bunny takes you to bonus mode! turing.target_.showBonusBunny(turing.enterBonusMode_, program.highlight); turing.setOpHighlightColor(program.highlight); turing.simulator_.run(turing.program_, turing.tape_, turing.SpeedSetting.FAST, turing.callIfNotInBonusMode_(function() { turing.winLevel_(index); })); } }), 3200); }; /** * Changes program and makes the play button pressable after the tape is set up. * @param {number} popOutPlayDelay ms to delay before popping button out. * @param {number} lightOpsDelay ms to delay before lighting clickable buttons. * @private */ turing.makeInteractive_ = function(popOutPlayDelay, lightOpsDelay) { turing.target_.setEqual('dim'); turing.anim.delay(function() { turing.controls_.popOutPlayButton(function() { turing.program_.setInteractive(false); turing.controls_.pushInPlayButton(); // Pause between lighting the play button and lighting the first // operation to make it clear these are two separate things happening. turing.anim.delay(function() { // Speed picks up a little after the initial programs, but slows back // down if the user has trouble. var speed = turing.inTutorial_() ? turing.SpeedSetting.TUTORIAL : turing.SpeedSetting.NORMAL; if (turing.numFailures_ >= turing.FAILURES_BEFORE_SLOWING) { // Having a hard time. speed = turing.inTutorial_() ? turing.SpeedSetting.SLOW : turing.SpeedSetting.TUTORIAL; } // Note: I tried dropping back down to SLOW if there are twice as many // failures, but this is just too slow for looping programs. turing.simulator_.run(turing.program_, turing.tape_, speed, turing.finishProgramRun_); }, 600); }); // Light up clickable ops a little after the play button pops out so that // people will first notice the play button, then things to click. turing.anim.delay(function() { turing.program_.setInteractive(true); }, lightOpsDelay); }, popOutPlayDelay); }; /** * Ends the game after the user has won. * This method is called twice: * - once to signal that the user has finished the game and start an * animation of the play-through. * - then, it is called again but instead navigates to serp. * @private */ turing.endGame_ = function() { turing.tape_.setString(''); turing.program_.change([[], []]); turing.program_.reset(); turing.target_.setValue('', 800); if (!turing.gameOver_) { if (turing.state_.getCurProgram() == turing.PROGRAMS.length - 1) { // Reset current program so the next playthrough will start over. turing.state_.setCurProgram(1); } else { // On next playthrough, begin at a new set of programs. turing.state_.setCurProgram(turing.state_.getCurProgram() + 1); } turing.gameOver_ = true; turing.anim.delay( goog.bind(turing.logo_.deluminate, turing.logo_, turing.replaySolutionsInSequence_), 1000); } else { window.location.href = '/search?q=Alan+Turing'; } turing.target_.setEqual('dim'); }; /** * Plays through solved programs in sequence. * @private */ turing.replaySolutionsInSequence_ = function() { // Because gameOver is now set, setupProgram_ will just step through programs // until the last. // We have already set up the new value of curProgram for the next game. Count // back six programs, wrapping, to figure out which program began this game, // so we can replay from the correct place. var firstProgramInNextGame = turing.state_.getCurProgram(); var firstProgramInThisGame = firstProgramInNextGame == 1 ? turing.PROGRAMS.length - 6 : firstProgramInNextGame - 6; turing.setupProgram_(firstProgramInThisGame); }; /** * Sets up a more complicated, interesting program after the game is done. * @private */ turing.enterBonusMode_ = function() { turing.simulator_.stop(); turing.logo_.destroy(); turing.controls_.destroy(); turing.target_.destroy(); turing.program_.destroy(); turing.switchProgramsToBonusMode(); turing.setOpHighlightColor('y'); turing.startSleepTimer_(); turing.tape_.slideUp(); turing.anim.delay(function() { // There may be another setString queued, so wait a while and then clear // the tape to be sure it starts out blank. turing.tape_.setString(''); turing.anim.delay(function() { turing.program_ = new turing.Program(); turing.program_.create(); turing.program_.attachTo(turing.logoContainer_); turing.program_.change(turing.BONUS_PROGRAM); turing.simulator_.setStepLimit(0); turing.simulator_.run(turing.program_, turing.tape_, turing.SpeedSetting.FAST); }, 2000); }, 2000); }; /** * Wraps a function with a test to check for bonus mode prior to calling. * @param {function()} func The function to call. * @return {function()} A function which first tests for bonus mode. * @private */ turing.callIfNotInBonusMode_ = function(func) { return function() { if (!turing.isInBonusMode()) { func(); } } }; /** * Called when a program is finished running. * @private */ turing.finishProgramRun_ = function() { // Let the last operation light remain off for a while to make it clear the // program is done. turing.anim.delay(function() { // First dim, but do not pop out the play button. turing.controls_.dimPlayButton(); // Give the user just long enough to notice the play button before starting // to check the tape. turing.anim.delay(turing.checkTape_, 1000); }, 700); }; /** * Checks to see whether the tape is correct * @private */ turing.checkTape_ = function() { // -1 seeks one position left of the first square to attract attention to // checking before it starts. turing.checkNextSquare_(-1, turing.winLevel_, turing.failLevel_); }; /** * Called when the user wins a level (the tape checks correct). * @param {number=} opt_index Iff present, use this as the index of the program * just completed. * @private */ turing.winLevel_ = function(opt_index) { turing.numFailures_ = 0; var index = opt_index || turing.state_.getCurProgram(); var letterIndex = turing.PROGRAMS[index].logoLetterIndex; // Change the current letter to be lit up. turing.logo_.lightLetterAtPosition(letterIndex, 500); if (!turing.isInBonusMode() && letterIndex == 5 /* 'e'. */) { // End the game when the 'e' program is solved. turing.anim.delay(turing.endGame_, 500); } else if (opt_index) { // Run new program but don't update state; used for end-game animation. turing.anim.delay(turing.callIfNotInBonusMode_(function() { turing.setupProgram_(/** @type {number} */(opt_index) + 1); }), 500); } else { // Update state. turing.anim.delay(turing.callIfNotInBonusMode_(function() { turing.state_.setCurProgram(index + 1); turing.setupProgram_(turing.state_.getCurProgram()); }), 500); } }; /** * Called when the user fails the level (tape doesn't check.) * @private */ turing.failLevel_ = function() { // Reset the tape and try again. turing.numFailures_++; var program = turing.PROGRAMS[turing.state_.getCurProgram()]; turing.anim.delay(function() { turing.tape_.resetString(program.tape); turing.anim.delay(function() { turing.makeInteractive_(0, 100); turing.program_.reset(); }, 400); }, 300); }; /** * Check the square in the tape pointed to by the index arg. * If it's past the last symbol on the tape and in the target, then * trigger success. * If it doesn't match the target's symbol at index, then trigger failure. * Otherwise wait a bit and check the next square. * @param {number} index The index to check. * @param {function()} successCallback What to do if all squares match * the target. * @param {function()} failureCallback What to do if there is a mismatch. * @private */ turing.checkNextSquare_ = function(index, successCallback, failureCallback) { var symbol = turing.tape_.scanToAndGetSymbol(index); var program = turing.PROGRAMS[turing.state_.getCurProgram()]; if (index == -1) { // First scan one square to the left of the solution to get people to // look up to the tape. turing.anim.delay( goog.partial(turing.checkNextSquare_, index + 1, successCallback, failureCallback), 600); return; } if (!symbol && !program.goal[index]) { turing.target_.highlightAt(program.goal, index, 1600); turing.target_.setEqual('eq', 1600); // Success. We've gone off the end of both strings. turing.anim.delay(successCallback, 2000); } else if (symbol != program.goal[index]) { turing.target_.highlightAt(program.goal, index, 1600); turing.target_.setEqual('neq', 1600); // Fail! turing.anim.delay(failureCallback, 2000); } else { // Speed up checking after we've passed the intro programs. var duration = turing.inTutorial_() ? 1000 : 500; turing.target_.highlightAt(program.goal, index, duration); turing.target_.setEqual('eq', duration - 200); turing.anim.delay( goog.partial(turing.checkNextSquare_, index + 1, successCallback, failureCallback), duration); } }; /** * Id for a timer which puts the doodle to sleep due to inactivity. * @type {?number} * @private */ turing.sleepTimerId_ = null; /** * True iff we saw the mouse move since the last sleep timer callback. * @type {boolean} * @private */ turing.sawMouseMove_ = false; /** * Period in ms of a timer which checks if it should put the doodle to sleep. * Note this means the doodle must be inactive for [t, 2*t] before going to * sleep. * @type {number} * @const */ turing.SLEEP_TIMEOUT = 20000; /** * Sets up a timer to put the doodle to sleep after a period of inactivity. * @private */ turing.startSleepTimer_ = function() { // Inactivity is defined as no mouse movement for a period of the sleep timer. turing.sawMouseMove_ = false; turing.util.listen(document, 'mousemove', turing.mouseMoveListener_); turing.util.listen(document, 'touchstart', turing.touchStartListener_); // Put the doodle to sleep when simulator is running with no user activity. turing.sleepTimerId_ = window.setTimeout(turing.sleepIfInactive_, turing.SLEEP_TIMEOUT); }; /** * Event listener for mouse movements on the document element. Used to detect * long periods of inactivity and put the doodle to sleep. * @private */ turing.mouseMoveListener_ = function() { turing.sawMouseMove_ = true; if (turing.anim.isStopped()) { // Wake the doodle up immediately so the user doesn't see it paused. turing.anim.start(); turing.simulator_.resumeIfPaused(); turing.sleepTimerId_ = window.setTimeout(turing.sleepIfInactive_, turing.SLEEP_TIMEOUT); } }; /** * Event listener for touchstart events. * @private */ turing.touchStartListener_ = function() { turing.program_.setTouchDevice(); turing.mouseMoveListener_(); }; /** * Called periodically to put the doodle to sleep if it is inactive. * @private */ turing.sleepIfInactive_ = function() { if (turing.simulator_.isRunning() && !turing.simulator_.hasStepLimit() && !turing.sawMouseMove_) { // Only sleep if the simulator is running forever; the game settles down to // an idle steady state when playing. turing.simulator_.pause(); turing.anim.stop(); } else { turing.sleepTimerId_ = window.setTimeout(turing.sleepIfInactive_, turing.SLEEP_TIMEOUT); } // This will be reset in onmousemove if the user is mousing. turing.sawMouseMove_ = false; }; /** * Tears down the sleep timeout timer. * @private */ turing.destroySleepTimer_ = function() { turing.util.unlisten(document, 'mousemove', turing.mouseMoveListener_); turing.util.unlisten(document, 'touchstart', turing.touchStartListener_); if (turing.sleepTimerId_ != null) { window.clearTimeout(turing.sleepTimerId_); turing.sleepTimerId_ = null; } }; /** * Preloads sprite, creates dom elements and binds event listeners. */ turing.init = function() { turing.logoContainer_ = document.getElementById(turing.LOGO_CONTAINER_ID); if (!turing.logoContainer_) { // Do not show if the logo container is missing. return; } var mainSprite = turing.sprites.preload(turing.sprites.PATH); turing.state_.restore(); turing.anim.reset(); turing.anim.start(); // In case we were previously in bonus mode. turing.switchProgramsToNormalMode(); turing.setOpHighlightColor('y'); turing.program_ = new turing.Program(); turing.gameOver_ = false; turing.numFailures_ = 0; turing.overlay_.create(turing.logoContainer_); // If the user has not solved the 'G' program, light the entire logo // initially, else light as many letters as they have solved. var curProgram = turing.state_.getCurProgram(); var letterIndex = turing.PROGRAMS[curProgram].logoLetterIndex; turing.logo_.create(letterIndex == 0 ? 6 : letterIndex); turing.tape_ = new turing.Tape(); turing.tape_.create(); turing.program_.create(); turing.controls_.create(); turing.target_.create(); // Start the demo when we have the image for the main sprite. // Set up the handlers after we've initialized everything above as // the handler does use some of those objects. if (turing.isImageReady_(mainSprite)) { turing.startDemo_(); } else { mainSprite.onload = turing.startDemo_; } }; /** * Cleans up dom elements and listeners. */ turing.destroy = function() { turing.state_.save(); turing.destroySleepTimer_(); turing.anim.reset(); turing.simulator_.stop(); turing.target_.destroy(); turing.overlay_.destroy(); if (turing.program_) { turing.program_.destroy(); turing.program_ = null; } if (turing.tape_) { turing.tape_.destroy(); turing.tape_ = null; } turing.logo_.destroy(); turing.controls_.destroy(); };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Offsets for sprites. Auto-generated; do not edit. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.deferredsprites.offsets'); goog.require('turing.sprites.offsets'); /** * Bounding boxes of sprites in combined image. * @type {Object.<string, turing.sprites.offsets.Rect>} */ turing.deferredsprites.offsets.RECTS = { 'light-00011-0': {x: 2454, y: 0, width: 129, height: 47}, 'light-00011-1': {x: 2583, y: 0, width: 129, height: 47}, 'light-00011-10': {x: 3744, y: 0, width: 129, height: 47}, 'light-00011-11': {x: 3873, y: 0, width: 129, height: 47}, 'light-00011-12': {x: 4002, y: 0, width: 129, height: 47}, 'light-00011-2': {x: 2712, y: 0, width: 129, height: 47}, 'light-00011-3': {x: 2841, y: 0, width: 129, height: 47}, 'light-00011-4': {x: 2970, y: 0, width: 129, height: 47}, 'light-00011-5': {x: 3099, y: 0, width: 129, height: 47}, 'light-00011-6': {x: 3228, y: 0, width: 129, height: 47}, 'light-00011-7': {x: 3357, y: 0, width: 129, height: 47}, 'light-00011-8': {x: 3486, y: 0, width: 129, height: 47}, 'light-00011-9': {x: 3615, y: 0, width: 129, height: 47}, 'light-01001-0': {x: 2454, y: 47, width: 129, height: 47}, 'light-01001-1': {x: 2583, y: 47, width: 129, height: 47}, 'light-01001-10': {x: 3744, y: 47, width: 129, height: 47}, 'light-01001-11': {x: 3873, y: 47, width: 129, height: 47}, 'light-01001-12': {x: 4002, y: 47, width: 129, height: 47}, 'light-01001-2': {x: 2712, y: 47, width: 129, height: 47}, 'light-01001-3': {x: 2841, y: 47, width: 129, height: 47}, 'light-01001-4': {x: 2970, y: 47, width: 129, height: 47}, 'light-01001-5': {x: 3099, y: 47, width: 129, height: 47}, 'light-01001-6': {x: 3228, y: 47, width: 129, height: 47}, 'light-01001-7': {x: 3357, y: 47, width: 129, height: 47}, 'light-01001-8': {x: 3486, y: 47, width: 129, height: 47}, 'light-01001-9': {x: 3615, y: 47, width: 129, height: 47}, 'light-01011-0': {x: 2454, y: 94, width: 129, height: 47}, 'light-01011-1': {x: 2583, y: 94, width: 129, height: 47}, 'light-01011-10': {x: 3744, y: 94, width: 129, height: 47}, 'light-01011-11': {x: 3873, y: 94, width: 129, height: 47}, 'light-01011-12': {x: 4002, y: 94, width: 129, height: 47}, 'light-01011-2': {x: 2712, y: 94, width: 129, height: 47}, 'light-01011-3': {x: 2841, y: 94, width: 129, height: 47}, 'light-01011-4': {x: 2970, y: 94, width: 129, height: 47}, 'light-01011-5': {x: 3099, y: 94, width: 129, height: 47}, 'light-01011-6': {x: 3228, y: 94, width: 129, height: 47}, 'light-01011-7': {x: 3357, y: 94, width: 129, height: 47}, 'light-01011-8': {x: 3486, y: 94, width: 129, height: 47}, 'light-01011-9': {x: 3615, y: 94, width: 129, height: 47}, 'light-10000-0': {x: 2454, y: 141, width: 129, height: 47}, 'light-10000-1': {x: 2583, y: 141, width: 129, height: 47}, 'light-10000-10': {x: 3744, y: 141, width: 129, height: 47}, 'light-10000-11': {x: 3873, y: 141, width: 129, height: 47}, 'light-10000-12': {x: 4002, y: 141, width: 129, height: 47}, 'light-10000-2': {x: 2712, y: 141, width: 129, height: 47}, 'light-10000-3': {x: 2841, y: 141, width: 129, height: 47}, 'light-10000-4': {x: 2970, y: 141, width: 129, height: 47}, 'light-10000-5': {x: 3099, y: 141, width: 129, height: 47}, 'light-10000-6': {x: 3228, y: 141, width: 129, height: 47}, 'light-10000-7': {x: 3357, y: 141, width: 129, height: 47}, 'light-10000-8': {x: 3486, y: 141, width: 129, height: 47}, 'light-10000-9': {x: 3615, y: 141, width: 129, height: 47}, 'scroll-00011-0': {x: 0, y: 47, width: 129, height: 47}, 'scroll-00011-1': {x: 129, y: 47, width: 129, height: 47}, 'scroll-00011-10': {x: 1290, y: 47, width: 129, height: 47}, 'scroll-00011-11': {x: 1419, y: 47, width: 129, height: 47}, 'scroll-00011-12': {x: 1548, y: 47, width: 129, height: 47}, 'scroll-00011-13': {x: 1677, y: 47, width: 129, height: 47}, 'scroll-00011-14': {x: 1806, y: 47, width: 129, height: 47}, 'scroll-00011-15': {x: 1935, y: 47, width: 129, height: 47}, 'scroll-00011-16': {x: 2064, y: 47, width: 129, height: 47}, 'scroll-00011-17': {x: 2193, y: 47, width: 129, height: 47}, 'scroll-00011-18': {x: 2322, y: 47, width: 129, height: 47}, 'scroll-00011-2': {x: 258, y: 47, width: 129, height: 47}, 'scroll-00011-3': {x: 387, y: 47, width: 129, height: 47}, 'scroll-00011-4': {x: 516, y: 47, width: 129, height: 47}, 'scroll-00011-5': {x: 645, y: 47, width: 129, height: 47}, 'scroll-00011-6': {x: 774, y: 47, width: 129, height: 47}, 'scroll-00011-7': {x: 903, y: 47, width: 129, height: 47}, 'scroll-00011-8': {x: 1032, y: 47, width: 129, height: 47}, 'scroll-00011-9': {x: 1161, y: 47, width: 129, height: 47}, 'scroll-01001-0': {x: 0, y: 94, width: 129, height: 47}, 'scroll-01001-1': {x: 129, y: 94, width: 129, height: 47}, 'scroll-01001-10': {x: 1290, y: 94, width: 129, height: 47}, 'scroll-01001-11': {x: 1419, y: 94, width: 129, height: 47}, 'scroll-01001-12': {x: 1548, y: 94, width: 129, height: 47}, 'scroll-01001-13': {x: 1677, y: 94, width: 129, height: 47}, 'scroll-01001-14': {x: 1806, y: 94, width: 129, height: 47}, 'scroll-01001-15': {x: 1935, y: 94, width: 129, height: 47}, 'scroll-01001-16': {x: 2064, y: 94, width: 129, height: 47}, 'scroll-01001-17': {x: 2193, y: 94, width: 129, height: 47}, 'scroll-01001-18': {x: 2322, y: 94, width: 129, height: 47}, 'scroll-01001-2': {x: 258, y: 94, width: 129, height: 47}, 'scroll-01001-3': {x: 387, y: 94, width: 129, height: 47}, 'scroll-01001-4': {x: 516, y: 94, width: 129, height: 47}, 'scroll-01001-5': {x: 645, y: 94, width: 129, height: 47}, 'scroll-01001-6': {x: 774, y: 94, width: 129, height: 47}, 'scroll-01001-7': {x: 903, y: 94, width: 129, height: 47}, 'scroll-01001-8': {x: 1032, y: 94, width: 129, height: 47}, 'scroll-01001-9': {x: 1161, y: 94, width: 129, height: 47}, 'scroll-01011-0': {x: 0, y: 0, width: 129, height: 47}, 'scroll-01011-1': {x: 129, y: 0, width: 129, height: 47}, 'scroll-01011-10': {x: 1290, y: 0, width: 129, height: 47}, 'scroll-01011-11': {x: 1419, y: 0, width: 129, height: 47}, 'scroll-01011-12': {x: 1548, y: 0, width: 129, height: 47}, 'scroll-01011-13': {x: 1677, y: 0, width: 129, height: 47}, 'scroll-01011-14': {x: 1806, y: 0, width: 129, height: 47}, 'scroll-01011-15': {x: 1935, y: 0, width: 129, height: 47}, 'scroll-01011-16': {x: 2064, y: 0, width: 129, height: 47}, 'scroll-01011-17': {x: 2193, y: 0, width: 129, height: 47}, 'scroll-01011-18': {x: 2322, y: 0, width: 129, height: 47}, 'scroll-01011-2': {x: 258, y: 0, width: 129, height: 47}, 'scroll-01011-3': {x: 387, y: 0, width: 129, height: 47}, 'scroll-01011-4': {x: 516, y: 0, width: 129, height: 47}, 'scroll-01011-5': {x: 645, y: 0, width: 129, height: 47}, 'scroll-01011-6': {x: 774, y: 0, width: 129, height: 47}, 'scroll-01011-7': {x: 903, y: 0, width: 129, height: 47}, 'scroll-01011-8': {x: 1032, y: 0, width: 129, height: 47}, 'scroll-01011-9': {x: 1161, y: 0, width: 129, height: 47}, 'scroll-10000-0': {x: 0, y: 141, width: 129, height: 47}, 'scroll-10000-1': {x: 129, y: 141, width: 129, height: 47}, 'scroll-10000-10': {x: 1290, y: 141, width: 129, height: 47}, 'scroll-10000-11': {x: 1419, y: 141, width: 129, height: 47}, 'scroll-10000-12': {x: 1548, y: 141, width: 129, height: 47}, 'scroll-10000-13': {x: 1677, y: 141, width: 129, height: 47}, 'scroll-10000-14': {x: 1806, y: 141, width: 129, height: 47}, 'scroll-10000-15': {x: 1935, y: 141, width: 129, height: 47}, 'scroll-10000-16': {x: 2064, y: 141, width: 129, height: 47}, 'scroll-10000-17': {x: 2193, y: 141, width: 129, height: 47}, 'scroll-10000-18': {x: 2322, y: 141, width: 129, height: 47}, 'scroll-10000-2': {x: 258, y: 141, width: 129, height: 47}, 'scroll-10000-3': {x: 387, y: 141, width: 129, height: 47}, 'scroll-10000-4': {x: 516, y: 141, width: 129, height: 47}, 'scroll-10000-5': {x: 645, y: 141, width: 129, height: 47}, 'scroll-10000-6': {x: 774, y: 141, width: 129, height: 47}, 'scroll-10000-7': {x: 903, y: 141, width: 129, height: 47}, 'scroll-10000-8': {x: 1032, y: 141, width: 129, height: 47}, 'scroll-10000-9': {x: 1161, y: 141, width: 129, height: 47} }; /** * @type {number} * @const */ turing.deferredsprites.offsets.NUM_SCROLL_FRAMES = 19; /** * @type {number} * @const */ turing.deferredsprites.offsets.MIDDLE_SCROLL_FRAME = 9;
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Animates a Turing machine tape. * @author jered@google.com (Jered Wierzbicki) */ goog.require('turing.anim'); goog.require('turing.sprites'); goog.require('turing.util'); goog.provide('turing.Tape'); /** * How many squares of the tape are visible. * Should be odd so that the read/write head is centered. * @type {number} * @const */ turing.NUM_VISIBLE_SQUARES = 9; /** * How many squares of the tape are left of the read/write head. * @type {number} * @const */ turing.NUM_VISIBLE_LEFT_SQUARES = (turing.NUM_VISIBLE_SQUARES - 1) / 2; /** * How many squares of the tape are right of the read/write head and may * scroll into view. Note that this is the number currently visible plus * up to target.length (5) extra squares. This is because when we check for * equality, we start at the beginning of the string and scrollRight until we've * reached the end of the string, possibly revealing an extra 5 squares. * @type {number} * @const */ turing.NUM_VISIBLE_RIGHT_SQUARES = (turing.NUM_VISIBLE_SQUARES - 1) / 2 + 5; /** * Number of extra squares to draw left and right of the fully visible tape * squares. This must be at least two, since we show part of the left neighbor * of the leftmost square while scanning right. * @type {number} * @const */ turing.NUM_MARGIN_SQUARES = 2; /** * How many total squares are on screen, visible or in the margins? * @type {number} * @const */ turing.NUM_SQUARES = turing.NUM_VISIBLE_SQUARES + 2 * turing.NUM_MARGIN_SQUARES; /** * The index of the tape square div under the read/write head when the tape is * stationary. When the tape moves, this div slides left or right, then pops * back into its original position showing a new symbol. * @type {number} * @const */ turing.HEAD_SQUARE = turing.NUM_MARGIN_SQUARES + turing.NUM_VISIBLE_LEFT_SQUARES; /** * Z-index of the tape squares. * @type {number} * @const */ turing.SQUARE_ZINDEX = 400; /** * Left offset for the tape. * @type {number} * @const */ turing.TAPE_LEFT = 63; /** * Top offset for the tape. * @type {number} * @const */ turing.TAPE_TOP = 74; /** * How many pixels of the tape to either side of the visible portion are * partially visible through the slot. * @type {number} * @const */ turing.VISIBLE_FEED_WIDTH = 7; /** * Height of the shadow at the bottom of the tape. * @type {number} * @const */ turing.TAPE_SHADOW_HEIGHT = 4; /** * Duration in ms of scan animation when tape is seeking. * @type {number} * @const */ turing.SEEK_MS = 50; /** * Map from tape symbol to its sprite name. * @type {Object.<string, string>} * @const */ turing.TAPE_SYMBOLS = { '': 'tape_', '_': 'tape_', ' ': 'tape_', '0': 'tape0', '1': 'tape1' }; /** * Sprite sequences to animate symbols being printed. * @type {Object.<string, Array.<string>>} * @const */ turing.PRINT_ANIMATIONS = { '0': ['tape_', 'tape0a', 'tape0b', 'tape0c', 'tape0d', 'tape0'], '1': ['tape_', 'tape1a', 'tape1b', 'tape1c', 'tape1d', 'tape1'] }; /** * Sprite sequences to animate symbols being erased. * @type {Object.<string, Array.<string>>} * @const */ turing.ERASE_ANIMATIONS = { '0': turing.PRINT_ANIMATIONS['0'].slice(0).reverse(), '1': turing.PRINT_ANIMATIONS['1'].slice(0).reverse() }; /** * A Turing machine tape. * @constructor */ turing.Tape = function() { /** * The symbols currently on the tape. * @type {Object.<number, string>} * @private */ this.contents_ = {}; /** * The position of the read/write head. * @type {number} * @private */ this.pos_ = 0; /** * The maximum written tape position. * @type {number} * @private */ this.maxWrittenPosition_ = 0; /** * The location on the tape that the current program started from. * @type {number} * @private */ this.lastStartPos_ = 0; /** * Divs for each visible tape square plus one off each edge. * @type {Array.<Element>} * @private */ this.squares_ = []; /** * A div that holds all the square divs. It is wider than the pane. * @type {Element} * @private */ this.squareHolder_; /** * A div which the square holder moves around inside. * @type {Element} * @private */ this.pane_; /** * A div representing the read/write head. * @type {Element} * @private */ this.readWriteHead_; /** * A div holding the tape squares and head. * @type {Element} * @private */ this.tapeDiv_; /** * A div showing the hole where the left of the tape emerges. * @type {Element} * @private */ this.slotLeft_; /** * A div showing the hole where the right of the tape emerges. * @type {Element} * @private */ this.slotRight_; /** * A div with a shadow to show over the left of the tape. * @type {Element} * @private */ this.shadowLeft_; /** * A div with a shadow to show over the right of the tape. * @type {Element} * @private */ this.shadowRight_; /** * Position currently seeking to, or null if none. * @type {?number} * @private */ this.seekPos_ = null; /** * Is the tape currently scanning left or right? * @type {boolean} * @private */ this.scanning_ = false; }; /** * Attaches tape DOM tree to element. * @param {Element} elem The parent for the tape. */ turing.Tape.prototype.attachTo = function(elem) { this.redrawTape_(); elem.appendChild(this.tapeDiv_); elem.appendChild(this.slotLeft_); elem.appendChild(this.slotRight_); elem.appendChild(this.shadowLeft_); elem.appendChild(this.shadowRight_); }; /** * Create DOM nodes for the tape. */ turing.Tape.prototype.create = function() { var squareSize = turing.sprites.getSize('tape_'); var paneWidth = turing.NUM_VISIBLE_SQUARES * squareSize.width + 2 * turing.VISIBLE_FEED_WIDTH + 2; this.pane_ = turing.sprites.getEmptyDiv(); this.pane_.style.width = paneWidth + 'px'; this.pane_.style.height = squareSize.height + 'px'; this.pane_.style.overflow = 'hidden'; this.pane_.style.left = '0'; this.pane_.style.top = '0'; this.pane_.style.zIndex = turing.SQUARE_ZINDEX; var holderWidth = turing.NUM_SQUARES * squareSize.width; this.squareHolder_ = turing.sprites.getEmptyDiv(); this.squareHolder_.style.width = holderWidth + 'px'; this.squareHolder_.style.left = -turing.NUM_MARGIN_SQUARES * squareSize.width + turing.VISIBLE_FEED_WIDTH + 'px'; // Create visible squares plus extra squares for padding when scrolling. for (var i = 0; i < turing.NUM_SQUARES; i++) { this.squares_[i] = turing.sprites.getDiv('tape_'); this.squares_[i].style.display = 'inline-block'; this.squares_[i].style.position = ''; this.squareHolder_.appendChild(this.squares_[i]); } this.pane_.appendChild(this.squareHolder_); var headSize = turing.sprites.getSize('head'); var extraHeadHeight = headSize.height - squareSize.height; var extraHeadWidth = headSize.width - squareSize.width; this.readWriteHead_ = turing.sprites.getDiv('head'); this.readWriteHead_.style.top = (-extraHeadHeight / 2 - 2) + 'px'; this.readWriteHead_.style.left = turing.VISIBLE_FEED_WIDTH + (turing.NUM_VISIBLE_LEFT_SQUARES * squareSize.width) - extraHeadWidth / 2 + 1 + 'px'; this.readWriteHead_.style.zIndex = turing.SQUARE_ZINDEX + 1; this.tapeDiv_ = turing.sprites.getEmptyDiv(); this.tapeDiv_.style.top = turing.TAPE_TOP + 'px'; this.tapeDiv_.style.left = turing.TAPE_LEFT + 'px'; this.tapeDiv_.appendChild(this.pane_); this.tapeDiv_.appendChild(this.readWriteHead_); this.slotLeft_ = this.createSlot_('slot-left', turing.TAPE_LEFT, -1, squareSize.height); this.slotRight_ = this.createSlot_('slot-right', turing.TAPE_LEFT + paneWidth, 0, squareSize.height); this.shadowLeft_ = this.createShadow_('tape-shadow-l', turing.TAPE_LEFT); this.shadowRight_ = this.createShadow_('tape-shadow-r', turing.TAPE_LEFT + paneWidth - turing.sprites.getSize('tape-shadow-r').width); }; /** * Creates a dom node for a tape slot (a black oval on either side of the tape * where it emerges onto the page). * @param {string} spriteName The sprite to use. * @param {number} leftEdge The left offset of the edge of the tape closest to * this slot. * @param {number} leftBump A small amount by which to move the left coordinate. * Needed because the sizes don't round evenly. * @param {number} squareHeight The height of a tape square. * @return {Element} The slot div. * @private */ turing.Tape.prototype.createSlot_ = function(spriteName, leftEdge, leftBump, squareHeight) { var size = turing.sprites.getSize(spriteName); var slot = turing.sprites.getDiv(spriteName); slot.style.zIndex = turing.SQUARE_ZINDEX - 1; // Behind tape. // On Windows, browsers seem to round 57.5 up to the next pixel right, // which looks wrong, so floor here to match cross platform. slot.style.left = Math.floor(leftEdge - leftBump - size.width / 2) + 'px'; slot.style.top = (turing.TAPE_TOP - turing.TAPE_SHADOW_HEIGHT / 2 + squareHeight / 2 - size.height / 2) + 'px'; return slot; }; /** * Creates a dom node for a tape slot shadow next to the black oval slots. * @param {string} spriteName The sprite to use. * @param {number} leftEdge The left offset of the edge of the tape closest to * this slot. * @return {Element} The slot div. * @private */ turing.Tape.prototype.createShadow_ = function(spriteName, leftEdge) { var slot = turing.sprites.getDiv(spriteName); slot.style.zIndex = turing.SQUARE_ZINDEX + 1; // Above tape. slot.style.left = leftEdge + 'px'; slot.style.top = turing.TAPE_TOP + 'px'; return slot; }; /** * Unbind event listeners, stop timers and tear down DOM. */ turing.Tape.prototype.destroy = function() { for (var i = 0; i < this.squares_.length; i++) { turing.util.removeNode(this.squares_[i]); } this.squares_.splice(0); turing.util.removeNode(this.squareHolder_); this.squareHolder_ = null; turing.util.removeNode(this.pane_); this.pane_ = null; turing.util.removeNode(this.readWriteHead_); this.readWriteHead_ = null; turing.util.removeNode(this.tapeDiv_); this.tapeDiv_ = null; turing.util.removeNode(this.slotLeft_); this.slotLeft_ = null; turing.util.removeNode(this.slotRight_); this.slotRight_ = null; turing.util.removeNode(this.shadowLeft_); this.shadowLeft_ = null; turing.util.removeNode(this.shadowRight_); this.shadowRight_ = null; }; /** * Scrolls the tape to the left. * @param {number} waitTime Delay before scanning starts in ms. * @param {number} scanTime Duration for scan animation in ms. */ turing.Tape.prototype.scanLeft = function(waitTime, scanTime) { this.scanning_ = true; this.pos_--; var squareSize = turing.sprites.getSize('tape_'); var newLeft = -(turing.NUM_MARGIN_SQUARES - 1) * squareSize.width + turing.VISIBLE_FEED_WIDTH; turing.anim.delay(goog.bind(function() { turing.anim.animate(this.squareHolder_, {'left': newLeft + 'px'}, scanTime, goog.bind(this.redrawTape_, this)); }, this), waitTime); }; /** * Scrolls the tape to the right. * @param {number} waitTime Delay before scanning starts in ms. * @param {number} scanTime Duration for scan animation in ms. */ turing.Tape.prototype.scanRight = function(waitTime, scanTime) { this.scanning_ = true; this.pos_++; var squareSize = turing.sprites.getSize('tape_'); var newLeft = -(turing.NUM_MARGIN_SQUARES + 1) * squareSize.width + turing.VISIBLE_FEED_WIDTH; turing.anim.delay(goog.bind(function() { turing.anim.animate(this.squareHolder_, {'left': newLeft + 'px'}, scanTime, goog.bind(this.redrawTape_, this)); }, this), waitTime); }; /** * Scans the tape until it reaches a particular position. This is done by * calling scanLeft/scanRight repeatedly. * @private */ turing.Tape.prototype.seek_ = function() { if (this.seekPos_ == null) { return; } if (this.pos_ < this.seekPos_) { this.scanRight(0, turing.SEEK_MS); } else if (this.pos_ > this.seekPos_) { this.scanLeft(0, turing.SEEK_MS); } else { // We've arrived at the seek position. Nuke everything except the currently // visible portion of the tape. this.seekPos_ = null; this.clearOutsideRange_( this.pos_ - turing.NUM_VISIBLE_LEFT_SQUARES, this.pos_ + turing.NUM_VISIBLE_RIGHT_SQUARES); } }; /** * Clears tape squares not in the range [start, end]. * @param {number} start The position of the first square to keep. * @param {number} end The position of the last square to keep. * @private */ turing.Tape.prototype.clearOutsideRange_ = function(start, end) { for (var i in this.contents_) { i = /** @type {number} */(i); // Reassure the compiler. if (i < start || i > end) { this.contents_[i] = ''; } } }; /** * Prints a symbol at the read/write head position. * @param {string} symbol Symbol to print. * @param {number} eraseTime Duration in ms for erasing old symbol. * @param {number} printTime Duration in ms for printing new symbol. */ turing.Tape.prototype.print = function(symbol, eraseTime, printTime) { var oldSymbol = this.contents_[this.pos_]; this.contents_[this.pos_] = symbol; this.maxWrittenPosition_ = Math.max(this.pos_, this.maxWrittenPosition_); // Always erase the old symbol and then print a new symbol, instead of // animating changing a 0 directly to a 1 or vice versa. this.showErase_(oldSymbol, eraseTime, goog.bind(this.showPrint_, this, symbol, printTime)); }; /** * Shows a symbol being erased from the tape. * @param {string} symbol The symbol to erase. * @param {number} time Duration in ms for erasing animation. * @param {function()} onDone Function to call when done erasing. * @private */ turing.Tape.prototype.showErase_ = function(symbol, time, onDone) { if (symbol == '0' || symbol == '1') { turing.anim.animateFromSprites(this.squares_[turing.HEAD_SQUARE], turing.ERASE_ANIMATIONS[symbol], time, onDone); } else { // Square is already blank. Delay before calling onDone anyway so that // there is a pause between when a print operation circle is lit and when we // show a symbol being printed. turing.anim.delay(onDone, time); } }; /** * Shows a symbol being printed on the tape. * @param {string} symbol The symbol to print. * @param {number} time Duration in ms for printing animation. * @private */ turing.Tape.prototype.showPrint_ = function(symbol, time) { if (symbol == '0' || symbol == '1') { turing.anim.animateFromSprites(this.squares_[turing.HEAD_SQUARE], turing.PRINT_ANIMATIONS[symbol], time, goog.bind(this.redrawSquare_, this, turing.HEAD_SQUARE)); } // Otherwise, assume square has already been erased by showErase_. }; /** * Gets the symbol under the read/write head. * @return {string} The symbol, or '_' if none. */ turing.Tape.prototype.getCurSymbol = function() { return this.contents_[this.pos_] || '_'; }; /** * Appends a string one visible tape width past the last written position on * the tape and scans to there. Used to set up initial tape for a program after * another program has been running for a while. * @param {string} str The desired initial contents of the tape. */ turing.Tape.prototype.setString = function(str) { this.maxWrittenPosition_ += turing.NUM_SQUARES; var start = this.maxWrittenPosition_; // Save this start position so we can reset to the same string if this next // program run is not correct. this.lastStartPos_ = start; this.writeString_(str, start); // We wrote str.length more characters. this.maxWrittenPosition += str.length; this.reinitializePositionOnTape_(str, start); }; /** * Similar to setString but resets to the last program start in-place. * @param {string} str The desired initial contents of the tape. */ turing.Tape.prototype.resetString = function(str) { var start = this.lastStartPos_; this.writeString_(str, start); // Clear everything to the left or right of the string. this.clearOutsideRange_(start, start + str.length - 1); this.reinitializePositionOnTape_(str, start); }; /** * Write the given string to the tape. * @param {string} str The desired contents of the tape. * @param {number} start The position to start writing the string on the tape. * @private */ turing.Tape.prototype.writeString_ = function(str, start) { // Reset the symbols on the tape. for (var i = 0; i < str.length; i++) { this.contents_[start + i] = str.charAt(i); } }; /** * Move to the middle of the current string on the tape. * @param {string} str The current string on the tape. * @param {number} start The start position of the current string on the tape. * @private */ turing.Tape.prototype.reinitializePositionOnTape_ = function(str, start) { this.seekPos_ = start + Math.floor(str.length / 2); if (!this.scanning_) { // If the tape is already scanning, redrawTape will get called when that // animation finishes, and will call seek_ to scan. this.redrawTape_(); } }; /** * @return {number} The index of the first symbol on the tape. * @private */ turing.Tape.prototype.getIndexOfFirstSymbol_ = function() { var minValidPos = null; for (var i in this.contents_) { i = /** @type {number} */(i); // Reassure the compiler. if (this.contents_[i] && this.contents_[i] != '_' && this.contents_[i] != ' ') { if (minValidPos == null) { minValidPos = i; } minValidPos = Math.min(minValidPos, i); } } if (minValidPos == null) { return -1; } return minValidPos; }; /** * Trigger a scan to the square that's offset spaces from the beginning of the * string on the tape and return the contents of that square. * @param {number} offset The number of spaces from the beginning of the string. * @return {string} The contents of the square or the empty string. */ turing.Tape.prototype.scanToAndGetSymbol = function(offset) { var index = this.getIndexOfFirstSymbol_() + offset; if (index == -1) { return ''; } this.seekPos_ = index; this.seek_(); return this.contents_[index]; }; /** * Updates the visible portion of the tape. * @private */ turing.Tape.prototype.redrawTape_ = function() { this.scanning_ = false; var squareSize = turing.sprites.getSize('tape_'); // Also set up the invisible squares just off the edges of the tape. for (var i = 0; i < turing.NUM_SQUARES; i++) { this.redrawSquare_(i); } this.squareHolder_.style.left = -turing.NUM_MARGIN_SQUARES * squareSize.width + turing.VISIBLE_FEED_WIDTH + 'px'; this.seek_(); }; /** * Redraws one square on the tape. * @param {number} i Index among _drawn_ squares. * @private */ turing.Tape.prototype.redrawSquare_ = function(i) { var offs = (i + this.pos_) - turing.HEAD_SQUARE; var symbol = this.contents_[offs] || ''; var spriteName = turing.TAPE_SYMBOLS[symbol]; this.squares_[i].style.background = turing.sprites.getBackground(spriteName); }; /** * Slides the entire tape assembly up to the top of the display area. * Used to make room for larger programs in bonus mode. */ turing.Tape.prototype.slideUp = function() { // 7px from the bottom of the tooltip. turing.anim.animate(this.tapeDiv_, {'top': '27px'}, 200); turing.anim.animate(this.shadowLeft_, {'top': '27px'}, 200); turing.anim.animate(this.shadowRight_, {'top': '27px'}, 200); turing.anim.animate(this.slotLeft_, {'top': '21px'}, 200); turing.anim.animate(this.slotRight_, {'top': '21px'}, 200); };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Offsets for the number plate sprite. * @author corrieann@google.com (Corrie Scalisi) */ goog.provide('turing.sprites.numberplate'); goog.require('turing.sprites'); goog.require('turing.sprites.offsets'); /** * The width of the number plate. * @type {number} * @const * @private */ turing.sprites.numberplate.WIDTH_ = 129; /** * Gets the CSS background for the given unlit number plate. * @param {string} target The target. * @return {string} The CSS background string. */ turing.sprites.numberplate.getUnlitNumberPlate = function(target) { return turing.sprites.getBackground('light-' + target + '-0'); }; /** * Return the background for the given number target and digit combination. * If the length of the target (5) is passed in, then the sprite representing * the entire string will be returned. * @param {string} target The target. * @param {number} digit The digit we care about right now. * @param {boolean} fullyLit Whether the digit should be fully lit. * @return {string} The CSS background string. */ turing.sprites.numberplate.getLitTargetForDigit = function( target, digit, fullyLit) { // The column number of the unlit version of that digit. // We always add at least 1 because the first column has no digits lit. var digitXOffset = digit * 2 + (fullyLit ? 2 : 1); return turing.sprites.getBackground('light-' + target + '-' + digitXOffset); }; /** * Get an array of backgrounds used to animate scrolling of the given target. * Grabs the first one from the main sprite and triggers a load of the sprites * with the other number plates. * @param {string} target The target. * @param {boolean} scrollIn Whether the target should scroll in, scrolls out if * false. * @return {Array.<string>} The CSS backgrounds. */ turing.sprites.numberplate.getScrollingTarget = function(target, scrollIn) { var backgrounds = []; for (var i = 0; i <= turing.deferredsprites.offsets.MIDDLE_SCROLL_FRAME; i++) { var col = scrollIn ? i : turing.deferredsprites.offsets.MIDDLE_SCROLL_FRAME + i; backgrounds.push(turing.sprites.getBackground( 'scroll-' + target + '-' + col)); } return backgrounds; };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Simulates a Turing machine program running. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.Simulator'); goog.require('turing.Program'); goog.require('turing.Tape'); goog.require('turing.anim'); /** * Speed settings the simulator can run at. * @enum {number} */ turing.SpeedSetting = { SLOW: 0, TUTORIAL: 1, NORMAL: 2, FAST: 3, LUDICROUS: 4 }; /** * Configuration for a simulator speed setting. * - stepTime: ms between simulation steps that do something. * - emptyStepTime: ms between no-op steps. * - tapeTime: ms for a tape operation. * - branchTime: ms for a branch operation. * @typedef {{stepTime: number, tapeTime: number, emptyStepTime: number, * branchTime: number}} * @private */ turing.Speeds; /** * The definitions for speed settings. * @type {Object.<turing.SpeedSetting, turing.Speeds>} * @const */ turing.SPEED_CONFIG = { 0 /* SLOW */: { stepTime: 750, tapeTime: 600, emptyStepTime: 400, branchTime: 850 }, 1 /* TUTORIAL */: { stepTime: 650, tapeTime: 500, emptyStepTime: 200, branchTime: 750 }, 2 /* NORMAL */: { stepTime: 450, tapeTime: 300, emptyStepTime: 200, branchTime: 550 }, 3 /* FAST */: { stepTime: 250, tapeTime: 200, emptyStepTime: 100, branchTime: 250 }, 4 /* LUDICROUS */: { stepTime: 100, tapeTime: 50, emptyStepTime: 100, branchTime: 100 } }; /** * How many times an operation can be repeated before it gets somewhat boring. * @type {number} * @const */ turing.SOMEWHAT_BORING_REPEAT_COUNT = 4; /** * How many times an operation can be repeated before it gets very boring. * @type {number} * @const */ turing.VERY_BORING_REPEAT_COUNT = 6; /** * Simulates programs. * @constructor */ turing.Simulator = function() { /** * The currently running program. * @type {turing.Program} * @private */ this.program_ = null; /** * The currently simulating tape. * @type {turing.Tape} * @private */ this.tape_ = null; /** * The id of the timeout which will step the program forward one step. * @type {number} * @private */ this.stepTimerId_ = -1; /** * Function to call when the program is done. * @type {?function()} * @private */ this.doneCallback_ = null; /** * Steps this program has run. * @type {number} * @private */ this.stepCount_ = 0; /** * Steps the program may run before we terminate it. * @type {number} * @private */ this.stepLimit_ = 0; /** * Maps from program locations to how many time operations at that location * have been run. * @type {Object.<string, number>} * @private */ this.runCount_ = {}; /** * How fast the simulation is going. * @type {turing.Speeds} * @private */ this.speeds_ = turing.SPEED_CONFIG[turing.SpeedSetting.NORMAL]; /** * True iff simulation is currently paused. * @type {boolean} * @private */ this.paused_ = false; }; /** * Returns whether the simulator is stepping the program. * @return {boolean} True iff the program is currently running. */ turing.Simulator.prototype.isRunning = function() { return this.stepTimerId_ != -1; }; /** * Sets a limit for the number of steps a program may execute. * @param {number} limit The number of steps, or 0 for no limit. */ turing.Simulator.prototype.setStepLimit = function(limit) { this.stepLimit_ = limit; }; /** * Used to check if the simulator will run until explicitly stopped, which is * the case in demo mode and when showing the bonus program. * @return {boolean} True iff the simulator has a step limit, false if it may * run forever. */ turing.Simulator.prototype.hasStepLimit = function() { return this.stepLimit_ != 0; }; /** * Starts running a program. * @param {turing.Program} program Program to run. * @param {turing.Tape} tape Tape for I/O. * @param {turing.SpeedSetting} speed How fast to run. * @param {function()=} opt_doneCallback Function to call when program halts or * times out. */ turing.Simulator.prototype.run = function(program, tape, speed, opt_doneCallback) { if (this.isRunning()) { return; } // Start at the first instruction. program.setNextPos(0, 0); this.speeds_ = turing.SPEED_CONFIG[speed]; this.stepCount_ = 0; this.runCount_ = {}; this.stepTimerId_ = turing.anim.delay(goog.bind(this.step, this), 0); this.program_ = program; this.tape_ = tape; this.doneCallback_ = opt_doneCallback || null; }; /** * Immediately stops running the current program, if running. */ turing.Simulator.prototype.stop = function() { if (this.stepTimerId_ != -1) { turing.anim.cancel(this.stepTimerId_); } this.stepTimerId_ = -1; this.program_ = null; this.tape_ = null; if (this.doneCallback_) { this.doneCallback_(); this.doneCallback_ = null; } }; /** * Pauses simulation: cancels the next step call, but does not reset any state. */ turing.Simulator.prototype.pause = function() { if (this.stepTimerId_ != -1) { turing.anim.cancel(this.stepTimerId_); } this.stepTimerId_ = -1; this.paused_ = true; }; /** * Resumes simulation at the next step. */ turing.Simulator.prototype.resumeIfPaused = function() { if (this.paused_) { this.stepTimerId_ = turing.anim.delay(goog.bind(this.step, this), 0); } this.paused_ = false; }; /** * Advances program simulation by one step. */ turing.Simulator.prototype.step = function() { if (!this.tape_ || !this.program_ || this.stepTimerId_ == -1) { return; } this.stepTimerId_ = -1; // Dim the current instruction and highlight the next (if not at end). Note // that this only changes the value of the current pos, not the next pos; // the next pos here is set by setNextPos from the previous call. this.program_.goToNextPos(); if (this.program_.isNextPosEnd() || (this.stepLimit_ > 0 && this.stepCount_ > this.stepLimit_)) { // Simulation stops when we try to move to an invalid position or run for // more than a maximum number of steps. // We must explicitly dim the current lit up op in case we exceeded the step // count (the Program object doesn't know this, so it will still be lit // after the goToNextPos call above.) this.program_.dimCurOp(); this.stop(); return; } if (this.stepLimit_ > 0) { // Only accelerate boring loops when they might be unintentional infinite // loops (i.e., when a step limit is set). this.speedUpBoringLoops_(); } this.stepCount_++; var op = this.program_.getCurOp(); if (op && op.charAt(0) == '*') { op = op.substr(1); } var implicitStep = true; // Most ops implicitly step one position. // Tape ops update tape state immediately, but take speeds_.tapeTime ms // to animate. Spend half the total animation time setting up (erasing before // printing or delaying before moving) and the other half animating, so that // there's a delay between when the op is lit and when it seems to happen. var tapeWaitTime = this.speeds_.tapeTime / 2; var tapeExecuteTime = this.speeds_.tapeTime / 2; if (op == '0' || op == '1' || op == '_') { this.tape_.print(op, tapeWaitTime, tapeExecuteTime); } else if (op == 'L') { this.tape_.scanLeft(tapeWaitTime, tapeExecuteTime); } else if (op == 'R') { this.tape_.scanRight(tapeWaitTime, tapeExecuteTime); } else if (/B[2-9]/.test(op)) { // Regexp matches a B followed by a digit from 2 to 9, which are allowable // branch offsets. Normal game programs only use B2-4, but our bonus program // needs longer branch offsets. this.program_.setNextPos(this.program_.getCurTrack(), this.program_.getCurTrackPos() - parseInt(op.charAt(1), 10)); implicitStep = false; } else if (/^D/.test(op)) { // 'Dx' jumps down one track if the current symbol is 'x'. 'D' by itself // jumps down unconditionally. if (op.length == 1 || this.tape_.getCurSymbol() == op.charAt(1)) { this.program_.setNextPos(this.program_.getCurTrack() + 1, this.program_.getCurTrackPos()); implicitStep = false; } } else if (/^U/.test(op)) { // 'Ux' jumps up one track if the current symbol is 'x'. 'U' by itself jumps // up unconditionally. if (op.length == 1 || this.tape_.getCurSymbol() == op.charAt(1)) { this.program_.setNextPos(this.program_.getCurTrack() - 1, this.program_.getCurTrackPos()); implicitStep = false; } } if (implicitStep) { this.program_.setNextPos(this.program_.getCurTrack(), this.program_.getCurTrackPos() + 1); } var stepTime = this.speeds_.stepTime; if (!op) { stepTime = this.speeds_.emptyStepTime; } else if (/^[UDB]/.test(op)) { // /^[UDB]/ matches a U, D or B at the start of op, which are branch // operations. stepTime = this.speeds_.branchTime; } this.stepTimerId_ = turing.anim.delay(goog.bind(this.step, this), stepTime); }; /** * Detects if the program has gotten stuck in a boring loop, and speeds up if * so. A loop is "somewhat boring" when the same operation has been repeated * more than 4 times (since game programs are only supposed to change 5 squares * on the tape, this is about right), and "very boring" when it has been * repeated more than 6 times. This speed boost only applies to the current * run() call, and speeds and operation run counts are reset at the beginning of * the next run. * @private */ turing.Simulator.prototype.speedUpBoringLoops_ = function() { var pc = this.program_.getCurTrack() + ',' + this.program_.getCurTrackPos(); var count = this.runCount_[pc] || 0; this.runCount_[pc] = count + 1; if (count > turing.VERY_BORING_REPEAT_COUNT) { // We have to go straight to ludicrous speed. this.speeds_ = turing.SPEED_CONFIG[turing.SpeedSetting.LUDICROUS]; } else if (count > turing.SOMEWHAT_BORING_REPEAT_COUNT) { // This is getting boring, speed it up. this.speeds_ = turing.SPEED_CONFIG[turing.SpeedSetting.FAST]; } };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Samples points on cubic Bézier curves. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.CubicBezier'); /** * How many points to pre-compute for evaluating curves. * This can be a fairly low number, since a 1 second animation at 60Hz will * update only about 60 times, and most of our animations are short. * @type {number} * @const */ turing.BEZIER_SAMPLES = 120; /** * The resolution for numerically solving the "x" polynomial when sampling. * I picked this value by staring at curves until they looked smooth. * @type {number} * @const */ turing.BEZIER_EPSILON = 0.0001; /** * How to evaluate curves. Different platforms have widely varying floating * point and Javascript performance. Here are times (in us) for some different * platforms for each of these methods: * Platform Solve Linear Nearest * MacBook Pro 150 88 18 * iPad1 3939 1258 692 * Nexus S 1074 616 252 * @enum {number} */ turing.BezierEvaluation = { SOLVE: 0, NEAREST_INTERP: 1, LINEAR_INTERP: 2 }; /** * Evaluates a cubic Bézier curve, * B(t) = (1-t)^3 P0 + 3(1-t)^2 t P1 + 3(1-t) t^2 P2 + t^3 P3, t in [0,1], * at positions x in [0,1] given P0=(0,0), P3=(1,1), and P1 and P2 specified. * Used for animation timing in browsers that do not support CSS transitions. * Based on WebKit: * trac.webkit.org/browser/trunk/Source/WebCore/platform/graphics/UnitBezier.h * @param {number} p1x x-coordinate of P1. * @param {number} p1y y-coordinate of P1. * @param {number} p2x x-coordinate of P2. * @param {number} p2y y-coordinate of P2. * @param {turing.BezierEvaluation} evalMode How to evaluate. * @constructor */ turing.CubicBezier = function(p1x, p1y, p2x, p2y, evalMode) { /** * Coefficients of the x polynomial. * @type {Array.<number>} * @private */ this.xCoefs_ = this.getCoefs_(p1x, p2x); /** * Coefficients of the y polynomial. * @type {Array.<number>} * @private */ this.yCoefs_ = this.getCoefs_(p1y, p2y); /** * How to evaluate the curve. * @type {turing.BezierEvaluation} * @private */ this.evalMode_ = evalMode; /** * Sampled points on the curve. * @type {Array.<number>} * @private */ this.samples_ = this.evalMode_ != turing.BezierEvaluation.SOLVE ? this.precompute_() : []; }; /** * Converts parametric form to an explicit polynomial. * @param {number} p1 The first parameteric point. * @param {number} p2 The second parameteric point. * @return {Array.<number>} Coefficients for an explicit polynomial. * @private */ turing.CubicBezier.prototype.getCoefs_ = function(p1, p2) { var c = 3 * p1; var b = 3 * (p2 - p1) - c; var a = 1 - c - b; return [a, b, c]; }; /** * Precomputes a table of (x, y) positions on the curve. * @return {Array.<number>} y coordinates on the curve for x positions in [0,1], * with indices of x * BEZIER_SAMPLES. * @private */ turing.CubicBezier.prototype.precompute_ = function() { var samples = []; for (var i = 0; i < turing.BEZIER_SAMPLES; i++) { var x = i / turing.BEZIER_SAMPLES; samples[i] = this.evaluate_(this.yCoefs_, this.solve_(x)); } return samples; }; /** * Samples the curve. * @param {number} x The x value to evaluate. * @return {number} The y value near there. */ turing.CubicBezier.prototype.sample = function(x) { if (this.evalMode_ == turing.BezierEvaluation.NEAREST_INTERP) { return this.sampleNearest_(x); } else if (this.evalMode_ == turing.BezierEvaluation.LINEAR_INTERP) { return this.sampleLinear_(x); } else { return this.evaluate_(this.yCoefs_, this.solve_(x)); } }; /** * Picks the nearest precomputed sample to get the y value of the curve near x * in [0,1]. * @param {number} x The x value to evaluate. * @return {number} The y value near there. * @private */ turing.CubicBezier.prototype.sampleNearest_ = function(x) { var s = Math.floor(x * turing.BEZIER_SAMPLES); return s < 0 ? 0 : (s >= turing.BEZIER_SAMPLES ? 1 : this.samples_[s]); }; /** * Uses linear interpolation between precomputed samples to get the y value of * the curve near x in [0,1]. * @param {number} x The x value to evaluate. * @return {number} The y value near there. * @private */ turing.CubicBezier.prototype.sampleLinear_ = function(x) { var s = x * turing.BEZIER_SAMPLES; // The sample number. var sLeft = Math.floor(s); var sRight = Math.ceil(s); if (sLeft < 0) { // x < 0: The leftmost point is fixed at (0,0). return 0; } else if (sLeft >= turing.BEZIER_SAMPLES) { // x >= 1: The rightmost point is fixed at (1,1). return 1; } else if (sLeft == sRight) { // x is exactly on a sample. return this.samples_[sLeft]; } else { // Linearly interpolate between the nearest samples to x. return ((sRight - s) * this.samples_[sLeft] + (s - sLeft) * this.samples_[sRight]); } }; /** * Evaluates a t^3 + b t^2 + c t expanded using Horner's rule. * @param {Array.<number>} coefs Coefficients [a, b, c]. * @param {number} t Input for polynmoial. * @return {number} The value of the polynomial. * @private */ turing.CubicBezier.prototype.evaluate_ = function(coefs, t) { return ((coefs[0] * t + coefs[1]) * t + coefs[2]) * t; }; /** * Evaluates the derivative of a t^3 + b t^2 + c t. * @param {Array.<number>} coefs Coefficients [a, b, c]. * @param {number} t Input for polynmoial. * @return {number} The value of the derivative polynomial. * @private */ turing.CubicBezier.prototype.evaluateDerivative_ = function(coefs, t) { return (3 * coefs[0] * t + 2 * coefs[1]) * t + coefs[2]; }; /** * Solves a t^3 + b t^2 + c t = x for t. * @param {number} x x position to solve for. * @return {number} The t (parameter) value corresponding to a given x. * @private */ turing.CubicBezier.prototype.solve_ = function(x) { var t0; var t1; var t2; var x2; var d2; var i; // First try a few iterations of Newton's method -- normally very fast. for (t2 = x, i = 0; i < 8; i++) { x2 = this.evaluate_(this.xCoefs_, t2) - x; if (Math.abs(x2) < turing.BEZIER_EPSILON) { return t2; } d2 = this.evaluateDerivative_(this.xCoefs_, t2); if (Math.abs(d2) < 1e-6) { break; } t2 = t2 - x2 / d2; } // Fall back to the bisection method for reliability. t0 = 0.0; t1 = 1.0; t2 = x; if (t2 < t0) { return t0; } if (t2 > t1) { return t1; } while (t0 < t1) { x2 = this.evaluate_(this.xCoefs_, t2); if (Math.abs(x2 - x) < turing.BEZIER_EPSILON) { return t2; } if (x > x2) { t0 = t2; } else { t1 = t2; } t2 = (t1 - t0) * .5 + t0; } // Failure. return t2; };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A clickable overlay covering the entire doodle area. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.Overlay'); goog.require('turing.sprites'); goog.require('turing.util'); /** * The z-index for the overlay div. Should be on top of everything else. * @type {number} * @const */ turing.OVERLAY_ZINDEX = 500; /** * An invisible div on top of the doodle in its passive mode. * @constructor */ turing.Overlay = function() { /** * An empty div element which fills its parent. * @type {Element} * @private */ this.div_; /** * Event listener for clicks. * @type {?function()} * @private */ this.clickHandler_; /** * Called to report a click to an observer. * @type {function()} * @private */ this.callback_; }; /** * Creates overlay div and registers a click event listener on it. * @param {Element} logoContainer Element to overlay; used for sizing. */ turing.Overlay.prototype.create = function(logoContainer) { this.div_ = turing.sprites.getEmptyDiv(); this.div_.style.width = logoContainer.offsetWidth + 'px'; this.div_.style.height = logoContainer.offsetHeight + 'px'; this.div_.style.cursor = 'pointer'; this.div_.style.zIndex = turing.OVERLAY_ZINDEX; this.clickHandler_ = goog.bind(this.onClick, this); turing.util.listen(this.div_, 'click', this.clickHandler_); }; /** * Destroys dom elements and cleans up event listeners. */ turing.Overlay.prototype.destroy = function() { turing.util.unlisten(this.div_, 'click', this.clickHandler_); turing.util.removeNode(this.div_); this.clickHandler_ = null; this.div_ = null; }; /** * Attaches to dom and sets click action. * @param {Element} elem Parent. * @param {function()} callback Called on a click. */ turing.Overlay.prototype.attachTo = function(elem, callback) { elem.appendChild(this.div_); this.callback_ = callback; }; /** * Event listener for clicks on the overlay. */ turing.Overlay.prototype.onClick = function() { this.destroy(); this.callback_(); };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Lightweight helper library for animation. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.anim'); goog.require('turing.sprites'); goog.require('turing.util'); /** * Iff true, do not schedule any more animations. * @type {boolean} * @private */ turing.anim.stopped_ = true; /** * A list of pending animation frames. * @type {Array.<Object>} * @private */ turing.anim.queue_ = []; /** * True iff there were more frames queued this tick and the queue needs to be * resorted. * @type {boolean} * @private */ turing.anim.queueDirty_ = false; /** * The current animation tick. * @type {number} * @private */ turing.anim.curTick_ = 0; /** * The next event id. * @private * @type {number} */ turing.anim.eventId_ = 1; /** * The time when the last animation tick started. * @type {number} * @private */ turing.anim.lastTickStartTime_ = 0; /** * A count of recent ticks which were were longer than the current target. * @type {number} * @private */ turing.anim.tooSlowTicks_ = 0; /** * Inverse of the maximum frame rate (60 Hz). * @type {number} * @private * @const */ turing.anim.MAX_FPS_MS_ = 1000 / 60; /** * Inverse of the minimum frame rate (20 Hz). * The game is functional, but really laggy to play below this frame rate. We'll * never schedule animations slower than this. * @type {number} * @private * @const */ turing.anim.MIN_FPS_MS_ = 1000 / 20; /** * The interval at which the next frame will be rescheduled. This is controlled * by throttleFrameRate_. * @type {number} * @private */ turing.anim.msPerFrame_ = turing.anim.MAX_FPS_MS_; /** * The name of the CSS3 transition property, or undefined if transitions are * unsupported. * @type {string|undefined} * @private */ turing.anim.transitionPropertyName_ = turing.util.getVendorCssPropertyName( 'transition'); /** * Map from CSS properties we know how to animate to the units we expect will be * attached. Used to trim units off and add them back when interpolating values. * @type {Object.<string, string>} */ turing.anim.UNITS = { 'top': 'px', 'left': 'px' }; /** * How to schedule the next animation frame. * @type {function(function())} */ window['requestAnimationFrame'] = (function() { return window['requestAnimationFrame'] || window['webkitRequestAnimationFrame'] || window['mozRequestAnimationFrame'] || window['oRequestAnimationFrame'] || window['msRequestAnimationFrame'] || function(callback) { // Binding this on window because Chrome gets cross if we do not. // If we have nothing better, just do a setTimeout; the caller should be // careful to check turing.anim.stopped_. It is not checked here because // it'd be weird to export that behavior. window.setTimeout(callback, turing.anim.msPerFrame_); }; })(); /** * @param {number} duration A duration in ms. * @return {number} The corresponding number of ticks at the current frame rate. * @private */ turing.anim.getNumTicks_ = function(duration) { return Math.ceil(duration / turing.anim.msPerFrame_); }; /** * Schedules callback to be run after a duration in ms. * @param {function()} callback The function to call when delay is elapsed. * @param {number} duration How long to wait in ms. * @return {number} An id for the event to be delayed. */ turing.anim.delay = function(callback, duration) { // Count ticks to wait based on the current frame rate. return turing.anim.delayTicks(callback, turing.anim.getNumTicks_(duration)); }; /** * Schedules callback to be run after a duration in animation ticks. * @param {function()} callback The function to call when delay is elapsed. * @param {number} ticksToWait How long to wait in animation loop ticks. * @return {number} An id for the event to be delayed. */ turing.anim.delayTicks = function(callback, ticksToWait) { var eventId = turing.anim.eventId_++; turing.anim.queue_.push({ ticks: turing.anim.curTick_ + ticksToWait, call: callback, eventId: eventId }); turing.anim.queueDirty_ = true; return eventId; }; /** * Cancels a pending event previously scheduled with some delay. * @param {number} eventId The id of the event in the animation queue. */ turing.anim.cancel = function(eventId) { for (var i = 0; i < turing.anim.queue_.length; i++) { if (turing.anim.queue_[i].eventId == eventId) { turing.anim.queue_.splice(i, 1); return; } } }; /** * Animates CSS properties on an element. * @param {Element} elem The element to animate. * @param {Object.<string, string>} properties CSS property names -> new values. * @param {number} duration How long the animation should run. * @param {function()=} opt_doneCallback Called when animation is done. */ turing.anim.animate = function(elem, properties, duration, opt_doneCallback) { var initialValue = {}; var finalValue = {}; for (var name in properties) { initialValue[name] = parseFloat(elem.style[name] || 0); finalValue[name] = parseFloat(properties[name]); } // Schedule ticks based on the current frame rate. var numTicks = turing.anim.getNumTicks_(duration); for (var tick = 0; tick <= numTicks; tick++) { var progress = Math.min(1, tick / numTicks); for (var name in properties) { turing.anim.delayTicks(goog.bind(function(progress) { var interp = (1 - progress) * initialValue[name] + progress * finalValue[name]; var value = interp + (turing.anim.UNITS[name] || ''); elem.style[name] = value; }, window, progress), tick); } } if (opt_doneCallback) { turing.anim.delayTicks(opt_doneCallback, numTicks); } }; /** * Sets the CSS3 transition property for an element or does nothing if * transitions aren't supported. * @param {Element} elem The element to set transition for. * @param {string} transitionValue The css value for transition. */ turing.anim.setTransitionStyle = function(elem, transitionValue) { if (turing.anim.transitionPropertyName_) { elem.style[turing.anim.transitionPropertyName_] = transitionValue; } }; /** * Clears CSS3 transitions on elem. * @param {Element} elem The element to clear transitions for. */ turing.anim.clearTransitionStyle = function(elem) { // Opera doesn't seem to completely support removing an animation // (setting it to 'none' still causes a delay when changing the left // offset), so instead set a dummy property to animate for. turing.anim.setTransitionStyle(elem, 'clear 0ms linear'); }; /** * Animates changing the sprite used for an element background. Goes through * the background list, retrieving the sprite background, and then calls * animateThroughBackgrounds. * @param {Element} elem The element to animate. * @param {Array.<string>} spriteNames The names of the desired elements in the * sprite to iterate through. * @param {number} duration How long the animation should run. * @param {function()=} opt_doneCallback Called when animation is done. */ turing.anim.animateFromSprites = function(elem, spriteNames, duration, opt_doneCallback) { var backgrounds = []; for (var i = 0; i < spriteNames.length; i++) { backgrounds[i] = turing.sprites.getBackground(spriteNames[i]); } turing.anim.animateThroughBackgrounds( elem, backgrounds, duration, opt_doneCallback); }; /** * Animates changing the backgrounds of an element. * @param {Element} elem The element to animate. * @param {Array.<string>} backgrounds The CSS backgrounds to iterate through. * @param {number} duration How long the animation should run. * @param {function()=} opt_doneCallback Called when animation is done. */ turing.anim.animateThroughBackgrounds = function(elem, backgrounds, duration, opt_doneCallback) { // Schedule ticks based on the current frame rate. var numTicks = turing.anim.getNumTicks_(duration); for (var tick = 0; tick <= numTicks; tick++) { var progress = Math.min(1, tick / numTicks); turing.anim.delayTicks(goog.bind(function(progress) { elem.style.background = backgrounds[ Math.min(backgrounds.length - 1, Math.floor(progress * backgrounds.length))]; }, window, progress), tick); } if (opt_doneCallback) { turing.anim.delayTicks(opt_doneCallback, numTicks); } }; /** * A monolithic animation loop implemented using requestAnimationFrame. At each * tick, it runs any functions deferred til this tick. * * All deferred calls are scheduled to run from this loop so that the game * simulation and animation update synchronously without being explicitly * stitched together through callbacks everywhere. * * We also tried an asynchronous approach, using CSS3 transitions and * requestAnimationFrame to update animations and separate setTimeout calls to * run the game. This performed better, but degraded poorly; there were odd * skips in animation, and weird behavior when changing browser tabs since * requestAnimationFrame and setTimeout turn down differently. With this * approach, the game slows down uniformly under load. * * @private */ turing.anim.loop_ = function() { window.requestAnimationFrame(function step() { if (turing.anim.stopped_) { return; } // Note we must do this even when using requestAnimationFrame, because it // isn't 60 Hz everywhere, and we may need to throttle down to its actual // rate for our delays to make sense. turing.anim.throttleFrameRate_(); if (turing.anim.queueDirty_) { // We'd like to keep frames in a priority queue but don't want to bother, // so just sort the frame queue when it changes. turing.anim.queue_.sort(function(a, b) { if (a.ticks == b.ticks) { // Guarantee the sort is stable. return a.eventId - b.eventId; } return a.ticks - b.ticks; }); turing.anim.queueDirty_ = false; } var numFrames = 0; for (var i = 0, frame; frame = turing.anim.queue_[i]; i++) { if (frame.ticks <= turing.anim.curTick_) { frame.call(); numFrames++; } else { break; } } turing.anim.queue_.splice(0, numFrames); turing.anim.curTick_++; window.requestAnimationFrame(step); }); }; /** * Measures and controls the interval between frames. * @private */ turing.anim.throttleFrameRate_ = function() { var tickStartTime = new Date().getTime(); // At the start of the doodle, wait until things stabilize a bit (i.e. the // page finishes loading) before throttling the frame rate. Arbitrarily guess // this happens after 30 frames (which is nominally ~0.5 seconds). // Also check that lastTickStartTime is non-zero, since it will be reset to // zero if the animation loop is stopped for any reason (and then tickLength // below would be invalid). if (turing.anim.curTick_ > 30 && turing.anim.lastTickStartTime_) { var tickLength = tickStartTime - turing.anim.lastTickStartTime_; if (tickLength >= 1.05 * turing.anim.msPerFrame_) { // The last tick was too slow. turing.anim.tooSlowTicks_++; } else { // The last tick was within tolerance. turing.anim.tooSlowTicks_ = turing.anim.tooSlowTicks_ >> 1; } if (turing.anim.tooSlowTicks_ > 20) { // Animation consistently isn't making our target frame rate; slow down // frame rate by 20% up to a minimum frame rate. turing.anim.msPerFrame_ = Math.min(turing.anim.MIN_FPS_MS_, turing.anim.msPerFrame_ * 1.2); turing.anim.tooSlowTicks_ = 0; } } turing.anim.lastTickStartTime_ = tickStartTime; }; /** * Start animation loop. */ turing.anim.start = function() { turing.anim.stopped_ = false; turing.anim.loop_(); }; /** * Resets controller state for frames-per-second throttling. * @private */ turing.anim.resetFpsController_ = function() { turing.anim.tooSlowTicks_ = 0; // Wait for a tick before measuring the interval between two ticks. turing.anim.lastTickStartTime_ = 0; }; /** * Emergency brake; stop animation loop next time through. */ turing.anim.stop = function() { turing.anim.stopped_ = true; turing.anim.resetFpsController_(); }; /** * Stops the animation loop and cancels any queued animations. */ turing.anim.reset = function() { turing.anim.stop(); turing.anim.queue_ = []; turing.anim.curTick_ = 0; turing.anim.queueDirty_ = false; turing.anim.eventId_ = 1; turing.anim.msPerFrame_ = turing.anim.MAX_FPS_MS_; turing.anim.resetFpsController_(); }; /** * @return {boolean} True iff animations are stopped. */ turing.anim.isStopped = function() { return turing.anim.stopped_; };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Shows Turing machine programs as rows of operations. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.Program'); goog.require('turing.anim'); goog.require('turing.sprites'); goog.require('turing.util'); /** * Number of rows of operations displayed in each mode. * @type {Object.<string, number>} * @const */ turing.NUM_PROGRAM_TRACKS = { normalMode: 2, bonusMode: 3 }; /** * Number of operations per track in each mode. Some may be blank. * @type {Object.<string, number>} * @const */ turing.NUM_OPS_PER_TRACK = { normalMode: 8, bonusMode: 13 }; /** * Left offset of program tracks. * @type {number} * @const */ turing.TRACK_LEFT = 74; /** * Width of a bonus mode track. As wide as the doodle will allow. * @type {number} * @const */ turing.BONUS_TRACK_WIDTH = 500; /** * Center vertical offsets of the buttons for each track. * @type {Array.<number>} * @const * @private */ turing.TRACK_BUTTON_VERTICAL_MIDDLE_ = [150, 194]; /** * Center vertical offsets of the buttons for each track in bonus mode. * @type {Array.<number>} * @const * @private */ turing.BONUS_TRACK_BUTTON_VERTICAL_MIDDLE_ = [100, 140, 180]; /** * Delay in ms for an op button to push in when pressed. * This ought to be short because the user has already done something. * @type {number} * @const */ turing.OP_PUSH_IN_DELAY = 20; /** * Delay in ms for an op button to pop out when released. * @type {number} * @const */ turing.OP_POP_OUT_DELAY = 20; /** * Pixels of padding left of the first circle on the track. This is subtracted * from total track width so that circles are centered in the non-padding area. * @type {number} * @const */ turing.TRACK_LEFT_PAD = 31; /** * Pixels of padding right of the last circle on the track. This is subtracted * from total track width so that circles are centered in the non-padding area. * @type {number} * @const */ turing.TRACK_RIGHT_PAD = 9; /** * Pixels of padding top above the track in the track image. * @type {number} * @const */ turing.TRACK_TOP_PAD = 4; /** * The number of operations per program track in the current mode. * @type {number} * @private */ turing.numOpsPerTrack_ = turing.NUM_OPS_PER_TRACK.normalMode; /** * The number of program tracks in the current mode. * @type {number} * @private */ turing.numTracks_ = turing.NUM_PROGRAM_TRACKS.normalMode; /** * True if the game is done and we are running in bonus mode, else false if we * are in the normal mode. * @type {boolean} * @private */ turing.inBonusMode_ = false; /** * Sets up program display for bonus mode. */ turing.switchProgramsToBonusMode = function() { turing.inBonusMode_ = true; turing.numTracks_ = turing.NUM_PROGRAM_TRACKS.bonusMode; turing.numOpsPerTrack_ = turing.NUM_OPS_PER_TRACK.bonusMode; }; /** * Sets up program display for normal mode. */ turing.switchProgramsToNormalMode = function() { turing.inBonusMode_ = false; turing.numTracks_ = turing.NUM_PROGRAM_TRACKS.normalMode; turing.numOpsPerTrack_ = turing.NUM_OPS_PER_TRACK.normalMode; }; /** * The current op highlight color. * @type {string} * @private */ turing.opHighlightColor_ = 'y'; /** * Sets the op highlight color. * @param {string} color One of 'b', 'r', 'y', 'g' to set the hilight color. */ turing.setOpHighlightColor = function(color) { if (/^[bryg]$/.test(color)) { // The color is valid. turing.opHighlightColor_ = color; } else { // Invalid color. Shouldn't happen. Fall back to yellow. turing.opHighlightColor_ = 'y'; } }; /** * @return {boolean} True iff program display is in bonus mode. */ turing.isInBonusMode = function() { return turing.inBonusMode_; }; /** * A primitive step a program can do in one movement of the program counter. * @typedef {string} */ turing.Op; /** * Map from operation strings used in stored programs to sprite names. * @type {Object.<turing.Op, string>} * @const */ turing.OP_SPRITES = { 'L': 'o-left', 'R': 'o-right', '0': 'o-print0', '1': 'o-print1', 'D0': 'o-down0', 'D1': 'o-down1', 'D_': 'o-down_', 'B2': 'o-back2', 'B3': 'o-back3', 'B4': 'o-back4', 'RB2': 'o-rback2', 'RB3': 'o-rback3', 'RB4': 'o-rback4', 'U0': 'o-up0', 'U1': 'o-up1', 'U_': 'o-up_', '': 'o-blank', // These operations are in the same spirit as the ones above, but are only // used in bonus mode, and are not part of normal gameplay. '_': 'o-x', 'U': 'o-blank-up', 'D': 'o-blank-down', 'B8': 'o-back8', 'B9': 'o-back9' }; /** * A track is a row of program operations arranged from left to right in control * flow order. * @param {number} verticalPosition The vertical offset of the track center. * @param {boolean} loopTracksDown Iff true, the loop track points down, else * up. * @constructor */ turing.Track = function(verticalPosition, loopTracksDown) { /** * The vertical offset of the middle of this track. * @type {number} * @private */ this.verticalPosition_ = verticalPosition; /** * Iff true, loop branch tracks go down from the track, else up. * @type {boolean} * @private */ this.loopTracksDown_ = loopTracksDown; /** * This track's ops. * @type {Array.<turing.Op>} */ this.ops = []; /** * Holds the track and operation divs. * @type {Element} * @private */ this.container_; /** * Divs for each operation on this track. * @type {Array.<Element>} * @private */ this.opDivs_ = []; /** * A div showing the path of the first loop branch on this track. * @type {Element} * @private */ this.loopBranchDiv_; /** * Index of the operation which is a loop branch, or null if none. * @type {?number} * @private */ this.loopBranchIndex_ = null; /** * Mousedown handlers for operation circles. * @type {Array.<Function>} * @private */ this.opMouseDownHandlers_ = []; /** * Touchstart handlers for operation circles. * @type {Array.<Function>} * @private */ this.opTouchHandlers_ = []; /** * Mouseup handlers for operation circles. * @type {Array.<Function>} * @private */ this.opMouseUpHandlers_ = []; /** * Mouseout handlers for operation circles. * @type {Array.<Function>} * @private */ this.opMouseOutHandlers_ = []; /** * Whether each operation is pushed in. * @type {Array.<boolean>} * @private */ this.opPushedIn_ = []; /** * Iff true, operations on this track are currently hidden. * @type {boolean} * @private */ this.hidden_ = true; /** * If true, listen to clicks on operations, else ignore them. * @type {boolean} * @private */ this.interactive_ = false; }; /** * Creates DOM elements for the track and its operations. * - container: An overflow:hidden wrapper to hold everything. * -- trackDiv: A vertically centered horizontal line (i.e. the track) * -- ...ops: Individual ops, centered in equal-sized regions of track. */ turing.Track.prototype.create = function() { // Size container based on interactive state, which is larger. var opSize = turing.sprites.getSize('o-blank-i'); var trackSize = turing.sprites.getSize('track'); if (turing.inBonusMode_) { trackSize.width = turing.BONUS_TRACK_WIDTH; } this.container_ = turing.sprites.getEmptyDiv(); this.container_.style.width = trackSize.width + 'px'; this.container_.style.height = opSize.height + 'px'; this.container_.style.zIndex = 400; for (var i = 0; i < turing.numOpsPerTrack_; i++) { this.createOp_(i); } if (!turing.inBonusMode_) { var loopBranchTrackSize = turing.sprites.getSize('track-l4'); this.loopBranchDiv_ = turing.sprites.getDiv('track-l4'); this.loopBranchDiv_.style.display = 'none'; this.loopBranchDiv_.style.top = this.verticalPosition_ + 'px'; } this.container_.style.zIndex = 399; // Beneath buttons. this.container_.style.top = (this.verticalPosition_ - opSize.height / 2) + 'px'; this.container_.style.left = turing.inBonusMode_ ? '0' : turing.TRACK_LEFT + 'px'; }; /** * Creates a single operation div and binds a lot of event listeners on it. * @param {number} i The index of the operation to create. * @private */ turing.Track.prototype.createOp_ = function(i) { this.opDivs_[i] = turing.sprites.getDiv('o-dim-s'); var pos = this.getOpPosition('o-blank-s', i); this.opDivs_[i].style.left = pos.left + 'px'; this.opDivs_[i].style.top = pos.top + 'px'; if (!turing.inBonusMode_) { this.opMouseDownHandlers_[i] = goog.bind(this.pushInOp, this, i); this.opTouchHandlers_[i] = goog.bind(function() { this.opPushedIn_[i] = true; this.popOutOp(i, true); }, this); this.opMouseUpHandlers_[i] = goog.bind(this.popOutOp, this, i, true); this.opMouseOutHandlers_[i] = goog.bind(this.popOutOp, this, i, false); turing.util.listen(this.opDivs_[i], 'mousedown', this.opMouseDownHandlers_[i]); turing.util.listen(this.opDivs_[i], 'touchstart', this.opTouchHandlers_[i]); turing.util.listen(this.opDivs_[i], 'mouseup', this.opMouseUpHandlers_[i]); turing.util.listen(this.opDivs_[i], 'mouseout', this.opMouseOutHandlers_[i]); } this.opPushedIn_[i] = false; this.container_.appendChild(this.opDivs_[i]); }; /** * Computes the offset of an operation inside the track's container div. * @param {string} spriteName The sprite used for this operation. * @param {number} i The index of the operation. * @return {{top: number, left: number}} The position for this operation. */ turing.Track.prototype.getOpPosition = function(spriteName, i) { // Interactive operations are bigger than static operations. The track is // sized to hold the bigger ones, and we center the smaller ones in the same // footprint. var bigOpSize = turing.sprites.getSize('o-blank-i'); var trackSize = turing.sprites.getSize('track'); if (turing.inBonusMode_) { trackSize.width = turing.BONUS_TRACK_WIDTH; } // Center the bonus mode on the track (use the same padding as we do on the // right, plus a few px to look correct). var leftPadding = turing.inBonusMode_ ? turing.TRACK_RIGHT_PAD + 4 : turing.TRACK_LEFT_PAD; var trackWidthPerOp = (trackSize.width - turing.TRACK_RIGHT_PAD - leftPadding) / turing.numOpsPerTrack_; var opSize = turing.sprites.getSize(spriteName); var xOffs = Math.ceil((bigOpSize.width - opSize.width) / 2); var yOffs = Math.ceil((bigOpSize.height - opSize.height) / 2); return { left: (leftPadding + Math.floor(i * trackWidthPerOp + trackWidthPerOp / 2 - opSize.width / 2) - xOffs), top: yOffs }; }; /** * Sets a flag indicating whether operations on this track are currently hidden. * If hidden, op divs are not redrawn as program execution proceeds. * @param {boolean} hidden True iff op divs are hidden. */ turing.Track.prototype.setHidden = function(hidden) { this.hidden_ = hidden; }; /** * Sets whether the track is currently clickable. * No operations on the track should respond to clicks when a program is * running or when we are changing programs. * @param {boolean} interactive True iff track should be interactive. */ turing.Track.prototype.setInteractive = function(interactive) { this.interactive_ = interactive; this.redrawProgram(); }; /** * Gets the ith operation div in control flow order on a track. * @param {number} i Index into operations. * @return {Element} The operation div. */ turing.Track.prototype.getOpDiv = function(i) { return this.opDivs_[i]; }; /** * Gets the ith operation in control flow order on a track. * @param {number} i Index into operations. * @return {turing.Op} The operation. */ turing.Track.prototype.getOp = function(i) { return this.ops[i]; }; /** * Sets the value of the ith operation in control flow order on track. * @param {number} i Index into operations. * @param {turing.Op} value Desired value. */ turing.Track.prototype.setOp = function(i, value) { this.ops[i] = value; }; /** * Conditional branch operations from a higher track to a lower one. * @type {Array.<turing.Op>} * @private * @const */ turing.COND_BRANCH_DOWN_OPS_ = ['D0', 'D1', 'D_']; /** * Conditional branch operations from a lower track to a higher one. * @type {Array.<turing.Op>} * @private * @const */ turing.COND_BRANCH_UP_OPS_ = ['U0', 'U1', 'U_']; /** * Loop branch operations. * @type {Array.<turing.Op>} * @private * @const */ turing.LOOP_BRANCH_OPS_ = ['B2', 'B3', 'B4']; /** * Printing operations. * @type {Array.<turing.Op>} * @private * @const */ turing.PRINT_OPS_ = ['0', '1']; /** * Tape movement operations. * @type {Array.<turing.Op>} * @private * @const */ turing.MOVE_OPS_ = ['L', 'R']; /** * Cycle to next valid op in this op's group. * @param {number} i Index of relevant op. */ turing.Track.prototype.cycleOp = function(i) { if (!this.interactive_) { return; } var op = this.getOp(i); if (!op || op.charAt(0) != '*') { // This operation is not clickable. return; } op = op.substr(1); this.setOp(i, '*' + ( turing.util.getNextValue(turing.COND_BRANCH_UP_OPS_, op) || turing.util.getNextValue(turing.COND_BRANCH_DOWN_OPS_, op) || turing.util.getNextValue(turing.LOOP_BRANCH_OPS_, op) || turing.util.getNextValue(turing.PRINT_OPS_, op) || turing.util.getNextValue(turing.MOVE_OPS_, op) || op)); }; /** * Push in an op button. * @param {number} i Index of the relevant op. * @param {Event} event mousedown or touchstart event. */ turing.Track.prototype.pushInOp = function(i, event) { var spec = this.getOp(i); if (!this.interactive_ || !spec || spec.charAt(0) != '*' || this.opPushedIn_[i]) { // The button might still be pushed in if the pop-out animation from a // previous click is still playing. return; } this.opPushedIn_[i] = true; var baseName = turing.Track.prototype.getOpSpriteBaseName_(spec); turing.anim.animateFromSprites(this.opDivs_[i], [baseName + '-i-out', baseName + '-i', baseName + '-i-in'], turing.OP_PUSH_IN_DELAY); }; /** * Pop out an op button. * @param {number} i Index of the relevant op. * @param {boolean} shouldChange True iff we should cycle the op button. * @param {Event} event mouseup or mouseout event. */ turing.Track.prototype.popOutOp = function(i, shouldChange, event) { var spec = this.getOp(i); if (!this.interactive_ || !spec || spec.charAt(0) != '*' || !this.opPushedIn_[i]) { return; } if (shouldChange) { this.cycleOp(i); } spec = this.getOp(i); var baseName = turing.Track.prototype.getOpSpriteBaseName_(spec); turing.anim.animateFromSprites(this.opDivs_[i], [baseName + '-i-in', baseName + '-i', baseName + '-i-out'], turing.OP_POP_OUT_DELAY, goog.bind(function(i) { this.opPushedIn_[i] = false; this.redrawOp(i, false); }, this, i)); }; /** * Gets the base name of the sprite for the given operation. * @param {string} spec An operation spec like D_. * @return {string} The name of the sprite with no suffixes. * @private */ turing.Track.prototype.getOpSpriteBaseName_ = function(spec) { if (spec && spec.charAt(0) == '*') { spec = spec.substr(1); } if (this.loopTracksDown_ && (spec == 'B2' || spec == 'B3' || spec == 'B4')) { // Appending R reverses the direction of the loop so that it looks like it's // pointing down to the lower track loop. spec = 'R' + spec; } return turing.OP_SPRITES[spec || '']; }; /** * Sets the track's abstract operations, without updating or showing it. * Makes a copy of the given array so that it can be changed without changing * a constant program definition. * @param {Array.<turing.Op>} ops Program operations. */ turing.Track.prototype.setOps = function(ops) { this.ops = ops.slice(0); // Copy ops. this.loopBranchIndex_ = null; for (var i = 0; i < this.ops.length; i++) { if (this.ops[i] && this.ops[i].match(/B/)) { // /B/ matches operation codes containing B. Loop branches are the only // such operations so this is a loop branch. this.loopBranchIndex_ = i; break; } } }; /** * Changes the operations on a track (and animates it into its new state). * @param {Array.<turing.Op>} ops A list of new operations. */ turing.Track.prototype.change = function(ops) { this.setOps(ops); this.redrawProgram(); }; /** * Redraws the current program. */ turing.Track.prototype.redrawProgram = function() { if (!turing.inBonusMode_ && this.loopBranchIndex_ == null) { // If there is no loop branch, hide backwards pointing track. // (If there is a loop branch, it'll be shown from redrawOp below.) this.loopBranchDiv_.style.display = 'none'; } for (var i = 0; i < turing.numOpsPerTrack_; i++) { this.redrawOp(i, false); } }; /** * Updates the sprite for an operation. * @param {number} i The index of the operation on the track. * @param {boolean} lit Whether the operation is currently active. */ turing.Track.prototype.redrawOp = function(i, lit) { if (this.hidden_) { return; } var opDiv = this.getOpDiv(i); var spec = this.getOp(i) || ''; var suffix = ''; if (spec && spec.charAt(0) == '*') { // * means the operation is clickable. if (this.interactive_) { if (this.opPushedIn_[i]) { suffix = '-i-in'; } else { suffix = '-i-out'; } opDiv.style.cursor = 'pointer'; } else { // The operation is clickable, but not right now. It should be flat. suffix = lit ? '-i-lit' : '-i'; opDiv.style.cursor = 'default'; } } else { // The operation is never clickable. suffix = lit ? '-s-lit-' + turing.opHighlightColor_ : '-s'; opDiv.style.cursor = 'default'; } var spriteName = this.getOpSpriteBaseName_(spec); var size = turing.sprites.getSize(spriteName + suffix); opDiv.style.background = turing.sprites.getBackground( spriteName + suffix); // Interactive buttons are bigger than static buttons, so we may need to // recenter the button. var pos = this.getOpPosition(spriteName + suffix, i); opDiv.style.left = pos.left + 'px'; opDiv.style.top = pos.top + 'px'; opDiv.style.width = size.width + 'px'; opDiv.style.height = size.height + 'px'; if (i == this.loopBranchIndex_) { this.redrawLoopBranchTrack_(spriteName + suffix); } }; /** * Redraws the segment showing the path for a loop branch on this track. * @param {string} opSpriteName The sprite name for the loop branch operation * where the segment begins. * @private */ turing.Track.prototype.redrawLoopBranchTrack_ = function(opSpriteName) { if (this.loopBranchIndex_ == null || turing.inBonusMode_) { return; } var spec = this.getOp(this.loopBranchIndex_); // /(\d)$/ extracts the last single digit in the operation code, which for // branches is the number of states to branch back (i.e. the distance). var branchDist = spec.match(/(\d)$/); var opSize = turing.sprites.getSize(opSpriteName); var pos = this.getOpPosition(opSpriteName, this.loopBranchIndex_); var loopBranchSprite = 'track-' + (this.loopTracksDown_ ? 'l' : 'u') + branchDist[1]; var loopBranchSize = turing.sprites.getSize(loopBranchSprite); this.loopBranchDiv_.style.background = turing.sprites.getBackground( loopBranchSprite); this.loopBranchDiv_.style.left = Math.floor(turing.TRACK_LEFT + pos.left - loopBranchSize.width + opSize.width / 2 + 4) + 'px'; var middleOfButtons = this.verticalPosition_; // For the top loop, its bottom should be aligned with the middle of the // buttons. var yOffs = this.loopTracksDown_ ? -3 : (-loopBranchSize.height + 2); this.loopBranchDiv_.style.top = Math.floor(middleOfButtons + yOffs) + 'px'; this.loopBranchDiv_.style.width = loopBranchSize.width + 'px'; this.loopBranchDiv_.style.height = loopBranchSize.height + 'px'; this.loopBranchDiv_.style.display = 'block'; }; /** * Since we're a touch device, destroy mouse handlers. */ turing.Track.prototype.setTouchDevice = function() { this.destroyEventHandlers_(true); }; /** * Destroy the event handlers. Optionally save the touch events. This allows * us to kill the mouse handlers if we're on a touch device. Note that we * lazily check if we're a touch device by waiting for a touchstart event in * turing.js rather than doing useragent parsing. * @param {boolean=} opt_saveTouch Whether to preserve touch event handlers. * @private */ turing.Track.prototype.destroyEventHandlers_ = function(opt_saveTouch) { for (var i = 0; i < this.opMouseDownHandlers_.length; i++) { turing.util.unlisten(this.opDivs_[i], 'mousedown', this.opMouseDownHandlers_[i]); } this.opMouseDownHandlers_.splice(0); if (!opt_saveTouch) { for (var i = 0; i < this.opTouchHandlers_.length; i++) { turing.util.unlisten(this.opDivs_[i], 'touchstart', this.opTouchHandlers_[i]); } this.opTouchHandlers_.splice(0); } for (var i = 0; i < this.opMouseUpHandlers_.length; i++) { turing.util.unlisten(this.opDivs_[i], 'mouseup', this.opMouseUpHandlers_[i]); } this.opMouseUpHandlers_.splice(0); for (var i = 0; i < this.opMouseOutHandlers_.length; i++) { turing.util.unlisten(this.opDivs_[i], 'mouseout', this.opMouseOutHandlers_[i]); } this.opMouseOutHandlers_.splice(0); }; /** * Cleans up dom elements and removes event listeners. */ turing.Track.prototype.destroy = function() { this.destroyEventHandlers_(); for (var i = 0; i < this.opDivs_.length; i++) { turing.util.removeNode(this.opDivs_[i]); } this.opDivs_.splice(0); turing.util.removeNode(this.container_); this.container_ = null; turing.util.removeNode(this.loopBranchDiv_); this.loopBranchDiv_ = null; }; /** * Adds to dom. * @param {Element} elem dom parent. */ turing.Track.prototype.attachTo = function(elem) { elem.appendChild(this.container_); if (this.loopBranchDiv_) { // Not shown in bonus mode. elem.appendChild(this.loopBranchDiv_); } }; /** * A Turing machine program shown as a set of tracks. * @constructor */ turing.Program = function() { /** * Tracks containing operations. * @type {Array.<turing.Track>} * @private */ this.tracks_ = []; for (var i = 0; i < turing.numTracks_; i++) { this.tracks_[i] = new turing.Track(turing.inBonusMode_ ? turing.BONUS_TRACK_BUTTON_VERTICAL_MIDDLE_[i] : turing.TRACK_BUTTON_VERTICAL_MIDDLE_[i], i == 1); } /** * The div containing the track image. * @type {Element} * @private */ this.trackDiv_; /** * Pieces of track joining the top track to the bottom track. * @type {Array.<Element>} * @private */ this.trackDescenders_ = []; /** * How many tracks does the current program have? * @type {number} * @private */ this.numActiveTracks_ = 0; /** * The current hilit operation's track number. * @type {number} * @private */ this.curTrack_ = 0; /** * The current hilit operation's position on its track. * @type {number} * @private */ this.curTrackPos_ = 0; /** * The next operation's track number. * @type {number} * @private */ this.nextTrack_ = 0; /** * The next operation's position on its track. * @type {number} * @private */ this.nextTrackPos_ = 0; /** * True iff the program should end on the next operation. * @type {boolean} * @private */ this.nextPosIsEnd_ = true; /** * Are the program's operations hidden? * @type {boolean} * @private */ this.hidden_ = true; /** * Can the user click on clickable operations right now? * @type {boolean} * @private */ this.interactive_ = false; }; /** * Creates dom elements for the program display. */ turing.Program.prototype.create = function() { for (var i = 0; i < this.tracks_.length; i++) { this.tracks_[i].create(); } if (!turing.inBonusMode_) { var opSize = turing.sprites.getSize('o-blank-i'); var middleOfTopTrack = turing.TRACK_BUTTON_VERTICAL_MIDDLE_[0]; this.trackDiv_ = turing.sprites.getDiv('track'); this.trackDiv_.style.left = turing.TRACK_LEFT + 'px'; this.trackDiv_.style.top = middleOfTopTrack - turing.TRACK_TOP_PAD + 'px'; // Bonus mode has no lines between tracks (they don't really fit). var trackDownSize = turing.sprites.getSize('track-vert'); var trackSize = turing.sprites.getSize('track'); var trackWidthPerOp = (trackSize.width - turing.TRACK_LEFT_PAD - turing.TRACK_RIGHT_PAD) / turing.numOpsPerTrack_; for (var i = 0; i < turing.numOpsPerTrack_; i++) { this.trackDescenders_[i] = turing.sprites.getDiv('track-vert'); // Vertical lines between operations on a pair of tracks are centered // beneath those operations. this.trackDescenders_[i].style.left = Math.floor(turing.TRACK_LEFT_PAD + turing.TRACK_LEFT + i * trackWidthPerOp + trackWidthPerOp / 2 - trackDownSize.width / 2 - 1) + 'px'; this.trackDescenders_[i].style.top = middleOfTopTrack + 'px'; this.trackDescenders_[i].style.zIndex = 398; // Behind operations. this.trackDescenders_[i].style.display = 'none'; } } }; /** * Cleans up dom elements and event listeners. */ turing.Program.prototype.destroy = function() { for (var i = 0; i < this.tracks_.length; i++) { this.tracks_[i].destroy(); } turing.util.removeNode(this.trackDiv_); for (var i = 0; i < this.trackDescenders_.length; i++) { turing.util.removeNode(this.trackDescenders_[i]); } this.trackDescenders_.splice(0); }; /** * Attaches dom nodes beneath elem. * @param {Element} elem Parent. */ turing.Program.prototype.attachTo = function(elem) { for (var i = 0; i < this.tracks_.length; i++) { this.tracks_[i].attachTo(elem); } if (!turing.inBonusMode_) { // Bonus mode doesn't have track lines. elem.appendChild(this.trackDiv_); for (var i = 0; i < this.trackDescenders_.length; i++) { elem.appendChild(this.trackDescenders_[i]); } } }; /** * Dims any lit operations. */ turing.Program.prototype.reset = function() { for (var i = 0; i < turing.numTracks_; i++) { this.tracks_[i].redrawProgram(); } if (!turing.inBonusMode_) { this.redrawDescenders_(); } }; /** * Draws lines connecting the tracks wherever there are up or down operations. * @private */ turing.Program.prototype.redrawDescenders_ = function() { for (var i = 0; i < turing.numOpsPerTrack_; i++) { this.trackDescenders_[i].style.background = turing.sprites.getBackground('track-vert'); var hasBranch = false; for (var j = 0; j < turing.numTracks_; j++) { var spec = this.tracks_[j].getOp(i); if (!this.hidden_ && spec && spec.match(/D|U/)) { // /D|U/ matches any conditional down-if or up-if branches (those are // the only operations which contain 'D' or 'U'). hasBranch = true; } } this.trackDescenders_[i].style.display = hasBranch ? 'block' : 'none'; } }; /** * Changes to a new program. * @param {Array.<Array.<turing.Op>>} trackOps The operations for each * valid program track. Note: This code supports 1 or 2 track programs. * @param {boolean=} opt_hidden Iff true, change the program contents, but * keep tracks hidden. */ turing.Program.prototype.change = function(trackOps, opt_hidden) { this.curTrack_ = 0; this.curTrackPos_ = 0; this.nextTrack_ = 0; this.nextTrackPos_ = 0; this.nextPosIsEnd_ = false; this.hidden_ = opt_hidden || false; this.numActiveTracks_ = trackOps.length; for (var i = 0; i < turing.numTracks_; i++) { this.tracks_[i].setOps(trackOps[i] || []); this.tracks_[i].setHidden(opt_hidden || false); } this.reset(); }; /** * Sets whether program tracks are currently accepting clicks. * @param {boolean} interactive True iff tracks should accept clicks. */ turing.Program.prototype.setInteractive = function(interactive) { this.interactive_ = interactive; for (var i = 0; i < turing.numTracks_; i++) { this.tracks_[i].setInteractive(interactive); } }; /** * Gets the current track number. * @return {number} Current instruction's track. */ turing.Program.prototype.getCurTrack = function() { return this.curTrack_; }; /** * Gets the current position on the current track. * @return {number} Current instruction's op index within track. */ turing.Program.prototype.getCurTrackPos = function() { return this.curTrackPos_; }; /** * @return {boolean} True iff next position is past end of program. */ turing.Program.prototype.isNextPosEnd = function() { return this.nextPosIsEnd_; }; /** * Sets the track and position for the next operation to be run. Stays put if * the new position is not a valid program position. * @param {number} track The new track. * @param {number} pos The new position. */ turing.Program.prototype.setNextPos = function(track, pos) { if (track >= 0 && track < this.numActiveTracks_ && pos >= 0 && pos < turing.numOpsPerTrack_) { this.nextTrack_ = track; this.nextTrackPos_ = pos; this.nextPosIsEnd_ = false; } else { this.nextPosIsEnd_ = true; } }; /** * Sets the current position to the next position and redraws highlights. */ turing.Program.prototype.goToNextPos = function() { this.dimCurOp(); if (!this.nextPosIsEnd_) { this.curTrack_ = this.nextTrack_; this.curTrackPos_ = this.nextTrackPos_; this.lightCurOp_(); } }; /** * Dims the current active program operation. */ turing.Program.prototype.dimCurOp = function() { this.tracks_[this.curTrack_].redrawOp(this.curTrackPos_, false); }; /** * Highlights the current active program operation. * @private */ turing.Program.prototype.lightCurOp_ = function() { this.tracks_[this.curTrack_].redrawOp(this.curTrackPos_, true); }; /** * Gets the current program operation to execute. * @return {turing.Op} The current operation. */ turing.Program.prototype.getCurOp = function() { return this.tracks_[this.curTrack_].getOp(this.curTrackPos_); }; /** * Notify the tracks that we're on a tablet. */ turing.Program.prototype.setTouchDevice = function() { for (var i = 0; i < turing.numTracks_; i++) { this.tracks_[i].setTouchDevice(); } };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Shows the Google logo. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.Logo'); goog.require('turing.anim'); goog.require('turing.sprites'); goog.require('turing.util'); /** * The names of letters in the logo, in order, corresponding to sprites. * @type {Array.<string>} * @const */ turing.LOGO_LETTERS = ['G', 'o1', 'o2', 'g', 'l', 'e']; /** * The left offset of the logo container. * @type {string} * @const */ turing.LOGO_LEFT = '79px'; /** * The top offset of the logo container. * @type {string} * @const */ turing.LOGO_TOP = '24px'; /** * The tops of each letter so that they line up correctly vertically. * @type {Array.<string>} * @const * @private */ turing.LETTER_TOPS_ = ['1px', '11px', '11px', '11px', '0', '11px']; /** * The lefts of each letter so that they line up correctly. * @type {Array.<string>} * @const * @private */ turing.LETTER_LEFTS_ = ['0', '33px', '57px', '79px', '100px', '111px']; /** * The number of animation frames used to light up the logo letters. * @type {number} * @const * @private */ turing.NUM_LETTER_ANIMATION_FRAMES_ = 8; /** * A Google logo where each letter can light up or dim individually. * @constructor */ turing.Logo = function() { /** * Divs for each letter. * @type {Array.<Element>} * @private */ this.letters_ = []; /** * Container div holding all letters. * @type {Element} * @private */ this.container_; }; /** * Attaches the logo under a dom element. * @param {Element} elem Parent element. */ turing.Logo.prototype.attachTo = function(elem) { elem.appendChild(this.container_); }; /** * Creates the dom elements for the logo letters. * @param {number} numLettersOn How many letters are initially on. */ turing.Logo.prototype.create = function(numLettersOn) { this.container_ = turing.sprites.getEmptyDiv(); this.container_.style.left = turing.LOGO_LEFT; this.container_.style.top = turing.LOGO_TOP; for (var i = 0, letter; letter = turing.LOGO_LETTERS[i]; i++) { var spriteName = i < numLettersOn ? letter + (turing.NUM_LETTER_ANIMATION_FRAMES_ - 1) : letter + '0'; this.letters_[i] = turing.sprites.getDiv(spriteName); this.letters_[i].style.left = turing.LETTER_LEFTS_[i]; this.letters_[i].style.top = turing.LETTER_TOPS_[i]; this.container_.appendChild(this.letters_[i]); var letterSize = turing.sprites.getSize(spriteName); } }; /** * Destroys the dom elements for logo letters. */ turing.Logo.prototype.destroy = function() { turing.util.removeNode(this.container_); this.container_ = null; for (var i = 0, letter; letter = this.letters_[i++]; ) { turing.util.removeNode(letter); } this.letters_.splice(0); }; /** * Return an array of backgrounds we can use to animate the hightlighting or * dimming of the given letter. * @param {string} letter The letter to animate. * @param {boolean} startDim If true, we dim the letter instead of highlighting. * @return {Array.<string>} The backgrounds which can be used to animate it. * @private */ turing.Logo.prototype.getAnimationBackgrounds_ = function(letter, startDim) { var backgrounds = []; for (var i = 0; i < turing.NUM_LETTER_ANIMATION_FRAMES_; i++) { backgrounds[i] = turing.sprites.getBackground( letter + (startDim ? i : turing.NUM_LETTER_ANIMATION_FRAMES_ - 1 - i)); } return backgrounds; }; /** * Lights up the letter at the given position. * @param {number} pos The index of the letter to light up. * @param {number=} opt_duration The duration to animate lighting the logo * letter. */ turing.Logo.prototype.lightLetterAtPosition = function(pos, opt_duration) { if (!this.letters_[pos]) { return; } var letter = turing.LOGO_LETTERS[pos]; if (!opt_duration) { this.letters_[pos].style.background = turing.sprites.getBackground( letter + (turing.NUM_LETTER_ANIMATION_FRAMES_ - 1)); } else { turing.anim.animateThroughBackgrounds(this.letters_[pos], this.getAnimationBackgrounds_(letter, true), opt_duration); } }; /** * Dims the letter at the given position. * @param {number} pos The index of the letter to dim. * @param {number=} opt_duration The duration to animate dimming the logo * letter. */ turing.Logo.prototype.dimLetterAtPosition = function(pos, opt_duration) { var letterDiv = this.letters_[pos]; if (!letterDiv) { return; } var letter = turing.LOGO_LETTERS[pos]; if (!opt_duration) { letterDiv.style.background = turing.sprites.getBackground(letter + '0'); } else { turing.anim.animateThroughBackgrounds(letterDiv, this.getAnimationBackgrounds_(letter, false), opt_duration); } }; /** * Dims all letters. * @param {number=} opt_duration The duration to animate dimming the logo * letters. */ turing.Logo.prototype.dim = function(opt_duration) { for (var i = 0; i < this.letters_.length; i++) { turing.anim.delay( goog.bind(this.dimLetterAtPosition, this, i, opt_duration), 250); } }; /** * Successively dim each letter of the logo from the last to the first. * @param {function()=} opt_doneCallback Called when the logo is dim again. */ turing.Logo.prototype.deluminate = function(opt_doneCallback) { var numLetters = turing.LOGO_LETTERS.length; for (var i = 0; i < numLetters; i++) { turing.anim.delay( goog.bind(this.dimLetterAtPosition, this, numLetters - (i + 1), 500), 250 * i); } turing.anim.delay( goog.bind(function() { this.dim(); opt_doneCallback(); }, this), 250 * (1 + turing.LOGO_LETTERS.length) + 500); };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Helpers for loading sprites. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.sprites'); goog.require('turing.deferredsprites.offsets'); goog.require('turing.sprites.offsets'); /** * Path to the main sprite. * @type {string} * @const */ turing.sprites.PATH = 'images/sprite.png'; /** * Path to the deferred sprite. * @type {string} * @const */ turing.sprites.DEFERRED_SPRITE_PATH = 'images/deferred_sprite.png'; /** * Gets the width and height of the named sprite. * @param {string} name A sprite name. * @return {{width: number, height: number}} */ turing.sprites.getSize = function(name) { var rect = turing.sprites.offsets.RECTS[name] || turing.deferredsprites.offsets.RECTS[name]; return {width: rect.width, height: rect.height}; }; /** * Gets a string with background: CSS to select a sprite. * @param {string} name The name of the desired sprite. * @return {string} background: CSS. */ turing.sprites.getBackground = function(name) { var rect = turing.sprites.offsets.RECTS[name] || turing.deferredsprites.offsets.RECTS[name]; if (!rect) { // For debugging purposes, make it easy to see the missing sprite. return 'red'; } var deferred = !turing.sprites.offsets.RECTS[name] && turing.deferredsprites.offsets.RECTS[name]; var path = deferred ? turing.sprites.DEFERRED_SPRITE_PATH : turing.sprites.PATH; return 'url(' + path + ') ' + -rect.x + 'px ' + -rect.y + 'px no-repeat'; }; /** * Gets a div containing the requested sprite. * @param {string} name The name of the desired sprite. * @return {Element} The sprite div. */ turing.sprites.getDiv = function(name) { var div = turing.sprites.getEmptyDiv(); var rect = turing.sprites.offsets.RECTS[name]; // In practice, we should always have a sprite offset for a given name so we // shouldn't be using these fallback values, but if we don't we render a // 50x50 square and getBackground will return 'red' so that we can quickly // and easily see the missing sprite. div.style.width = rect ? (rect.width + 'px') : '50px'; div.style.height = rect ? (rect.height + 'px') : '50px'; div.style.background = turing.sprites.getBackground(name); div.style['webkitTapHighlightColor'] = 'rgba(0,0,0,0)'; return div; }; /** * Gets an empty, unselectable div. * @return {Element} The div. */ turing.sprites.getEmptyDiv = function() { var div = document.createElement('div'); div.style.position = 'absolute'; div.style.userSelect = 'none'; div.style.webkitUserSelect = 'none'; div.style['webkitTapHighlightColor'] = 'rgba(0,0,0,0)'; div.style.MozUserSelect = 'none'; div.unselectable = 'on'; return div; }; /** * Preloads sprites. * @param {string} path The path to the image to preload. * @return {Element} the image element used to preload the sprite. */ turing.sprites.preload = function(path) { var img = document.createElement('img'); img.src = path; return img; };
JavaScript
/** * jquery.gridrotator.js v1.1.0 * http://www.codrops.com * * Licensed under the MIT license. * http://www.opensource.org/licenses/mit-license.php * * Copyright 2012, Codrops * http://www.codrops.com */ ;( function( $, window, undefined ) { 'use strict'; /* * debouncedresize: special jQuery event that happens once after a window resize * * latest version and complete README available on Github: * https://github.com/louisremi/jquery-smartresize/blob/master/jquery.debouncedresize.js * * Copyright 2011 @louis_remi * Licensed under the MIT license. */ var $event = $.event, $special, resizeTimeout; $special = $event.special.debouncedresize = { setup: function() { $( this ).on( "resize", $special.handler ); }, teardown: function() { $( this ).off( "resize", $special.handler ); }, handler: function( event, execAsap ) { // Save the context var context = this, args = arguments, dispatch = function() { // set correct event type event.type = "debouncedresize"; $event.dispatch.apply( context, args ); }; if ( resizeTimeout ) { clearTimeout( resizeTimeout ); } execAsap ? dispatch() : resizeTimeout = setTimeout( dispatch, $special.threshold ); }, threshold: 100 }; // http://www.hardcode.nl/subcategory_1/article_317-array-shuffle-function Array.prototype.shuffle = function() { var i=this.length,p,t; while (i--) { p = Math.floor(Math.random()*i); t = this[i]; this[i]=this[p]; this[p]=t; } return this; }; // HTML5 PageVisibility API // http://www.html5rocks.com/en/tutorials/pagevisibility/intro/ // by Joe Marini (@joemarini) function getHiddenProp(){ var prefixes = ['webkit','moz','ms','o']; // if 'hidden' is natively supported just return it if ('hidden' in document) return 'hidden'; // otherwise loop over all the known prefixes until we find one for (var i = 0; i < prefixes.length; i++){ if ((prefixes[i] + 'Hidden') in document) return prefixes[i] + 'Hidden'; } // otherwise it's not supported return null; } function isHidden() { var prop = getHiddenProp(); if (!prop) return false; return document[prop]; } function isEmpty( obj ) { return Object.keys(obj).length === 0; } // global var $window = $( window ), Modernizr = window.Modernizr; $.GridRotator = function( options, element ) { this.$el = $( element ); if( Modernizr.backgroundsize ) { var self = this; this.$el.addClass( 'ri-grid-loading' ); this._init( options ); } }; // the options $.GridRotator.defaults = { // number of rows rows : 4, // number of columns columns : 10, w1024 : { rows : 3, columns : 8 }, w768 : {rows : 3,columns : 7 }, w480 : {rows : 3,columns : 5 }, w320 : {rows : 2,columns : 4 }, w240 : {rows : 2,columns : 3 }, // step: number of items that are replaced at the same time // random || [some number] // note: for performance issues, the number "can't" be > options.maxStep step : 'random', // change it as you wish.. maxStep : 3, // prevent user to click the items preventClick : true, // animation type // showHide || fadeInOut || // slideLeft || slideRight || slideTop || slideBottom || // rotateBottom || rotateLeft || rotateRight || rotateTop || // scale || // rotate3d || // rotateLeftScale || rotateRightScale || rotateTopScale || rotateBottomScale || // random animType : 'random', // animation speed animSpeed : 800, // animation easings animEasingOut : 'linear', animEasingIn: 'linear', // the item(s) will be replaced every 3 seconds // note: for performance issues, the time "can't" be < 300 ms interval : 3000, // if false the animations will not start // use false if onhover is true for example slideshow : true, // if true the items will switch when hovered onhover : false, // ids of elements that shouldn't change nochange : [] }; $.GridRotator.prototype = { _init : function( options ) { // options this.options = $.extend( true, {}, $.GridRotator.defaults, options ); // cache some elements + variables this._config(); }, _config : function() { var self = this, transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd', 'MozTransition' : 'transitionend', 'OTransition' : 'oTransitionEnd', 'msTransition' : 'MSTransitionEnd', 'transition' : 'transitionend' }; // support CSS transitions and 3d transforms this.supportTransitions = Modernizr.csstransitions; this.supportTransforms3D = Modernizr.csstransforms3d; this.transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ] + '.gridrotator'; // all animation types for the random option this.animTypes = this.supportTransforms3D ? [ 'fadeInOut', 'slideLeft', 'slideRight', 'slideTop', 'slideBottom', 'rotateLeft', 'rotateRight', 'rotateTop', 'rotateBottom', 'scale', 'rotate3d', 'rotateLeftScale', 'rotateRightScale', 'rotateTopScale', 'rotateBottomScale' ] : [ 'fadeInOut', 'slideLeft', 'slideRight', 'slideTop', 'slideBottom' ]; this.animType = this.options.animType; if( this.animType !== 'random' && !this.supportTransforms3D && $.inArray( this.animType, this.animTypes ) === -1 && this.animType !== 'showHide' ) { // fallback to 'fadeInOut' if user sets a type which is not supported this.animType = 'fadeInOut'; } this.animTypesTotal = this.animTypes.length; // the <ul> where the items are placed this.$list = this.$el.children( 'ul' ); // remove images and add background-image to anchors // preload the images before var loaded = 0, $imgs = this.$list.find( 'img' ), count = $imgs.length; $imgs.each( function() { var $img = $( this ), src = $img.attr( 'src' ); $( '<img/>' ).load( function() { ++loaded; $img.parent().css( 'background-image', 'url(' + src + ')' ); if( loaded === count ) { $imgs.remove(); self.$el.removeClass( 'ri-grid-loading' ); // the items self.$items = self.$list.children( 'li' ); // make a copy of the items self.$itemsCache = self.$items.clone(); // total number of items self.itemsTotal = self.$items.length; // the items that will be out of the grid // actually the item's child (anchor element) self.outItems= []; self._layout( function() { self._initEvents(); } ); // replace [options.step] items after [options.interval] time // the items that go out are randomly chosen, while the ones that get in // follow a "First In First Out" logic self._start(); } } ).attr( 'src', src ) } ); }, _layout : function( callback ) { var self = this; // sets the grid dimentions based on the container's width this._setGridDim(); // reset this.$list.empty(); this.$items = this.$itemsCache.clone().appendTo( this.$list ); var $outItems = this.$items.filter( ':gt(' + ( this.showTotal - 1 ) + ')' ), $outAItems = $outItems.children( 'a' ); this.outItems.length = 0; $outAItems.each( function( i ) { self.outItems.push( $( this ) ); } ); $outItems.remove(); // container's width var containerWidth = ( document.defaultView ) ? parseInt( document.defaultView.getComputedStyle( this.$el.get( 0 ), null ).width ) : this.$el.width(), // item's width itemWidth = Math.floor( containerWidth / this.columns ), // calculate gap gapWidth = containerWidth - ( this.columns * Math.floor( itemWidth ) ); for( var i = 0; i < this.rows; ++i ) { for( var j = 0; j < this.columns; ++j ) { var idx = this.columns * i + j, $item = this.$items.eq( idx ); $item.css( { width : j < Math.floor( gapWidth ) ? itemWidth + 1 : itemWidth, height : itemWidth } ); if( $.inArray( idx, this.options.nochange ) !== -1 ) { $item.addClass( 'ri-nochange' ).data( 'nochange', true ); } } } if( this.options.preventClick ) { this.$items.children().css( 'cursor', 'default' ).on( 'click.gridrotator', false ); } if( callback ) { callback.call(); } }, // set the grid rows and columns _setGridDim : function() { // container's width var c_w = this.$el.width(); // we will choose the number of rows/columns according to the container's width and the values set in the plugin options switch( true ) { case ( c_w < 240 ) : this.rows = this.options.w240.rows; this.columns = this.options.w240.columns; break; case ( c_w < 320 ) : this.rows = this.options.w320.rows; this.columns = this.options.w320.columns; break; case ( c_w < 480 ) : this.rows = this.options.w480.rows; this.columns = this.options.w480.columns; break; case ( c_w < 768 ) : this.rows = this.options.w768.rows; this.columns = this.options.w768.columns; break; case ( c_w < 1024 ) : this.rows = this.options.w1024.rows; this.columns = this.options.w1024.columns; break; default : this.rows = this.options.rows; this.columns = this.options.columns; break; } this.showTotal = this.rows * this.columns; }, // init window resize event _initEvents : function() { var self = this; $window.on( 'debouncedresize.gridrotator', function() { self._layout(); } ); // use the property name to generate the prefixed event name var visProp = getHiddenProp(); // HTML5 PageVisibility API // http://www.html5rocks.com/en/tutorials/pagevisibility/intro/ // by Joe Marini (@joemarini) if (visProp) { var evtname = visProp.replace(/[H|h]idden/,'') + 'visibilitychange'; document.addEventListener(evtname, function() { self._visChange(); } ); } if( !Modernizr.touch && this.options.onhover ) { self.$items.on( 'mouseenter.gridrotator', function() { var $item = $( this ); if( !$item.data( 'active' ) && !$item.data( 'hovered' ) && !$item.data( 'nochange' ) ) { $item.data( 'hovered', true ); self._replace( $item ); } } ).on( 'mouseleave.gridrotator', function() { $( this ).data( 'hovered', false ); } ); } }, _visChange : function() { isHidden() ? clearTimeout( this.playtimeout ) : this._start(); }, // start rotating elements _start : function() { if( this.showTotal < this.itemsTotal && this.options.slideshow ) { this._showNext(); } }, // get which type of animation _getAnimType : function() { return this.animType === 'random' ? this.animTypes[ Math.floor( Math.random() * this.animTypesTotal ) ] : this.animType; }, // get css properties for the transition effect _getAnimProperties : function( $out ) { var startInProp = {}, startOutProp = {}, endInProp = {}, endOutProp = {}, animType = this._getAnimType(), speed, delay = 0; switch( animType ) { case 'showHide' : speed = 0; endOutProp.opacity = 0; break; case 'fadeInOut' : endOutProp.opacity = 0; break; case 'slideLeft' : startInProp.left = $out.width(); endInProp.left = 0; endOutProp.left = -$out.width(); break; case 'slideRight' : startInProp.left = -$out.width(); endInProp.left = 0; endOutProp.left = $out.width(); break; case 'slideTop' : startInProp.top = $out.height(); endInProp.top = 0; endOutProp.top = -$out.height(); break; case 'slideBottom' : startInProp.top = -$out.height(); endInProp.top = 0; endOutProp.top = $out.height(); break; case 'rotateLeft' : speed = this.options.animSpeed / 2; startInProp.transform = 'rotateY(90deg)'; endInProp.transform = 'rotateY(0deg)'; delay = speed; endOutProp.transform = 'rotateY(-90deg)'; break; case 'rotateRight' : speed = this.options.animSpeed / 2; startInProp.transform = 'rotateY(-90deg)'; endInProp.transform = 'rotateY(0deg)'; delay = speed; endOutProp.transform = 'rotateY(90deg)'; break; case 'rotateTop' : speed = this.options.animSpeed / 2; startInProp.transform= 'rotateX(90deg)'; endInProp.transform = 'rotateX(0deg)'; delay = speed; endOutProp.transform = 'rotateX(-90deg)'; break; case 'rotateBottom' : speed = this.options.animSpeed / 2; startInProp.transform = 'rotateX(-90deg)'; endInProp.transform = 'rotateX(0deg)'; delay = speed; endOutProp.transform = 'rotateX(90deg)'; break; case 'scale' : speed = this.options.animSpeed / 2; startInProp.transform = 'scale(0)'; startOutProp.transform = 'scale(1)'; endInProp.transform = 'scale(1)'; delay = speed; endOutProp.transform = 'scale(0)'; break; case 'rotateLeftScale' : startOutProp.transform = 'scale(1)'; speed = this.options.animSpeed / 2; startInProp.transform = 'scale(0.3) rotateY(90deg)'; endInProp.transform = 'scale(1) rotateY(0deg)'; delay = speed; endOutProp.transform = 'scale(0.3) rotateY(-90deg)'; break; case 'rotateRightScale' : startOutProp.transform = 'scale(1)'; speed = this.options.animSpeed / 2; startInProp.transform = 'scale(0.3) rotateY(-90deg)'; endInProp.transform = 'scale(1) rotateY(0deg)'; delay = speed; endOutProp.transform = 'scale(0.3) rotateY(90deg)'; break; case 'rotateTopScale' : startOutProp.transform = 'scale(1)'; speed = this.options.animSpeed / 2; startInProp.transform = 'scale(0.3) rotateX(90deg)'; endInProp.transform = 'scale(1) rotateX(0deg)'; delay = speed; endOutProp.transform = 'scale(0.3) rotateX(-90deg)'; break; case 'rotateBottomScale' : startOutProp.transform = 'scale(1)'; speed = this.options.animSpeed / 2; startInProp.transform = 'scale(0.3) rotateX(-90deg)'; endInProp.transform = 'scale(1) rotateX(0deg)'; delay = speed; endOutProp.transform = 'scale(0.3) rotateX(90deg)'; break; case 'rotate3d' : speed = this.options.animSpeed / 2; startInProp.transform = 'rotate3d( 1, 1, 0, 90deg )'; endInProp.transform = 'rotate3d( 1, 1, 0, 0deg )'; delay = speed; endOutProp.transform = 'rotate3d( 1, 1, 0, -90deg )'; break; } return { startInProp : startInProp, startOutProp : startOutProp, endInProp : endInProp, endOutProp : endOutProp, delay : delay, animSpeed : speed != undefined ? speed : this.options.animSpeed }; }, // show next [option.step] elements _showNext : function( time ) { var self = this; clearTimeout( this.playtimeout ); this.playtimeout = setTimeout( function() { var step = self.options.step, max= self.options.maxStep, min = 1; if( max > self.showTotal ) { max = self.showTotal; } // number of items to swith at this point of time var nmbOut = step === 'random' ? Math.floor( Math.random() * max + min ) : Math.min( Math.abs( step ) , max ) , // array with random indexes. These will be the indexes of the items we will replace randArr = self._getRandom( nmbOut, self.showTotal ); for( var i = 0; i < nmbOut; ++i ) { // element to go out var $out = self.$items.eq( randArr[ i ] ); // if element is active, which means it is currently animating, // then we need to get different positions.. if( $out.data( 'active' ) || $out.data( 'nochange' ) ) { // one of the items is active, call again.. self._showNext( 1 ); return false; } self._replace( $out ); } // again and again.. self._showNext(); }, time || Math.max( Math.abs( this.options.interval ) , 300 ) ); }, _replace : function( $out ) { $out.data( 'active', true ); var self = this, $outA = $out.children( 'a:last' ), newElProp = { width : $outA.width(), height : $outA.height() }; // element stays active $out.data( 'active', true ); // get the element (anchor) that will go in (first one inserted in this.outItems) var $inA = this.outItems.shift(); // save element that went out this.outItems.push( $outA.clone().css( 'transition', 'none' ) ); // prepend in element $inA.css( newElProp ).prependTo( $out ); var animProp = this._getAnimProperties( $outA ); $inA.css( animProp.startInProp ); $outA.css( animProp.startOutProp ); this._setTransition( $inA, 'all', animProp.animSpeed, animProp.delay, this.options.animEasingIn ); this._setTransition( $outA, 'all', animProp.animSpeed, 0, this.options.animEasingOut ); this._applyTransition( $inA, animProp.endInProp, animProp.animSpeed, function() { var $el = $( this ), t = animProp.animSpeed === self.options.animSpeed && isEmpty( animProp.endInProp ) ? animProp.animSpeed : 0; setTimeout( function() { if( self.supportTransitions ) { $el.off( self.transEndEventName ); } $el.next().remove(); $el.parent().data( 'active', false ); }, t ); }, animProp.animSpeed === 0 || isEmpty( animProp.endInProp ) ); this._applyTransition( $outA, animProp.endOutProp, animProp.animSpeed ); }, _getRandom : function( cnt, limit ) { var randArray = []; for( var i = 0; i < limit; ++i ) { randArray.push( i ) } return randArray.shuffle().slice( 0, cnt ); }, _setTransition : function( el, prop, speed, delay, easing ) { setTimeout( function() { el.css( 'transition', prop + ' ' + speed + 'ms ' + delay + 'ms ' + easing ); }, 25 ); }, _applyTransition : function( el, styleCSS, speed, fncomplete, force ) { var self = this; setTimeout( function() { $.fn.applyStyle = self.supportTransitions ? $.fn.css : $.fn.animate; if( fncomplete && self.supportTransitions ) { el.on( self.transEndEventName, fncomplete ); if( force ) { fncomplete.call( el ); } } fncomplete = fncomplete || function() { return false; }; el.stop().applyStyle( styleCSS, $.extend( true, [], { duration : speed + 'ms', complete : fncomplete } ) ); }, 25 ); } }; var logError = function( message ) { if ( window.console ) { window.console.error( message ); } }; $.fn.gridrotator = function( options ) { var instance = $.data( this, 'gridrotator' ); if ( typeof options === 'string' ) { var args = Array.prototype.slice.call( arguments, 1 ); this.each(function() { if ( !instance ) { logError( "cannot call methods on gridrotator prior to initialization; " + "attempted to call method '" + options + "'" ); return; } if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) { logError( "no such method '" + options + "' for gridrotator instance" ); return; } instance[ options ].apply( instance, args ); }); } else { this.each(function() { if ( instance ) { instance._init(); } else { instance = $.data( this, 'gridrotator', new $.GridRotator( options, this ) ); } }); } return instance; }; } )( jQuery, window );
JavaScript
/*! * classie - class helper functions * from bonzo https://github.com/ded/bonzo * * classie.has( elem, 'my-class' ) -> true/false * classie.add( elem, 'my-new-class' ) * classie.remove( elem, 'my-unwanted-class' ) * classie.toggle( elem, 'my-class' ) */ /*jshint browser: true, strict: true, undef: true */ /*global define: false */ ( function( window ) { 'use strict'; // class helper functions from bonzo https://github.com/ded/bonzo function classReg( className ) { return new RegExp("(^|\\s+)" + className + "(\\s+|$)"); } // classList support for class management // altho to be fair, the api sucks because it won't accept multiple classes at once var hasClass, addClass, removeClass; if ( 'classList' in document.documentElement ) { hasClass = function( elem, c ) { return elem.classList.contains( c ); }; addClass = function( elem, c ) { elem.classList.add( c ); }; removeClass = function( elem, c ) { elem.classList.remove( c ); }; } else { hasClass = function( elem, c ) { return classReg( c ).test( elem.className ); }; addClass = function( elem, c ) { if ( !hasClass( elem, c ) ) { elem.className = elem.className + ' ' + c; } }; removeClass = function( elem, c ) { elem.className = elem.className.replace( classReg( c ), ' ' ); }; } function toggleClass( elem, c ) { var fn = hasClass( elem, c ) ? removeClass : addClass; fn( elem, c ); } var classie = { // full names hasClass: hasClass, addClass: addClass, removeClass: removeClass, toggleClass: toggleClass, // short names has: hasClass, add: addClass, remove: removeClass, toggle: toggleClass }; // transport if ( typeof define === 'function' && define.amd ) { // AMD define( classie ); } else { // browser global window.classie = classie; } })( window );
JavaScript
/** * cbpGridGallery.js v1.0.0 * http://www.codrops.com * * Licensed under the MIT license. * http://www.opensource.org/licenses/mit-license.php * * Copyright 2014, Codrops * http://www.codrops.com */ ;( function( window ) { 'use strict'; var docElem = window.document.documentElement, transEndEventNames = { 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'transitionend', 'OTransition': 'oTransitionEnd', 'msTransition': 'MSTransitionEnd', 'transition': 'transitionend' }, transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ], support = { transitions : Modernizr.csstransitions, support3d : Modernizr.csstransforms3d }; function setTransform( el, transformStr ) { el.style.WebkitTransform = transformStr; el.style.msTransform = transformStr; el.style.transform = transformStr; } // from http://responsejs.com/labs/dimensions/ function getViewportW() { var client = docElem['clientWidth'], inner = window['innerWidth']; if( client < inner ) return inner; else return client; } function extend( a, b ) { for( var key in b ) { if( b.hasOwnProperty( key ) ) { a[key] = b[key]; } } return a; } function CBPGridGallery( el, options ) { this.el = el; this.options = extend( {}, this.options ); extend( this.options, options ); this._init(); } CBPGridGallery.prototype.options = { }; CBPGridGallery.prototype._init = function() { // main grid this.grid = this.el.querySelector( 'section.grid-wrap > ul.grid' ); // main grid items this.gridItems = [].slice.call( this.grid.querySelectorAll( 'li:not(.grid-sizer)' ) ); // items total this.itemsCount = this.gridItems.length; // slideshow grid this.slideshow = this.el.querySelector( 'section.slideshow > ul' ); // slideshow grid items this.slideshowItems = [].slice.call( this.slideshow.children ); // index of current slideshow item this.current = -1; // slideshow control buttons this.ctrlPrev = this.el.querySelector( 'section.slideshow > nav > span.nav-prev' ); this.ctrlNext = this.el.querySelector( 'section.slideshow > nav > span.nav-next' ); this.ctrlClose = this.el.querySelector( 'section.slideshow > nav > span.nav-close' ); // init masonry grid this._initMasonry(); // init events this._initEvents(); }; CBPGridGallery.prototype._initMasonry = function() { var grid = this.grid; imagesLoaded( grid, function() { new Masonry( grid, { itemSelector: 'li', columnWidth: grid.querySelector( '.grid-sizer' ) }); }); }; CBPGridGallery.prototype._initEvents = function() { var self = this; // open the slideshow when clicking on the main grid items this.gridItems.forEach( function( item, idx ) { item.addEventListener( 'click', function() { self._openSlideshow( idx ); } ); } ); // slideshow controls this.ctrlPrev.addEventListener( 'click', function() { self._navigate( 'prev' ); } ); this.ctrlNext.addEventListener( 'click', function() { self._navigate( 'next' ); } ); this.ctrlClose.addEventListener( 'click', function() { self._closeSlideshow(); } ); // window resize window.addEventListener( 'resize', function() { self._resizeHandler(); } ); // keyboard navigation events document.addEventListener( 'keydown', function( ev ) { if ( self.isSlideshowVisible ) { var keyCode = ev.keyCode || ev.which; switch (keyCode) { case 37: self._navigate( 'prev' ); break; case 39: self._navigate( 'next' ); break; case 27: self._closeSlideshow(); break; } } } ); // trick to prevent scrolling when slideshow is visible window.addEventListener( 'scroll', function() { if ( self.isSlideshowVisible ) { window.scrollTo( self.scrollPosition ? self.scrollPosition.x : 0, self.scrollPosition ? self.scrollPosition.y : 0 ); } else { self.scrollPosition = { x : window.pageXOffset || docElem.scrollLeft, y : window.pageYOffset || docElem.scrollTop }; } }); }; CBPGridGallery.prototype._openSlideshow = function( pos ) { this.isSlideshowVisible = true; this.current = pos; classie.addClass( this.el, 'slideshow-open' ); /* position slideshow items */ // set viewport items (current, next and previous) this._setViewportItems(); // add class "current" and "show" to currentItem classie.addClass( this.currentItem, 'current' ); classie.addClass( this.currentItem, 'show' ); // add class show to next and previous items // position previous item on the left side and the next item on the right side if( this.prevItem ) { classie.addClass( this.prevItem, 'show' ); var translateVal = Number( -1 * ( getViewportW() / 2 + this.prevItem.offsetWidth / 2 ) ); setTransform( this.prevItem, support.support3d ? 'translate3d(' + translateVal + 'px, 0, -150px)' : 'translate(' + translateVal + 'px)' ); } if( this.nextItem ) { classie.addClass( this.nextItem, 'show' ); var translateVal = Number( getViewportW() / 2 + this.nextItem.offsetWidth / 2 ); setTransform( this.nextItem, support.support3d ? 'translate3d(' + translateVal + 'px, 0, -150px)' : 'translate(' + translateVal + 'px)' ); } }; CBPGridGallery.prototype._navigate = function( dir ) { if( this.isAnimating ) return; if( dir === 'next' && this.current === this.itemsCount - 1 || dir === 'prev' && this.current === 0 ) { this._closeSlideshow(); return; } this.isAnimating = true; // reset viewport items this._setViewportItems(); var self = this, itemWidth = this.currentItem.offsetWidth, // positions for the centered/current item, both the side items and the incoming ones transformLeftStr = support.support3d ? 'translate3d(-' + Number( getViewportW() / 2 + itemWidth / 2 ) + 'px, 0, -150px)' : 'translate(-' + Number( getViewportW() / 2 + itemWidth / 2 ) + 'px)', transformRightStr = support.support3d ? 'translate3d(' + Number( getViewportW() / 2 + itemWidth / 2 ) + 'px, 0, -150px)' : 'translate(' + Number( getViewportW() / 2 + itemWidth / 2 ) + 'px)', transformCenterStr = '', transformOutStr, transformIncomingStr, // incoming item incomingItem; if( dir === 'next' ) { transformOutStr = support.support3d ? 'translate3d( -' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px, 0, -150px )' : 'translate(-' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px)'; transformIncomingStr = support.support3d ? 'translate3d( ' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px, 0, -150px )' : 'translate(' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px)'; } else { transformOutStr = support.support3d ? 'translate3d( ' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px, 0, -150px )' : 'translate(' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px)'; transformIncomingStr = support.support3d ? 'translate3d( -' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px, 0, -150px )' : 'translate(-' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px)'; } // remove class animatable from the slideshow grid (if it has already) classie.removeClass( self.slideshow, 'animatable' ); if( dir === 'next' && this.current < this.itemsCount - 2 || dir === 'prev' && this.current > 1 ) { // we have an incoming item! incomingItem = this.slideshowItems[ dir === 'next' ? this.current + 2 : this.current - 2 ]; setTransform( incomingItem, transformIncomingStr ); classie.addClass( incomingItem, 'show' ); } var slide = function() { // add class animatable to the slideshow grid classie.addClass( self.slideshow, 'animatable' ); // overlays: classie.removeClass( self.currentItem, 'current' ); var nextCurrent = dir === 'next' ? self.nextItem : self.prevItem; classie.addClass( nextCurrent, 'current' ); setTransform( self.currentItem, dir === 'next' ? transformLeftStr : transformRightStr ); if( self.nextItem ) { setTransform( self.nextItem, dir === 'next' ? transformCenterStr : transformOutStr ); } if( self.prevItem ) { setTransform( self.prevItem, dir === 'next' ? transformOutStr : transformCenterStr ); } if( incomingItem ) { setTransform( incomingItem, dir === 'next' ? transformRightStr : transformLeftStr ); } var onEndTransitionFn = function( ev ) { if( support.transitions ) { if( ev.propertyName.indexOf( 'transform' ) === -1 ) return false; this.removeEventListener( transEndEventName, onEndTransitionFn ); } if( self.prevItem && dir === 'next' ) { classie.removeClass( self.prevItem, 'show' ); } else if( self.nextItem && dir === 'prev' ) { classie.removeClass( self.nextItem, 'show' ); } if( dir === 'next' ) { self.prevItem = self.currentItem; self.currentItem = self.nextItem; if( incomingItem ) { self.nextItem = incomingItem; } } else { self.nextItem = self.currentItem; self.currentItem = self.prevItem; if( incomingItem ) { self.prevItem = incomingItem; } } self.current = dir === 'next' ? self.current + 1 : self.current - 1; self.isAnimating = false; }; if( support.transitions ) { self.currentItem.addEventListener( transEndEventName, onEndTransitionFn ); } else { onEndTransitionFn(); } }; setTimeout( slide, 25 ); } CBPGridGallery.prototype._closeSlideshow = function( pos ) { // remove class slideshow-open from the grid gallery elem classie.removeClass( this.el, 'slideshow-open' ); // remove class animatable from the slideshow grid classie.removeClass( this.slideshow, 'animatable' ); var self = this, onEndTransitionFn = function( ev ) { if( support.transitions ) { if( ev.target.tagName.toLowerCase() !== 'ul' ) return; this.removeEventListener( transEndEventName, onEndTransitionFn ); } // remove classes show and current from the slideshow items classie.removeClass( self.currentItem, 'current' ); classie.removeClass( self.currentItem, 'show' ); if( self.prevItem ) { classie.removeClass( self.prevItem, 'show' ); } if( self.nextItem ) { classie.removeClass( self.nextItem, 'show' ); } // also reset any transforms for all the items self.slideshowItems.forEach( function( item ) { setTransform( item, '' ); } ); self.isSlideshowVisible = false; }; if( support.transitions ) { this.el.addEventListener( transEndEventName, onEndTransitionFn ); } else { onEndTransitionFn(); } }; CBPGridGallery.prototype._setViewportItems = function() { this.currentItem = null; this.prevItem = null; this.nextItem = null; if( this.current > 0 ) { this.prevItem = this.slideshowItems[ this.current - 1 ]; } if( this.current < this.itemsCount - 1 ) { this.nextItem = this.slideshowItems[ this.current + 1 ]; } this.currentItem = this.slideshowItems[ this.current ]; } // taken from https://github.com/desandro/vanilla-masonry/blob/master/masonry.js by David DeSandro // original debounce by John Hann // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/ CBPGridGallery.prototype._resizeHandler = function() { var self = this; function delayed() { self._resize(); self._resizeTimeout = null; } if ( this._resizeTimeout ) { clearTimeout( this._resizeTimeout ); } this._resizeTimeout = setTimeout( delayed, 50 ); } CBPGridGallery.prototype._resize = function() { if ( this.isSlideshowVisible ) { // update width value if( this.prevItem ) { var translateVal = Number( -1 * ( getViewportW() / 2 + this.prevItem.offsetWidth / 2 ) ); setTransform( this.prevItem, support.support3d ? 'translate3d(' + translateVal + 'px, 0, -150px)' : 'translate(' + translateVal + 'px)' ); } if( this.nextItem ) { var translateVal = Number( getViewportW() / 2 + this.nextItem.offsetWidth / 2 ); setTransform( this.nextItem, support.support3d ? 'translate3d(' + translateVal + 'px, 0, -150px)' : 'translate(' + translateVal + 'px)' ); } } } // add to global namespace window.CBPGridGallery = CBPGridGallery; })( window );
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Simple utilities for dealing with URI strings. * * This is intended to be a lightweight alternative to constructing goog.Uri * objects. Whereas goog.Uri adds several kilobytes to the binary regardless * of how much of its functionality you use, this is designed to be a set of * mostly-independent utilities so that the compiler includes only what is * necessary for the task. Estimated savings of porting is 5k pre-gzip and * 1.5k post-gzip. To ensure the savings remain, future developers should * avoid adding new functionality to existing functions, but instead create * new ones and factor out shared code. * * Many of these utilities have limited functionality, tailored to common * cases. The query parameter utilities assume that the parameter keys are * already encoded, since most keys are compile-time alphanumeric strings. The * query parameter mutation utilities also do not tolerate fragment identifiers. * * By design, these functions can be slower than goog.Uri equivalents. * Repeated calls to some of functions may be quadratic in behavior for IE, * although the effect is somewhat limited given the 2kb limit. * * One advantage of the limited functionality here is that this approach is * less sensitive to differences in URI encodings than goog.Uri, since these * functions modify the strings in place, rather than decoding and * re-encoding. * * Uses features of RFC 3986 for parsing/formatting URIs: * http://gbiv.com/protocols/uri/rfc/rfc3986.html * * @author gboyer@google.com (Garrett Boyer) - The "lightened" design. * @author msamuel@google.com (Mike Samuel) - Domain knowledge and regexes. */ goog.provide('goog.uri.utils'); goog.provide('goog.uri.utils.ComponentIndex'); goog.provide('goog.uri.utils.QueryArray'); goog.provide('goog.uri.utils.QueryValue'); goog.provide('goog.uri.utils.StandardQueryParam'); goog.require('goog.asserts'); goog.require('goog.string'); goog.require('goog.userAgent'); /** * Character codes inlined to avoid object allocations due to charCode. * @enum {number} * @private */ goog.uri.utils.CharCode_ = { AMPERSAND: 38, EQUAL: 61, HASH: 35, QUESTION: 63 }; /** * Builds a URI string from already-encoded parts. * * No encoding is performed. Any component may be omitted as either null or * undefined. * * @param {?string=} opt_scheme The scheme such as 'http'. * @param {?string=} opt_userInfo The user name before the '@'. * @param {?string=} opt_domain The domain such as 'www.google.com', already * URI-encoded. * @param {(string|number|null)=} opt_port The port number. * @param {?string=} opt_path The path, already URI-encoded. If it is not * empty, it must begin with a slash. * @param {?string=} opt_queryData The URI-encoded query data. * @param {?string=} opt_fragment The URI-encoded fragment identifier. * @return {string} The fully combined URI. */ goog.uri.utils.buildFromEncodedParts = function(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) { var out = ''; if (opt_scheme) { out += opt_scheme + ':'; } if (opt_domain) { out += '//'; if (opt_userInfo) { out += opt_userInfo + '@'; } out += opt_domain; if (opt_port) { out += ':' + opt_port; } } if (opt_path) { out += opt_path; } if (opt_queryData) { out += '?' + opt_queryData; } if (opt_fragment) { out += '#' + opt_fragment; } return out; }; /** * A regular expression for breaking a URI into its component parts. * * {@link http://www.gbiv.com/protocols/uri/rfc/rfc3986.html#RFC2234} says * As the "first-match-wins" algorithm is identical to the "greedy" * disambiguation method used by POSIX regular expressions, it is natural and * commonplace to use a regular expression for parsing the potential five * components of a URI reference. * * The following line is the regular expression for breaking-down a * well-formed URI reference into its components. * * <pre> * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? * 12 3 4 5 6 7 8 9 * </pre> * * The numbers in the second line above are only to assist readability; they * indicate the reference points for each subexpression (i.e., each paired * parenthesis). We refer to the value matched for subexpression <n> as $<n>. * For example, matching the above expression to * <pre> * http://www.ics.uci.edu/pub/ietf/uri/#Related * </pre> * results in the following subexpression matches: * <pre> * $1 = http: * $2 = http * $3 = //www.ics.uci.edu * $4 = www.ics.uci.edu * $5 = /pub/ietf/uri/ * $6 = <undefined> * $7 = <undefined> * $8 = #Related * $9 = Related * </pre> * where <undefined> indicates that the component is not present, as is the * case for the query component in the above example. Therefore, we can * determine the value of the five components as * <pre> * scheme = $2 * authority = $4 * path = $5 * query = $7 * fragment = $9 * </pre> * * The regular expression has been modified slightly to expose the * userInfo, domain, and port separately from the authority. * The modified version yields * <pre> * $1 = http scheme * $2 = <undefined> userInfo -\ * $3 = www.ics.uci.edu domain | authority * $4 = <undefined> port -/ * $5 = /pub/ietf/uri/ path * $6 = <undefined> query without ? * $7 = Related fragment without # * </pre> * @type {!RegExp} * @private */ goog.uri.utils.splitRe_ = new RegExp( '^' + '(?:' + '([^:/?#.]+)' + // scheme - ignore special characters // used by other URL parts such as :, // ?, /, #, and . ':)?' + '(?://' + '(?:([^/?#]*)@)?' + // userInfo '([^/#?]*?)' + // domain '(?::([0-9]+))?' + // port '(?=[/#?]|$)' + // authority-terminating character ')?' + '([^?#]+)?' + // path '(?:\\?([^#]*))?' + // query '(?:#(.*))?' + // fragment '$'); /** * The index of each URI component in the return value of goog.uri.utils.split. * @enum {number} */ goog.uri.utils.ComponentIndex = { SCHEME: 1, USER_INFO: 2, DOMAIN: 3, PORT: 4, PATH: 5, QUERY_DATA: 6, FRAGMENT: 7 }; /** * Splits a URI into its component parts. * * Each component can be accessed via the component indices; for example: * <pre> * goog.uri.utils.split(someStr)[goog.uri.utils.CompontentIndex.QUERY_DATA]; * </pre> * * @param {string} uri The URI string to examine. * @return {!Array.<string|undefined>} Each component still URI-encoded. * Each component that is present will contain the encoded value, whereas * components that are not present will be undefined or empty, depending * on the browser's regular expression implementation. Never null, since * arbitrary strings may still look like path names. */ goog.uri.utils.split = function(uri) { // See @return comment -- never null. return /** @type {!Array.<string|undefined>} */ ( uri.match(goog.uri.utils.splitRe_)); }; /** * @param {?string} uri A possibly null string. * @return {?string} The string URI-decoded, or null if uri is null. * @private */ goog.uri.utils.decodeIfPossible_ = function(uri) { return uri && decodeURIComponent(uri); }; /** * Gets a URI component by index. * * It is preferred to use the getPathEncoded() variety of functions ahead, * since they are more readable. * * @param {goog.uri.utils.ComponentIndex} componentIndex The component index. * @param {string} uri The URI to examine. * @return {?string} The still-encoded component, or null if the component * is not present. * @private */ goog.uri.utils.getComponentByIndex_ = function(componentIndex, uri) { // Convert undefined, null, and empty string into null. return goog.uri.utils.split(uri)[componentIndex] || null; }; /** * @param {string} uri The URI to examine. * @return {?string} The protocol or scheme, or null if none. Does not * include trailing colons or slashes. */ goog.uri.utils.getScheme = function(uri) { return goog.uri.utils.getComponentByIndex_( goog.uri.utils.ComponentIndex.SCHEME, uri); }; /** * Gets the effective scheme for the URL. If the URL is relative then the * scheme is derived from the page's location. * @param {string} uri The URI to examine. * @return {string} The protocol or scheme, always lower case. */ goog.uri.utils.getEffectiveScheme = function(uri) { var scheme = goog.uri.utils.getScheme(uri); if (!scheme && self.location) { var protocol = self.location.protocol; scheme = protocol.substr(0, protocol.length - 1); } // NOTE: When called from a web worker in Firefox 3.5, location maybe null. // All other browsers with web workers support self.location from the worker. return scheme ? scheme.toLowerCase() : ''; }; /** * @param {string} uri The URI to examine. * @return {?string} The user name still encoded, or null if none. */ goog.uri.utils.getUserInfoEncoded = function(uri) { return goog.uri.utils.getComponentByIndex_( goog.uri.utils.ComponentIndex.USER_INFO, uri); }; /** * @param {string} uri The URI to examine. * @return {?string} The decoded user info, or null if none. */ goog.uri.utils.getUserInfo = function(uri) { return goog.uri.utils.decodeIfPossible_( goog.uri.utils.getUserInfoEncoded(uri)); }; /** * @param {string} uri The URI to examine. * @return {?string} The domain name still encoded, or null if none. */ goog.uri.utils.getDomainEncoded = function(uri) { return goog.uri.utils.getComponentByIndex_( goog.uri.utils.ComponentIndex.DOMAIN, uri); }; /** * @param {string} uri The URI to examine. * @return {?string} The decoded domain, or null if none. */ goog.uri.utils.getDomain = function(uri) { return goog.uri.utils.decodeIfPossible_(goog.uri.utils.getDomainEncoded(uri)); }; /** * @param {string} uri The URI to examine. * @return {?number} The port number, or null if none. */ goog.uri.utils.getPort = function(uri) { // Coerce to a number. If the result of getComponentByIndex_ is null or // non-numeric, the number coersion yields NaN. This will then return // null for all non-numeric cases (though also zero, which isn't a relevant // port number). return Number(goog.uri.utils.getComponentByIndex_( goog.uri.utils.ComponentIndex.PORT, uri)) || null; }; /** * @param {string} uri The URI to examine. * @return {?string} The path still encoded, or null if none. Includes the * leading slash, if any. */ goog.uri.utils.getPathEncoded = function(uri) { return goog.uri.utils.getComponentByIndex_( goog.uri.utils.ComponentIndex.PATH, uri); }; /** * @param {string} uri The URI to examine. * @return {?string} The decoded path, or null if none. Includes the leading * slash, if any. */ goog.uri.utils.getPath = function(uri) { return goog.uri.utils.decodeIfPossible_(goog.uri.utils.getPathEncoded(uri)); }; /** * @param {string} uri The URI to examine. * @return {?string} The query data still encoded, or null if none. Does not * include the question mark itself. */ goog.uri.utils.getQueryData = function(uri) { return goog.uri.utils.getComponentByIndex_( goog.uri.utils.ComponentIndex.QUERY_DATA, uri); }; /** * @param {string} uri The URI to examine. * @return {?string} The fragment identifier, or null if none. Does not * include the hash mark itself. */ goog.uri.utils.getFragmentEncoded = function(uri) { // The hash mark may not appear in any other part of the URL. var hashIndex = uri.indexOf('#'); return hashIndex < 0 ? null : uri.substr(hashIndex + 1); }; /** * @param {string} uri The URI to examine. * @param {?string} fragment The encoded fragment identifier, or null if none. * Does not include the hash mark itself. * @return {string} The URI with the fragment set. */ goog.uri.utils.setFragmentEncoded = function(uri, fragment) { return goog.uri.utils.removeFragment(uri) + (fragment ? '#' + fragment : ''); }; /** * @param {string} uri The URI to examine. * @return {?string} The decoded fragment identifier, or null if none. Does * not include the hash mark. */ goog.uri.utils.getFragment = function(uri) { return goog.uri.utils.decodeIfPossible_( goog.uri.utils.getFragmentEncoded(uri)); }; /** * Extracts everything up to the port of the URI. * @param {string} uri The URI string. * @return {string} Everything up to and including the port. */ goog.uri.utils.getHost = function(uri) { var pieces = goog.uri.utils.split(uri); return goog.uri.utils.buildFromEncodedParts( pieces[goog.uri.utils.ComponentIndex.SCHEME], pieces[goog.uri.utils.ComponentIndex.USER_INFO], pieces[goog.uri.utils.ComponentIndex.DOMAIN], pieces[goog.uri.utils.ComponentIndex.PORT]); }; /** * Extracts the path of the URL and everything after. * @param {string} uri The URI string. * @return {string} The URI, starting at the path and including the query * parameters and fragment identifier. */ goog.uri.utils.getPathAndAfter = function(uri) { var pieces = goog.uri.utils.split(uri); return goog.uri.utils.buildFromEncodedParts(null, null, null, null, pieces[goog.uri.utils.ComponentIndex.PATH], pieces[goog.uri.utils.ComponentIndex.QUERY_DATA], pieces[goog.uri.utils.ComponentIndex.FRAGMENT]); }; /** * Gets the URI with the fragment identifier removed. * @param {string} uri The URI to examine. * @return {string} Everything preceding the hash mark. */ goog.uri.utils.removeFragment = function(uri) { // The hash mark may not appear in any other part of the URL. var hashIndex = uri.indexOf('#'); return hashIndex < 0 ? uri : uri.substr(0, hashIndex); }; /** * Ensures that two URI's have the exact same domain, scheme, and port. * * Unlike the version in goog.Uri, this checks protocol, and therefore is * suitable for checking against the browser's same-origin policy. * * @param {string} uri1 The first URI. * @param {string} uri2 The second URI. * @return {boolean} Whether they have the same domain and port. */ goog.uri.utils.haveSameDomain = function(uri1, uri2) { var pieces1 = goog.uri.utils.split(uri1); var pieces2 = goog.uri.utils.split(uri2); return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] == pieces2[goog.uri.utils.ComponentIndex.DOMAIN] && pieces1[goog.uri.utils.ComponentIndex.SCHEME] == pieces2[goog.uri.utils.ComponentIndex.SCHEME] && pieces1[goog.uri.utils.ComponentIndex.PORT] == pieces2[goog.uri.utils.ComponentIndex.PORT]; }; /** * Asserts that there are no fragment or query identifiers, only in uncompiled * mode. * @param {string} uri The URI to examine. * @private */ goog.uri.utils.assertNoFragmentsOrQueries_ = function(uri) { // NOTE: would use goog.asserts here, but jscompiler doesn't know that // indexOf has no side effects. if (goog.DEBUG && (uri.indexOf('#') >= 0 || uri.indexOf('?') >= 0)) { throw Error('goog.uri.utils: Fragment or query identifiers are not ' + 'supported: [' + uri + ']'); } }; /** * Supported query parameter values by the parameter serializing utilities. * * If a value is null or undefined, the key-value pair is skipped, as an easy * way to omit parameters conditionally. Non-array parameters are converted * to a string and URI encoded. Array values are expanded into multiple * &key=value pairs, with each element stringized and URI-encoded. * * @typedef {*} */ goog.uri.utils.QueryValue; /** * An array representing a set of query parameters with alternating keys * and values. * * Keys are assumed to be URI encoded already and live at even indices. See * goog.uri.utils.QueryValue for details on how parameter values are encoded. * * Example: * <pre> * var data = [ * // Simple param: ?name=BobBarker * 'name', 'BobBarker', * // Conditional param -- may be omitted entirely. * 'specialDietaryNeeds', hasDietaryNeeds() ? getDietaryNeeds() : null, * // Multi-valued param: &house=LosAngeles&house=NewYork&house=null * 'house', ['LosAngeles', 'NewYork', null] * ]; * </pre> * * @typedef {!Array.<string|goog.uri.utils.QueryValue>} */ goog.uri.utils.QueryArray; /** * Appends a URI and query data in a string buffer with special preconditions. * * Internal implementation utility, performing very few object allocations. * * @param {!Array.<string|undefined>} buffer A string buffer. The first element * must be the base URI, and may have a fragment identifier. If the array * contains more than one element, the second element must be an ampersand, * and may be overwritten, depending on the base URI. Undefined elements * are treated as empty-string. * @return {string} The concatenated URI and query data. * @private */ goog.uri.utils.appendQueryData_ = function(buffer) { if (buffer[1]) { // At least one query parameter was added. We need to check the // punctuation mark, which is currently an ampersand, and also make sure // there aren't any interfering fragment identifiers. var baseUri = /** @type {string} */ (buffer[0]); var hashIndex = baseUri.indexOf('#'); if (hashIndex >= 0) { // Move the fragment off the base part of the URI into the end. buffer.push(baseUri.substr(hashIndex)); buffer[0] = baseUri = baseUri.substr(0, hashIndex); } var questionIndex = baseUri.indexOf('?'); if (questionIndex < 0) { // No question mark, so we need a question mark instead of an ampersand. buffer[1] = '?'; } else if (questionIndex == baseUri.length - 1) { // Question mark is the very last character of the existing URI, so don't // append an additional delimiter. buffer[1] = undefined; } } return buffer.join(''); }; /** * Appends key=value pairs to an array, supporting multi-valued objects. * @param {string} key The key prefix. * @param {goog.uri.utils.QueryValue} value The value to serialize. * @param {!Array.<string>} pairs The array to which the 'key=value' strings * should be appended. * @private */ goog.uri.utils.appendKeyValuePairs_ = function(key, value, pairs) { if (goog.isArray(value)) { // Convince the compiler it's an array. goog.asserts.assertArray(value); for (var j = 0; j < value.length; j++) { // Convert to string explicitly, to short circuit the null and array // logic in this function -- this ensures that null and undefined get // written as literal 'null' and 'undefined', and arrays don't get // expanded out but instead encoded in the default way. goog.uri.utils.appendKeyValuePairs_(key, String(value[j]), pairs); } } else if (value != null) { // Skip a top-level null or undefined entirely. pairs.push('&', key, // Check for empty string. Zero gets encoded into the url as literal // strings. For empty string, skip the equal sign, to be consistent // with UriBuilder.java. value === '' ? '' : '=', goog.string.urlEncode(value)); } }; /** * Builds a buffer of query data from a sequence of alternating keys and values. * * @param {!Array.<string|undefined>} buffer A string buffer to append to. The * first element appended will be an '&', and may be replaced by the caller. * @param {goog.uri.utils.QueryArray|Arguments} keysAndValues An array with * alternating keys and values -- see the typedef. * @param {number=} opt_startIndex A start offset into the arary, defaults to 0. * @return {!Array.<string|undefined>} The buffer argument. * @private */ goog.uri.utils.buildQueryDataBuffer_ = function( buffer, keysAndValues, opt_startIndex) { goog.asserts.assert(Math.max(keysAndValues.length - (opt_startIndex || 0), 0) % 2 == 0, 'goog.uri.utils: Key/value lists must be even in length.'); for (var i = opt_startIndex || 0; i < keysAndValues.length; i += 2) { goog.uri.utils.appendKeyValuePairs_( keysAndValues[i], keysAndValues[i + 1], buffer); } return buffer; }; /** * Builds a query data string from a sequence of alternating keys and values. * Currently generates "&key&" for empty args. * * @param {goog.uri.utils.QueryArray} keysAndValues Alternating keys and * values. See the typedef. * @param {number=} opt_startIndex A start offset into the arary, defaults to 0. * @return {string} The encoded query string, in the for 'a=1&b=2'. */ goog.uri.utils.buildQueryData = function(keysAndValues, opt_startIndex) { var buffer = goog.uri.utils.buildQueryDataBuffer_( [], keysAndValues, opt_startIndex); buffer[0] = ''; // Remove the leading ampersand. return buffer.join(''); }; /** * Builds a buffer of query data from a map. * * @param {!Array.<string|undefined>} buffer A string buffer to append to. The * first element appended will be an '&', and may be replaced by the caller. * @param {Object.<goog.uri.utils.QueryValue>} map An object where keys are * URI-encoded parameter keys, and the values conform to the contract * specified in the goog.uri.utils.QueryValue typedef. * @return {!Array.<string|undefined>} The buffer argument. * @private */ goog.uri.utils.buildQueryDataBufferFromMap_ = function(buffer, map) { for (var key in map) { goog.uri.utils.appendKeyValuePairs_(key, map[key], buffer); } return buffer; }; /** * Builds a query data string from a map. * Currently generates "&key&" for empty args. * * @param {Object} map An object where keys are URI-encoded parameter keys, * and the values are arbitrary types or arrays. Keys with a null value * are dropped. * @return {string} The encoded query string, in the for 'a=1&b=2'. */ goog.uri.utils.buildQueryDataFromMap = function(map) { var buffer = goog.uri.utils.buildQueryDataBufferFromMap_([], map); buffer[0] = ''; return buffer.join(''); }; /** * Appends URI parameters to an existing URI. * * The variable arguments may contain alternating keys and values. Keys are * assumed to be already URI encoded. The values should not be URI-encoded, * and will instead be encoded by this function. * <pre> * appendParams('http://www.foo.com?existing=true', * 'key1', 'value1', * 'key2', 'value?willBeEncoded', * 'key3', ['valueA', 'valueB', 'valueC'], * 'key4', null); * result: 'http://www.foo.com?existing=true&' + * 'key1=value1&' + * 'key2=value%3FwillBeEncoded&' + * 'key3=valueA&key3=valueB&key3=valueC' * </pre> * * A single call to this function will not exhibit quadratic behavior in IE, * whereas multiple repeated calls may, although the effect is limited by * fact that URL's generally can't exceed 2kb. * * @param {string} uri The original URI, which may already have query data. * @param {...(goog.uri.utils.QueryArray|string|goog.uri.utils.QueryValue)} var_args * An array or argument list conforming to goog.uri.utils.QueryArray. * @return {string} The URI with all query parameters added. */ goog.uri.utils.appendParams = function(uri, var_args) { return goog.uri.utils.appendQueryData_( arguments.length == 2 ? goog.uri.utils.buildQueryDataBuffer_([uri], arguments[1], 0) : goog.uri.utils.buildQueryDataBuffer_([uri], arguments, 1)); }; /** * Appends query parameters from a map. * * @param {string} uri The original URI, which may already have query data. * @param {Object} map An object where keys are URI-encoded parameter keys, * and the values are arbitrary types or arrays. Keys with a null value * are dropped. * @return {string} The new parameters. */ goog.uri.utils.appendParamsFromMap = function(uri, map) { return goog.uri.utils.appendQueryData_( goog.uri.utils.buildQueryDataBufferFromMap_([uri], map)); }; /** * Appends a single URI parameter. * * Repeated calls to this can exhibit quadratic behavior in IE6 due to the * way string append works, though it should be limited given the 2kb limit. * * @param {string} uri The original URI, which may already have query data. * @param {string} key The key, which must already be URI encoded. * @param {*} value The value, which will be stringized and encoded (assumed * not already to be encoded). * @return {string} The URI with the query parameter added. */ goog.uri.utils.appendParam = function(uri, key, value) { return goog.uri.utils.appendQueryData_( [uri, '&', key, '=', goog.string.urlEncode(value)]); }; /** * Finds the next instance of a query parameter with the specified name. * * Does not instantiate any objects. * * @param {string} uri The URI to search. May contain a fragment identifier * if opt_hashIndex is specified. * @param {number} startIndex The index to begin searching for the key at. A * match may be found even if this is one character after the ampersand. * @param {string} keyEncoded The URI-encoded key. * @param {number} hashOrEndIndex Index to stop looking at. If a hash * mark is present, it should be its index, otherwise it should be the * length of the string. * @return {number} The position of the first character in the key's name, * immediately after either a question mark or a dot. * @private */ goog.uri.utils.findParam_ = function( uri, startIndex, keyEncoded, hashOrEndIndex) { var index = startIndex; var keyLength = keyEncoded.length; // Search for the key itself and post-filter for surronuding punctuation, // rather than expensively building a regexp. while ((index = uri.indexOf(keyEncoded, index)) >= 0 && index < hashOrEndIndex) { var precedingChar = uri.charCodeAt(index - 1); // Ensure that the preceding character is '&' or '?'. if (precedingChar == goog.uri.utils.CharCode_.AMPERSAND || precedingChar == goog.uri.utils.CharCode_.QUESTION) { // Ensure the following character is '&', '=', '#', or NaN // (end of string). var followingChar = uri.charCodeAt(index + keyLength); if (!followingChar || followingChar == goog.uri.utils.CharCode_.EQUAL || followingChar == goog.uri.utils.CharCode_.AMPERSAND || followingChar == goog.uri.utils.CharCode_.HASH) { return index; } } index += keyLength + 1; } return -1; }; /** * Regular expression for finding a hash mark or end of string. * @type {RegExp} * @private */ goog.uri.utils.hashOrEndRe_ = /#|$/; /** * Determines if the URI contains a specific key. * * Performs no object instantiations. * * @param {string} uri The URI to process. May contain a fragment * identifier. * @param {string} keyEncoded The URI-encoded key. Case-sensitive. * @return {boolean} Whether the key is present. */ goog.uri.utils.hasParam = function(uri, keyEncoded) { return goog.uri.utils.findParam_(uri, 0, keyEncoded, uri.search(goog.uri.utils.hashOrEndRe_)) >= 0; }; /** * Gets the first value of a query parameter. * @param {string} uri The URI to process. May contain a fragment. * @param {string} keyEncoded The URI-encoded key. Case-sensitive. * @return {?string} The first value of the parameter (URI-decoded), or null * if the parameter is not found. */ goog.uri.utils.getParamValue = function(uri, keyEncoded) { var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_); var foundIndex = goog.uri.utils.findParam_( uri, 0, keyEncoded, hashOrEndIndex); if (foundIndex < 0) { return null; } else { var endPosition = uri.indexOf('&', foundIndex); if (endPosition < 0 || endPosition > hashOrEndIndex) { endPosition = hashOrEndIndex; } // Progress forth to the end of the "key=" or "key&" substring. foundIndex += keyEncoded.length + 1; // Use substr, because it (unlike substring) will return empty string // if foundIndex > endPosition. return goog.string.urlDecode( uri.substr(foundIndex, endPosition - foundIndex)); } }; /** * Gets all values of a query parameter. * @param {string} uri The URI to process. May contain a framgnet. * @param {string} keyEncoded The URI-encoded key. Case-snsitive. * @return {!Array.<string>} All URI-decoded values with the given key. * If the key is not found, this will have length 0, but never be null. */ goog.uri.utils.getParamValues = function(uri, keyEncoded) { var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_); var position = 0; var foundIndex; var result = []; while ((foundIndex = goog.uri.utils.findParam_( uri, position, keyEncoded, hashOrEndIndex)) >= 0) { // Find where this parameter ends, either the '&' or the end of the // query parameters. position = uri.indexOf('&', foundIndex); if (position < 0 || position > hashOrEndIndex) { position = hashOrEndIndex; } // Progress forth to the end of the "key=" or "key&" substring. foundIndex += keyEncoded.length + 1; // Use substr, because it (unlike substring) will return empty string // if foundIndex > position. result.push(goog.string.urlDecode(uri.substr( foundIndex, position - foundIndex))); } return result; }; /** * Regexp to find trailing question marks and ampersands. * @type {RegExp} * @private */ goog.uri.utils.trailingQueryPunctuationRe_ = /[?&]($|#)/; /** * Removes all instances of a query parameter. * @param {string} uri The URI to process. Must not contain a fragment. * @param {string} keyEncoded The URI-encoded key. * @return {string} The URI with all instances of the parameter removed. */ goog.uri.utils.removeParam = function(uri, keyEncoded) { var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_); var position = 0; var foundIndex; var buffer = []; // Look for a query parameter. while ((foundIndex = goog.uri.utils.findParam_( uri, position, keyEncoded, hashOrEndIndex)) >= 0) { // Get the portion of the query string up to, but not including, the ? // or & starting the parameter. buffer.push(uri.substring(position, foundIndex)); // Progress to immediately after the '&'. If not found, go to the end. // Avoid including the hash mark. position = Math.min((uri.indexOf('&', foundIndex) + 1) || hashOrEndIndex, hashOrEndIndex); } // Append everything that is remaining. buffer.push(uri.substr(position)); // Join the buffer, and remove trailing punctuation that remains. return buffer.join('').replace( goog.uri.utils.trailingQueryPunctuationRe_, '$1'); }; /** * Replaces all existing definitions of a parameter with a single definition. * * Repeated calls to this can exhibit quadratic behavior due to the need to * find existing instances and reconstruct the string, though it should be * limited given the 2kb limit. Consider using appendParams to append multiple * parameters in bulk. * * @param {string} uri The original URI, which may already have query data. * @param {string} keyEncoded The key, which must already be URI encoded. * @param {*} value The value, which will be stringized and encoded (assumed * not already to be encoded). * @return {string} The URI with the query parameter added. */ goog.uri.utils.setParam = function(uri, keyEncoded, value) { return goog.uri.utils.appendParam( goog.uri.utils.removeParam(uri, keyEncoded), keyEncoded, value); }; /** * Generates a URI path using a given URI and a path with checks to * prevent consecutive "//". The baseUri passed in must not contain * query or fragment identifiers. The path to append may not contain query or * fragment identifiers. * * @param {string} baseUri URI to use as the base. * @param {string} path Path to append. * @return {string} Updated URI. */ goog.uri.utils.appendPath = function(baseUri, path) { goog.uri.utils.assertNoFragmentsOrQueries_(baseUri); // Remove any trailing '/' if (goog.string.endsWith(baseUri, '/')) { baseUri = baseUri.substr(0, baseUri.length - 1); } // Remove any leading '/' if (goog.string.startsWith(path, '/')) { path = path.substr(1); } return goog.string.buildString(baseUri, '/', path); }; /** * Standard supported query parameters. * @enum {string} */ goog.uri.utils.StandardQueryParam = { /** Unused parameter for unique-ifying. */ RANDOM: 'zx' }; /** * Sets the zx parameter of a URI to a random value. * @param {string} uri Any URI. * @return {string} That URI with the "zx" parameter added or replaced to * contain a random string. */ goog.uri.utils.makeUnique = function(uri) { return goog.uri.utils.setParam(uri, goog.uri.utils.StandardQueryParam.RANDOM, goog.string.getRandomString()); };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Class for parsing and formatting URIs. * * Use goog.Uri(string) to parse a URI string. Use goog.Uri.create(...) to * create a new instance of the goog.Uri object from Uri parts. * * e.g: <code>var myUri = new goog.Uri(window.location);</code> * * Implements RFC 3986 for parsing/formatting URIs. * http://gbiv.com/protocols/uri/rfc/rfc3986.html * * Some changes have been made to the interface (more like .NETs), though the * internal representation is now of un-encoded parts, this will change the * behavior slightly. * */ goog.provide('goog.Uri'); goog.provide('goog.Uri.QueryData'); goog.require('goog.array'); goog.require('goog.string'); goog.require('goog.structs'); goog.require('goog.structs.Map'); goog.require('goog.uri.utils'); goog.require('goog.uri.utils.ComponentIndex'); /** * This class contains setters and getters for the parts of the URI. * The <code>getXyz</code>/<code>setXyz</code> methods return the decoded part * -- so<code>goog.Uri.parse('/foo%20bar').getPath()</code> will return the * decoded path, <code>/foo bar</code>. * * The constructor accepts an optional unparsed, raw URI string. The parser * is relaxed, so special characters that aren't escaped but don't cause * ambiguities will not cause parse failures. * * All setters return <code>this</code> and so may be chained, a la * <code>goog.Uri.parse('/foo').setFragment('part').toString()</code>. * * @param {*=} opt_uri Optional string URI to parse * (use goog.Uri.create() to create a URI from parts), or if * a goog.Uri is passed, a clone is created. * @param {boolean=} opt_ignoreCase If true, #getParameterValue will ignore * the case of the parameter name. * * @constructor */ goog.Uri = function(opt_uri, opt_ignoreCase) { // Parse in the uri string var m; if (opt_uri instanceof goog.Uri) { this.ignoreCase_ = goog.isDef(opt_ignoreCase) ? opt_ignoreCase : opt_uri.getIgnoreCase(); this.setScheme(opt_uri.getScheme()); this.setUserInfo(opt_uri.getUserInfo()); this.setDomain(opt_uri.getDomain()); this.setPort(opt_uri.getPort()); this.setPath(opt_uri.getPath()); this.setQueryData(opt_uri.getQueryData().clone()); this.setFragment(opt_uri.getFragment()); } else if (opt_uri && (m = goog.uri.utils.split(String(opt_uri)))) { this.ignoreCase_ = !!opt_ignoreCase; // Set the parts -- decoding as we do so. // COMPATABILITY NOTE - In IE, unmatched fields may be empty strings, // whereas in other browsers they will be undefined. this.setScheme(m[goog.uri.utils.ComponentIndex.SCHEME] || '', true); this.setUserInfo(m[goog.uri.utils.ComponentIndex.USER_INFO] || '', true); this.setDomain(m[goog.uri.utils.ComponentIndex.DOMAIN] || '', true); this.setPort(m[goog.uri.utils.ComponentIndex.PORT]); this.setPath(m[goog.uri.utils.ComponentIndex.PATH] || '', true); this.setQueryData(m[goog.uri.utils.ComponentIndex.QUERY_DATA] || '', true); this.setFragment(m[goog.uri.utils.ComponentIndex.FRAGMENT] || '', true); } else { this.ignoreCase_ = !!opt_ignoreCase; this.queryData_ = new goog.Uri.QueryData(null, null, this.ignoreCase_); } }; /** * If true, we preserve the type of query parameters set programmatically. * * This means that if you set a parameter to a boolean, and then call * getParameterValue, you will get a boolean back. * * If false, we will coerce parameters to strings, just as they would * appear in real URIs. * * TODO(nicksantos): Remove this once people have time to fix all tests. * * @type {boolean} */ goog.Uri.preserveParameterTypesCompatibilityFlag = false; /** * Parameter name added to stop caching. * @type {string} */ goog.Uri.RANDOM_PARAM = goog.uri.utils.StandardQueryParam.RANDOM; /** * Scheme such as "http". * @type {string} * @private */ goog.Uri.prototype.scheme_ = ''; /** * User credentials in the form "username:password". * @type {string} * @private */ goog.Uri.prototype.userInfo_ = ''; /** * Domain part, e.g. "www.google.com". * @type {string} * @private */ goog.Uri.prototype.domain_ = ''; /** * Port, e.g. 8080. * @type {?number} * @private */ goog.Uri.prototype.port_ = null; /** * Path, e.g. "/tests/img.png". * @type {string} * @private */ goog.Uri.prototype.path_ = ''; /** * Object representing query data. * @type {!goog.Uri.QueryData} * @private */ goog.Uri.prototype.queryData_; /** * The fragment without the #. * @type {string} * @private */ goog.Uri.prototype.fragment_ = ''; /** * Whether or not this Uri should be treated as Read Only. * @type {boolean} * @private */ goog.Uri.prototype.isReadOnly_ = false; /** * Whether or not to ignore case when comparing query params. * @type {boolean} * @private */ goog.Uri.prototype.ignoreCase_ = false; /** * @return {string} The string form of the url. * @override */ goog.Uri.prototype.toString = function() { var out = []; var scheme = this.getScheme(); if (scheme) { out.push(goog.Uri.encodeSpecialChars_( scheme, goog.Uri.reDisallowedInSchemeOrUserInfo_), ':'); } var domain = this.getDomain(); if (domain) { out.push('//'); var userInfo = this.getUserInfo(); if (userInfo) { out.push(goog.Uri.encodeSpecialChars_( userInfo, goog.Uri.reDisallowedInSchemeOrUserInfo_), '@'); } out.push(goog.string.urlEncode(domain)); var port = this.getPort(); if (port != null) { out.push(':', String(port)); } } var path = this.getPath(); if (path) { if (this.hasDomain() && path.charAt(0) != '/') { out.push('/'); } out.push(goog.Uri.encodeSpecialChars_( path, path.charAt(0) == '/' ? goog.Uri.reDisallowedInAbsolutePath_ : goog.Uri.reDisallowedInRelativePath_)); } var query = this.getEncodedQuery(); if (query) { out.push('?', query); } var fragment = this.getFragment(); if (fragment) { out.push('#', goog.Uri.encodeSpecialChars_( fragment, goog.Uri.reDisallowedInFragment_)); } return out.join(''); }; /** * Resolves the given relative URI (a goog.Uri object), using the URI * represented by this instance as the base URI. * * There are several kinds of relative URIs:<br> * 1. foo - replaces the last part of the path, the whole query and fragment<br> * 2. /foo - replaces the the path, the query and fragment<br> * 3. //foo - replaces everything from the domain on. foo is a domain name<br> * 4. ?foo - replace the query and fragment<br> * 5. #foo - replace the fragment only * * Additionally, if relative URI has a non-empty path, all ".." and "." * segments will be resolved, as described in RFC 3986. * * @param {goog.Uri} relativeUri The relative URI to resolve. * @return {!goog.Uri} The resolved URI. */ goog.Uri.prototype.resolve = function(relativeUri) { var absoluteUri = this.clone(); // we satisfy these conditions by looking for the first part of relativeUri // that is not blank and applying defaults to the rest var overridden = relativeUri.hasScheme(); if (overridden) { absoluteUri.setScheme(relativeUri.getScheme()); } else { overridden = relativeUri.hasUserInfo(); } if (overridden) { absoluteUri.setUserInfo(relativeUri.getUserInfo()); } else { overridden = relativeUri.hasDomain(); } if (overridden) { absoluteUri.setDomain(relativeUri.getDomain()); } else { overridden = relativeUri.hasPort(); } var path = relativeUri.getPath(); if (overridden) { absoluteUri.setPort(relativeUri.getPort()); } else { overridden = relativeUri.hasPath(); if (overridden) { // resolve path properly if (path.charAt(0) != '/') { // path is relative if (this.hasDomain() && !this.hasPath()) { // RFC 3986, section 5.2.3, case 1 path = '/' + path; } else { // RFC 3986, section 5.2.3, case 2 var lastSlashIndex = absoluteUri.getPath().lastIndexOf('/'); if (lastSlashIndex != -1) { path = absoluteUri.getPath().substr(0, lastSlashIndex + 1) + path; } } } path = goog.Uri.removeDotSegments(path); } } if (overridden) { absoluteUri.setPath(path); } else { overridden = relativeUri.hasQuery(); } if (overridden) { absoluteUri.setQueryData(relativeUri.getDecodedQuery()); } else { overridden = relativeUri.hasFragment(); } if (overridden) { absoluteUri.setFragment(relativeUri.getFragment()); } return absoluteUri; }; /** * Clones the URI instance. * @return {!goog.Uri} New instance of the URI objcet. */ goog.Uri.prototype.clone = function() { return new goog.Uri(this); }; /** * @return {string} The encoded scheme/protocol for the URI. */ goog.Uri.prototype.getScheme = function() { return this.scheme_; }; /** * Sets the scheme/protocol. * @param {string} newScheme New scheme value. * @param {boolean=} opt_decode Optional param for whether to decode new value. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setScheme = function(newScheme, opt_decode) { this.enforceReadOnly(); this.scheme_ = opt_decode ? goog.Uri.decodeOrEmpty_(newScheme) : newScheme; // remove an : at the end of the scheme so somebody can pass in // window.location.protocol if (this.scheme_) { this.scheme_ = this.scheme_.replace(/:$/, ''); } return this; }; /** * @return {boolean} Whether the scheme has been set. */ goog.Uri.prototype.hasScheme = function() { return !!this.scheme_; }; /** * @return {string} The decoded user info. */ goog.Uri.prototype.getUserInfo = function() { return this.userInfo_; }; /** * Sets the userInfo. * @param {string} newUserInfo New userInfo value. * @param {boolean=} opt_decode Optional param for whether to decode new value. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setUserInfo = function(newUserInfo, opt_decode) { this.enforceReadOnly(); this.userInfo_ = opt_decode ? goog.Uri.decodeOrEmpty_(newUserInfo) : newUserInfo; return this; }; /** * @return {boolean} Whether the user info has been set. */ goog.Uri.prototype.hasUserInfo = function() { return !!this.userInfo_; }; /** * @return {string} The decoded domain. */ goog.Uri.prototype.getDomain = function() { return this.domain_; }; /** * Sets the domain. * @param {string} newDomain New domain value. * @param {boolean=} opt_decode Optional param for whether to decode new value. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setDomain = function(newDomain, opt_decode) { this.enforceReadOnly(); this.domain_ = opt_decode ? goog.Uri.decodeOrEmpty_(newDomain) : newDomain; return this; }; /** * @return {boolean} Whether the domain has been set. */ goog.Uri.prototype.hasDomain = function() { return !!this.domain_; }; /** * @return {?number} The port number. */ goog.Uri.prototype.getPort = function() { return this.port_; }; /** * Sets the port number. * @param {*} newPort Port number. Will be explicitly casted to a number. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setPort = function(newPort) { this.enforceReadOnly(); if (newPort) { newPort = Number(newPort); if (isNaN(newPort) || newPort < 0) { throw Error('Bad port number ' + newPort); } this.port_ = newPort; } else { this.port_ = null; } return this; }; /** * @return {boolean} Whether the port has been set. */ goog.Uri.prototype.hasPort = function() { return this.port_ != null; }; /** * @return {string} The decoded path. */ goog.Uri.prototype.getPath = function() { return this.path_; }; /** * Sets the path. * @param {string} newPath New path value. * @param {boolean=} opt_decode Optional param for whether to decode new value. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setPath = function(newPath, opt_decode) { this.enforceReadOnly(); this.path_ = opt_decode ? goog.Uri.decodeOrEmpty_(newPath) : newPath; return this; }; /** * @return {boolean} Whether the path has been set. */ goog.Uri.prototype.hasPath = function() { return !!this.path_; }; /** * @return {boolean} Whether the query string has been set. */ goog.Uri.prototype.hasQuery = function() { return this.queryData_.toString() !== ''; }; /** * Sets the query data. * @param {goog.Uri.QueryData|string|undefined} queryData QueryData object. * @param {boolean=} opt_decode Optional param for whether to decode new value. * Applies only if queryData is a string. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setQueryData = function(queryData, opt_decode) { this.enforceReadOnly(); if (queryData instanceof goog.Uri.QueryData) { this.queryData_ = queryData; this.queryData_.setIgnoreCase(this.ignoreCase_); } else { if (!opt_decode) { // QueryData accepts encoded query string, so encode it if // opt_decode flag is not true. queryData = goog.Uri.encodeSpecialChars_(queryData, goog.Uri.reDisallowedInQuery_); } this.queryData_ = new goog.Uri.QueryData(queryData, null, this.ignoreCase_); } return this; }; /** * Sets the URI query. * @param {string} newQuery New query value. * @param {boolean=} opt_decode Optional param for whether to decode new value. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setQuery = function(newQuery, opt_decode) { return this.setQueryData(newQuery, opt_decode); }; /** * @return {string} The encoded URI query, not including the ?. */ goog.Uri.prototype.getEncodedQuery = function() { return this.queryData_.toString(); }; /** * @return {string} The decoded URI query, not including the ?. */ goog.Uri.prototype.getDecodedQuery = function() { return this.queryData_.toDecodedString(); }; /** * Returns the query data. * @return {goog.Uri.QueryData} QueryData object. */ goog.Uri.prototype.getQueryData = function() { return this.queryData_; }; /** * @return {string} The encoded URI query, not including the ?. * * Warning: This method, unlike other getter methods, returns encoded * value, instead of decoded one. */ goog.Uri.prototype.getQuery = function() { return this.getEncodedQuery(); }; /** * Sets the value of the named query parameters, clearing previous values for * that key. * * @param {string} key The parameter to set. * @param {*} value The new value. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setParameterValue = function(key, value) { this.enforceReadOnly(); this.queryData_.set(key, value); return this; }; /** * Sets the values of the named query parameters, clearing previous values for * that key. Not new values will currently be moved to the end of the query * string. * * So, <code>goog.Uri.parse('foo?a=b&c=d&e=f').setParameterValues('c', ['new']) * </code> yields <tt>foo?a=b&e=f&c=new</tt>.</p> * * @param {string} key The parameter to set. * @param {*} values The new values. If values is a single * string then it will be treated as the sole value. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setParameterValues = function(key, values) { this.enforceReadOnly(); if (!goog.isArray(values)) { values = [String(values)]; } // TODO(nicksantos): This cast shouldn't be necessary. this.queryData_.setValues(key, /** @type {Array} */ (values)); return this; }; /** * Returns the value<b>s</b> for a given cgi parameter as a list of decoded * query parameter values. * @param {string} name The parameter to get values for. * @return {Array} The values for a given cgi parameter as a list of * decoded query parameter values. */ goog.Uri.prototype.getParameterValues = function(name) { return this.queryData_.getValues(name); }; /** * Returns the first value for a given cgi parameter or undefined if the given * parameter name does not appear in the query string. * @param {string} paramName Unescaped parameter name. * @return {string|undefined} The first value for a given cgi parameter or * undefined if the given parameter name does not appear in the query * string. */ goog.Uri.prototype.getParameterValue = function(paramName) { // NOTE(nicksantos): This type-cast is a lie when // preserveParameterTypesCompatibilityFlag is set to true. // But this should only be set to true in tests. return /** @type {string|undefined} */ (this.queryData_.get(paramName)); }; /** * @return {string} The URI fragment, not including the #. */ goog.Uri.prototype.getFragment = function() { return this.fragment_; }; /** * Sets the URI fragment. * @param {string} newFragment New fragment value. * @param {boolean=} opt_decode Optional param for whether to decode new value. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setFragment = function(newFragment, opt_decode) { this.enforceReadOnly(); this.fragment_ = opt_decode ? goog.Uri.decodeOrEmpty_(newFragment) : newFragment; return this; }; /** * @return {boolean} Whether the URI has a fragment set. */ goog.Uri.prototype.hasFragment = function() { return !!this.fragment_; }; /** * Returns true if this has the same domain as that of uri2. * @param {goog.Uri} uri2 The URI object to compare to. * @return {boolean} true if same domain; false otherwise. */ goog.Uri.prototype.hasSameDomainAs = function(uri2) { return ((!this.hasDomain() && !uri2.hasDomain()) || this.getDomain() == uri2.getDomain()) && ((!this.hasPort() && !uri2.hasPort()) || this.getPort() == uri2.getPort()); }; /** * Adds a random parameter to the Uri. * @return {!goog.Uri} Reference to this Uri object. */ goog.Uri.prototype.makeUnique = function() { this.enforceReadOnly(); this.setParameterValue(goog.Uri.RANDOM_PARAM, goog.string.getRandomString()); return this; }; /** * Removes the named query parameter. * * @param {string} key The parameter to remove. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.removeParameter = function(key) { this.enforceReadOnly(); this.queryData_.remove(key); return this; }; /** * Sets whether Uri is read only. If this goog.Uri is read-only, * enforceReadOnly_ will be called at the start of any function that may modify * this Uri. * @param {boolean} isReadOnly whether this goog.Uri should be read only. * @return {!goog.Uri} Reference to this Uri object. */ goog.Uri.prototype.setReadOnly = function(isReadOnly) { this.isReadOnly_ = isReadOnly; return this; }; /** * @return {boolean} Whether the URI is read only. */ goog.Uri.prototype.isReadOnly = function() { return this.isReadOnly_; }; /** * Checks if this Uri has been marked as read only, and if so, throws an error. * This should be called whenever any modifying function is called. */ goog.Uri.prototype.enforceReadOnly = function() { if (this.isReadOnly_) { throw Error('Tried to modify a read-only Uri'); } }; /** * Sets whether to ignore case. * NOTE: If there are already key/value pairs in the QueryData, and * ignoreCase_ is set to false, the keys will all be lower-cased. * @param {boolean} ignoreCase whether this goog.Uri should ignore case. * @return {!goog.Uri} Reference to this Uri object. */ goog.Uri.prototype.setIgnoreCase = function(ignoreCase) { this.ignoreCase_ = ignoreCase; if (this.queryData_) { this.queryData_.setIgnoreCase(ignoreCase); } return this; }; /** * @return {boolean} Whether to ignore case. */ goog.Uri.prototype.getIgnoreCase = function() { return this.ignoreCase_; }; //============================================================================== // Static members //============================================================================== /** * Creates a uri from the string form. Basically an alias of new goog.Uri(). * If a Uri object is passed to parse then it will return a clone of the object. * * @param {*} uri Raw URI string or instance of Uri * object. * @param {boolean=} opt_ignoreCase Whether to ignore the case of parameter * names in #getParameterValue. * @return {!goog.Uri} The new URI object. */ goog.Uri.parse = function(uri, opt_ignoreCase) { return uri instanceof goog.Uri ? uri.clone() : new goog.Uri(uri, opt_ignoreCase); }; /** * Creates a new goog.Uri object from unencoded parts. * * @param {?string=} opt_scheme Scheme/protocol or full URI to parse. * @param {?string=} opt_userInfo username:password. * @param {?string=} opt_domain www.google.com. * @param {?number=} opt_port 9830. * @param {?string=} opt_path /some/path/to/a/file.html. * @param {string|goog.Uri.QueryData=} opt_query a=1&b=2. * @param {?string=} opt_fragment The fragment without the #. * @param {boolean=} opt_ignoreCase Whether to ignore parameter name case in * #getParameterValue. * * @return {!goog.Uri} The new URI object. */ goog.Uri.create = function(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_query, opt_fragment, opt_ignoreCase) { var uri = new goog.Uri(null, opt_ignoreCase); // Only set the parts if they are defined and not empty strings. opt_scheme && uri.setScheme(opt_scheme); opt_userInfo && uri.setUserInfo(opt_userInfo); opt_domain && uri.setDomain(opt_domain); opt_port && uri.setPort(opt_port); opt_path && uri.setPath(opt_path); opt_query && uri.setQueryData(opt_query); opt_fragment && uri.setFragment(opt_fragment); return uri; }; /** * Resolves a relative Uri against a base Uri, accepting both strings and * Uri objects. * * @param {*} base Base Uri. * @param {*} rel Relative Uri. * @return {!goog.Uri} Resolved uri. */ goog.Uri.resolve = function(base, rel) { if (!(base instanceof goog.Uri)) { base = goog.Uri.parse(base); } if (!(rel instanceof goog.Uri)) { rel = goog.Uri.parse(rel); } return base.resolve(rel); }; /** * Removes dot segments in given path component, as described in * RFC 3986, section 5.2.4. * * @param {string} path A non-empty path component. * @return {string} Path component with removed dot segments. */ goog.Uri.removeDotSegments = function(path) { if (path == '..' || path == '.') { return ''; } else if (!goog.string.contains(path, './') && !goog.string.contains(path, '/.')) { // This optimization detects uris which do not contain dot-segments, // and as a consequence do not require any processing. return path; } else { var leadingSlash = goog.string.startsWith(path, '/'); var segments = path.split('/'); var out = []; for (var pos = 0; pos < segments.length; ) { var segment = segments[pos++]; if (segment == '.') { if (leadingSlash && pos == segments.length) { out.push(''); } } else if (segment == '..') { if (out.length > 1 || out.length == 1 && out[0] != '') { out.pop(); } if (leadingSlash && pos == segments.length) { out.push(''); } } else { out.push(segment); leadingSlash = true; } } return out.join('/'); } }; /** * Decodes a value or returns the empty string if it isn't defined or empty. * @param {string|undefined} val Value to decode. * @return {string} Decoded value. * @private */ goog.Uri.decodeOrEmpty_ = function(val) { // Don't use UrlDecode() here because val is not a query parameter. return val ? decodeURIComponent(val) : ''; }; /** * If unescapedPart is non null, then escapes any characters in it that aren't * valid characters in a url and also escapes any special characters that * appear in extra. * * @param {*} unescapedPart The string to encode. * @param {RegExp} extra A character set of characters in [\01-\177]. * @return {?string} null iff unescapedPart == null. * @private */ goog.Uri.encodeSpecialChars_ = function(unescapedPart, extra) { if (goog.isString(unescapedPart)) { return encodeURI(unescapedPart).replace(extra, goog.Uri.encodeChar_); } return null; }; /** * Converts a character in [\01-\177] to its unicode character equivalent. * @param {string} ch One character string. * @return {string} Encoded string. * @private */ goog.Uri.encodeChar_ = function(ch) { var n = ch.charCodeAt(0); return '%' + ((n >> 4) & 0xf).toString(16) + (n & 0xf).toString(16); }; /** * Regular expression for characters that are disallowed in the scheme or * userInfo part of the URI. * @type {RegExp} * @private */ goog.Uri.reDisallowedInSchemeOrUserInfo_ = /[#\/\?@]/g; /** * Regular expression for characters that are disallowed in a relative path. * @type {RegExp} * @private */ goog.Uri.reDisallowedInRelativePath_ = /[\#\?:]/g; /** * Regular expression for characters that are disallowed in an absolute path. * @type {RegExp} * @private */ goog.Uri.reDisallowedInAbsolutePath_ = /[\#\?]/g; /** * Regular expression for characters that are disallowed in the query. * @type {RegExp} * @private */ goog.Uri.reDisallowedInQuery_ = /[\#\?@]/g; /** * Regular expression for characters that are disallowed in the fragment. * @type {RegExp} * @private */ goog.Uri.reDisallowedInFragment_ = /#/g; /** * Checks whether two URIs have the same domain. * @param {string} uri1String First URI string. * @param {string} uri2String Second URI string. * @return {boolean} true if the two URIs have the same domain; false otherwise. */ goog.Uri.haveSameDomain = function(uri1String, uri2String) { // Differs from goog.uri.utils.haveSameDomain, since this ignores scheme. // TODO(gboyer): Have this just call goog.uri.util.haveSameDomain. var pieces1 = goog.uri.utils.split(uri1String); var pieces2 = goog.uri.utils.split(uri2String); return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] == pieces2[goog.uri.utils.ComponentIndex.DOMAIN] && pieces1[goog.uri.utils.ComponentIndex.PORT] == pieces2[goog.uri.utils.ComponentIndex.PORT]; }; /** * Class used to represent URI query parameters. It is essentially a hash of * name-value pairs, though a name can be present more than once. * * Has the same interface as the collections in goog.structs. * * @param {?string=} opt_query Optional encoded query string to parse into * the object. * @param {goog.Uri=} opt_uri Optional uri object that should have its * cache invalidated when this object updates. Deprecated -- this * is no longer required. * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter * name in #get. * @constructor */ goog.Uri.QueryData = function(opt_query, opt_uri, opt_ignoreCase) { /** * Encoded query string, or null if it requires computing from the key map. * @type {?string} * @private */ this.encodedQuery_ = opt_query || null; /** * If true, ignore the case of the parameter name in #get. * @type {boolean} * @private */ this.ignoreCase_ = !!opt_ignoreCase; }; /** * If the underlying key map is not yet initialized, it parses the * query string and fills the map with parsed data. * @private */ goog.Uri.QueryData.prototype.ensureKeyMapInitialized_ = function() { if (!this.keyMap_) { this.keyMap_ = new goog.structs.Map(); this.count_ = 0; if (this.encodedQuery_) { var pairs = this.encodedQuery_.split('&'); for (var i = 0; i < pairs.length; i++) { var indexOfEquals = pairs[i].indexOf('='); var name = null; var value = null; if (indexOfEquals >= 0) { name = pairs[i].substring(0, indexOfEquals); value = pairs[i].substring(indexOfEquals + 1); } else { name = pairs[i]; } name = goog.string.urlDecode(name); name = this.getKeyName_(name); this.add(name, value ? goog.string.urlDecode(value) : ''); } } } }; /** * Creates a new query data instance from a map of names and values. * * @param {!goog.structs.Map|!Object} map Map of string parameter * names to parameter value. If parameter value is an array, it is * treated as if the key maps to each individual value in the * array. * @param {goog.Uri=} opt_uri URI object that should have its cache * invalidated when this object updates. * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter * name in #get. * @return {!goog.Uri.QueryData} The populated query data instance. */ goog.Uri.QueryData.createFromMap = function(map, opt_uri, opt_ignoreCase) { var keys = goog.structs.getKeys(map); if (typeof keys == 'undefined') { throw Error('Keys are undefined'); } var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase); var values = goog.structs.getValues(map); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = values[i]; if (!goog.isArray(value)) { queryData.add(key, value); } else { queryData.setValues(key, value); } } return queryData; }; /** * Creates a new query data instance from parallel arrays of parameter names * and values. Allows for duplicate parameter names. Throws an error if the * lengths of the arrays differ. * * @param {Array.<string>} keys Parameter names. * @param {Array} values Parameter values. * @param {goog.Uri=} opt_uri URI object that should have its cache * invalidated when this object updates. * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter * name in #get. * @return {!goog.Uri.QueryData} The populated query data instance. */ goog.Uri.QueryData.createFromKeysValues = function( keys, values, opt_uri, opt_ignoreCase) { if (keys.length != values.length) { throw Error('Mismatched lengths for keys/values'); } var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase); for (var i = 0; i < keys.length; i++) { queryData.add(keys[i], values[i]); } return queryData; }; /** * The map containing name/value or name/array-of-values pairs. * May be null if it requires parsing from the query string. * * We need to use a Map because we cannot guarantee that the key names will * not be problematic for IE. * * @type {goog.structs.Map} * @private */ goog.Uri.QueryData.prototype.keyMap_ = null; /** * The number of params, or null if it requires computing. * @type {?number} * @private */ goog.Uri.QueryData.prototype.count_ = null; /** * @return {?number} The number of parameters. */ goog.Uri.QueryData.prototype.getCount = function() { this.ensureKeyMapInitialized_(); return this.count_; }; /** * Adds a key value pair. * @param {string} key Name. * @param {*} value Value. * @return {!goog.Uri.QueryData} Instance of this object. */ goog.Uri.QueryData.prototype.add = function(key, value) { this.ensureKeyMapInitialized_(); this.invalidateCache_(); key = this.getKeyName_(key); var values = this.keyMap_.get(key); if (!values) { this.keyMap_.set(key, (values = [])); } values.push(value); this.count_++; return this; }; /** * Removes all the params with the given key. * @param {string} key Name. * @return {boolean} Whether any parameter was removed. */ goog.Uri.QueryData.prototype.remove = function(key) { this.ensureKeyMapInitialized_(); key = this.getKeyName_(key); if (this.keyMap_.containsKey(key)) { this.invalidateCache_(); // Decrement parameter count. this.count_ -= this.keyMap_.get(key).length; return this.keyMap_.remove(key); } return false; }; /** * Clears the parameters. */ goog.Uri.QueryData.prototype.clear = function() { this.invalidateCache_(); this.keyMap_ = null; this.count_ = 0; }; /** * @return {boolean} Whether we have any parameters. */ goog.Uri.QueryData.prototype.isEmpty = function() { this.ensureKeyMapInitialized_(); return this.count_ == 0; }; /** * Whether there is a parameter with the given name * @param {string} key The parameter name to check for. * @return {boolean} Whether there is a parameter with the given name. */ goog.Uri.QueryData.prototype.containsKey = function(key) { this.ensureKeyMapInitialized_(); key = this.getKeyName_(key); return this.keyMap_.containsKey(key); }; /** * Whether there is a parameter with the given value. * @param {*} value The value to check for. * @return {boolean} Whether there is a parameter with the given value. */ goog.Uri.QueryData.prototype.containsValue = function(value) { // NOTE(arv): This solution goes through all the params even if it was the // first param. We can get around this by not reusing code or by switching to // iterators. var vals = this.getValues(); return goog.array.contains(vals, value); }; /** * Returns all the keys of the parameters. If a key is used multiple times * it will be included multiple times in the returned array * @return {!Array.<string>} All the keys of the parameters. */ goog.Uri.QueryData.prototype.getKeys = function() { this.ensureKeyMapInitialized_(); // We need to get the values to know how many keys to add. var vals = /** @type {Array.<Array|*>} */ (this.keyMap_.getValues()); var keys = this.keyMap_.getKeys(); var rv = []; for (var i = 0; i < keys.length; i++) { var val = vals[i]; for (var j = 0; j < val.length; j++) { rv.push(keys[i]); } } return rv; }; /** * Returns all the values of the parameters with the given name. If the query * data has no such key this will return an empty array. If no key is given * all values wil be returned. * @param {string=} opt_key The name of the parameter to get the values for. * @return {!Array} All the values of the parameters with the given name. */ goog.Uri.QueryData.prototype.getValues = function(opt_key) { this.ensureKeyMapInitialized_(); var rv = []; if (opt_key) { if (this.containsKey(opt_key)) { rv = goog.array.concat(rv, this.keyMap_.get(this.getKeyName_(opt_key))); } } else { // Return all values. var values = /** @type {Array.<Array|*>} */ (this.keyMap_.getValues()); for (var i = 0; i < values.length; i++) { rv = goog.array.concat(rv, values[i]); } } return rv; }; /** * Sets a key value pair and removes all other keys with the same value. * * @param {string} key Name. * @param {*} value Value. * @return {!goog.Uri.QueryData} Instance of this object. */ goog.Uri.QueryData.prototype.set = function(key, value) { this.ensureKeyMapInitialized_(); this.invalidateCache_(); // TODO(user): This could be better written as // this.remove(key), this.add(key, value), but that would reorder // the key (since the key is first removed and then added at the // end) and we would have to fix unit tests that depend on key // ordering. key = this.getKeyName_(key); if (this.containsKey(key)) { this.count_ -= this.keyMap_.get(key).length; } this.keyMap_.set(key, [value]); this.count_++; return this; }; /** * Returns the first value associated with the key. If the query data has no * such key this will return undefined or the optional default. * @param {string} key The name of the parameter to get the value for. * @param {*=} opt_default The default value to return if the query data * has no such key. * @return {*} The first string value associated with the key, or opt_default * if there's no value. */ goog.Uri.QueryData.prototype.get = function(key, opt_default) { var values = key ? this.getValues(key) : []; if (goog.Uri.preserveParameterTypesCompatibilityFlag) { return values.length > 0 ? values[0] : opt_default; } else { return values.length > 0 ? String(values[0]) : opt_default; } }; /** * Sets the values for a key. If the key already exists, this will * override all of the existing values that correspond to the key. * @param {string} key The key to set values for. * @param {Array} values The values to set. */ goog.Uri.QueryData.prototype.setValues = function(key, values) { this.remove(key); if (values.length > 0) { this.invalidateCache_(); this.keyMap_.set(this.getKeyName_(key), goog.array.clone(values)); this.count_ += values.length; } }; /** * @return {string} Encoded query string. * @override */ goog.Uri.QueryData.prototype.toString = function() { if (this.encodedQuery_) { return this.encodedQuery_; } if (!this.keyMap_) { return ''; } var sb = []; // In the past, we use this.getKeys() and this.getVals(), but that // generates a lot of allocations as compared to simply iterating // over the keys. var keys = this.keyMap_.getKeys(); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var encodedKey = goog.string.urlEncode(key); var val = this.getValues(key); for (var j = 0; j < val.length; j++) { var param = encodedKey; // Ensure that null and undefined are encoded into the url as // literal strings. if (val[j] !== '') { param += '=' + goog.string.urlEncode(val[j]); } sb.push(param); } } return this.encodedQuery_ = sb.join('&'); }; /** * @return {string} Decoded query string. */ goog.Uri.QueryData.prototype.toDecodedString = function() { return goog.Uri.decodeOrEmpty_(this.toString()); }; /** * Invalidate the cache. * @private */ goog.Uri.QueryData.prototype.invalidateCache_ = function() { this.encodedQuery_ = null; }; /** * Removes all keys that are not in the provided list. (Modifies this object.) * @param {Array.<string>} keys The desired keys. * @return {!goog.Uri.QueryData} a reference to this object. */ goog.Uri.QueryData.prototype.filterKeys = function(keys) { this.ensureKeyMapInitialized_(); goog.structs.forEach(this.keyMap_, /** @this {goog.Uri.QueryData} */ function(value, key, map) { if (!goog.array.contains(keys, key)) { this.remove(key); } }, this); return this; }; /** * Clone the query data instance. * @return {!goog.Uri.QueryData} New instance of the QueryData object. */ goog.Uri.QueryData.prototype.clone = function() { var rv = new goog.Uri.QueryData(); rv.encodedQuery_ = this.encodedQuery_; if (this.keyMap_) { rv.keyMap_ = this.keyMap_.clone(); rv.count_ = this.count_; } return rv; }; /** * Helper function to get the key name from a JavaScript object. Converts * the object to a string, and to lower case if necessary. * @private * @param {*} arg The object to get a key name from. * @return {string} valid key name which can be looked up in #keyMap_. */ goog.Uri.QueryData.prototype.getKeyName_ = function(arg) { var keyName = String(arg); if (this.ignoreCase_) { keyName = keyName.toLowerCase(); } return keyName; }; /** * Ignore case in parameter names. * NOTE: If there are already key/value pairs in the QueryData, and * ignoreCase_ is set to false, the keys will all be lower-cased. * @param {boolean} ignoreCase whether this goog.Uri should ignore case. */ goog.Uri.QueryData.prototype.setIgnoreCase = function(ignoreCase) { var resetKeys = ignoreCase && !this.ignoreCase_; if (resetKeys) { this.ensureKeyMapInitialized_(); this.invalidateCache_(); goog.structs.forEach(this.keyMap_, /** @this {goog.Uri.QueryData} */ function(value, key) { var lowerCase = key.toLowerCase(); if (key != lowerCase) { this.remove(key); this.setValues(lowerCase, value); } }, this); } this.ignoreCase_ = ignoreCase; }; /** * Extends a query data object with another query data or map like object. This * operates 'in-place', it does not create a new QueryData object. * * @param {...(goog.Uri.QueryData|goog.structs.Map|Object)} var_args The object * from which key value pairs will be copied. */ goog.Uri.QueryData.prototype.extend = function(var_args) { for (var i = 0; i < arguments.length; i++) { var data = arguments[i]; goog.structs.forEach(data, /** @this {goog.Uri.QueryData} */ function(value, key) { this.add(key, value); }, this); } };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Functions for detecting user's time zone. * This work is based on Charlie Luo and Hong Yan's time zone detection work * for CBG. */ goog.provide('goog.locale.timeZoneDetection'); goog.require('goog.locale'); goog.require('goog.locale.TimeZoneFingerprint'); /** * Array of time instances for checking the time zone offset. * @type {Array.<number>} * @private */ goog.locale.timeZoneDetection.TZ_POKE_POINTS_ = [ 1109635200, 1128902400, 1130657000, 1143333000, 1143806400, 1145000000, 1146380000, 1152489600, 1159800000, 1159500000, 1162095000, 1162075000, 1162105500]; /** * Calculates time zone fingerprint by poking time zone offsets for 13 * preselected time points. * See {@link goog.locale.timeZoneDetection.TZ_POKE_POINTS_} * @param {Date} date Date for calculating the fingerprint. * @return {number} Fingerprint of user's time zone setting. */ goog.locale.timeZoneDetection.getFingerprint = function(date) { var hash = 0; var stdOffset; var isComplex = false; for (var i = 0; i < goog.locale.timeZoneDetection.TZ_POKE_POINTS_.length; i++) { date.setTime(goog.locale.timeZoneDetection.TZ_POKE_POINTS_[i] * 1000); var offset = date.getTimezoneOffset() / 30 + 48; if (i == 0) { stdOffset = offset; } else if (stdOffset != offset) { isComplex = true; } hash = (hash << 2) ^ offset; } return isComplex ? hash : /** @type {number} */ (stdOffset); }; /** * Detects browser's time zone setting. If user's country is known, a better * time zone choice could be guessed. * @param {string=} opt_country Two-letter ISO 3166 country code. * @param {Date=} opt_date Date for calculating the fingerprint. Defaults to the * current date. * @return {string} Time zone ID of best guess. */ goog.locale.timeZoneDetection.detectTimeZone = function(opt_country, opt_date) { var date = opt_date || new Date(); var fingerprint = goog.locale.timeZoneDetection.getFingerprint(date); var timeZoneList = goog.locale.TimeZoneFingerprint[fingerprint]; // Timezones in goog.locale.TimeZoneDetection.TimeZoneMap are in the format // US-America/Los_Angeles. Country code needs to be stripped before a // timezone is returned. if (timeZoneList) { if (opt_country) { for (var i = 0; i < timeZoneList.length; ++i) { if (timeZoneList[i].indexOf(opt_country) == 0) { return timeZoneList[i].substring(3); } } } return timeZoneList[0].substring(3); } return ''; }; /** * Returns an array of time zones that are consistent with user's platform * setting. If user's country is given, only the time zone for that country is * returned. * @param {string=} opt_country 2 letter ISO 3166 country code. Helps in making * a better guess for user's time zone. * @param {Date=} opt_date Date for retrieving timezone list. Defaults to the * current date. * @return {Array.<string>} Array of time zone IDs. */ goog.locale.timeZoneDetection.getTimeZoneList = function(opt_country, opt_date) { var date = opt_date || new Date(); var fingerprint = goog.locale.timeZoneDetection.getFingerprint(date); var timeZoneList = goog.locale.TimeZoneFingerprint[fingerprint]; if (!timeZoneList) { return []; } var chosenList = []; for (var i = 0; i < timeZoneList.length; i++) { if (!opt_country || timeZoneList[i].indexOf(opt_country) == 0) { chosenList.push(timeZoneList[i].substring(3)); } } return chosenList; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Default list of locale specific country and language names. * * Warning: this file is automatically generated from CLDR. * Please contact i18n team or change the script and regenerate data. * Code location: http://go/generate_js_lang_country_constan * */ /** * Namespace for locale specific country and lanugage names */ goog.provide('goog.locale.defaultLocaleNameConstants'); /** * Default list of locale specific country and language names */ goog.locale.defaultLocaleNameConstants = { 'COUNTRY': { '001': 'World', '002': 'Africa', '003': 'North America', '005': 'South America', '009': 'Oceania', '011': 'Western Africa', '013': 'Central America', '014': 'Eastern Africa', '015': 'Northern Africa', '017': 'Middle Africa', '018': 'Southern Africa', '019': 'Americas', '021': 'Northern America', '029': 'Caribbean', '030': 'Eastern Asia', '034': 'Southern Asia', '035': 'South-Eastern Asia', '039': 'Southern Europe', '053': 'Australia and New Zealand', '054': 'Melanesia', '057': 'Micronesian Region', '061': 'Polynesia', '062': 'South-Central Asia', '142': 'Asia', '143': 'Central Asia', '145': 'Western Asia', '150': 'Europe', '151': 'Eastern Europe', '154': 'Northern Europe', '155': 'Western Europe', '172': 'Commonwealth of Independent States', '200': 'Czechoslovakia', '419': 'Latin America', '830': 'Channel Islands', 'AC': 'Ascension Island', 'AD': 'Andorra', 'AE': 'United Arab Emirates', 'AF': 'Afghanistan', 'AG': 'Antigua and Barbuda', 'AI': 'Anguilla', 'AL': 'Albania', 'AM': 'Armenia', 'AN': 'Netherlands Antilles', 'AO': 'Angola', 'AQ': 'Antarctica', 'AR': 'Argentina', 'AS': 'American Samoa', 'AT': 'Austria', 'AU': 'Australia', 'AW': 'Aruba', 'AX': '\u00c5land Islands', 'AZ': 'Azerbaijan', 'BA': 'Bosnia and Herzegovina', 'BB': 'Barbados', 'BD': 'Bangladesh', 'BE': 'Belgium', 'BF': 'Burkina Faso', 'BG': 'Bulgaria', 'BH': 'Bahrain', 'BI': 'Burundi', 'BJ': 'Benin', 'BL': 'Saint Barth\u00e9lemy', 'BM': 'Bermuda', 'BN': 'Brunei', 'BO': 'Bolivia', 'BQ': 'Bonaire, Saint Eustatius, and Saba', 'BR': 'Brazil', 'BS': 'Bahamas', 'BT': 'Bhutan', 'BV': 'Bouvet Island', 'BW': 'Botswana', 'BY': 'Belarus', 'BZ': 'Belize', 'CA': 'Canada', 'CC': 'Cocos [Keeling] Islands', 'CD': 'Congo [DRC]', 'CF': 'Central African Republic', 'CG': 'Congo [Republic]', 'CH': 'Switzerland', 'CI': 'C\u00f4te d\u2019Ivoire', 'CK': 'Cook Islands', 'CL': 'Chile', 'CM': 'Cameroon', 'CN': 'China', 'CO': 'Colombia', 'CP': 'Clipperton Island', 'CR': 'Costa Rica', 'CS': 'Serbia and Montenegro', 'CT': 'Canton and Enderbury Islands', 'CU': 'Cuba', 'CV': 'Cape Verde', 'CW': 'Cura\u00e7ao', 'CX': 'Christmas Island', 'CY': 'Cyprus', 'CZ': 'Czech Republic', 'DD': 'East Germany', 'DE': 'Germany', 'DG': 'Diego Garcia', 'DJ': 'Djibouti', 'DK': 'Denmark', 'DM': 'Dominica', 'DO': 'Dominican Republic', 'DZ': 'Algeria', 'EA': 'Ceuta and Melilla', 'EC': 'Ecuador', 'EE': 'Estonia', 'EG': 'Egypt', 'EH': 'Western Sahara', 'ER': 'Eritrea', 'ES': 'Spain', 'ET': 'Ethiopia', 'EU': 'European Union', 'FI': 'Finland', 'FJ': 'Fiji', 'FK': 'Falkland Islands [Islas Malvinas]', 'FM': 'Micronesia', 'FO': 'Faroe Islands', 'FQ': 'French Southern and Antarctic Territories', 'FR': 'France', 'FX': 'Metropolitan France', 'GA': 'Gabon', 'GB': 'United Kingdom', 'GD': 'Grenada', 'GE': 'Georgia', 'GF': 'French Guiana', 'GG': 'Guernsey', 'GH': 'Ghana', 'GI': 'Gibraltar', 'GL': 'Greenland', 'GM': 'Gambia', 'GN': 'Guinea', 'GP': 'Guadeloupe', 'GQ': 'Equatorial Guinea', 'GR': 'Greece', 'GS': 'South Georgia and the South Sandwich Islands', 'GT': 'Guatemala', 'GU': 'Guam', 'GW': 'Guinea-Bissau', 'GY': 'Guyana', 'HK': 'Hong Kong', 'HM': 'Heard Island and McDonald Islands', 'HN': 'Honduras', 'HR': 'Croatia', 'HT': 'Haiti', 'HU': 'Hungary', 'IC': 'Canary Islands', 'ID': 'Indonesia', 'IE': 'Ireland', 'IL': 'Israel', 'IM': 'Isle of Man', 'IN': 'India', 'IO': 'British Indian Ocean Territory', 'IQ': 'Iraq', 'IR': 'Iran', 'IS': 'Iceland', 'IT': 'Italy', 'JE': 'Jersey', 'JM': 'Jamaica', 'JO': 'Jordan', 'JP': 'Japan', 'JT': 'Johnston Island', 'KE': 'Kenya', 'KG': 'Kyrgyzstan', 'KH': 'Cambodia', 'KI': 'Kiribati', 'KM': 'Comoros', 'KN': 'Saint Kitts and Nevis', 'KP': 'North Korea', 'KR': 'South Korea', 'KW': 'Kuwait', 'KY': 'Cayman Islands', 'KZ': 'Kazakhstan', 'LA': 'Laos', 'LB': 'Lebanon', 'LC': 'Saint Lucia', 'LI': 'Liechtenstein', 'LK': 'Sri Lanka', 'LR': 'Liberia', 'LS': 'Lesotho', 'LT': 'Lithuania', 'LU': 'Luxembourg', 'LV': 'Latvia', 'LY': 'Libya', 'MA': 'Morocco', 'MC': 'Monaco', 'MD': 'Moldova', 'ME': 'Montenegro', 'MF': 'Saint Martin', 'MG': 'Madagascar', 'MH': 'Marshall Islands', 'MI': 'Midway Islands', 'MK': 'Macedonia [FYROM]', 'ML': 'Mali', 'MM': 'Myanmar [Burma]', 'MN': 'Mongolia', 'MO': 'Macau', 'MP': 'Northern Mariana Islands', 'MQ': 'Martinique', 'MR': 'Mauritania', 'MS': 'Montserrat', 'MT': 'Malta', 'MU': 'Mauritius', 'MV': 'Maldives', 'MW': 'Malawi', 'MX': 'Mexico', 'MY': 'Malaysia', 'MZ': 'Mozambique', 'NA': 'Namibia', 'NC': 'New Caledonia', 'NE': 'Niger', 'NF': 'Norfolk Island', 'NG': 'Nigeria', 'NI': 'Nicaragua', 'NL': 'Netherlands', 'NO': 'Norway', 'NP': 'Nepal', 'NQ': 'Dronning Maud Land', 'NR': 'Nauru', 'NT': 'Neutral Zone', 'NU': 'Niue', 'NZ': 'New Zealand', 'OM': 'Oman', 'PA': 'Panama', 'PC': 'Pacific Islands Trust Territory', 'PE': 'Peru', 'PF': 'French Polynesia', 'PG': 'Papua New Guinea', 'PH': 'Philippines', 'PK': 'Pakistan', 'PL': 'Poland', 'PM': 'Saint Pierre and Miquelon', 'PN': 'Pitcairn Islands', 'PR': 'Puerto Rico', 'PS': 'Palestinian Territories', 'PT': 'Portugal', 'PU': 'U.S. Miscellaneous Pacific Islands', 'PW': 'Palau', 'PY': 'Paraguay', 'PZ': 'Panama Canal Zone', 'QA': 'Qatar', 'QO': 'Outlying Oceania', 'RE': 'R\u00e9union', 'RO': 'Romania', 'RS': 'Serbia', 'RU': 'Russia', 'RW': 'Rwanda', 'SA': 'Saudi Arabia', 'SB': 'Solomon Islands', 'SC': 'Seychelles', 'SD': 'Sudan', 'SE': 'Sweden', 'SG': 'Singapore', 'SH': 'Saint Helena', 'SI': 'Slovenia', 'SJ': 'Svalbard and Jan Mayen', 'SK': 'Slovakia', 'SL': 'Sierra Leone', 'SM': 'San Marino', 'SN': 'Senegal', 'SO': 'Somalia', 'SR': 'Suriname', 'SS': 'South Sudan', 'ST': 'S\u00e3o Tom\u00e9 and Pr\u00edncipe', 'SU': 'Union of Soviet Socialist Republics', 'SV': 'El Salvador', 'SX': 'Sint Maarten', 'SY': 'Syria', 'SZ': 'Swaziland', 'TA': 'Tristan da Cunha', 'TC': 'Turks and Caicos Islands', 'TD': 'Chad', 'TF': 'French Southern Territories', 'TG': 'Togo', 'TH': 'Thailand', 'TJ': 'Tajikistan', 'TK': 'Tokelau', 'TL': 'Timor-Leste', 'TM': 'Turkmenistan', 'TN': 'Tunisia', 'TO': 'Tonga', 'TR': 'Turkey', 'TT': 'Trinidad and Tobago', 'TV': 'Tuvalu', 'TW': 'Taiwan', 'TZ': 'Tanzania', 'UA': 'Ukraine', 'UG': 'Uganda', 'UM': 'U.S. Minor Outlying Islands', 'US': 'United States', 'UY': 'Uruguay', 'UZ': 'Uzbekistan', 'VA': 'Vatican City', 'VC': 'Saint Vincent and the Grenadines', 'VD': 'North Vietnam', 'VE': 'Venezuela', 'VG': 'British Virgin Islands', 'VI': 'U.S. Virgin Islands', 'VN': 'Vietnam', 'VU': 'Vanuatu', 'WF': 'Wallis and Futuna', 'WK': 'Wake Island', 'WS': 'Samoa', 'YD': 'People\u2019s Democratic Republic of Yemen', 'YE': 'Yemen', 'YT': 'Mayotte', 'ZA': 'South Africa', 'ZM': 'Zambia', 'ZW': 'Zimbabwe', 'ZZ': 'Unknown Region' }, 'LANGUAGE': { 'aa': 'Afar', 'ab': 'Abkhazian', 'ace': 'Achinese', 'ach': 'Acoli', 'ada': 'Adangme', 'ady': 'Adyghe', 'ae': 'Avestan', 'af': 'Afrikaans', 'afa': 'Afro-Asiatic Language', 'afh': 'Afrihili', 'agq': 'Aghem', 'ain': 'Ainu', 'ak': 'Akan', 'akk': 'Akkadian', 'ale': 'Aleut', 'alg': 'Algonquian Language', 'alt': 'Southern Altai', 'am': 'Amharic', 'an': 'Aragonese', 'ang': 'Old English', 'anp': 'Angika', 'apa': 'Apache Language', 'ar': 'Arabic', 'arc': 'Aramaic', 'arn': 'Araucanian', 'arp': 'Arapaho', 'art': 'Artificial Language', 'arw': 'Arawak', 'as': 'Assamese', 'asa': 'Asu', 'ast': 'Asturian', 'ath': 'Athapascan Language', 'aus': 'Australian Language', 'av': 'Avaric', 'awa': 'Awadhi', 'ay': 'Aymara', 'az': 'Azerbaijani', 'ba': 'Bashkir', 'bad': 'Banda', 'bai': 'Bamileke Language', 'bal': 'Baluchi', 'ban': 'Balinese', 'bas': 'Basaa', 'bat': 'Baltic Language', 'be': 'Belarusian', 'bej': 'Beja', 'bem': 'Bemba', 'ber': 'Berber', 'bez': 'Bena', 'bg': 'Bulgarian', 'bh': 'Bihari', 'bho': 'Bhojpuri', 'bi': 'Bislama', 'bik': 'Bikol', 'bin': 'Bini', 'bla': 'Siksika', 'bm': 'Bambara', 'bn': 'Bengali', 'bnt': 'Bantu', 'bo': 'Tibetan', 'br': 'Breton', 'bra': 'Braj', 'brx': 'Bodo', 'bs': 'Bosnian', 'btk': 'Batak', 'bua': 'Buriat', 'bug': 'Buginese', 'byn': 'Blin', 'ca': 'Catalan', 'cad': 'Caddo', 'cai': 'Central American Indian Language', 'car': 'Carib', 'cau': 'Caucasian Language', 'cay': 'Cayuga', 'cch': 'Atsam', 'ce': 'Chechen', 'ceb': 'Cebuano', 'cel': 'Celtic Language', 'cgg': 'Chiga', 'ch': 'Chamorro', 'chb': 'Chibcha', 'chg': 'Chagatai', 'chk': 'Chuukese', 'chm': 'Mari', 'chn': 'Chinook Jargon', 'cho': 'Choctaw', 'chp': 'Chipewyan', 'chr': 'Cherokee', 'chy': 'Cheyenne', 'ckb': 'Sorani Kurdish', 'cmc': 'Chamic Language', 'co': 'Corsican', 'cop': 'Coptic', 'cpe': 'English-based Creole or Pidgin', 'cpf': 'French-based Creole or Pidgin', 'cpp': 'Portuguese-based Creole or Pidgin', 'cr': 'Cree', 'crh': 'Crimean Turkish', 'crp': 'Creole or Pidgin', 'cs': 'Czech', 'csb': 'Kashubian', 'cu': 'Church Slavic', 'cus': 'Cushitic Language', 'cv': 'Chuvash', 'cy': 'Welsh', 'da': 'Danish', 'dak': 'Dakota', 'dar': 'Dargwa', 'dav': 'Taita', 'day': 'Dayak', 'de': 'German', 'de_AT': 'Austrian German', 'de_CH': 'Swiss High German', 'del': 'Delaware', 'den': 'Slave', 'dgr': 'Dogrib', 'din': 'Dinka', 'dje': 'Zarma', 'doi': 'Dogri', 'dra': 'Dravidian Language', 'dsb': 'Lower Sorbian', 'dua': 'Duala', 'dum': 'Middle Dutch', 'dv': 'Divehi', 'dyo': 'Jola-Fonyi', 'dyu': 'Dyula', 'dz': 'Dzongkha', 'ebu': 'Embu', 'ee': 'Ewe', 'efi': 'Efik', 'egy': 'Ancient Egyptian', 'eka': 'Ekajuk', 'el': 'Greek', 'elx': 'Elamite', 'en': 'English', 'en_AU': 'Australian English', 'en_CA': 'Canadian English', 'en_GB': 'British English', 'en_US': 'U.S. English', 'enm': 'Middle English', 'eo': 'Esperanto', 'es': 'Spanish', 'es_419': 'Latin American Spanish', 'es_ES': 'Iberian Spanish', 'et': 'Estonian', 'eu': 'Basque', 'ewo': 'Ewondo', 'fa': 'Persian', 'fan': 'Fang', 'fat': 'Fanti', 'ff': 'Fulah', 'fi': 'Finnish', 'fil': 'Filipino', 'fiu': 'Finno-Ugrian Language', 'fj': 'Fijian', 'fo': 'Faroese', 'fon': 'Fon', 'fr': 'French', 'fr_CA': 'Canadian French', 'fr_CH': 'Swiss French', 'frm': 'Middle French', 'fro': 'Old French', 'frr': 'Northern Frisian', 'frs': 'Eastern Frisian', 'fur': 'Friulian', 'fy': 'Western Frisian', 'ga': 'Irish', 'gaa': 'Ga', 'gay': 'Gayo', 'gba': 'Gbaya', 'gd': 'Scottish Gaelic', 'gem': 'Germanic Language', 'gez': 'Geez', 'gil': 'Gilbertese', 'gl': 'Galician', 'gmh': 'Middle High German', 'gn': 'Guarani', 'goh': 'Old High German', 'gon': 'Gondi', 'gor': 'Gorontalo', 'got': 'Gothic', 'grb': 'Grebo', 'grc': 'Ancient Greek', 'gsw': 'Swiss German', 'gu': 'Gujarati', 'guz': 'Gusii', 'gv': 'Manx', 'gwi': 'Gwich\u02bcin', 'ha': 'Hausa', 'hai': 'Haida', 'haw': 'Hawaiian', 'he': 'Hebrew', 'hi': 'Hindi', 'hil': 'Hiligaynon', 'him': 'Himachali', 'hit': 'Hittite', 'hmn': 'Hmong', 'ho': 'Hiri Motu', 'hr': 'Croatian', 'hsb': 'Upper Sorbian', 'ht': 'Haitian', 'hu': 'Hungarian', 'hup': 'Hupa', 'hy': 'Armenian', 'hz': 'Herero', 'ia': 'Interlingua', 'iba': 'Iban', 'id': 'Indonesian', 'ie': 'Interlingue', 'ig': 'Igbo', 'ii': 'Sichuan Yi', 'ijo': 'Ijo', 'ik': 'Inupiaq', 'ilo': 'Iloko', 'inc': 'Indic Language', 'ine': 'Indo-European Language', 'inh': 'Ingush', 'io': 'Ido', 'ira': 'Iranian Language', 'iro': 'Iroquoian Language', 'is': 'Icelandic', 'it': 'Italian', 'iu': 'Inuktitut', 'ja': 'Japanese', 'jbo': 'Lojban', 'jmc': 'Machame', 'jpr': 'Judeo-Persian', 'jrb': 'Judeo-Arabic', 'jv': 'Javanese', 'ka': 'Georgian', 'kaa': 'Kara-Kalpak', 'kab': 'Kabyle', 'kac': 'Kachin', 'kaj': 'Jju', 'kam': 'Kamba', 'kar': 'Karen', 'kaw': 'Kawi', 'kbd': 'Kabardian', 'kcg': 'Tyap', 'kde': 'Makonde', 'kea': 'Kabuverdianu', 'kfo': 'Koro', 'kg': 'Kongo', 'kha': 'Khasi', 'khi': 'Khoisan Language', 'kho': 'Khotanese', 'khq': 'Koyra Chiini', 'ki': 'Kikuyu', 'kj': 'Kuanyama', 'kk': 'Kazakh', 'kl': 'Kalaallisut', 'kln': 'Kalenjin', 'km': 'Khmer', 'kmb': 'Kimbundu', 'kn': 'Kannada', 'ko': 'Korean', 'kok': 'Konkani', 'kos': 'Kosraean', 'kpe': 'Kpelle', 'kr': 'Kanuri', 'krc': 'Karachay-Balkar', 'krl': 'Karelian', 'kro': 'Kru', 'kru': 'Kurukh', 'ks': 'Kashmiri', 'ksb': 'Shambala', 'ksf': 'Bafia', 'ksh': 'Colognian', 'ku': 'Kurdish', 'kum': 'Kumyk', 'kut': 'Kutenai', 'kv': 'Komi', 'kw': 'Cornish', 'ky': 'Kirghiz', 'la': 'Latin', 'lad': 'Ladino', 'lag': 'Langi', 'lah': 'Lahnda', 'lam': 'Lamba', 'lb': 'Luxembourgish', 'lez': 'Lezghian', 'lg': 'Ganda', 'li': 'Limburgish', 'ln': 'Lingala', 'lo': 'Lao', 'lol': 'Mongo', 'loz': 'Lozi', 'lt': 'Lithuanian', 'lu': 'Luba-Katanga', 'lua': 'Luba-Lulua', 'lui': 'Luiseno', 'lun': 'Lunda', 'luo': 'Luo', 'lus': 'Lushai', 'luy': 'Luyia', 'lv': 'Latvian', 'mad': 'Madurese', 'mag': 'Magahi', 'mai': 'Maithili', 'mak': 'Makasar', 'man': 'Mandingo', 'map': 'Austronesian Language', 'mas': 'Masai', 'mdf': 'Moksha', 'mdr': 'Mandar', 'men': 'Mende', 'mer': 'Meru', 'mfe': 'Morisyen', 'mg': 'Malagasy', 'mga': 'Middle Irish', 'mgh': 'Makhuwa-Meetto', 'mh': 'Marshallese', 'mi': 'Maori', 'mic': 'Micmac', 'min': 'Minangkabau', 'mis': 'Miscellaneous Language', 'mk': 'Macedonian', 'mkh': 'Mon-Khmer Language', 'ml': 'Malayalam', 'mn': 'Mongolian', 'mnc': 'Manchu', 'mni': 'Manipuri', 'mno': 'Manobo Language', 'mo': 'Moldavian', 'moh': 'Mohawk', 'mos': 'Mossi', 'mr': 'Marathi', 'ms': 'Malay', 'mt': 'Maltese', 'mua': 'Mundang', 'mul': 'Multiple Languages', 'mun': 'Munda Language', 'mus': 'Creek', 'mwl': 'Mirandese', 'mwr': 'Marwari', 'my': 'Burmese', 'myn': 'Mayan Language', 'myv': 'Erzya', 'na': 'Nauru', 'nah': 'Nahuatl', 'nai': 'North American Indian Language', 'nap': 'Neapolitan', 'naq': 'Nama', 'nb': 'Norwegian Bokm\u00e5l', 'nd': 'North Ndebele', 'nds': 'Low German', 'ne': 'Nepali', 'new': 'Newari', 'ng': 'Ndonga', 'nia': 'Nias', 'nic': 'Niger-Kordofanian Language', 'niu': 'Niuean', 'nl': 'Dutch', 'nl_BE': 'Flemish', 'nmg': 'Kwasio', 'nn': 'Norwegian Nynorsk', 'no': 'Norwegian', 'nog': 'Nogai', 'non': 'Old Norse', 'nqo': 'N\u2019Ko', 'nr': 'South Ndebele', 'nso': 'Northern Sotho', 'nub': 'Nubian Language', 'nus': 'Nuer', 'nv': 'Navajo', 'nwc': 'Classical Newari', 'ny': 'Nyanja', 'nym': 'Nyamwezi', 'nyn': 'Nyankole', 'nyo': 'Nyoro', 'nzi': 'Nzima', 'oc': 'Occitan', 'oj': 'Ojibwa', 'om': 'Oromo', 'or': 'Oriya', 'os': 'Ossetic', 'osa': 'Osage', 'ota': 'Ottoman Turkish', 'oto': 'Otomian Language', 'pa': 'Punjabi', 'paa': 'Papuan Language', 'pag': 'Pangasinan', 'pal': 'Pahlavi', 'pam': 'Pampanga', 'pap': 'Papiamento', 'pau': 'Palauan', 'peo': 'Old Persian', 'phi': 'Philippine Language', 'phn': 'Phoenician', 'pi': 'Pali', 'pl': 'Polish', 'pon': 'Pohnpeian', 'pra': 'Prakrit Language', 'pro': 'Old Proven\u00e7al', 'ps': 'Pashto', 'pt': 'Portuguese', 'pt_BR': 'Brazilian Portuguese', 'pt_PT': 'Iberian Portuguese', 'qu': 'Quechua', 'raj': 'Rajasthani', 'rap': 'Rapanui', 'rar': 'Rarotongan', 'rm': 'Romansh', 'rn': 'Rundi', 'ro': 'Romanian', 'roa': 'Romance Language', 'rof': 'Rombo', 'rom': 'Romany', 'root': 'Root', 'ru': 'Russian', 'rup': 'Aromanian', 'rw': 'Kinyarwanda', 'rwk': 'Rwa', 'sa': 'Sanskrit', 'sad': 'Sandawe', 'sah': 'Sakha', 'sai': 'South American Indian Language', 'sal': 'Salishan Language', 'sam': 'Samaritan Aramaic', 'saq': 'Samburu', 'sas': 'Sasak', 'sat': 'Santali', 'sbp': 'Sangu', 'sc': 'Sardinian', 'scn': 'Sicilian', 'sco': 'Scots', 'sd': 'Sindhi', 'se': 'Northern Sami', 'see': 'Seneca', 'seh': 'Sena', 'sel': 'Selkup', 'sem': 'Semitic Language', 'ses': 'Koyraboro Senni', 'sg': 'Sango', 'sga': 'Old Irish', 'sgn': 'Sign Language', 'sh': 'Serbo-Croatian', 'shi': 'Tachelhit', 'shn': 'Shan', 'si': 'Sinhala', 'sid': 'Sidamo', 'sio': 'Siouan Language', 'sit': 'Sino-Tibetan Language', 'sk': 'Slovak', 'sl': 'Slovenian', 'sla': 'Slavic Language', 'sm': 'Samoan', 'sma': 'Southern Sami', 'smi': 'Sami Language', 'smj': 'Lule Sami', 'smn': 'Inari Sami', 'sms': 'Skolt Sami', 'sn': 'Shona', 'snk': 'Soninke', 'so': 'Somali', 'sog': 'Sogdien', 'son': 'Songhai', 'sq': 'Albanian', 'sr': 'Serbian', 'srn': 'Sranan Tongo', 'srr': 'Serer', 'ss': 'Swati', 'ssa': 'Nilo-Saharan Language', 'ssy': 'Saho', 'st': 'Southern Sotho', 'su': 'Sundanese', 'suk': 'Sukuma', 'sus': 'Susu', 'sux': 'Sumerian', 'sv': 'Swedish', 'sw': 'Swahili', 'swb': 'Comorian', 'swc': 'Congo Swahili', 'syc': 'Classical Syriac', 'syr': 'Syriac', 'ta': 'Tamil', 'tai': 'Tai Language', 'te': 'Telugu', 'tem': 'Timne', 'teo': 'Teso', 'ter': 'Tereno', 'tet': 'Tetum', 'tg': 'Tajik', 'th': 'Thai', 'ti': 'Tigrinya', 'tig': 'Tigre', 'tiv': 'Tiv', 'tk': 'Turkmen', 'tkl': 'Tokelau', 'tl': 'Tagalog', 'tlh': 'Klingon', 'tli': 'Tlingit', 'tmh': 'Tamashek', 'tn': 'Tswana', 'to': 'Tongan', 'tog': 'Nyasa Tonga', 'tpi': 'Tok Pisin', 'tr': 'Turkish', 'trv': 'Taroko', 'ts': 'Tsonga', 'tsi': 'Tsimshian', 'tt': 'Tatar', 'tum': 'Tumbuka', 'tup': 'Tupi Language', 'tut': 'Altaic Language', 'tvl': 'Tuvalu', 'tw': 'Twi', 'twq': 'Tasawaq', 'ty': 'Tahitian', 'tyv': 'Tuvinian', 'tzm': 'Central Morocco Tamazight', 'udm': 'Udmurt', 'ug': 'Uighur', 'uga': 'Ugaritic', 'uk': 'Ukrainian', 'umb': 'Umbundu', 'und': 'Unknown Language', 'ur': 'Urdu', 'uz': 'Uzbek', 'vai': 'Vai', 've': 'Venda', 'vi': 'Vietnamese', 'vo': 'Volap\u00fck', 'vot': 'Votic', 'vun': 'Vunjo', 'wa': 'Walloon', 'wae': 'Walser', 'wak': 'Wakashan Language', 'wal': 'Walamo', 'war': 'Waray', 'was': 'Washo', 'wen': 'Sorbian Language', 'wo': 'Wolof', 'xal': 'Kalmyk', 'xh': 'Xhosa', 'xog': 'Soga', 'yao': 'Yao', 'yap': 'Yapese', 'yav': 'Yangben', 'yi': 'Yiddish', 'yo': 'Yoruba', 'ypk': 'Yupik Language', 'yue': 'Cantonese', 'za': 'Zhuang', 'zap': 'Zapotec', 'zbl': 'Blissymbols', 'zen': 'Zenaga', 'zh': 'Chinese', 'zh_Hans': 'Simplified Chinese', 'zh_Hant': 'Traditional Chinese', 'znd': 'Zande', 'zu': 'Zulu', 'zun': 'Zuni', 'zxx': 'No linguistic content', 'zza': 'Zaza' } };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Functions for dealing with Date formatting & Parsing, * County and language name, TimeZone list. * @suppress {deprecated} Use goog.i18n instead. */ /** * Namespace for locale related functions. */ goog.provide('goog.locale'); goog.require('goog.locale.nativeNameConstants'); /** * Set currnet locale to the specified one. * @param {string} localeName Locale name string. We are following the usage * in CLDR, but can make a few compromise for existing name compatibility. */ goog.locale.setLocale = function(localeName) { // it is common to see people use '-' as locale part separator, normalize it. localeName = localeName.replace(/-/g, '_'); goog.locale.activeLocale_ = localeName; }; /** * Retrieve the currnet locale * @return {string} Current locale name string. * @deprecated Use goog.LOCALE and goog.i18n instead. */ goog.locale.getLocale = function() { if (!goog.locale.activeLocale_) { goog.locale.activeLocale_ = 'en'; } return goog.locale.activeLocale_; }; // Couple of constants to represent predefined Date/Time format type. /** * Enum of resources that can be registered. * @enum {string} */ goog.locale.Resource = { DATE_TIME_CONSTANTS: 'DateTimeConstants', NUMBER_FORMAT_CONSTANTS: 'NumberFormatConstants', TIME_ZONE_CONSTANTS: 'TimeZoneConstants', LOCAL_NAME_CONSTANTS: 'LocaleNameConstants', TIME_ZONE_SELECTED_IDS: 'TimeZoneSelectedIds', TIME_ZONE_SELECTED_SHORT_NAMES: 'TimeZoneSelectedShortNames', TIME_ZONE_SELECTED_LONG_NAMES: 'TimeZoneSelectedLongNames', TIME_ZONE_ALL_LONG_NAMES: 'TimeZoneAllLongNames' }; // BCP 47 language code: // // LanguageCode := LanguageSubtag // ("-" ScriptSubtag)? // ("-" RegionSubtag)? // ("-" VariantSubtag)? // ("@" Keyword "=" Value ("," Keyword "=" Value)* )? // // e.g. en-Latn-GB // // NOTICE: // No special format checking is performed. If you pass a none valid // language code as parameter to the following functions, // you might get an unexpected result. /** * Returns the language-subtag of the given language code. * * @param {string} languageCode Language code to extract language subtag from. * @return {string} Language subtag (in lowercase). */ goog.locale.getLanguageSubTag = function(languageCode) { var result = languageCode.match(/^\w{2,3}([-_]|$)/); return result ? result[0].replace(/[_-]/g, '') : ''; }; /** * Returns the region-sub-tag of the given language code. * * @param {string} languageCode Language code to extract region subtag from. * @return {string} Region sub-tag (in uppercase). */ goog.locale.getRegionSubTag = function(languageCode) { var result = languageCode.match(/[-_]([a-zA-Z]{2}|\d{3})([-_]|$)/); return result ? result[0].replace(/[_-]/g, '') : ''; }; /** * Returns the script subtag of the locale with the first alphabet in uppercase * and the rest 3 characters in lower case. * * @param {string} languageCode Language Code to extract script subtag from. * @return {string} Script subtag. */ goog.locale.getScriptSubTag = function(languageCode) { var result = languageCode.split(/[-_]/g); return result.length > 1 && result[1].match(/^[a-zA-Z]{4}$/) ? result[1] : ''; }; /** * Returns the variant-sub-tag of the given language code. * * @param {string} languageCode Language code to extract variant subtag from. * @return {string} Variant sub-tag. */ goog.locale.getVariantSubTag = function(languageCode) { var result = languageCode.match(/[-_]([a-z]{2,})/); return result ? result[1] : ''; }; /** * Returns the country name of the provided language code in its native * language. * * This method depends on goog.locale.nativeNameConstants available from * nativenameconstants.js. User of this method has to add dependency to this. * * @param {string} countryCode Code to lookup the country name for. * * @return {string} Country name for the provided language code. */ goog.locale.getNativeCountryName = function(countryCode) { var key = goog.locale.getLanguageSubTag(countryCode) + '_' + goog.locale.getRegionSubTag(countryCode); return key in goog.locale.nativeNameConstants['COUNTRY'] ? goog.locale.nativeNameConstants['COUNTRY'][key] : countryCode; }; /** * Returns the localized country name for the provided language code in the * current or provided locale symbols set. * * This method depends on goog.locale.LocaleNameConstants__<locale> available * from http://go/js_locale_data. User of this method has to add dependency to * this. * * @param {string} languageCode Language code to lookup the country name for. * @param {Object=} opt_localeSymbols If omitted the current locale symbol * set is used. * * @return {string} Localized country name. */ goog.locale.getLocalizedCountryName = function(languageCode, opt_localeSymbols) { if (!opt_localeSymbols) { opt_localeSymbols = goog.locale.getResource('LocaleNameConstants', goog.locale.getLocale()); } var code = goog.locale.getRegionSubTag(languageCode); return code in opt_localeSymbols['COUNTRY'] ? opt_localeSymbols['COUNTRY'][code] : languageCode; }; /** * Returns the language name of the provided language code in its native * language. * * This method depends on goog.locale.nativeNameConstants available from * nativenameconstants.js. User of this method has to add dependency to this. * * @param {string} languageCode Language code to lookup the language name for. * * @return {string} Language name for the provided language code. */ goog.locale.getNativeLanguageName = function(languageCode) { if (languageCode in goog.locale.nativeNameConstants['LANGUAGE']) return goog.locale.nativeNameConstants['LANGUAGE'][languageCode]; var code = goog.locale.getLanguageSubTag(languageCode); return code in goog.locale.nativeNameConstants['LANGUAGE'] ? goog.locale.nativeNameConstants['LANGUAGE'][code] : languageCode; }; /** * Returns the localized language name for the provided language code in * the current or provided locale symbols set. * * This method depends on goog.locale.LocaleNameConstants__<locale> available * from http://go/js_locale_data. User of this method has to add dependency to * this. * * @param {string} languageCode Language code to lookup the language name for. * @param {Object=} opt_localeSymbols locale symbol set if given. * * @return {string} Localized language name of the provided language code. */ goog.locale.getLocalizedLanguageName = function(languageCode, opt_localeSymbols) { if (!opt_localeSymbols) { opt_localeSymbols = goog.locale.getResource('LocaleNameConstants', goog.locale.getLocale()); } if (languageCode in opt_localeSymbols['LANGUAGE']) return opt_localeSymbols['LANGUAGE'][languageCode]; var code = goog.locale.getLanguageSubTag(languageCode); return code in opt_localeSymbols['LANGUAGE'] ? opt_localeSymbols['LANGUAGE'][code] : languageCode; }; /** * Register a resource object for certain locale. * @param {Object} dataObj The resource object being registered. * @param {goog.locale.Resource|string} resourceName String that represents * the type of resource. * @param {string} localeName Locale ID. */ goog.locale.registerResource = function(dataObj, resourceName, localeName) { if (!goog.locale.resourceRegistry_[resourceName]) { goog.locale.resourceRegistry_[resourceName] = {}; } goog.locale.resourceRegistry_[resourceName][localeName] = dataObj; // the first registered locale becomes active one. Usually there will be // only one locale per js binary bundle. if (!goog.locale.activeLocale_) { goog.locale.activeLocale_ = localeName; } }; /** * Returns true if the required resource has already been registered. * @param {goog.locale.Resource|string} resourceName String that represents * the type of resource. * @param {string} localeName Locale ID. * @return {boolean} Whether the required resource has already been registered. */ goog.locale.isResourceRegistered = function(resourceName, localeName) { return resourceName in goog.locale.resourceRegistry_ && localeName in goog.locale.resourceRegistry_[resourceName]; }; /** * This object maps (resourceName, localeName) to a resourceObj. * @type {Object} * @private */ goog.locale.resourceRegistry_ = {}; /** * Registers the timezone constants object for a given locale name. * @param {Object} dataObj The resource object. * @param {string} localeName Locale ID. * @deprecated Use goog.i18n.TimeZone, no longer need this. */ goog.locale.registerTimeZoneConstants = function(dataObj, localeName) { goog.locale.registerResource( dataObj, goog.locale.Resource.TIME_ZONE_CONSTANTS, localeName); }; /** * Registers the LocaleNameConstants constants object for a given locale name. * @param {Object} dataObj The resource object. * @param {string} localeName Locale ID. */ goog.locale.registerLocaleNameConstants = function(dataObj, localeName) { goog.locale.registerResource( dataObj, goog.locale.Resource.LOCAL_NAME_CONSTANTS, localeName); }; /** * Registers the TimeZoneSelectedIds constants object for a given locale name. * @param {Object} dataObj The resource object. * @param {string} localeName Locale ID. */ goog.locale.registerTimeZoneSelectedIds = function(dataObj, localeName) { goog.locale.registerResource( dataObj, goog.locale.Resource.TIME_ZONE_SELECTED_IDS, localeName); }; /** * Registers the TimeZoneSelectedShortNames constants object for a given * locale name. * @param {Object} dataObj The resource object. * @param {string} localeName Locale ID. */ goog.locale.registerTimeZoneSelectedShortNames = function(dataObj, localeName) { goog.locale.registerResource( dataObj, goog.locale.Resource.TIME_ZONE_SELECTED_SHORT_NAMES, localeName); }; /** * Registers the TimeZoneSelectedLongNames constants object for a given locale * name. * @param {Object} dataObj The resource object. * @param {string} localeName Locale ID. */ goog.locale.registerTimeZoneSelectedLongNames = function(dataObj, localeName) { goog.locale.registerResource( dataObj, goog.locale.Resource.TIME_ZONE_SELECTED_LONG_NAMES, localeName); }; /** * Registers the TimeZoneAllLongNames constants object for a given locale name. * @param {Object} dataObj The resource object. * @param {string} localeName Locale ID. */ goog.locale.registerTimeZoneAllLongNames = function(dataObj, localeName) { goog.locale.registerResource( dataObj, goog.locale.Resource.TIME_ZONE_ALL_LONG_NAMES, localeName); }; /** * Retrieve specified resource for certain locale. * @param {string} resourceName String that represents the type of resource. * @param {string=} opt_locale Locale ID, if not given, current locale * will be assumed. * @return {Object|undefined} The resource object that hold all the resource * data, or undefined if not available. */ goog.locale.getResource = function(resourceName, opt_locale) { var locale = opt_locale ? opt_locale : goog.locale.getLocale(); if (!(resourceName in goog.locale.resourceRegistry_)) { return undefined; } return goog.locale.resourceRegistry_[resourceName][locale]; }; /** * Retrieve specified resource for certain locale with fallback. For example, * request of 'zh_CN' will be resolved in following order: zh_CN, zh, en. * If none of the above succeeds, of if the resource as indicated by * resourceName does not exist at all, undefined will be returned. * * @param {string} resourceName String that represents the type of resource. * @param {string=} opt_locale locale ID, if not given, current locale * will be assumed. * @return {Object|undefined} The resource object for desired locale. */ goog.locale.getResourceWithFallback = function(resourceName, opt_locale) { var locale = opt_locale ? opt_locale : goog.locale.getLocale(); if (!(resourceName in goog.locale.resourceRegistry_)) { return undefined; } if (locale in goog.locale.resourceRegistry_[resourceName]) { return goog.locale.resourceRegistry_[resourceName][locale]; } // if locale has multiple parts (2 atmost in reality), fallback to base part. var locale_parts = locale.split('_'); if (locale_parts.length > 1 && locale_parts[0] in goog.locale.resourceRegistry_[resourceName]) { return goog.locale.resourceRegistry_[resourceName][locale_parts[0]]; } // otherwise, fallback to 'en' return goog.locale.resourceRegistry_[resourceName]['en']; }; // Export global functions that are used by the date time constants files. // See http://go/js_locale_data var registerLocalNameConstants = goog.locale.registerLocaleNameConstants; var registerTimeZoneSelectedIds = goog.locale.registerTimeZoneSelectedIds; var registerTimeZoneSelectedShortNames = goog.locale.registerTimeZoneSelectedShortNames; var registerTimeZoneSelectedLongNames = goog.locale.registerTimeZoneSelectedLongNames; var registerTimeZoneAllLongNames = goog.locale.registerTimeZoneAllLongNames;
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview List of generic font names and font fallbacks. * This file lists the font fallback for each font family for each locale or * script. In this map, each value is an array of pair. The pair is stored * as an array of two elements. * * First element of the pair is the generic name * for the font family in that locale. In case of script indexed entries, * It will be just font family name. Second element in the pair is a string * comma seperated list of font names. API to access this data is provided * thru goog.locale.genericFontNames. * * Warning: this file is automatically generated from CLDR. * Please contact i18n team or change the script and regenerate data. * Code location: http://go/generate_genericfontnames * */ /** * Namespace for Generic Font Names */ goog.provide('goog.locale.genericFontNamesData'); /** * Map from script code or language code to list of pairs of (generic name, * font name fallback list). * @type {Object} */ /* ~!@# genmethods.genericFontNamesData() #@!~ */ goog.locale.genericFontNamesData = { 'Arab': [ [ 'sans-serif', 'Arial,Al Bayan' ], [ 'serif', 'Arabic Typesetting,Times New Roman' ] ], 'Armn': [[ 'serif', 'Sylfaen,Mshtakan' ]], 'Beng': [[ 'sans-serif', 'Vrinda,Lohit Bengali' ]], 'Cans': [[ 'sans-serif', 'Euphemia,Euphemia UCAS' ]], 'Cher': [[ 'serif', 'Plantagenet,Plantagenet Cherokee' ]], 'Deva': [ [ 'sans-serif', 'Mangal,Lohit Hindi' ], [ 'serif', 'Arial Unicode MS,Devanagari' ] ], 'Ethi': [[ 'serif', 'Nyala' ]], 'Geor': [[ 'serif', 'Sylfaen' ]], 'Gujr': [ [ 'sans-serif', 'Shruti,Lohit Gujarati' ], [ 'serif', 'Gujarati' ] ], 'Guru': [ [ 'sans-serif', 'Raavi,Lohit Punjabi' ], [ 'serif', 'Gurmukhi' ] ], 'Hebr': [ [ 'sans-serif', 'Gisha,Aharoni,Arial Hebrew' ], [ 'serif', 'David' ], [ 'monospace', 'Miriam Fixed' ] ], 'Khmr': [ [ 'sans-serif', 'MoolBoran,Khmer OS' ], [ 'serif', 'DaunPenh' ] ], 'Knda': [ [ 'sans-serif', 'Tunga' ], [ 'serif', 'Kedage' ] ], 'Laoo': [[ 'sans-serif', 'DokChampa,Phetsarath OT' ]], 'Mlym': [ [ 'sans-serif', 'AnjaliOldLipi,Kartika' ], [ 'serif', 'Rachana' ] ], 'Mong': [[ 'serif', 'Mongolian Baiti' ]], 'Nkoo': [[ 'serif', 'Conakry' ]], 'Orya': [[ 'sans-serif', 'Kalinga,utkal' ]], 'Sinh': [[ 'serif', 'Iskoola Pota,Malithi Web' ]], 'Syrc': [[ 'sans-serif', 'Estrangelo Edessa' ]], 'Taml': [ [ 'sans-serif', 'Latha,Lohit Tamil' ], [ 'serif', 'Inai Mathi' ] ], 'Telu': [ [ 'sans-serif', 'Gautami' ], [ 'serif', 'Pothana' ] ], 'Thaa': [[ 'sans-serif', 'MV Boli' ]], 'Thai': [ [ 'sans-serif', 'Tahoma,Thonburi' ], [ 'monospace', 'Tahoma,Ayuthaya' ] ], 'Tibt': [[ 'serif', 'Microsoft Himalaya' ]], 'Yiii': [[ 'sans-serif', 'Microsoft Yi Baiti' ]], 'Zsym': [[ 'sans-serif', 'Apple Symbols' ]], 'jp': [ [ '\uff30\u30b4\u30b7\u30c3\u30af', 'MS PGothic,\uff2d\uff33 \uff30\u30b4\u30b7\u30c3\u30af,Hiragino Kaku G' + 'othic Pro,\u30d2\u30e9\u30ae\u30ce\u89d2\u30b4 Pro W3,Sazanami Gothic' + ',\u3055\u3056\u306a\u307f\u30b4\u30b7\u30c3\u30af,sans-serif' ], [ '\u30e1\u30a4\u30ea\u30aa', 'Meiryo,\u30e1\u30a4\u30ea\u30aa,sans-serif' ], [ '\uff30\u660e\u671d', 'MS PMincho,\uff2d\uff33 \uff30\u660e\u671d,Hiragino Mincho Pro,\u30d2' + '\u30e9\u30ae\u30ce\u660e\u671d Pro W3,Sazanami Mincho,\u3055\u3056' + '\u306a\u307f\u660e\u671d,serif' ], [ '\u7b49\u5e45', 'MS Gothic,\uff2d\uff33 \u30b4\u30b7\u30c3\u30af,Osaka-Mono,Osaka\uff0d' + '\u7b49\u5e45,monospace' ] ], 'ko': [ [ '\uace0\ub515', 'Gulim,\uad74\ub9bc,AppleGothic,\uc560\ud50c\uace0\ub515,UnDotum,\uc740' + ' \ub3cb\uc6c0,Baekmuk Gulim,\ubc31\ubb35 \uad74\ub9bc,sans-serif' ], [ '\ub9d1\uc740\uace0\ub515', 'Malgun Gothic,\ub9d1\uc740\uace0\ub515,sans-serif' ], [ '\ubc14\ud0d5', 'Batang,\ubc14\ud0d5,AppleMyungjo,\uc560\ud50c\uba85\uc870,UnBatang,' + '\uc740 \ubc14\ud0d5,Baekmuk Batang,\ubc31\ubb35 \ubc14\ud0d5,serif' ], [ '\uad81\uc11c', 'Gungseo,\uad81\uc11c,serif' ], [ '\uace0\uc815\ud3ed', 'GulimChe,\uad74\ub9bc\uccb4,AppleGothic,\uc560\ud50c\uace0\ub515,monos' + 'pace' ] ], 'root': [ [ 'sans-serif', 'FreeSans' ], [ 'serif', 'FreeSerif' ], [ 'monospace', 'FreeMono' ] ], 'transpose': { 'zh': { 'zh_Hant': { '\u5b8b\u4f53': '\u65b0\u7d30\u660e\u9ad4', '\u9ed1\u4f53': '\u5fae\u8edf\u6b63\u9ed1\u9ad4' } } }, 'ug': [[ 'serif', 'Microsoft Uighur' ]], 'zh': [ [ '\u9ed1\u4f53', 'Microsoft JhengHei,\u5fae\u8edf\u6b63\u9ed1\u9ad4,SimHei,\u9ed1\u4f53,' + 'MS Hei,STHeiti,\u534e\u6587\u9ed1\u4f53,Apple LiGothic Medium,\u860b' + '\u679c\u5137\u4e2d\u9ed1,LiHei Pro Medium,\u5137\u9ed1 Pro,STHeiti Li' + 'ght,\u534e\u6587\u7ec6\u9ed1,AR PL ZenKai Uni,\u6587\u9f0ePL\u4e2d' + '\u6977Uni,sans-serif' ], [ '\u5fae\u8f6f\u96c5\u9ed1\u5b57\u4f53', 'Microsoft YaHei,\u5fae\u8f6f\u96c5\u9ed1\u5b57\u4f53,sans-serif' ], [ '\u5b8b\u4f53', 'SimSun,\u5b8b\u4f53,MS Song,STSong,\u534e\u6587\u5b8b\u4f53,Apple LiSu' + 'ng Light,\u860b\u679c\u5137\u7d30\u5b8b,LiSong Pro Light,\u5137\u5b8b' + ' Pro,STFangSong,\u534e\u6587\u4eff\u5b8b,AR PL ShanHeiSun Uni,\u6587' + '\u9f0ePL\u7ec6\u4e0a\u6d77\u5b8bUni,AR PL New Sung,\u6587\u9f0e PL ' + '\u65b0\u5b8b,serif' ], [ '\u7d30\u660e\u9ad4', 'NSimsun,\u65b0\u5b8b\u4f53,monospace' ] ] }; /* ~!@# END #@!~ */
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Data for time zone detection. * * The following code was generated by the timezone_detect.py script in: * http://go/i18n_tools which uses following files in this directory: * http://go/timezone_data * Files: olson2fingerprint.txt, country2olsons.txt, popular_olsons.txt * * After automatic generation, we added some manual editing. Projecting on * future changes, it is very unlikely that we will need to change the time * zone ID groups. Most of the further modifications will be about relative * time zone order in each time zone group. The easiest way to do that is * to modify this code directly, and that's what we decide to do. * */ goog.provide('goog.locale.TimeZoneFingerprint'); /** * Time zone fingerprint mapping to time zone list. * @enum {Array.<string>} */ goog.locale.TimeZoneFingerprint = { 919994368: ['CA-America/Halifax', 'CA-America/Glace_Bay', 'GL-America/Thule', 'BM-Atlantic/Bermuda'], 6: ['AQ-Antarctica/Rothera'], 8: ['GY-America/Guyana'], 839516172: ['US-America/Denver', 'MX-America/Chihuahua', 'US-America/Boise', 'CA-America/Cambridge_Bay', 'CA-America/Edmonton', 'CA-America/Inuvik', 'MX-America/Mazatlan', 'US-America/Shiprock', 'CA-America/Yellowknife'], 983564836: ['UY-America/Montevideo'], 487587858: ['AU-Australia/Lord_Howe'], 20: ['KI-Pacific/Kiritimati'], 22: ['TO-Pacific/Tongatapu', 'KI-Pacific/Enderbury'], 24: ['FJ-Pacific/Fiji', 'TV-Pacific/Funafuti', 'MH-Pacific/Kwajalein', 'MH-Pacific/Majuro', 'NR-Pacific/Nauru', 'KI-Pacific/Tarawa', 'UM-Pacific/Wake', 'WF-Pacific/Wallis'], 25: ['NF-Pacific/Norfolk'], 26: ['RU-Asia/Magadan', 'VU-Pacific/Efate', 'SB-Pacific/Guadalcanal', 'FM-Pacific/Kosrae', 'NC-Pacific/Noumea', 'FM-Pacific/Ponape'], 28: ['AQ-Antarctica/DumontDUrville', 'AU-Australia/Brisbane', 'AU-Australia/Lindeman', 'GU-Pacific/Guam', 'PG-Pacific/Port_Moresby', 'MP-Pacific/Saipan', 'FM-Pacific/Truk'], 931091802: ['US-America/New_York', 'US-America/Detroit', 'CA-America/Iqaluit', 'US-America/Kentucky/Monticello', 'US-America/Louisville', 'CA-America/Montreal', 'BS-America/Nassau', 'CA-America/Nipigon', 'CA-America/Pangnirtung', 'CA-America/Thunder_Bay', 'CA-America/Toronto'], 30: ['JP-Asia/Tokyo', 'KR-Asia/Seoul', 'TL-Asia/Dili', 'ID-Asia/Jayapura', 'KP-Asia/Pyongyang', 'PW-Pacific/Palau'], 32: ['HK-Asia/Hong_Kong', 'CN-Asia/Shanghai', 'AU-Australia/Perth', 'TW-Asia/Taipei', 'SG-Asia/Singapore', 'AQ-Antarctica/Casey', 'BN-Asia/Brunei', 'CN-Asia/Chongqing', 'CN-Asia/Harbin', 'CN-Asia/Kashgar', 'MY-Asia/Kuala_Lumpur', 'MY-Asia/Kuching', 'MO-Asia/Macau', 'ID-Asia/Makassar', 'PH-Asia/Manila', 'CN-Asia/Urumqi'], 34: ['TH-Asia/Bangkok', 'AQ-Antarctica/Davis', 'ID-Asia/Jakarta', 'KH-Asia/Phnom_Penh', 'ID-Asia/Pontianak', 'VN-Asia/Saigon', 'LA-Asia/Vientiane', 'CX-Indian/Christmas'], 35: ['MM-Asia/Rangoon', 'CC-Indian/Cocos'], 941621262: ['BR-America/Sao_Paulo'], 37: ['IN-Asia/Calcutta'], 38: ['PK-Asia/Karachi', 'KZ-Asia/Aqtobe', 'TM-Asia/Ashgabat', 'TJ-Asia/Dushanbe', 'UZ-Asia/Samarkand', 'UZ-Asia/Tashkent', 'TF-Indian/Kerguelen', 'MV-Indian/Maldives'], 39: ['AF-Asia/Kabul'], 40: ['OM-Asia/Muscat', 'AE-Asia/Dubai', 'SC-Indian/Mahe', 'MU-Indian/Mauritius', 'RE-Indian/Reunion'], 626175324: ['JO-Asia/Amman'], 42: ['KE-Africa/Nairobi', 'SA-Asia/Riyadh', 'ET-Africa/Addis_Ababa', 'ER-Africa/Asmera', 'TZ-Africa/Dar_es_Salaam', 'DJ-Africa/Djibouti', 'UG-Africa/Kampala', 'SD-Africa/Khartoum', 'SO-Africa/Mogadishu', 'AQ-Antarctica/Syowa', 'YE-Asia/Aden', 'BH-Asia/Bahrain', 'KW-Asia/Kuwait', 'QA-Asia/Qatar', 'MG-Indian/Antananarivo', 'KM-Indian/Comoro', 'YT-Indian/Mayotte'], 44: ['ZA-Africa/Johannesburg', 'IL-Asia/Jerusalem', 'MW-Africa/Blantyre', 'BI-Africa/Bujumbura', 'BW-Africa/Gaborone', 'ZW-Africa/Harare', 'RW-Africa/Kigali', 'CD-Africa/Lubumbashi', 'ZM-Africa/Lusaka', 'MZ-Africa/Maputo', 'LS-Africa/Maseru', 'SZ-Africa/Mbabane', 'LY-Africa/Tripoli'], 46: ['NG-Africa/Lagos', 'DZ-Africa/Algiers', 'CF-Africa/Bangui', 'CG-Africa/Brazzaville', 'CM-Africa/Douala', 'CD-Africa/Kinshasa', 'GA-Africa/Libreville', 'AO-Africa/Luanda', 'GQ-Africa/Malabo', 'TD-Africa/Ndjamena', 'NE-Africa/Niamey', 'BJ-Africa/Porto-Novo'], 48: ['MA-Africa/Casablanca', 'CI-Africa/Abidjan', 'GH-Africa/Accra', 'ML-Africa/Bamako', 'GM-Africa/Banjul', 'GW-Africa/Bissau', 'GN-Africa/Conakry', 'SN-Africa/Dakar', 'EH-Africa/El_Aaiun', 'SL-Africa/Freetown', 'TG-Africa/Lome', 'LR-Africa/Monrovia', 'MR-Africa/Nouakchott', 'BF-Africa/Ouagadougou', 'ST-Africa/Sao_Tome', 'GL-America/Danmarkshavn', 'IS-Atlantic/Reykjavik', 'SH-Atlantic/St_Helena'], 570425352: ['GE-Asia/Tbilisi'], 50: ['CV-Atlantic/Cape_Verde'], 52: ['GS-Atlantic/South_Georgia', 'BR-America/Noronha'], 54: ['AR-America/Buenos_Aires', 'BR-America/Araguaina', 'AR-America/Argentina/La_Rioja', 'AR-America/Argentina/Rio_Gallegos', 'AR-America/Argentina/San_Juan', 'AR-America/Argentina/Tucuman', 'AR-America/Argentina/Ushuaia', 'BR-America/Bahia', 'BR-America/Belem', 'AR-America/Catamarca', 'GF-America/Cayenne', 'AR-America/Cordoba', 'BR-America/Fortaleza', 'AR-America/Jujuy', 'BR-America/Maceio', 'AR-America/Mendoza', 'SR-America/Paramaribo', 'BR-America/Recife', 'AQ-Antarctica/Rothera'], 56: ['VE-America/Caracas', 'AI-America/Anguilla', 'AG-America/Antigua', 'AW-America/Aruba', 'BB-America/Barbados', 'BR-America/Boa_Vista', 'AN-America/Curacao', 'DM-America/Dominica', 'GD-America/Grenada', 'GP-America/Guadeloupe', 'GY-America/Guyana', 'CU-America/Havana', 'BO-America/La_Paz', 'BR-America/Manaus', 'MQ-America/Martinique', 'MS-America/Montserrat', 'TT-America/Port_of_Spain', 'BR-America/Porto_Velho', 'PR-America/Puerto_Rico', 'DO-America/Santo_Domingo', 'KN-America/St_Kitts', 'LC-America/St_Lucia', 'VI-America/St_Thomas', 'VC-America/St_Vincent', 'VG-America/Tortola'], 58: ['US-America/Indianapolis', 'US-America/Indianapolis', 'CO-America/Bogota', 'KY-America/Cayman', 'CA-America/Coral_Harbour', 'BR-America/Eirunepe', 'EC-America/Guayaquil', 'US-America/Indiana/Knox', 'JM-America/Jamaica', 'PE-America/Lima', 'PA-America/Panama', 'BR-America/Rio_Branco'], 60: ['NI-America/Managua', 'CA-America/Regina', 'BZ-America/Belize', 'CR-America/Costa_Rica', 'SV-America/El_Salvador', 'CA-America/Swift_Current', 'EC-Pacific/Galapagos'], 62: ['US-America/Phoenix', 'CA-America/Dawson_Creek', 'MX-America/Hermosillo'], 64: ['PN-Pacific/Pitcairn'], 66: ['PF-Pacific/Gambier'], 67: ['PF-Pacific/Marquesas'], 68: ['US-Pacific/Honolulu', 'TK-Pacific/Fakaofo', 'UM-Pacific/Johnston', 'KI-Pacific/Kiritimati', 'CK-Pacific/Rarotonga', 'PF-Pacific/Tahiti'], 70: ['UM-Pacific/Midway', 'WS-Pacific/Apia', 'KI-Pacific/Enderbury', 'NU-Pacific/Niue', 'AS-Pacific/Pago_Pago'], 72: ['MH-Pacific/Kwajalein'], 49938444: ['MX-America/Chihuahua'], 905969678: ['CA-America/Halifax'], 626339164: ['EG-Africa/Cairo'], 939579406: ['FK-Atlantic/Stanley'], 487915538: ['AU-Australia/Lord_Howe'], 937427058: ['CL-Pacific/Easter'], 778043508: ['RU-Asia/Novosibirsk', 'RU-Asia/Omsk'], 474655352: ['RU-Asia/Anadyr', 'RU-Asia/Kamchatka'], 269133956: ['NZ-Pacific/Chatham'], 948087430: ['GL-America/Godthab'], 671787146: ['MN-Asia/Hovd'], 617261764: ['TR-Europe/Istanbul', 'RU-Europe/Kaliningrad', 'BY-Europe/Minsk'], 830603252: ['MX-America/Mexico_City', 'US-America/Chicago', 'MX-America/Cancun', 'US-America/Menominee', 'MX-America/Merida', 'MX-America/Monterrey', 'US-America/North_Dakota/Center', 'CA-America/Rainy_River', 'CA-America/Rankin_Inlet'], 805300897: ['LK-Asia/Colombo'], 805312524: ['MX-America/Mexico_City', 'HN-America/Tegucigalpa'], 984437412: ['GS-Atlantic/South_Georgia'], 850043558: ['MX-America/Chihuahua'], 29: ['AU-Australia/Darwin'], 710950176: ['MN-Asia/Ulaanbaatar'], 617786052: ['RO-Europe/Bucharest', 'FI-Europe/Helsinki', 'CY-Asia/Nicosia', 'GR-Europe/Athens', 'MD-Europe/Chisinau', 'TR-Europe/Istanbul', 'UA-Europe/Kiev', 'LV-Europe/Riga', 'UA-Europe/Simferopol', 'BG-Europe/Sofia', 'EE-Europe/Tallinn', 'UA-Europe/Uzhgorod', 'LT-Europe/Vilnius', 'UA-Europe/Zaporozhye'], 105862464: ['US-America/Juneau'], 581567010: ['IQ-Asia/Baghdad'], 1294772902: ['US-America/Los_Angeles', 'CA-America/Dawson', 'MX-America/Tijuana', 'CA-America/Vancouver', 'CA-America/Whitehorse'], 483044050: ['AU-Australia/Sydney', 'AU-Australia/Melbourne'], 491433170: ['AU-Australia/Hobart'], 36: ['NP-Asia/Katmandu', 'LK-Asia/Colombo', 'BD-Asia/Dhaka', 'AQ-Antarctica/Mawson', 'AQ-Antarctica/Vostok', 'KZ-Asia/Almaty', 'KZ-Asia/Qyzylorda', 'BT-Asia/Thimphu', 'IO-Indian/Chagos'], 626175196: ['IL-Asia/Jerusalem'], 919994592: ['CA-America/Goose_Bay'], 946339336: ['GB-Europe/London', 'ES-Atlantic/Canary', 'FO-Atlantic/Faeroe', 'PT-Atlantic/Madeira', 'IE-Europe/Dublin', 'PT-Europe/Lisbon'], 1037565906: ['PT-Atlantic/Azores', 'GL-America/Scoresbysund'], 670913918: ['TN-Africa/Tunis'], 41: ['IR-Asia/Tehran'], 572522538: ['RU-Europe/Moscow'], 403351686: ['MN-Asia/Choibalsan'], 626338524: ['PS-Asia/Gaza'], 411740806: ['RU-Asia/Yakutsk'], 635437856: ['RU-Asia/Irkutsk'], 617261788: ['RO-Europe/Bucharest', 'LB-Asia/Beirut'], 947956358: ['GL-America/Godthab', 'PM-America/Miquelon'], 12: ['EC-Pacific/Galapagos'], 626306268: ['SY-Asia/Damascus'], 497024903: ['AU-Australia/Adelaide', 'AU-Australia/Broken_Hill'], 456480044: ['RU-Asia/Vladivostok', 'RU-Asia/Sakhalin'], 312471854: ['NZ-Pacific/Auckland', 'AQ-Antarctica/McMurdo'], 626347356: ['EG-Africa/Cairo'], 897537370: ['CU-America/Havana'], 680176266: ['RU-Asia/Krasnoyarsk'], 1465210176: ['US-America/Anchorage'], 805312908: ['NI-America/Managua'], 492088530: ['AU-Australia/Currie', 'AU-Australia/Hobart'], 901076366: ['BR-America/Campo_Grande', 'BR-America/Cuiaba'], 943019406: ['CL-America/Santiago', 'AQ-Antarctica/Palmer'], 928339288: ['US-America/New_York', 'CA-America/Montreal', 'CA-America/Toronto', 'US-America/Detroit'], 939480410: ['US-America/Indiana/Marengo', 'US-America/Indiana/Vevay'], 626392412: ['NA-Africa/Windhoek'], 559943005: ['IR-Asia/Tehran'], 592794974: ['KZ-Asia/Aqtau', 'KZ-Asia/Oral'], 76502378: ['CA-America/Pangnirtung'], 838860812: ['US-America/Denver', 'CA-America/Edmonton'], 931091834: ['TC-America/Grand_Turk', 'HT-America/Port-au-Prince'], 662525310: ['FR-Europe/Paris', 'DE-Europe/Berlin', 'BA-Europe/Sarajevo', 'CS-Europe/Belgrade', 'ES-Africa/Ceuta', 'NL-Europe/Amsterdam', 'AD-Europe/Andorra', 'SK-Europe/Bratislava', 'BE-Europe/Brussels', 'HU-Europe/Budapest', 'DK-Europe/Copenhagen', 'GI-Europe/Gibraltar', 'SI-Europe/Ljubljana', 'LU-Europe/Luxembourg', 'ES-Europe/Madrid', 'MT-Europe/Malta', 'MC-Europe/Monaco', 'NO-Europe/Oslo', 'CZ-Europe/Prague', 'IT-Europe/Rome', 'MK-Europe/Skopje', 'SE-Europe/Stockholm', 'AL-Europe/Tirane', 'LI-Europe/Vaduz', 'AT-Europe/Vienna', 'PL-Europe/Warsaw', 'HR-Europe/Zagreb', 'CH-Europe/Zurich'], 1465865536: ['US-America/Anchorage', 'US-America/Juneau', 'US-America/Nome', 'US-America/Yakutat'], 495058823: ['AU-Australia/Adelaide', 'AU-Australia/Broken_Hill'], 599086472: ['GE-Asia/Tbilisi', 'AM-Asia/Yerevan', 'RU-Europe/Samara'], 805337484: ['GT-America/Guatemala'], 1001739662: ['PY-America/Asuncion'], 836894706: ['CA-America/Winnipeg'], 599086512: ['AZ-Asia/Baku'], 836894708: ['CA-America/Winnipeg'], 41025476: ['US-America/Menominee'], 501219282: ['RU-Asia/Magadan'], 970325971: ['CA-America/St_Johns'], 769654750: ['RU-Asia/Yekaterinburg'], 1286253222: ['US-America/Los_Angeles', 'CA-America/Vancouver', 'CA-America/Whitehorse'], 1373765610: ['US-America/Adak'], 973078513: ['CA-America/St_Johns'], 838860786: ['US-America/Chicago', 'CA-America/Winnipeg'], 970326003: ['CA-America/St_Johns'], 771751924: ['KG-Asia/Bishkek'], 952805774: ['AQ-Antarctica/Palmer'], 483699410: ['AU-Australia/Sydney', 'AU-Australia/Melbourne'] };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Functions for listing timezone names. * @suppress {deprecated} Use goog.i18n instead. */ /** @suppress {extraProvide} */ goog.provide('goog.locale.TimeZoneList'); goog.require('goog.locale'); /** * Returns the displayable list of short timezone names paired with its id for * the current locale, selected based on the region or language provided. * * This method depends on goog.locale.TimeZone*__<locale> available * from http://go/js_locale_data. User of this method * has to add dependacy to this. * * @param {string=} opt_regionOrLang If region tag is provided, timezone ids * specific this region are considered. If language is provided, all regions * for which this language is defacto official is considered. If * this parameter is not speficied, current locale is used to * extract this information. * * @return {Array.<Object>} Localized and relevant list of timezone names * and ids. */ goog.locale.getTimeZoneSelectedShortNames = function(opt_regionOrLang) { return goog.locale.getTimeZoneNameList_('TimeZoneSelectedShortNames', opt_regionOrLang); }; /** * Returns the displayable list of long timezone names paired with its id for * the current locale, selected based on the region or language provided. * * This method depends on goog.locale.TimeZone*__<locale> available * from http://go/js_locale_data. User of this method * has to add dependacy to this. * * @param {string=} opt_regionOrLang If region tag is provided, timezone ids * specific this region are considered. If language is provided, all regions * for which this language is defacto official is considered. If * this parameter is not speficied, current locale is used to * extract this information. * * @return {Array.<Object>} Localized and relevant list of timezone names * and ids. */ goog.locale.getTimeZoneSelectedLongNames = function(opt_regionOrLang) { return goog.locale.getTimeZoneNameList_('TimeZoneSelectedLongNames', opt_regionOrLang); }; /** * Returns the displayable list of long timezone names paired with its id for * the current locale. * * This method depends on goog.locale.TimeZoneAllLongNames__<locale> available * from http://go/js_locale_data. User of this method * has to add dependacy to this. * * @return {Array.<Object>} localized and relevant list of timezone names * and ids. */ goog.locale.getTimeZoneAllLongNames = function() { var locale = goog.locale.getLocale(); return /** @type {Array} */ ( goog.locale.getResource('TimeZoneAllLongNames', locale)); }; /** * Returns the displayable list of timezone names paired with its id for * the current locale, selected based on the region or language provided. * * This method depends on goog.locale.TimeZone*__<locale> available * from http://go/js_locale_data. User of this method * has to add dependacy to this. * * @param {string} nameType Resource name to be loaded to get the names. * * @param {string=} opt_resource If resource is region tag, timezone ids * specific this region are considered. If it is language, all regions * for which this language is defacto official is considered. If it is * undefined, current locale is used to extract this information. * * @return {Array.<Object>} Localized and relevant list of timezone names * and ids. * @private */ goog.locale.getTimeZoneNameList_ = function(nameType, opt_resource) { var locale = goog.locale.getLocale(); if (!opt_resource) { opt_resource = goog.locale.getRegionSubTag(locale); } // if there is no region subtag, use the language itself as the resource if (!opt_resource) { opt_resource = locale; } var names = goog.locale.getResource(nameType, locale); var ids = goog.locale.getResource('TimeZoneSelectedIds', opt_resource); var len = ids.length; var result = []; for (var i = 0; i < len; i++) { var id = ids[i]; result.push({'id': id, 'name': names[id]}); } return result; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Current list of countries of the world. This list uses * CLDR xml files for data. Algorithm is to list all country codes * that are not containments (representing a group of countries) and does * have a territory alias (old countries). * * Warning: this file is automatically generated from CLDR. * Please contact i18n team or change the script and regenerate data. * Code location: http://go/cldr_scripts:generate_countries * */ /** * Namespace for current country codes. */ goog.provide('goog.locale.countries'); /** * List of codes for countries valid today. * @type {Array} */ /* ~!@# Countries #@!~ (special comment meaningful to generation script) */ goog.locale.countries = [ 'AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AN', 'AO', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BL', 'BM', 'BN', 'BO', 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', 'CU', 'CV', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EE', 'EG', 'EH', 'ER', 'ES', 'ET', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF', 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KP', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'ME', 'MF', 'MG', 'MH', 'MK', 'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NC', 'NE', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RS', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'ST', 'SV', 'SY', 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UM', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'ZA', 'ZM', 'ZW' ]; /* ~!@# END #@!~ */
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview list of native country and language names. * * Warning: this file is automatically generated from CLDR. * Please contact i18n team or change the script and regenerate data. * Code location: http://go/generate_js_native_names.py * */ /** * Namespace for native country and lanugage names */ goog.provide('goog.locale.nativeNameConstants'); /** * Native country and language names * @type {Object} */ /* ~!@# genmethods.NativeDictAsJson() #@!~ */ goog.locale.nativeNameConstants = { 'COUNTRY': { 'AD': 'Andorra', 'AE': '\u0627\u0644\u0627\u0645\u0627\u0631\u0627\u062a \u0627' + '\u0644\u0639\u0631\u0628\u064a\u0629 \u0627\u0644' + '\u0645\u062a\u062d\u062f\u0629', 'AF': '\u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627\u0646', 'AG': 'Antigua and Barbuda', 'AI': 'Anguilla', 'AL': 'Shqip\u00ebria', 'AM': '\u0540\u0561\u0575\u0561\u057d\u057f\u0561\u0576\u056b ' + '\u0540\u0561\u0576\u0580\u0561\u057a\u0565\u057f\u0578' + '\u0582\u0569\u056b\u0582\u0576', 'AN': 'Nederlandse Antillen', 'AO': 'Angola', 'AQ': 'Antarctica', 'AR': 'Argentina', 'AS': 'American Samoa', 'AT': '\u00d6sterreich', 'AU': 'Australia', 'AW': 'Aruba', 'AX': '\u00c5land', 'AZ': 'Az\u0259rbaycan', 'BA': 'Bosna i Hercegovina', 'BB': 'Barbados', 'BD': '\u09ac\u09be\u0982\u09b2\u09be\u09a6\u09c7\u09b6', 'BE': 'Belgi\u00eb', 'BF': 'Burkina Faso', 'BG': '\u0411\u044a\u043b\u0433\u0430\u0440\u0438\u044f', 'BH': '\u0627\u0644\u0628\u062d\u0631\u064a\u0646', 'BI': 'Burundi', 'BJ': 'B\u00e9nin', 'BM': 'Bermuda', 'BN': 'Brunei', 'BO': 'Bolivia', 'BR': 'Brasil', 'BS': 'Bahamas', 'BT': '\u092d\u0942\u091f\u093e\u0928', 'BV': 'Bouvet Island', 'BW': 'Botswana', 'BY': '\u0411\u0435\u043b\u0430\u0440\u0443\u0441\u044c', 'BZ': 'Belize', 'CA': 'Canada', 'CC': 'Cocos (Keeling) Islands', 'CD': 'R\u00e9publique d\u00e9mocratique du Congo', 'CF': 'R\u00e9publique centrafricaine', 'CG': 'Congo', 'CH': 'Schweiz', 'CI': 'C\u00f4te d\u2019Ivoire', 'CK': 'Cook Islands', 'CL': 'Chile', 'CM': 'Cameroun', 'CN': '\u4e2d\u56fd', 'CO': 'Colombia', 'CR': 'Costa Rica', 'CS': 'Serbia and Montenegro', 'CU': 'Cuba', 'CV': 'Cabo Verde', 'CX': 'Christmas Island', 'CY': '\u039a\u03cd\u03c0\u03c1\u03bf\u03c2', 'CZ': '\u010cesk\u00e1 republika', 'DD': 'East Germany', 'DE': 'Deutschland', 'DJ': 'Jabuuti', 'DK': 'Danmark', 'DM': 'Dominica', 'DO': 'Rep\u00fablica Dominicana', 'DZ': '\u0627\u0644\u062c\u0632\u0627\u0626\u0631', 'EC': 'Ecuador', 'EE': 'Eesti', 'EG': '\u0645\u0635\u0631', 'EH': '\u0627\u0644\u0635\u062d\u0631\u0627\u0621 \u0627\u0644' + '\u063a\u0631\u0628\u064a\u0629', 'ER': '\u0627\u0631\u064a\u062a\u0631\u064a\u0627', 'ES': 'Espa\u00f1a', 'ET': '\u12a2\u1275\u12ee\u1335\u12eb', 'FI': 'Suomi', 'FJ': '\u092b\u093f\u091c\u0940', 'FK': 'Falkland Islands', 'FM': 'Micronesia', 'FO': 'F\u00f8royar', 'FR': 'France', 'FX': 'Metropolitan France', 'GA': 'Gabon', 'GB': 'United Kingdom', 'GD': 'Grenada', 'GE': '\u10e1\u10d0\u10e5\u10d0\u10e0\u10d7\u10d5\u10d4\u10da' + '\u10dd', 'GF': 'Guyane fran\u00e7aise', 'GG': 'Guernsey', 'GH': 'Ghana', 'GI': 'Gibraltar', 'GL': 'Kalaallit Nunaat', 'GM': 'Gambia', 'GN': 'Guin\u00e9e', 'GP': 'Guadeloupe', 'GQ': 'Guin\u00e9e \u00e9quatoriale', 'GR': '\u0395\u03bb\u03bb\u03ac\u03b4\u03b1', 'GS': 'South Georgia and the South Sandwich Islands', 'GT': 'Guatemala', 'GU': 'Guam', 'GW': 'Guin\u00e9 Bissau', 'GY': 'Guyana', 'HK': '\u9999\u6e2f', 'HM': 'Heard Island and McDonald Islands', 'HN': 'Honduras', 'HR': 'Hrvatska', 'HT': 'Ha\u00efti', 'HU': 'Magyarorsz\u00e1g', 'ID': 'Indonesia', 'IE': 'Ireland', 'IL': '\u05d9\u05e9\u05e8\u05d0\u05dc', 'IM': 'Isle of Man', 'IN': '\u092d\u093e\u0930\u0924', 'IO': 'British Indian Ocean Territory', 'IQ': '\u0627\u0644\u0639\u0631\u0627\u0642', 'IR': '\u0627\u06cc\u0631\u0627\u0646', 'IS': '\u00cdsland', 'IT': 'Italia', 'JE': 'Jersey', 'JM': 'Jamaica', 'JO': '\u0627\u0644\u0623\u0631\u062f\u0646', 'JP': '\u65e5\u672c', 'KE': 'Kenya', 'KG': '\u041a\u044b\u0440\u0433\u044b\u0437\u0441\u0442\u0430' + '\u043d', 'KH': '\u1780\u1798\u17d2\u1796\u17bb\u1787\u17b6', 'KI': 'Kiribati', 'KM': '\u062c\u0632\u0631 \u0627\u0644\u0642\u0645\u0631', 'KN': 'Saint Kitts and Nevis', 'KP': '\uc870\uc120 \ubbfc\uc8fc\uc8fc\uc758 \uc778\ubbfc ' + '\uacf5\ud654\uad6d', 'KR': '\ub300\ud55c\ubbfc\uad6d', 'KW': '\u0627\u0644\u0643\u0648\u064a\u062a', 'KY': 'Cayman Islands', 'KZ': '\u041a\u0430\u0437\u0430\u0445\u0441\u0442\u0430\u043d', 'LA': '\u0e25\u0e32\u0e27', 'LB': '\u0644\u0628\u0646\u0627\u0646', 'LC': 'Saint Lucia', 'LI': 'Liechtenstein', 'LK': '\u0b87\u0bb2\u0b99\u0bcd\u0b95\u0bc8', 'LR': 'Liberia', 'LS': 'Lesotho', 'LT': 'Lietuva', 'LU': 'Luxembourg', 'LV': 'Latvija', 'LY': '\u0644\u064a\u0628\u064a\u0627', 'MA': '\u0627\u0644\u0645\u063a\u0631\u0628', 'MC': 'Monaco', 'MD': 'Moldova, Republica', 'ME': '\u0426\u0440\u043d\u0430 \u0413\u043e\u0440\u0430', 'MG': 'Madagascar', 'MH': 'Marshall Islands', 'MK': '\u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0438\u0458' + '\u0430', 'ML': '\u0645\u0627\u0644\u064a', 'MM': 'Myanmar', 'MN': '\u8499\u53e4', 'MO': '\u6fb3\u95e8', 'MP': 'Northern Mariana Islands', 'MQ': 'Martinique', 'MR': '\u0645\u0648\u0631\u064a\u062a\u0627\u0646\u064a\u0627', 'MS': 'Montserrat', 'MT': 'Malta', 'MU': 'Mauritius', 'MV': 'Maldives', 'MW': 'Malawi', 'MX': 'M\u00e9xico', 'MY': 'Malaysia', 'MZ': 'Mo\u00e7ambique', 'NA': 'Namibia', 'NC': 'Nouvelle-Cal\u00e9donie', 'NE': 'Niger', 'NF': 'Norfolk Island', 'NG': 'Nigeria', 'NI': 'Nicaragua', 'NL': 'Nederland', 'NO': 'Norge', 'NP': '\u0928\u0947\u092a\u093e\u0932', 'NR': 'Nauru', 'NT': 'Neutral Zone', 'NU': 'Niue', 'NZ': 'New Zealand', 'OM': '\u0639\u0645\u0627\u0646', 'PA': 'Panam\u00e1', 'PE': 'Per\u00fa', 'PF': 'Polyn\u00e9sie fran\u00e7aise', 'PG': 'Papua New Guinea', 'PH': 'Philippines', 'PK': '\u067e\u0627\u06a9\u0633\u062a\u0627\u0646', 'PL': 'Polska', 'PM': 'Saint-Pierre-et-Miquelon', 'PN': 'Pitcairn', 'PR': 'Puerto Rico', 'PS': '\u0641\u0644\u0633\u0637\u064a\u0646', 'PT': 'Portugal', 'PW': 'Palau', 'PY': 'Paraguay', 'QA': '\u0642\u0637\u0631', 'QO': 'Outlying Oceania', 'QU': 'European Union', 'RE': 'R\u00e9union', 'RO': 'Rom\u00e2nia', 'RS': '\u0421\u0440\u0431\u0438\u0458\u0430', 'RU': '\u0420\u043e\u0441\u0441\u0438\u044f', 'RW': 'Rwanda', 'SA': '\u0627\u0644\u0645\u0645\u0644\u0643\u0629 \u0627\u0644' + '\u0639\u0631\u0628\u064a\u0629 \u0627\u0644\u0633' + '\u0639\u0648\u062f\u064a\u0629', 'SB': 'Solomon Islands', 'SC': 'Seychelles', 'SD': '\u0627\u0644\u0633\u0648\u062f\u0627\u0646', 'SE': 'Sverige', 'SG': '\u65b0\u52a0\u5761', 'SH': 'Saint Helena', 'SI': 'Slovenija', 'SJ': 'Svalbard og Jan Mayen', 'SK': 'Slovensk\u00e1 republika', 'SL': 'Sierra Leone', 'SM': 'San Marino', 'SN': 'S\u00e9n\u00e9gal', 'SO': 'Somali', 'SR': 'Suriname', 'ST': 'S\u00e3o Tom\u00e9 e Pr\u00edncipe', 'SU': 'Union of Soviet Socialist Republics', 'SV': 'El Salvador', 'SY': '\u0633\u0648\u0631\u064a\u0627', 'SZ': 'Swaziland', 'TC': 'Turks and Caicos Islands', 'TD': '\u062a\u0634\u0627\u062f', 'TF': 'French Southern Territories', 'TG': 'Togo', 'TH': '\u0e1b\u0e23\u0e30\u0e40\u0e17\u0e28\u0e44\u0e17\u0e22', 'TJ': '\u062a\u0627\u062c\u06cc\u06a9\u0633\u062a\u0627\u0646', 'TK': 'Tokelau', 'TL': 'Timor Leste', 'TM': '\u0422\u0443\u0440\u043a\u043c\u0435\u043d\u0438\u0441' + '\u0442\u0430\u043d', 'TN': '\u062a\u0648\u0646\u0633', 'TO': 'Tonga', 'TR': 'T\u00fcrkiye', 'TT': 'Trinidad y Tobago', 'TV': 'Tuvalu', 'TW': '\u53f0\u6e7e', 'TZ': 'Tanzania', 'UA': '\u0423\u043a\u0440\u0430\u0457\u043d\u0430', 'UG': 'Uganda', 'UM': 'United States Minor Outlying Islands', 'US': 'United States', 'UY': 'Uruguay', 'UZ': '\u040e\u0437\u0431\u0435\u043a\u0438\u0441\u0442\u043e' + '\u043d', 'VA': 'Vaticano', 'VC': 'Saint Vincent and the Grenadines', 'VE': 'Venezuela', 'VG': 'British Virgin Islands', 'VI': 'U.S. Virgin Islands', 'VN': 'Vi\u1ec7t Nam', 'VU': 'Vanuatu', 'WF': 'Wallis-et-Futuna', 'WS': 'Samoa', 'YD': 'People\'s Democratic Republic of Yemen', 'YE': '\u0627\u0644\u064a\u0645\u0646', 'YT': 'Mayotte', 'ZA': 'South Africa', 'ZM': 'Zambia', 'ZW': 'Zimbabwe', 'ZZ': 'Unknown or Invalid Region', 'aa_DJ': 'Jabuuti', 'aa_ER': '\u00c9rythr\u00e9e', 'aa_ER_SAAHO': '\u00c9rythr\u00e9e', 'aa_ET': 'Itoophiyaa', 'af_NA': 'Namibi\u00eb', 'af_ZA': 'Suid-Afrika', 'ak_GH': 'Ghana', 'am_ET': '\u12a2\u1275\u12ee\u1335\u12eb', 'ar_AE': '\u0627\u0644\u0627\u0645\u0627\u0631\u0627\u062a ' + '\u0627\u0644\u0639\u0631\u0628\u064a\u0629 \u0627' + '\u0644\u0645\u062a\u062d\u062f\u0629', 'ar_BH': '\u0627\u0644\u0628\u062d\u0631\u064a\u0646', 'ar_DJ': '\u062c\u064a\u0628\u0648\u062a\u064a', 'ar_DZ': '\u0627\u0644\u062c\u0632\u0627\u0626\u0631', 'ar_EG': '\u0645\u0635\u0631', 'ar_EH': '\u0627\u0644\u0635\u062d\u0631\u0627\u0621 \u0627' + '\u0644\u063a\u0631\u0628\u064a\u0629', 'ar_ER': '\u0627\u0631\u064a\u062a\u0631\u064a\u0627', 'ar_IL': '\u0627\u0633\u0631\u0627\u0626\u064a\u0644', 'ar_IQ': '\u0627\u0644\u0639\u0631\u0627\u0642', 'ar_JO': '\u0627\u0644\u0623\u0631\u062f\u0646', 'ar_KM': '\u062c\u0632\u0631 \u0627\u0644\u0642\u0645\u0631', 'ar_KW': '\u0627\u0644\u0643\u0648\u064a\u062a', 'ar_LB': '\u0644\u0628\u0646\u0627\u0646', 'ar_LY': '\u0644\u064a\u0628\u064a\u0627', 'ar_MA': '\u0627\u0644\u0645\u063a\u0631\u0628', 'ar_MR': '\u0645\u0648\u0631\u064a\u062a\u0627\u0646\u064a' + '\u0627', 'ar_OM': '\u0639\u0645\u0627\u0646', 'ar_PS': '\u0641\u0644\u0633\u0637\u064a\u0646', 'ar_QA': '\u0642\u0637\u0631', 'ar_SA': '\u0627\u0644\u0645\u0645\u0644\u0643\u0629 \u0627' + '\u0644\u0639\u0631\u0628\u064a\u0629 \u0627\u0644' + '\u0633\u0639\u0648\u062f\u064a\u0629', 'ar_SD': '\u0627\u0644\u0633\u0648\u062f\u0627\u0646', 'ar_SY': '\u0633\u0648\u0631\u064a\u0627', 'ar_TD': '\u062a\u0634\u0627\u062f', 'ar_TN': '\u062a\u0648\u0646\u0633', 'ar_YE': '\u0627\u0644\u064a\u0645\u0646', 'as_IN': '\u09ad\u09be\u09f0\u09a4', 'ay_BO': 'Bolivia', 'az_AZ': 'Az\u0259rbaycan', 'az_Cyrl_AZ': '\u0410\u0437\u04d9\u0440\u0431\u0430\u0458' + '\u04b9\u0430\u043d', 'az_Latn_AZ': 'Azerbaycan', 'be_BY': '\u0411\u0435\u043b\u0430\u0440\u0443\u0441\u044c', 'bg_BG': '\u0411\u044a\u043b\u0433\u0430\u0440\u0438\u044f', 'bi_VU': 'Vanuatu', 'bn_BD': '\u09ac\u09be\u0982\u09b2\u09be\u09a6\u09c7\u09b6', 'bn_IN': '\u09ad\u09be\u09b0\u09a4', 'bo_CN': '\u0f62\u0f92\u0fb1\u0f0b\u0f53\u0f42', 'bo_IN': '\u0f62\u0f92\u0fb1\u0f0b\u0f42\u0f62\u0f0b', 'bs_BA': 'Bosna i Hercegovina', 'byn_ER': '\u12a4\u122d\u1275\u122b', 'ca_AD': 'Andorra', 'ca_ES': 'Espanya', 'cch_NG': 'Nigeria', 'ch_GU': 'Guam', 'chk_FM': 'Micronesia', 'cop_Arab_EG': '\u0645\u0635\u0631', 'cop_Arab_US': '\u0627\u0644\u0648\u0644\u0627\u064a\u0627' + '\u062a \u0627\u0644\u0645\u062a\u062d\u062f' + '\u0629 \u0627\u0644\u0623\u0645\u0631\u064a' + '\u0643\u064a\u0629', 'cop_EG': '\u0645\u0635\u0631', 'cop_US': '\u0627\u0644\u0648\u0644\u0627\u064a\u0627\u062a ' + '\u0627\u0644\u0645\u062a\u062d\u062f\u0629 \u0627' + '\u0644\u0623\u0645\u0631\u064a\u0643\u064a\u0629', 'cs_CZ': '\u010cesk\u00e1 republika', 'cy_GB': 'Prydain Fawr', 'da_DK': 'Danmark', 'da_GL': 'Gr\u00f8nland', 'de_AT': '\u00d6sterreich', 'de_BE': 'Belgien', 'de_CH': 'Schweiz', 'de_DE': 'Deutschland', 'de_LI': 'Liechtenstein', 'de_LU': 'Luxemburg', 'dv_MV': 'Maldives', 'dz_BT': 'Bhutan', 'ee_GH': 'Ghana', 'ee_TG': 'Togo', 'efi_NG': 'Nigeria', 'el_CY': '\u039a\u03cd\u03c0\u03c1\u03bf\u03c2', 'el_GR': '\u0395\u03bb\u03bb\u03ac\u03b4\u03b1', 'en_AG': 'Antigua and Barbuda', 'en_AI': 'Anguilla', 'en_AS': 'American Samoa', 'en_AU': 'Australia', 'en_BB': 'Barbados', 'en_BE': 'Belgium', 'en_BM': 'Bermuda', 'en_BS': 'Bahamas', 'en_BW': 'Botswana', 'en_BZ': 'Belize', 'en_CA': 'Canada', 'en_CC': 'Cocos Islands', 'en_CK': 'Cook Islands', 'en_CM': 'Cameroon', 'en_CX': 'Christmas Island', 'en_DM': 'Dominica', 'en_FJ': 'Fiji', 'en_FK': 'Falkland Islands', 'en_FM': 'Micronesia', 'en_GB': 'United Kingdom', 'en_GD': 'Grenada', 'en_GG': 'Guernsey', 'en_GH': 'Ghana', 'en_GI': 'Gibraltar', 'en_GM': 'Gambia', 'en_GU': 'Guam', 'en_GY': 'Guyana', 'en_HK': 'Hong Kong', 'en_HN': 'Honduras', 'en_IE': 'Ireland', 'en_IM': 'Isle of Man', 'en_IN': 'India', 'en_JE': 'Jersey', 'en_JM': 'Jamaica', 'en_KE': 'Kenya', 'en_KI': 'Kiribati', 'en_KN': 'Saint Kitts and Nevis', 'en_KY': 'Cayman Islands', 'en_LC': 'Saint Lucia', 'en_LR': 'Liberia', 'en_LS': 'Lesotho', 'en_MH': 'Marshall Islands', 'en_MP': 'Northern Mariana Islands', 'en_MS': 'Montserrat', 'en_MT': 'Malta', 'en_MU': 'Mauritius', 'en_MW': 'Malawi', 'en_NA': 'Namibia', 'en_NF': 'Norfolk Island', 'en_NG': 'Nigeria', 'en_NR': 'Nauru', 'en_NU': 'Niue', 'en_NZ': 'New Zealand', 'en_PG': 'Papua New Guinea', 'en_PH': 'Philippines', 'en_PK': 'Pakistan', 'en_PN': 'Pitcairn', 'en_PR': 'Puerto Rico', 'en_RW': 'Rwanda', 'en_SB': 'Solomon Islands', 'en_SC': 'Seychelles', 'en_SG': 'Singapore', 'en_SH': 'Saint Helena', 'en_SL': 'Sierra Leone', 'en_SZ': 'Swaziland', 'en_TC': 'Turks and Caicos Islands', 'en_TK': 'Tokelau', 'en_TO': 'Tonga', 'en_TT': 'Trinidad and Tobago', 'en_TV': 'Tuvalu', 'en_TZ': 'Tanzania', 'en_UG': 'Uganda', 'en_UM': 'United States Minor Outlying Islands', 'en_US': 'United States', 'en_US_POSIX': 'United States', 'en_VC': 'Saint Vincent and the Grenadines', 'en_VG': 'British Virgin Islands', 'en_VI': 'U.S. Virgin Islands', 'en_VU': 'Vanuatu', 'en_WS': 'Samoa', 'en_ZA': 'South Africa', 'en_ZM': 'Zambia', 'en_ZW': 'Zimbabwe', 'es_AR': 'Argentina', 'es_BO': 'Bolivia', 'es_CL': 'Chile', 'es_CO': 'Colombia', 'es_CR': 'Costa Rica', 'es_CU': 'Cuba', 'es_DO': 'Rep\u00fablica Dominicana', 'es_EC': 'Ecuador', 'es_ES': 'Espa\u00f1a', 'es_GQ': 'Guinea Ecuatorial', 'es_GT': 'Guatemala', 'es_HN': 'Honduras', 'es_MX': 'M\u00e9xico', 'es_NI': 'Nicaragua', 'es_PA': 'Panam\u00e1', 'es_PE': 'Per\u00fa', 'es_PH': 'Filipinas', 'es_PR': 'Puerto Rico', 'es_PY': 'Paraguay', 'es_SV': 'El Salvador', 'es_US': 'Estados Unidos', 'es_UY': 'Uruguay', 'es_VE': 'Venezuela', 'et_EE': 'Eesti', 'eu_ES': 'Espainia', 'fa_AF': '\u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627' + '\u0646', 'fa_IR': '\u0627\u06cc\u0631\u0627\u0646', 'fi_FI': 'Suomi', 'fil_PH': 'Philippines', 'fj_FJ': 'Fiji', 'fo_FO': 'F\u00f8royar', 'fr_BE': 'Belgique', 'fr_BF': 'Burkina Faso', 'fr_BI': 'Burundi', 'fr_BJ': 'B\u00e9nin', 'fr_CA': 'Canada', 'fr_CD': 'R\u00e9publique d\u00e9mocratique du Congo', 'fr_CF': 'R\u00e9publique centrafricaine', 'fr_CG': 'Congo', 'fr_CH': 'Suisse', 'fr_CI': 'C\u00f4te d\u2019Ivoire', 'fr_CM': 'Cameroun', 'fr_DJ': 'Djibouti', 'fr_DZ': 'Alg\u00e9rie', 'fr_FR': 'France', 'fr_GA': 'Gabon', 'fr_GF': 'Guyane fran\u00e7aise', 'fr_GN': 'Guin\u00e9e', 'fr_GP': 'Guadeloupe', 'fr_GQ': 'Guin\u00e9e \u00e9quatoriale', 'fr_HT': 'Ha\u00efti', 'fr_KM': 'Comores', 'fr_LU': 'Luxembourg', 'fr_MA': 'Maroc', 'fr_MC': 'Monaco', 'fr_MG': 'Madagascar', 'fr_ML': 'Mali', 'fr_MQ': 'Martinique', 'fr_MU': 'Maurice', 'fr_NC': 'Nouvelle-Cal\u00e9donie', 'fr_NE': 'Niger', 'fr_PF': 'Polyn\u00e9sie fran\u00e7aise', 'fr_PM': 'Saint-Pierre-et-Miquelon', 'fr_RE': 'R\u00e9union', 'fr_RW': 'Rwanda', 'fr_SC': 'Seychelles', 'fr_SN': 'S\u00e9n\u00e9gal', 'fr_SY': 'Syrie', 'fr_TD': 'Tchad', 'fr_TG': 'Togo', 'fr_TN': 'Tunisie', 'fr_VU': 'Vanuatu', 'fr_WF': 'Wallis-et-Futuna', 'fr_YT': 'Mayotte', 'fur_IT': 'Italia', 'ga_IE': '\u00c9ire', 'gaa_GH': 'Ghana', 'gez_ER': '\u12a4\u122d\u1275\u122b', 'gez_ET': '\u12a2\u1275\u12ee\u1335\u12eb', 'gil_KI': 'Kiribati', 'gl_ES': 'Espa\u00f1a', 'gn_PY': 'Paraguay', 'gu_IN': '\u0aad\u0abe\u0ab0\u0aa4', 'gv_GB': 'Rywvaneth Unys', 'ha_Arab_NG': '\u0646\u064a\u062c\u064a\u0631\u064a\u0627', 'ha_GH': '\u063a\u0627\u0646\u0627', 'ha_Latn_GH': 'Ghana', 'ha_Latn_NE': 'Niger', 'ha_Latn_NG': 'Nig\u00e9ria', 'ha_NE': '\u0627\u0644\u0646\u064a\u062c\u0631', 'ha_NG': '\u0646\u064a\u062c\u064a\u0631\u064a\u0627', 'haw_US': '\u02bbAmelika Hui P\u016b \u02bbIa', 'he_IL': '\u05d9\u05e9\u05e8\u05d0\u05dc', 'hi_IN': '\u092d\u093e\u0930\u0924', 'ho_PG': 'Papua New Guinea', 'hr_BA': 'Bosna i Hercegovina', 'hr_HR': 'Hrvatska', 'ht_HT': 'Ha\u00efti', 'hu_HU': 'Magyarorsz\u00e1g', 'hy_AM': '\u0540\u0561\u0575\u0561\u057d\u057f\u0561\u0576' + '\u056b \u0540\u0561\u0576\u0580\u0561\u057a\u0565' + '\u057f\u0578\u0582\u0569\u056b\u0582\u0576', 'hy_AM_REVISED': '\u0540\u0561\u0575\u0561\u057d\u057f\u0561' + '\u0576\u056b \u0540\u0561\u0576\u0580\u0561' + '\u057a\u0565\u057f\u0578\u0582\u0569\u056b' + '\u0582\u0576', 'id_ID': 'Indonesia', 'ig_NG': 'Nigeria', 'ii_CN': '\ua34f\ua1e9', 'is_IS': '\u00cdsland', 'it_CH': 'Svizzera', 'it_IT': 'Italia', 'it_SM': 'San Marino', 'ja_JP': '\u65e5\u672c', 'ka_GE': '\u10e1\u10d0\u10e5\u10d0\u10e0\u10d7\u10d5\u10d4' + '\u10da\u10dd', 'kaj_NG': 'Nigeria', 'kam_KE': 'Kenya', 'kcg_NG': 'Nigeria', 'kfo_NG': 'Nig\u00e9ria', 'kk_KZ': '\u049a\u0430\u0437\u0430\u049b\u0441\u0442\u0430' + '\u043d', 'kl_GL': 'Kalaallit Nunaat', 'km_KH': '\u1780\u1798\u17d2\u1796\u17bb\u1787\u17b6', 'kn_IN': '\u0cad\u0cbe\u0cb0\u0ca4', 'ko_KP': '\uc870\uc120 \ubbfc\uc8fc\uc8fc\uc758 \uc778\ubbfc ' + '\uacf5\ud654\uad6d', 'ko_KR': '\ub300\ud55c\ubbfc\uad6d', 'kok_IN': '\u092d\u093e\u0930\u0924', 'kos_FM': 'Micronesia', 'kpe_GN': 'Guin\u00e9e', 'kpe_LR': 'Lib\u00e9ria', 'ks_IN': '\u092d\u093e\u0930\u0924', 'ku_IQ': 'Irak', 'ku_IR': '\u0130ran', 'ku_Latn_IQ': 'Irak', 'ku_Latn_IR': '\u0130ran', 'ku_Latn_SY': 'Suriye', 'ku_Latn_TR': 'T\u00fcrkiye', 'ku_SY': 'Suriye', 'ku_TR': 'T\u00fcrkiye', 'kw_GB': 'Rywvaneth Unys', 'ky_Cyrl_KG': '\u041a\u044b\u0440\u0433\u044b\u0437\u0441' + '\u0442\u0430\u043d', 'ky_KG': 'K\u0131rg\u0131zistan', 'la_VA': 'Vaticano', 'lb_LU': 'Luxembourg', 'ln_CD': 'R\u00e9publique d\u00e9mocratique du Congo', 'ln_CG': 'Kongo', 'lo_LA': 'Laos', 'lt_LT': 'Lietuva', 'lv_LV': 'Latvija', 'mg_MG': 'Madagascar', 'mh_MH': 'Marshall Islands', 'mi_NZ': 'New Zealand', 'mk_MK': '\u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0438' + '\u0458\u0430', 'ml_IN': '\u0d07\u0d28\u0d4d\u0d24\u0d4d\u0d2f', 'mn_Cyrl_MN': '\u041c\u043e\u043d\u0433\u043e\u043b\u0438' + '\u044f', 'mn_MN': '\u041c\u043e\u043d\u0433\u043e\u043b\u0438\u044f', 'mr_IN': '\u092d\u093e\u0930\u0924', 'ms_BN': 'Brunei', 'ms_MY': 'Malaysia', 'ms_SG': 'Singapura', 'mt_MT': 'Malta', 'my_MM': 'Myanmar', 'na_NR': 'Nauru', 'nb_NO': 'Norge', 'nb_SJ': 'Svalbard og Jan Mayen', 'ne_NP': '\u0928\u0947\u092a\u093e\u0932', 'niu_NU': 'Niue', 'nl_AN': 'Nederlandse Antillen', 'nl_AW': 'Aruba', 'nl_BE': 'Belgi\u00eb', 'nl_NL': 'Nederland', 'nl_SR': 'Suriname', 'nn_NO': 'Noreg', 'nr_ZA': 'South Africa', 'nso_ZA': 'South Africa', 'ny_MW': 'Malawi', 'om_ET': 'Itoophiyaa', 'om_KE': 'Keeniyaa', 'or_IN': '\u0b2d\u0b3e\u0b30\u0b24', 'pa_Arab_PK': '\u067e\u0627\u06a9\u0633\u062a\u0627\u0646', 'pa_Guru_IN': '\u0a2d\u0a3e\u0a30\u0a24', 'pa_IN': '\u0a2d\u0a3e\u0a30\u0a24', 'pa_PK': '\u067e\u0627\u06a9\u0633\u062a\u0627\u0646', 'pap_AN': 'Nederlandse Antillen', 'pau_PW': 'Palau', 'pl_PL': 'Polska', 'pon_FM': 'Micronesia', 'ps_AF': '\u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627' + '\u0646', 'pt_AO': 'Angola', 'pt_BR': 'Brasil', 'pt_CV': 'Cabo Verde', 'pt_GW': 'Guin\u00e9 Bissau', 'pt_MZ': 'Mo\u00e7ambique', 'pt_PT': 'Portugal', 'pt_ST': 'S\u00e3o Tom\u00e9 e Pr\u00edncipe', 'pt_TL': 'Timor Leste', 'qu_BO': 'Bolivia', 'qu_PE': 'Per\u00fa', 'rm_CH': 'Schweiz', 'rn_BI': 'Burundi', 'ro_MD': 'Moldova, Republica', 'ro_RO': 'Rom\u00e2nia', 'ru_BY': '\u0411\u0435\u043b\u0430\u0440\u0443\u0441\u044c', 'ru_KG': '\u041a\u044b\u0440\u0433\u044b\u0437\u0441\u0442' + '\u0430\u043d', 'ru_KZ': '\u041a\u0430\u0437\u0430\u0445\u0441\u0442\u0430' + '\u043d', 'ru_RU': '\u0420\u043e\u0441\u0441\u0438\u044f', 'ru_UA': '\u0423\u043a\u0440\u0430\u0438\u043d\u0430', 'rw_RW': 'Rwanda', 'sa_IN': '\u092d\u093e\u0930\u0924', 'sd_Deva_IN': '\u092d\u093e\u0930\u0924', 'sd_IN': '\u092d\u093e\u0930\u0924', 'se_FI': 'Finland', 'se_NO': 'Norge', 'sg_CF': 'R\u00e9publique centrafricaine', 'sh_BA': 'Bosnia and Herzegovina', 'sh_CS': 'Serbia and Montenegro', 'si_LK': 'Sri Lanka', 'sid_ET': 'Itoophiyaa', 'sk_SK': 'Slovensk\u00e1 republika', 'sl_SI': 'Slovenija', 'sm_AS': 'American Samoa', 'sm_WS': 'Samoa', 'so_DJ': 'Jabuuti', 'so_ET': 'Itoobiya', 'so_KE': 'Kiiniya', 'so_SO': 'Soomaaliya', 'sq_AL': 'Shqip\u00ebria', 'sr_BA': '\u0411\u043e\u0441\u043d\u0430 \u0438 \u0425\u0435' + '\u0440\u0446\u0435\u0433\u043e\u0432\u0438\u043d' + '\u0430', 'sr_CS': '\u0421\u0440\u0431\u0438\u0458\u0430 \u0438 \u0426' + '\u0440\u043d\u0430 \u0413\u043e\u0440\u0430', 'sr_Cyrl_BA': '\u0411\u043e\u0441\u043d\u0438\u044f', 'sr_Cyrl_CS': '\u0421\u0435\u0440\u0431\u0438\u044f \u0438 ' + '\u0427\u0435\u0440\u043d\u043e\u0433\u043e' + '\u0440\u0438\u044f', 'sr_Cyrl_ME': '\u0427\u0435\u0440\u043d\u043e\u0433\u043e' + '\u0440\u0438\u044f', 'sr_Cyrl_RS': '\u0421\u0435\u0440\u0431\u0438\u044f', 'sr_Latn_BA': 'Bosna i Hercegovina', 'sr_Latn_CS': 'Srbija i Crna Gora', 'sr_Latn_ME': 'Crna Gora', 'sr_Latn_RS': 'Srbija', 'sr_ME': '\u0426\u0440\u043d\u0430 \u0413\u043e\u0440\u0430', 'sr_RS': '\u0421\u0440\u0431\u0438\u0458\u0430', 'ss_SZ': 'Swaziland', 'ss_ZA': 'South Africa', 'st_LS': 'Lesotho', 'st_ZA': 'South Africa', 'su_ID': 'Indonesia', 'sv_AX': '\u00c5land', 'sv_FI': 'Finland', 'sv_SE': 'Sverige', 'sw_KE': 'Kenya', 'sw_TZ': 'Tanzania', 'sw_UG': 'Uganda', 'swb_KM': '\u062c\u0632\u0631 \u0627\u0644\u0642\u0645\u0631', 'syr_SY': 'Syria', 'ta_IN': '\u0b87\u0ba8\u0bcd\u0ba4\u0bbf\u0baf\u0bbe', 'ta_LK': '\u0b87\u0bb2\u0b99\u0bcd\u0b95\u0bc8', 'ta_SG': '\u0b9a\u0bbf\u0b99\u0bcd\u0b95\u0baa\u0bcd\u0baa' + '\u0bc2\u0bb0\u0bcd', 'te_IN': '\u0c2d\u0c3e\u0c30\u0c24 \u0c26\u0c47\u0c33\u0c02', 'tet_TL': 'Timor Leste', 'tg_Cyrl_TJ': '\u0422\u0430\u0434\u0436\u0438\u043a\u0438' + '\u0441\u0442\u0430\u043d', 'tg_TJ': '\u062a\u0627\u062c\u06a9\u0633\u062a\u0627\u0646', 'th_TH': '\u0e1b\u0e23\u0e30\u0e40\u0e17\u0e28\u0e44\u0e17' + '\u0e22', 'ti_ER': '\u12a4\u122d\u1275\u122b', 'ti_ET': '\u12a2\u1275\u12ee\u1335\u12eb', 'tig_ER': '\u12a4\u122d\u1275\u122b', 'tk_TM': '\u062a\u0631\u06a9\u0645\u0646\u0633\u062a\u0627' + '\u0646', 'tkl_TK': 'Tokelau', 'tn_BW': 'Botswana', 'tn_ZA': 'South Africa', 'to_TO': 'Tonga', 'tpi_PG': 'Papua New Guinea', 'tr_CY': 'G\u00fcney K\u0131br\u0131s Rum Kesimi', 'tr_TR': 'T\u00fcrkiye', 'ts_ZA': 'South Africa', 'tt_RU': '\u0420\u043e\u0441\u0441\u0438\u044f', 'tvl_TV': 'Tuvalu', 'ty_PF': 'Polyn\u00e9sie fran\u00e7aise', 'uk_UA': '\u0423\u043a\u0440\u0430\u0457\u043d\u0430', 'uli_FM': 'Micronesia', 'und_ZZ': 'Unknown or Invalid Region', 'ur_IN': '\u0628\u06be\u0627\u0631\u062a', 'ur_PK': '\u067e\u0627\u06a9\u0633\u062a\u0627\u0646', 'uz_AF': 'Afganistan', 'uz_Arab_AF': '\u0627\u0641\u063a\u0627\u0646\u0633\u062a' + '\u0627\u0646', 'uz_Cyrl_UZ': '\u0423\u0437\u0431\u0435\u043a\u0438\u0441' + '\u0442\u0430\u043d', 'uz_Latn_UZ': 'O\u02bfzbekiston', 'uz_UZ': '\u040e\u0437\u0431\u0435\u043a\u0438\u0441\u0442' + '\u043e\u043d', 've_ZA': 'South Africa', 'vi_VN': 'Vi\u1ec7t Nam', 'wal_ET': '\u12a2\u1275\u12ee\u1335\u12eb', 'wo_Arab_SN': '\u0627\u0644\u0633\u0646\u063a\u0627\u0644', 'wo_Latn_SN': 'S\u00e9n\u00e9gal', 'wo_SN': 'S\u00e9n\u00e9gal', 'xh_ZA': 'South Africa', 'yap_FM': 'Micronesia', 'yo_NG': 'Nigeria', 'zh_CN': '\u4e2d\u56fd', 'zh_HK': '\u9999\u6e2f', 'zh_Hans_CN': '\u4e2d\u56fd', 'zh_Hans_SG': '\u65b0\u52a0\u5761', 'zh_Hant_HK': '\u4e2d\u83ef\u4eba\u6c11\u5171\u548c\u570b' + '\u9999\u6e2f\u7279\u5225\u884c\u653f\u5340', 'zh_Hant_MO': '\u6fb3\u9580', 'zh_Hant_TW': '\u81fa\u7063', 'zh_MO': '\u6fb3\u95e8', 'zh_SG': '\u65b0\u52a0\u5761', 'zh_TW': '\u53f0\u6e7e', 'zu_ZA': 'South Africa' }, 'LANGUAGE': { 'aa': 'afar', 'ab': '\u0430\u0431\u0445\u0430\u0437\u0441\u043a\u0438\u0439', 'ace': 'Aceh', 'ach': 'Acoli', 'ada': 'Adangme', 'ady': '\u0430\u0434\u044b\u0433\u0435\u0439\u0441\u043a' + '\u0438\u0439', 'ae': 'Avestan', 'af': 'Afrikaans', 'afa': 'Afro-Asiatic Language', 'afh': 'Afrihili', 'ain': 'Ainu', 'ak': 'Akan', 'akk': 'Akkadian', 'ale': 'Aleut', 'alg': 'Algonquian Language', 'alt': 'Southern Altai', 'am': '\u12a0\u121b\u122d\u129b', 'an': 'Aragonese', 'ang': 'Old English', 'anp': 'Angika', 'apa': 'Apache Language', 'ar': '\u0627\u0644\u0639\u0631\u0628\u064a\u0629', 'arc': 'Aramaic', 'arn': 'Araucanian', 'arp': 'Arapaho', 'art': 'Artificial Language', 'arw': 'Arawak', 'as': '\u0985\u09b8\u09ae\u09c0\u09af\u09bc\u09be', 'ast': 'asturiano', 'ath': 'Athapascan Language', 'aus': 'Australian Language', 'av': '\u0430\u0432\u0430\u0440\u0441\u043a\u0438\u0439', 'awa': 'Awadhi', 'ay': 'aimara', 'az': 'az\u0259rbaycanca', 'az_Arab': '\u062a\u0631\u06a9\u06cc \u0622\u0630\u0631\u0628' + '\u0627\u06cc\u062c\u0627\u0646\u06cc', 'az_Cyrl': '\u0410\u0437\u04d9\u0440\u0431\u0430\u0458\u04b9' + '\u0430\u043d', 'az_Latn': 'Azerice', 'ba': '\u0431\u0430\u0448\u043a\u0438\u0440\u0441\u043a\u0438' + '\u0439', 'bad': 'Banda', 'bai': 'Bamileke Language', 'bal': '\u0628\u0644\u0648\u0686\u06cc', 'ban': 'Balin', 'bas': 'Basa', 'bat': 'Baltic Language', 'be': '\u0431\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430' + '\u044f', 'bej': 'Beja', 'bem': 'Bemba', 'ber': 'Berber', 'bg': '\u0431\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438', 'bh': '\u092c\u093f\u0939\u093e\u0930\u0940', 'bho': 'Bhojpuri', 'bi': 'bichelamar ; bislama', 'bik': 'Bikol', 'bin': 'Bini', 'bla': 'Siksika', 'bm': 'bambara', 'bn': '\u09ac\u09be\u0982\u09b2\u09be', 'bnt': 'Bantu', 'bo': '\u0f54\u0f7c\u0f51\u0f0b\u0f66\u0f90\u0f51\u0f0b', 'br': 'breton', 'bra': 'Braj', 'bs': 'Bosanski', 'btk': 'Batak', 'bua': 'Buriat', 'bug': 'Bugis', 'byn': '\u1265\u120a\u1295', 'ca': 'catal\u00e0', 'cad': 'Caddo', 'cai': 'Central American Indian Language', 'car': 'Carib', 'cau': 'Caucasian Language', 'cch': 'Atsam', 'ce': '\u0447\u0435\u0447\u0435\u043d\u0441\u043a\u0438\u0439', 'ceb': 'Cebuano', 'cel': 'Celtic Language', 'ch': 'Chamorro', 'chb': 'Chibcha', 'chg': 'Chagatai', 'chk': 'Chuukese', 'chm': '\u043c\u0430\u0440\u0438\u0439\u0441\u043a\u0438' + '\u0439 (\u0447\u0435\u0440\u0435\u043c\u0438\u0441' + '\u0441\u043a\u0438\u0439)', 'chn': 'Chinook Jargon', 'cho': 'Choctaw', 'chp': 'Chipewyan', 'chr': 'Cherokee', 'chy': 'Cheyenne', 'cmc': 'Chamic Language', 'co': 'corse', 'cop': '\u0642\u0628\u0637\u064a\u0629', 'cop_Arab': '\u0642\u0628\u0637\u064a\u0629', 'cpe': 'English-based Creole or Pidgin', 'cpf': 'French-based Creole or Pidgin', 'cpp': 'Portuguese-based Creole or Pidgin', 'cr': 'Cree', 'crh': 'Crimean Turkish', 'crp': 'Creole or Pidgin', 'cs': '\u010de\u0161tina', 'csb': 'Kashubian', 'cu': 'Church Slavic', 'cus': 'Cushitic Language', 'cv': '\u0447\u0443\u0432\u0430\u0448\u0441\u043a\u0438\u0439', 'cy': 'Cymraeg', 'da': 'dansk', 'dak': 'Dakota', 'dar': '\u0434\u0430\u0440\u0433\u0432\u0430', 'day': 'Dayak', 'de': 'Deutsch', 'del': 'Delaware', 'den': 'Slave', 'dgr': 'Dogrib', 'din': 'Dinka', 'doi': '\u0627\u0644\u062f\u0648\u062c\u0631\u0649', 'dra': 'Dravidian Language', 'dsb': 'Lower Sorbian', 'dua': 'Duala', 'dum': 'Middle Dutch', 'dv': 'Divehi', 'dyu': 'dioula', 'dz': '\u0f62\u0fab\u0f7c\u0f44\u0f0b\u0f41', 'ee': 'Ewe', 'efi': 'Efik', 'egy': 'Ancient Egyptian', 'eka': 'Ekajuk', 'el': '\u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac', 'elx': 'Elamite', 'en': 'English', 'enm': 'Middle English', 'eo': 'esperanto', 'es': 'espa\u00f1ol', 'et': 'eesti', 'eu': 'euskara', 'ewo': 'Ewondo', 'fa': '\u0641\u0627\u0631\u0633\u06cc', 'fan': 'fang', 'fat': 'Fanti', 'ff': 'Fulah', 'fi': 'suomi', 'fil': 'Filipino', 'fiu': 'Finno-Ugrian Language', 'fj': 'Fijian', 'fo': 'f\u00f8royskt', 'fon': 'Fon', 'fr': 'fran\u00e7ais', 'frm': 'Middle French', 'fro': 'Old French', 'frr': 'Northern Frisian', 'frs': 'Eastern Frisian', 'fur': 'friulano', 'fy': 'Fries', 'ga': 'Gaeilge', 'gaa': 'Ga', 'gay': 'Gayo', 'gba': 'Gbaya', 'gd': 'Scottish Gaelic', 'gem': 'Germanic Language', 'gez': '\u130d\u12d5\u12dd\u129b', 'gil': 'Gilbertese', 'gl': 'galego', 'gmh': 'Middle High German', 'gn': 'guaran\u00ed', 'goh': 'Old High German', 'gon': 'Gondi', 'gor': 'Gorontalo', 'got': 'Gothic', 'grb': 'Grebo', 'grc': '\u0391\u03c1\u03c7\u03b1\u03af\u03b1 \u0395\u03bb' + '\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac', 'gsw': 'Schweizerdeutsch', 'gu': '\u0a97\u0ac1\u0a9c\u0ab0\u0abe\u0aa4\u0ac0', 'gv': 'Gaelg', 'gwi': 'Gwich\u02bcin', 'ha': '\u0627\u0644\u0647\u0648\u0633\u0627', 'ha_Arab': '\u0627\u0644\u0647\u0648\u0633\u0627', 'ha_Latn': 'haoussa', 'hai': 'Haida', 'haw': '\u02bb\u014dlelo Hawai\u02bbi', 'he': '\u05e2\u05d1\u05e8\u05d9\u05ea', 'hi': '\u0939\u093f\u0902\u0926\u0940', 'hil': 'Hiligaynon', 'him': 'Himachali', 'hit': 'Hittite', 'hmn': 'Hmong', 'ho': 'Hiri Motu', 'hr': 'hrvatski', 'hsb': 'Upper Sorbian', 'ht': 'ha\u00eftien', 'hu': 'magyar', 'hup': 'Hupa', 'hy': '\u0540\u0561\u0575\u0565\u0580\u0567\u0576', 'hz': 'Herero', 'ia': 'interlingvao', 'iba': 'Iban', 'id': 'Bahasa Indonesia', 'ie': 'Interlingue', 'ig': 'Igbo', 'ii': '\ua188\ua320\ua259', 'ijo': 'Ijo', 'ik': 'Inupiaq', 'ilo': 'Iloko', 'inc': 'Indic Language', 'ine': 'Indo-European Language', 'inh': '\u0438\u043d\u0433\u0443\u0448\u0441\u043a\u0438' + '\u0439', 'io': 'Ido', 'ira': 'Iranian Language', 'iro': 'Iroquoian Language', 'is': '\u00edslenska', 'it': 'italiano', 'iu': 'Inuktitut', 'ja': '\u65e5\u672c\u8a9e', 'jbo': 'Lojban', 'jpr': 'Judeo-Persian', 'jrb': 'Judeo-Arabic', 'jv': 'Jawa', 'ka': '\u10e5\u10d0\u10e0\u10d7\u10e3\u10da\u10d8', 'kaa': '\u043a\u0430\u0440\u0430\u043a\u0430\u043b\u043f' + '\u0430\u043a\u0441\u043a\u0438\u0439', 'kab': 'kabyle', 'kac': 'Kachin', 'kaj': 'Jju', 'kam': 'Kamba', 'kar': 'Karen', 'kaw': 'Kawi', 'kbd': '\u043a\u0430\u0431\u0430\u0440\u0434\u0438\u043d' + '\u0441\u043a\u0438\u0439', 'kcg': 'Tyap', 'kfo': 'koro', 'kg': 'Kongo', 'kha': 'Khasi', 'khi': 'Khoisan Language', 'kho': 'Khotanese', 'ki': 'Kikuyu', 'kj': 'Kuanyama', 'kk': '\u049a\u0430\u0437\u0430\u049b', 'kl': 'kalaallisut', 'km': '\u1797\u17b6\u179f\u17b6\u1781\u17d2\u1798\u17c2\u179a', 'kmb': 'quimbundo', 'kn': '\u0c95\u0ca8\u0ccd\u0ca8\u0ca1', 'ko': '\ud55c\uad6d\uc5b4', 'kok': '\u0915\u094b\u0902\u0915\u0923\u0940', 'kos': 'Kosraean', 'kpe': 'kpell\u00e9', 'kr': 'Kanuri', 'krc': '\u043a\u0430\u0440\u0430\u0447\u0430\u0435\u0432' + '\u043e-\u0431\u0430\u043b\u043a\u0430\u0440\u0441' + '\u043a\u0438\u0439', 'krl': '\u043a\u0430\u0440\u0435\u043b\u044c\u0441\u043a' + '\u0438\u0439', 'kro': 'Kru', 'kru': 'Kurukh', 'ks': '\u0915\u093e\u0936\u094d\u092e\u093f\u0930\u0940', 'ku': 'K\u00fcrt\u00e7e', 'ku_Arab': '\u0627\u0644\u0643\u0631\u062f\u064a\u0629', 'ku_Latn': 'K\u00fcrt\u00e7e', 'kum': '\u043a\u0443\u043c\u044b\u043a\u0441\u043a\u0438' + '\u0439', 'kut': 'Kutenai', 'kv': 'Komi', 'kw': 'kernewek', 'ky': 'K\u0131rg\u0131zca', 'ky_Arab': '\u0627\u0644\u0642\u064a\u0631\u063a\u0633\u062a' + '\u0627\u0646\u064a\u0629', 'ky_Cyrl': '\u043a\u0438\u0440\u0433\u0438\u0437\u0441\u043a' + '\u0438\u0439', 'la': 'latino', 'lad': '\u05dc\u05d3\u05d9\u05e0\u05d5', 'lah': '\u0644\u0627\u0647\u0646\u062f\u0627', 'lam': 'Lamba', 'lb': 'luxembourgeois', 'lez': '\u043b\u0435\u0437\u0433\u0438\u043d\u0441\u043a' + '\u0438\u0439', 'lg': 'Ganda', 'li': 'Limburgs', 'ln': 'lingala', 'lo': 'Lao', 'lol': 'mongo', 'loz': 'Lozi', 'lt': 'lietuvi\u0173', 'lu': 'luba-katanga', 'lua': 'luba-lulua', 'lui': 'Luiseno', 'lun': 'Lunda', 'luo': 'Luo', 'lus': 'Lushai', 'lv': 'latvie\u0161u', 'mad': 'Madura', 'mag': 'Magahi', 'mai': 'Maithili', 'mak': 'Makassar', 'man': 'Mandingo', 'map': 'Austronesian', 'mas': 'Masai', 'mdf': '\u043c\u043e\u043a\u0448\u0430', 'mdr': 'Mandar', 'men': 'Mende', 'mg': 'malgache', 'mga': 'Middle Irish', 'mh': 'Marshallese', 'mi': 'Maori', 'mic': 'Micmac', 'min': 'Minangkabau', 'mis': 'Miscellaneous Language', 'mk': '\u043c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a' + '\u0438', 'mkh': 'Mon-Khmer Language', 'ml': '\u0d2e\u0d32\u0d2f\u0d3e\u0d33\u0d02', 'mn': '\u043c\u043e\u043d\u0433\u043e\u043b\u044c\u0441\u043a' + '\u0438\u0439', 'mn_Cyrl': '\u043c\u043e\u043d\u0433\u043e\u043b\u044c\u0441' + '\u043a\u0438\u0439', 'mn_Mong': '\u043c\u043e\u043d\u0433\u043e\u043b\u044c\u0441' + '\u043a\u0438\u0439', 'mnc': 'Manchu', 'mni': 'Manipuri', 'mno': 'Manobo Language', 'mo': 'Moldavian', 'moh': 'Mohawk', 'mos': 'mor\u00e9 ; mossi', 'mr': '\u092e\u0930\u093e\u0920\u0940', 'ms': 'Bahasa Melayu', 'mt': 'Malti', 'mul': 'Multiple Languages', 'mun': 'Munda Language', 'mus': 'Creek', 'mwl': 'Mirandese', 'mwr': 'Marwari', 'my': 'Burmese', 'myn': 'Mayan Language', 'myv': '\u044d\u0440\u0437\u044f', 'na': 'Nauru', 'nah': 'Nahuatl', 'nai': 'North American Indian Language', 'nap': 'napoletano', 'nb': 'norsk bokm\u00e5l', 'nd': 'North Ndebele', 'nds': 'Low German', 'ne': '\u0928\u0947\u092a\u093e\u0932\u0940', 'new': 'Newari', 'ng': 'Ndonga', 'nia': 'Nias', 'nic': 'Niger-Kordofanian Language', 'niu': 'Niuean', 'nl': 'Nederlands', 'nn': 'nynorsk', 'no': 'Norwegian', 'nog': '\u043d\u043e\u0433\u0430\u0439\u0441\u043a\u0438' + '\u0439', 'non': 'Old Norse', 'nqo': 'N\u2019Ko', 'nr': 'South Ndebele', 'nso': 'Northern Sotho', 'nub': 'Nubian Language', 'nv': 'Navajo', 'nwc': 'Classical Newari', 'ny': 'nianja; chicheua; cheua', 'nym': 'Nyamwezi', 'nyn': 'Nyankole', 'nyo': 'Nyoro', 'nzi': 'Nzima', 'oc': 'occitan', 'oj': 'Ojibwa', 'om': 'Oromoo', 'or': '\u0b13\u0b21\u0b3c\u0b3f\u0b06', 'os': '\u043e\u0441\u0435\u0442\u0438\u043d\u0441\u043a\u0438' + '\u0439', 'osa': 'Osage', 'ota': 'Ottoman Turkish', 'oto': 'Otomian Language', 'pa': '\u0a2a\u0a70\u0a1c\u0a3e\u0a2c\u0a40', 'pa_Arab': '\u067e\u0646\u062c\u0627\u0628', 'pa_Guru': '\u0a2a\u0a70\u0a1c\u0a3e\u0a2c\u0a40', 'paa': 'Papuan Language', 'pag': 'Pangasinan', 'pal': 'Pahlavi', 'pam': 'Pampanga', 'pap': 'Papiamento', 'pau': 'Palauan', 'peo': 'Old Persian', 'phi': 'Philippine Language', 'phn': 'Phoenician', 'pi': '\u0e1a\u0e32\u0e25\u0e35', 'pl': 'polski', 'pon': 'Pohnpeian', 'pra': 'Prakrit Language', 'pro': 'Old Proven\u00e7al', 'ps': '\u067e\u069a\u062a\u0648', 'pt': 'portugu\u00eas', 'qu': 'quechua', 'raj': 'Rajasthani', 'rap': 'Rapanui', 'rar': 'Rarotongan', 'rm': 'R\u00e4toromanisch', 'rn': 'roundi', 'ro': 'rom\u00e2n\u0103', 'roa': 'Romance Language', 'rom': 'Romany', 'ru': '\u0440\u0443\u0441\u0441\u043a\u0438\u0439', 'rup': 'Aromanian', 'rw': 'rwanda', 'sa': '\u0938\u0902\u0938\u094d\u0915\u0943\u0924 \u092d' + '\u093e\u0937\u093e', 'sad': 'Sandawe', 'sah': '\u044f\u043a\u0443\u0442\u0441\u043a\u0438\u0439', 'sai': 'South American Indian Language', 'sal': 'Salishan Language', 'sam': '\u05d0\u05e8\u05de\u05d9\u05ea \u05e9\u05d5\u05de' + '\u05e8\u05d5\u05e0\u05d9\u05ea', 'sas': 'Sasak', 'sat': 'Santali', 'sc': 'Sardinian', 'scn': 'siciliano', 'sco': 'Scots', 'sd': '\u0938\u093f\u0928\u094d\u0927\u0940', 'sd_Arab': '\u0633\u0646\u062f\u06cc', 'sd_Deva': '\u0938\u093f\u0928\u094d\u0927\u0940', 'se': 'nordsamiska', 'sel': '\u0441\u0435\u043b\u044c\u043a\u0443\u043f\u0441' + '\u043a\u0438\u0439', 'sem': 'Semitic Language', 'sg': 'sangho', 'sga': 'Old Irish', 'sgn': 'Sign Language', 'sh': 'Serbo-Croatian', 'shn': 'Shan', 'si': 'Sinhalese', 'sid': 'Sidamo', 'sio': 'Siouan Language', 'sit': 'Sino-Tibetan Language', 'sk': 'slovensk\u00fd', 'sl': 'sloven\u0161\u010dina', 'sla': 'Slavic Language', 'sm': 'Samoan', 'sma': 'sydsamiska', 'smi': 'Sami Language', 'smj': 'lulesamiska', 'smn': 'Inari Sami', 'sms': 'Skolt Sami', 'sn': 'Shona', 'snk': 'sonink\u00e9', 'so': 'Soomaali', 'sog': 'Sogdien', 'son': 'Songhai', 'sq': 'shqipe', 'sr': '\u0421\u0440\u043f\u0441\u043a\u0438', 'sr_Cyrl': '\u0441\u0435\u0440\u0431\u0441\u043a\u0438\u0439', 'sr_Latn': 'Srpski', 'srn': 'Sranantongo', 'srr': 's\u00e9r\u00e8re', 'ss': 'Swati', 'ssa': 'Nilo-Saharan Language', 'st': 'Sesotho', 'su': 'Sundan', 'suk': 'Sukuma', 'sus': 'soussou', 'sux': 'Sumerian', 'sv': 'svenska', 'sw': 'Kiswahili', 'syc': 'Classical Syriac', 'syr': 'Syriac', 'ta': '\u0ba4\u0bae\u0bbf\u0bb4\u0bcd', 'tai': 'Tai Language', 'te': '\u0c24\u0c46\u0c32\u0c41\u0c17\u0c41', 'tem': 'Timne', 'ter': 'Tereno', 'tet': 't\u00e9tum', 'tg': '\u062a\u0627\u062c\u06a9', 'tg_Arab': '\u062a\u0627\u062c\u06a9', 'tg_Cyrl': '\u0442\u0430\u0434\u0436\u0438\u043a\u0441\u043a' + '\u0438\u0439', 'th': '\u0e44\u0e17\u0e22', 'ti': '\u1275\u130d\u122d\u129b', 'tig': '\u1275\u130d\u1228', 'tiv': 'Tiv', 'tk': '\u062a\u0631\u06a9\u0645\u0646\u06cc', 'tkl': 'Tokelau', 'tl': 'Tagalog', 'tlh': 'Klingon', 'tli': 'Tlingit', 'tmh': 'tamacheq', 'tn': 'Tswana', 'to': 'Tonga', 'tog': 'Nyasa Tonga', 'tpi': 'Tok Pisin', 'tr': 'T\u00fcrk\u00e7e', 'ts': 'Tsonga', 'tsi': 'Tsimshian', 'tt': '\u0442\u0430\u0442\u0430\u0440\u0441\u043a\u0438\u0439', 'tum': 'Tumbuka', 'tup': 'Tupi Language', 'tut': '\u0430\u043b\u0442\u0430\u0439\u0441\u043a\u0438' + '\u0435 (\u0434\u0440\u0443\u0433\u0438\u0435)', 'tvl': 'Tuvalu', 'tw': 'Twi', 'ty': 'tahitien', 'tyv': '\u0442\u0443\u0432\u0438\u043d\u0441\u043a\u0438' + '\u0439', 'udm': '\u0443\u0434\u043c\u0443\u0440\u0442\u0441\u043a' + '\u0438\u0439', 'ug': '\u0443\u0439\u0433\u0443\u0440\u0441\u043a\u0438\u0439', 'uga': 'Ugaritic', 'uk': '\u0443\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a' + '\u0430', 'umb': 'umbundu', 'und': 'English', 'ur': '\u0627\u0631\u062f\u0648', 'uz': '\u040e\u0437\u0431\u0435\u043a', 'uz_Arab': '\u0627\u06c9\u0632\u0628\u06d0\u06a9', 'uz_Cyrl': '\u0443\u0437\u0431\u0435\u043a\u0441\u043a\u0438' + '\u0439', 'uz_Latn': 'o\'zbekcha', 'vai': 'Vai', 've': 'Venda', 'vi': 'Ti\u1ebfng Vi\u1ec7t', 'vo': 'volapuko', 'vot': 'Votic', 'wa': 'Wallonisch', 'wak': 'Wakashan Language', 'wal': 'Walamo', 'war': 'Waray', 'was': 'Washo', 'wen': 'Sorbian Language', 'wo': 'wolof', 'wo_Arab': '\u0627\u0644\u0648\u0644\u0648\u0641', 'wo_Latn': 'wolof', 'xal': '\u043a\u0430\u043b\u043c\u044b\u0446\u043a\u0438' + '\u0439', 'xh': 'Xhosa', 'yao': 'iao', 'yap': 'Yapese', 'yi': '\u05d9\u05d9\u05d3\u05d9\u05e9', 'yo': 'Yoruba', 'ypk': 'Yupik Language', 'za': 'Zhuang', 'zap': 'Zapotec', 'zen': 'Zenaga', 'zh': '\u4e2d\u6587', 'zh_Hans': '\u4e2d\u6587', 'zh_Hant': '\u4e2d\u6587', 'znd': 'Zande', 'zu': 'Zulu', 'zun': 'Zuni', 'zxx': 'No linguistic content', 'zza': 'Zaza' } }; /* ~!@# END #@!~ */
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Script to Languages mapping. Typically, one script is used by * many languages of the world. This map captures that information as a mapping * from script to array of two letter or three letter language codes. * * This map is used by goog.locale.genericFontNames for listing * font fallbacks for a font family for a locale. That file * uses this map in conjunction with goog.locale.genericFontNamesData. * * Warning: this file is automatically generated from CLDR. * Please contact i18n team or change the script and regenerate data. * Code location: http://go/generate_genericfontnames.py * */ /** * Namespace for Script to Languages mapping */ goog.provide('goog.locale.scriptToLanguages'); goog.require('goog.locale'); /** * The script code to list of language codes map. * @type {Object} */ /* ~!@# genmethods.scriptToLanguages() #@!~ */ goog.locale.scriptToLanguages = { 'Arab': [ 'prd', 'doi', 'lah', 'uz', 'cjm', 'swb', 'az', 'ps', 'ur', 'ks', 'fa', 'ar', 'tk', 'ku', 'tg', 'bal', 'ha', 'ky', 'ug', 'sd' ], 'Armn': ['hy'], 'Beng': [ 'mni', 'grt', 'bn', 'syl', 'as', 'ril', 'ccp' ], 'Blis': ['zbl'], 'Cans': [ 'cr', 'iu', 'cwd', 'crk' ], 'Cham': ['cja'], 'Cher': ['chr'], 'Cyrl': [ 'ab', 'rom', 'mns', 'mdf', 'ce', 'myv', 'ude', 'sah', 'inh', 'uk', 'tab', 'av', 'yrk', 'az', 'cv', 'koi', 'ru', 'dng', 'sel', 'tt', 'chm', 'ady', 'tyv', 'abq', 'kum', 'xal', 'tg', 'cjs', 'tk', 'be', 'kaa', 'bg', 'kca', 'ba', 'nog', 'krl', 'bxr', 'kbd', 'dar', 'krc', 'lez', 'ttt', 'udm', 'evn', 'kpv', 'uz', 'kk', 'kpy', 'kjh', 'mn', 'gld', 'mk', 'ckt', 'aii', 'kv', 'ku', 'sr', 'lbe', 'ky', 'os' ], 'Deva': [ 'btv', 'kfr', 'bho', 'mr', 'bhb', 'bjj', 'hi', 'mag', 'mai', 'awa', 'lif', 'xsr', 'mwr', 'kok', 'gon', 'hne', 'hoc', 'gbm', 'hoj', 'ne', 'kru', 'ks', 'bra', 'bft', 'new', 'bfy', 'sd' ], 'Ethi': [ 'byn', 'wal', 'ti', 'tig', 'am' ], 'Geor': ['ka'], 'Grek': ['el'], 'Gujr': ['gu'], 'Guru': ['pa'], 'Hans': [ 'zh', 'za' ], 'Hant': ['zh'], 'Hebr': [ 'lad', 'yi', 'he' ], 'Jpan': ['ja'], 'Khmr': ['km'], 'Knda': [ 'kn', 'tcy' ], 'Kore': ['ko'], 'Laoo': ['lo'], 'Latn': [ 'gv', 'sco', 'scn', 'mfe', 'hnn', 'suk', 'tkl', 'gd', 'ga', 'gn', 'gl', 'rom', 'hai', 'lb', 'la', 'ln', 'tsg', 'tr', 'ts', 'li', 'lv', 'to', 'lt', 'lu', 'tk', 'tg', 'fo', 'fil', 'bya', 'bin', 'kcg', 'ceb', 'amo', 'yao', 'mos', 'dyu', 'de', 'tbw', 'da', 'fan', 'st', 'hil', 'fon', 'efi', 'tl', 'qu', 'uz', 'kpe', 'ban', 'bal', 'gor', 'tru', 'mo', 'mdh', 'en', 'tem', 'ee', 'tvl', 'cr', 'eu', 'et', 'tet', 'nbf', 'es', 'rw', 'lut', 'kmb', 'ast', 'sms', 'lua', 'sus', 'smj', 'fy', 'tmh', 'rm', 'rn', 'ro', 'dsb', 'sma', 'luo', 'hsb', 'wa', 'lg', 'wo', 'bm', 'jv', 'men', 'bi', 'tum', 'br', 'bs', 'smn', 'om', 'ace', 'ilo', 'ty', 'oc', 'srr', 'krl', 'tw', 'nds', 'os', 'xh', 'ch', 'co', 'nso', 'ca', 'sn', 'eo', 'son', 'pon', 'cy', 'cs', 'kfo', 'fj', 'tn', 'srn', 'pt', 'sm', 'chk', 'bbc', 'chm', 'lol', 'frs', 'frr', 'chr', 'yap', 'vi', 'kos', 'gil', 'ak', 'pl', 'sid', 'hr', 'ht', 'hu', 'hmn', 'ho', 'gag', 'buc', 'ha', 'bug', 'gaa', 'mg', 'fur', 'bem', 'ibb', 'mi', 'mh', 'war', 'mt', 'uli', 'ms', 'sr', 'haw', 'sq', 'aa', 've', 'af', 'gwi', 'is', 'it', 'sv', 'ii', 'sas', 'ik', 'tpi', 'zu', 'ay', 'kha', 'az', 'tzm', 'id', 'ig', 'pap', 'nl', 'pau', 'nn', 'no', 'na', 'nb', 'nd', 'umb', 'ng', 'ny', 'nap', 'gcr', 'nyn', 'hop', 'lis', 'so', 'nr', 'pam', 'nv', 'kv', 'kab', 'fr', 'nym', 'kaj', 'rcf', 'yo', 'snk', 'kam', 'dgr', 'mad', 'fi', 'mak', 'niu', 'kg', 'pag', 'gsw', 'ss', 'kj', 'ki', 'min', 'sw', 'cpe', 'su', 'kl', 'sk', 'kr', 'kw', 'cch', 'ku', 'sl', 'sg', 'tiv', 'se' ], 'Lepc': ['lep'], 'Limb': ['lif'], 'Mlym': ['ml'], 'Mong': [ 'mnc', 'mn' ], 'Mymr': [ 'my', 'kht', 'shn', 'mnw' ], 'Nkoo': [ 'nqo', 'emk' ], 'Orya': ['or'], 'Sinh': ['si'], 'Tale': ['tdd'], 'Talu': ['khb'], 'Taml': [ 'bfq', 'ta' ], 'Telu': [ 'te', 'gon', 'lmn' ], 'Tfng': ['tzm'], 'Thaa': ['dv'], 'Thai': [ 'tts', 'lwl', 'th', 'kdt', 'lcp' ], 'Tibt': [ 'bo', 'dz' ], 'Yiii': ['ii'], 'und': ['sat'] }; /* ~!@# END #@!~ */
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Functions to list locale-specific font list and generic name. * Generic name used for a font family would be locale dependant. For example, * for 'zh'(Chinese) users, the name for Serif family would be in Chinese. * Further documentation at: http://go/genericfontnames. */ goog.provide('goog.locale.genericFontNames'); /** * This object maps (resourceName, localeName) to a resourceObj. * @type {Object} * @private */ goog.locale.genericFontNames.data_ = {}; /** * Normalizes the given locale id to standard form. eg: zh_Hant_TW. * Many a times, input locale would be like: zh-tw, zh-hant-tw. * @param {string} locale The locale id to be normalized. * @return {string} Normalized locale id. * @private */ goog.locale.genericFontNames.normalize_ = function(locale) { locale = locale.replace(/-/g, '_'); locale = locale.replace(/_[a-z]{2}$/, function(str) { return str.toUpperCase(); }); locale = locale.replace(/[a-z]{4}/, function(str) { return str.substring(0, 1).toUpperCase() + str.substring(1); }); return locale; }; /** * Gets the list of fonts and their generic names for the given locale. * @param {string} locale The locale for which font lists and font family names * to be produced. The expected locale id is as described in * http://wiki/Main/IIISynonyms in all lowercase for easy matching. * Smallest possible id is expected. * Examples: 'zh', 'zh-tw', 'iw' instead of 'zh-CN', 'zh-Hant-TW', 'he'. * @return {Array.<Object>} List of objects with generic name as 'caption' and * corresponding font name lists as 'value' property. */ goog.locale.genericFontNames.getList = function(locale) { locale = goog.locale.genericFontNames.normalize_(locale); if (locale in goog.locale.genericFontNames.data_) { return goog.locale.genericFontNames.data_[locale]; } return []; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // All Rights Reserved. /** * @fileoverview Provides utility routines for copying modified * {@code CSSRule} objects from the parent document into iframes so that any * content in the iframe will be styled as if it was inline in the parent * document. * * <p> * For example, you might have this CSS rule: * * #content .highlighted { background-color: yellow; } * * And this DOM structure: * * <div id="content"> * <iframe /> * </div> * * Then inside the iframe you have: * * <body> * <div class="highlighted"> * </body> * * If you copied the CSS rule directly into the iframe, it wouldn't match the * .highlighted div. So we rewrite the original stylesheets based on the * context where the iframe is going to be inserted. In this case the CSS * selector would be rewritten to: * * body .highlighted { background-color: yellow; } * </p> * */ goog.provide('goog.cssom.iframe.style'); goog.require('goog.cssom'); goog.require('goog.dom'); goog.require('goog.dom.NodeType'); goog.require('goog.dom.classes'); goog.require('goog.string'); goog.require('goog.style'); goog.require('goog.userAgent'); /** * Regexp that matches "a", "a:link", "a:visited", etc. * @type {RegExp} * @private */ goog.cssom.iframe.style.selectorPartAnchorRegex_ = /a(:(link|visited|active|hover))?/; /** * Delimiter between selectors (h1, h2) * @type {string} * @private */ goog.cssom.iframe.style.SELECTOR_DELIMITER_ = ','; /** * Delimiter between selector parts (.main h1) * @type {string} * @private */ goog.cssom.iframe.style.SELECTOR_PART_DELIMITER_ = ' '; /** * Delimiter marking the start of a css rules section ( h1 { ) * @type {string} * @private */ goog.cssom.iframe.style.DECLARATION_START_DELIMITER_ = '{'; /** * Delimiter marking the end of a css rules section ( } ) * @type {string} * @private */ goog.cssom.iframe.style.DECLARATION_END_DELIMITER_ = '}\n'; /** * Class representing a CSS rule set. A rule set is something like this: * h1, h2 { font-family: Arial; color: red; } * @constructor * @private */ goog.cssom.iframe.style.CssRuleSet_ = function() { /** * Text of the declarations inside the rule set. * For example: 'font-family: Arial; color: red;' * @type {string} */ this.declarationText = ''; /** * Array of CssSelector objects, one for each selector. * Example: [h1, h2] * @type {Array.<goog.cssom.iframe.style.CssSelector_>} */ this.selectors = []; }; /** * Initializes the rule set from a {@code CSSRule}. * * @param {CSSRule} cssRule The {@code CSSRule} to initialize from. * @return {boolean} True if initialization succeeded. We only support * {@code CSSStyleRule} and {@code CSSFontFaceRule} objects. */ goog.cssom.iframe.style.CssRuleSet_.prototype.initializeFromCssRule = function(cssRule) { var ruleStyle = cssRule.style; // Cache object for performance. if (!ruleStyle) { return false; } var selector; var declarations; if (ruleStyle && (selector = cssRule.selectorText) && (declarations = ruleStyle.cssText)) { // IE get confused about cssText context if a stylesheet uses the // mid-pass hack, and it ends up with an open comment (/*) but no // closing comment. This will effectively comment out large parts // of generated stylesheets later. This errs on the safe side by // always tacking on an empty comment to force comments to be closed // We used to check for a troublesome open comment using a regular // expression, but it's faster not to check and always do this. if (goog.userAgent.IE) { declarations += '/* */'; } } else if (cssRule.cssText) { var cssSelectorMatch = /([^\{]+)\{/; var endTagMatch = /\}[^\}]*$/g; // cssRule.cssText contains both selector and declarations: // parse them out. selector = cssSelectorMatch.exec(cssRule.cssText)[1]; // Remove selector, {, and trailing }. declarations = cssRule.cssText.replace(cssSelectorMatch, '').replace( endTagMatch, ''); } if (selector) { this.setSelectorsFromString(selector); this.declarationText = declarations; return true; } return false; }; /** * Parses a selectors string (which may contain multiple comma-delimited * selectors) and loads the results into this.selectors. * @param {string} selectorsString String containing selectors. */ goog.cssom.iframe.style.CssRuleSet_.prototype.setSelectorsFromString = function(selectorsString) { this.selectors = []; var selectors = selectorsString.split(/,\s*/gm); for (var i = 0; i < selectors.length; i++) { var selector = selectors[i]; if (selector.length > 0) { this.selectors.push(new goog.cssom.iframe.style.CssSelector_(selector)); } } }; /** * Make a copy of this ruleset. * @return {goog.cssom.iframe.style.CssRuleSet_} A new CssRuleSet containing * the same data as this one. */ goog.cssom.iframe.style.CssRuleSet_.prototype.clone = function() { var newRuleSet = new goog.cssom.iframe.style.CssRuleSet_(); newRuleSet.selectors = this.selectors.concat(); newRuleSet.declarationText = this.declarationText; return newRuleSet; }; /** * Set the declaration text with properties from a given object. * @param {Object} sourceObject Object whose properties and values should * be used to generate the declaration text. * @param {boolean=} opt_important Whether !important should be added to each * declaration. */ goog.cssom.iframe.style.CssRuleSet_.prototype.setDeclarationTextFromObject = function(sourceObject, opt_important) { var stringParts = []; // TODO(user): for ... in is costly in IE6 (extra garbage collection). for (var prop in sourceObject) { var value = sourceObject[prop]; if (value) { stringParts.push(prop, ':', value, (opt_important ? ' !important' : ''), ';'); } } this.declarationText = stringParts.join(''); }; /** * Serializes this CssRuleSet_ into an array as a series of strings. * The array can then be join()-ed to get a string representation * of this ruleset. * @param {Array.<string>} array The array to which to append strings. */ goog.cssom.iframe.style.CssRuleSet_.prototype.writeToArray = function(array) { var selectorCount = this.selectors.length; var matchesAnchorTag = false; for (var i = 0; i < selectorCount; i++) { var selectorParts = this.selectors[i].parts; var partCount = selectorParts.length; for (var j = 0; j < partCount; j++) { array.push(selectorParts[j].inputString_, goog.cssom.iframe.style.SELECTOR_PART_DELIMITER_); } if (i < (selectorCount - 1)) { array.push(goog.cssom.iframe.style.SELECTOR_DELIMITER_); } if (goog.userAgent.GECKO && !goog.userAgent.isVersion('1.9a')) { // In Gecko pre-1.9 (Firefox 2 and lower) we need to add !important // to rulesets that match "A" tags, otherwise Gecko's built-in // stylesheet will take precedence when designMode is on. matchesAnchorTag = matchesAnchorTag || goog.cssom.iframe.style.selectorPartAnchorRegex_.test( selectorParts[partCount - 1].inputString_); } } var declarationText = this.declarationText; if (matchesAnchorTag) { declarationText = goog.cssom.iframe.style.makeColorRuleImportant_( declarationText); } array.push(goog.cssom.iframe.style.DECLARATION_START_DELIMITER_, declarationText, goog.cssom.iframe.style.DECLARATION_END_DELIMITER_); }; /** * Regexp that matches "color: value;". * @type {RegExp} * @private */ goog.cssom.iframe.style.colorImportantReplaceRegex_ = /(^|;|{)\s*color:([^;]+);/g; /** * Adds !important to a css color: rule * @param {string} cssText Text of the CSS rule(s) to modify. * @return {string} Text with !important added to the color: rule if found. * @private */ goog.cssom.iframe.style.makeColorRuleImportant_ = function(cssText) { // Replace to insert a "! important" string. return cssText.replace(goog.cssom.iframe.style.colorImportantReplaceRegex_, '$1 color: $2 ! important; '); }; /** * Represents a single CSS selector, as described in * http://www.w3.org/TR/REC-CSS2/selector.html * Currently UNSUPPORTED are the following selector features: * <ul> * <li>pseudo-classes (:hover) * <li>child selectors (div > h1) * <li>adjacent sibling selectors (div + h1) * <li>attribute selectors (input[type=submit]) * </ul> * @param {string=} opt_selectorString String containing selectors to parse. * @constructor * @private */ goog.cssom.iframe.style.CssSelector_ = function(opt_selectorString) { /** * Array of CssSelectorPart objects representing the parts of this selector * Example: for the selector 'body h1' the parts would be [body, h1]. * @type {Array.<goog.cssom.iframe.style.CssSelectorPart_>} * @private */ this.parts_ = []; /** * Object to track ancestry matches to speed up repeatedly testing this * CssSelector against the same NodeAncestry object. * @type {Object} * @private */ this.ancestryMatchCache_ = {}; if (opt_selectorString) { this.setPartsFromString_(opt_selectorString); } }; /** * Parses a selector string into individual parts. * @param {string} selectorString A string containing a CSS selector. * @private */ goog.cssom.iframe.style.CssSelector_.prototype.setPartsFromString_ = function(selectorString) { var parts = []; var selectorPartStrings = selectorString.split(/\s+/gm); for (var i = 0; i < selectorPartStrings.length; i++) { if (!selectorPartStrings[i]) { continue; // Skip empty strings. } var part = new goog.cssom.iframe.style.CssSelectorPart_( selectorPartStrings[i]); parts.push(part); } this.parts = parts; }; /** * Tests to see what part of a DOM element hierarchy would be matched by * this selector, and returns the indexes of the matching element and matching * selector part. * <p> * For example, given this hierarchy: * document > html > body > div.content > div.sidebar > p * and this CSS selector: * body div.sidebar h1 * This would return {elementIndex: 4, selectorPartIndex: 1}, * indicating that the element at index 4 matched * the css selector at index 1. * </p> * @param {goog.cssom.iframe.style.NodeAncestry_} elementAncestry Object * representing an element and its ancestors. * @return {Object} Object with the properties elementIndex and * selectorPartIndex, or null if there was no match. */ goog.cssom.iframe.style.CssSelector_.prototype.matchElementAncestry = function(elementAncestry) { var ancestryUid = elementAncestry.uid; if (this.ancestryMatchCache_[ancestryUid]) { return this.ancestryMatchCache_[ancestryUid]; } // Walk through the selector parts and see how far down the element hierarchy // we can go while matching the selector parts. var elementIndex = 0; var match = null; var selectorPart = null; var lastSelectorPart = null; var ancestorNodes = elementAncestry.nodes; var ancestorNodeCount = ancestorNodes.length; for (var i = 0; i <= this.parts.length; i++) { selectorPart = this.parts[i]; while (elementIndex < ancestorNodeCount) { var currentElementInfo = ancestorNodes[elementIndex]; if (selectorPart && selectorPart.testElement(currentElementInfo)) { match = { elementIndex: elementIndex, selectorPartIndex: i }; elementIndex++; break; } else if (lastSelectorPart && lastSelectorPart.testElement(currentElementInfo)) { match = { elementIndex: elementIndex, selectorPartIndex: i - 1 }; } elementIndex++; } lastSelectorPart = selectorPart; } this.ancestryMatchCache_[ancestryUid] = match; return match; }; /** * Represents one part of a CSS Selector. For example in the selector * 'body #foo .bar', body, #foo, and .bar would be considered selector parts. * In the official CSS spec these are called "simple selectors". * @param {string} selectorPartString A string containing the selector part * in css format. * @constructor * @private */ goog.cssom.iframe.style.CssSelectorPart_ = function(selectorPartString) { // Only one CssSelectorPart instance should exist for a given string. var cacheEntry = goog.cssom.iframe.style.CssSelectorPart_.instances_[ selectorPartString]; if (cacheEntry) { return cacheEntry; } // Optimization to avoid the more-expensive lookahead. var identifiers; if (selectorPartString.match(/[#\.]/)) { // Lookahead regexp, won't work on IE 5.0. identifiers = selectorPartString.split(/(?=[#\.])/); } else { identifiers = [selectorPartString]; } var properties = {}; for (var i = 0; i < identifiers.length; i++) { var identifier = identifiers[i]; if (identifier.charAt(0) == '.') { properties.className = identifier.substring(1, identifier.length); } else if (identifier.charAt(0) == '#') { properties.id = identifier.substring(1, identifier.length); } else { properties.tagName = identifier.toUpperCase(); } } this.inputString_ = selectorPartString; this.matchProperties_ = properties; this.testedElements_ = {}; goog.cssom.iframe.style.CssSelectorPart_.instances_[selectorPartString] = this; }; /** * Cache of existing CssSelectorPart_ instances. * @type {Object} * @private */ goog.cssom.iframe.style.CssSelectorPart_.instances_ = {}; /** * Test whether an element matches this selector part, considered in isolation. * @param {Object} elementInfo Element properties to test. * @return {boolean} Whether the element matched. */ goog.cssom.iframe.style.CssSelectorPart_.prototype.testElement = function(elementInfo) { var elementUid = elementInfo.uid; var cachedMatch = this.testedElements_[elementUid]; if (typeof cachedMatch != 'undefined') { return cachedMatch; } var matchProperties = this.matchProperties_; var testTag = matchProperties.tagName; var testClass = matchProperties.className; var testId = matchProperties.id; var matched = true; if (testTag && testTag != '*' && testTag != elementInfo.nodeName) { matched = false; } else if (testId && testId != elementInfo.id) { matched = false; } else if (testClass && !elementInfo.classNames[testClass]) { matched = false; } this.testedElements_[elementUid] = matched; return matched; }; /** * Represents an element and all its parent/ancestor nodes. * This class exists as an optimization so we run tests on an element * hierarchy multiple times without walking the dom each time. * @param {Element} el The DOM element whose ancestry should be stored. * @constructor * @private */ goog.cssom.iframe.style.NodeAncestry_ = function(el) { var node = el; var nodeUid = goog.getUid(node); // Return an existing object from the cache if one exits for this node. var ancestry = goog.cssom.iframe.style.NodeAncestry_.instances_[nodeUid]; if (ancestry) { return ancestry; } var nodes = []; do { var nodeInfo = { id: node.id, nodeName: node.nodeName }; nodeInfo.uid = goog.getUid(nodeInfo); var className = node.className; var classNamesLookup = {}; if (className) { var classNames = goog.dom.classes.get(node); for (var i = 0; i < classNames.length; i++) { classNamesLookup[classNames[i]] = 1; } } nodeInfo.classNames = classNamesLookup; nodes.unshift(nodeInfo); } while (node = node.parentNode); /** * Array of nodes in order of hierarchy from the top of the document * to the node passed to the constructor * @type {Array.<Node>} */ this.nodes = nodes; this.uid = goog.getUid(this); goog.cssom.iframe.style.NodeAncestry_.instances_[nodeUid] = this; }; /** * Object for caching existing NodeAncestry instances. * @private */ goog.cssom.iframe.style.NodeAncestry_.instances_ = {}; /** * Throw away all cached dom information. Call this if you've modified * the structure or class/id attributes of your document and you want * to recalculate the currently applied CSS rules. */ goog.cssom.iframe.style.resetDomCache = function() { goog.cssom.iframe.style.NodeAncestry_.instances_ = {}; }; /** * Inspects a document and returns all active rule sets * @param {Document} doc The document from which to read CSS rules. * @return {Array.<goog.cssom.iframe.style.CssRuleSet_>} An array of CssRuleSet * objects representing all the active rule sets in the document. * @private */ goog.cssom.iframe.style.getRuleSetsFromDocument_ = function(doc) { var ruleSets = []; var styleSheets = goog.cssom.getAllCssStyleSheets(doc.styleSheets); for (var i = 0, styleSheet; styleSheet = styleSheets[i]; i++) { var domRuleSets = goog.cssom.getCssRulesFromStyleSheet(styleSheet); if (domRuleSets && domRuleSets.length) { for (var j = 0, n = domRuleSets.length; j < n; j++) { var ruleSet = new goog.cssom.iframe.style.CssRuleSet_(); if (ruleSet.initializeFromCssRule(domRuleSets[j])) { ruleSets.push(ruleSet); } } } } return ruleSets; }; /** * Static object to cache rulesets read from documents. Inspecting all * active css rules is an expensive operation, so its best to only do * it once and then cache the results. * @type {Object} * @private */ goog.cssom.iframe.style.ruleSetCache_ = {}; /** * Cache of ruleset objects keyed by document unique ID. * @type {Object} * @private */ goog.cssom.iframe.style.ruleSetCache_.ruleSetCache_ = {}; /** * Loads ruleset definitions from a document. If the cache already * has rulesets for this document the cached version will be replaced. * @param {Document} doc The document from which to load rulesets. */ goog.cssom.iframe.style.ruleSetCache_.loadRuleSetsForDocument = function(doc) { var docUid = goog.getUid(doc); goog.cssom.iframe.style.ruleSetCache_.ruleSetCache_[docUid] = goog.cssom.iframe.style.getRuleSetsFromDocument_(doc); }; /** * Retrieves the array of css rulesets for this document. A cached * version will be used when possible. * @param {Document} doc The document for which to get rulesets. * @return {Array.<goog.cssom.iframe.style.CssRuleSet_>} An array of CssRuleSet * objects representing the css rule sets in the supplied document. */ goog.cssom.iframe.style.ruleSetCache_.getRuleSetsForDocument = function(doc) { var docUid = goog.getUid(doc); var cache = goog.cssom.iframe.style.ruleSetCache_.ruleSetCache_; if (!cache[docUid]) { goog.cssom.iframe.style.ruleSetCache_.loadRuleSetsForDocument(doc); } // Build a cloned copy of rulesets array, so if object in the returned array // get modified future calls will still return the original unmodified // versions. var ruleSets = cache[docUid]; var ruleSetsCopy = []; for (var i = 0; i < ruleSets.length; i++) { ruleSetsCopy.push(ruleSets[i].clone()); } return ruleSetsCopy; }; /** * Array of CSS properties that are inherited by child nodes, according to * the CSS 2.1 spec. Properties that may be set to relative values, such * as font-size, and line-height, are omitted. * @type {Array.<string>} * @private */ goog.cssom.iframe.style.inheritedProperties_ = [ 'color', 'visibility', 'quotes', 'list-style-type', 'list-style-image', 'list-style-position', 'list-style', 'page-break-inside', 'orphans', 'widows', 'font-family', 'font-style', 'font-variant', 'font-weight', 'text-indent', 'text-align', 'text-transform', 'white-space', 'caption-side', 'border-collapse', 'border-spacing', 'empty-cells', 'cursor' ]; /** * Array of CSS 2.1 properties that directly effect text nodes. * @type {Array.<string>} * @private */ goog.cssom.iframe.style.textProperties_ = [ 'font-family', 'font-size', 'font-weight', 'font-variant', 'font-style', 'color', 'text-align', 'text-decoration', 'text-indent', 'text-transform', 'letter-spacing', 'white-space', 'word-spacing' ]; /** * Reads the current css rules from element's document, and returns them * rewriting selectors so that any rules that formerly applied to element will * be applied to doc.body. This makes it possible to replace a block in a page * with an iframe and preserve the css styling of the contents. * * @param {Element} element The element for which context should be calculated. * @param {boolean=} opt_forceRuleSetCacheUpdate Flag to force the internal * cache of rulesets to refresh itself before we read the same. * @param {boolean=} opt_copyBackgroundContext Flag indicating that if the * {@code element} has a transparent background, background rules * from the nearest ancestor element(s) that have background-color * and/or background-image set should be copied. * @return {string} String containing all CSS rules present in the original * document, with modified selectors. * @see goog.cssom.iframe.style.getBackgroundContext. */ goog.cssom.iframe.style.getElementContext = function( element, opt_forceRuleSetCacheUpdate, opt_copyBackgroundContext) { var sourceDocument = element.ownerDocument; if (opt_forceRuleSetCacheUpdate) { goog.cssom.iframe.style.ruleSetCache_.loadRuleSetsForDocument( sourceDocument); } var ruleSets = goog.cssom.iframe.style.ruleSetCache_. getRuleSetsForDocument(sourceDocument); var elementAncestry = new goog.cssom.iframe.style.NodeAncestry_(element); var bodySelectorPart = new goog.cssom.iframe.style.CssSelectorPart_('body'); for (var i = 0; i < ruleSets.length; i++) { var ruleSet = ruleSets[i]; var selectors = ruleSet.selectors; // Cache selectors.length since we may be adding rules in the loop. var ruleCount = selectors.length; for (var j = 0; j < ruleCount; j++) { var selector = selectors[j]; // Test whether all or part of this selector would match // this element or one of its ancestors var match = selector.matchElementAncestry(elementAncestry); if (match) { var ruleIndex = match.selectorPartIndex; var selectorParts = selector.parts; var lastSelectorPartIndex = selectorParts.length - 1; var selectorCopy; if (match.elementIndex == elementAncestry.nodes.length - 1 || ruleIndex < lastSelectorPartIndex) { // Either the first part(s) of the selector matched this element, // or the first part(s) of the selector matched a parent element // and there are more parts of the selector that could target // children of this element. // So we inject a new selector, replacing the part that matched this // element with 'body' so it will continue to match. var selectorPartsCopy = selectorParts.concat(); selectorPartsCopy.splice(0, ruleIndex + 1, bodySelectorPart); selectorCopy = new goog.cssom.iframe.style.CssSelector_(); selectorCopy.parts = selectorPartsCopy; selectors.push(selectorCopy); } else if (ruleIndex > 0 && ruleIndex == lastSelectorPartIndex) { // The rule didn't match this element, but the entire rule did // match an ancestor element. In this case we want to copy // just the last part of the rule, to give it a chance to be applied // to additional matching elements inside this element. // Example DOM structure: body > div.funky > ul > li#editme // Example CSS selector: .funky ul // New CSS selector: body ul selectorCopy = new goog.cssom.iframe.style.CssSelector_(); selectorCopy.parts = [ bodySelectorPart, selectorParts[lastSelectorPartIndex] ]; selectors.push(selectorCopy); } } } } // Insert a new ruleset, setting the current inheritable styles of this // element as the defaults for everything under in the frame. var defaultPropertiesRuleSet = new goog.cssom.iframe.style.CssRuleSet_(); var declarationParts = []; var computedStyle = goog.cssom.iframe.style.getComputedStyleObject_(element); // Copy inheritable styles so they are applied to everything under HTML. var htmlSelector = new goog.cssom.iframe.style.CssSelector_(); htmlSelector.parts = [new goog.cssom.iframe.style.CssSelectorPart_('html')]; defaultPropertiesRuleSet.selectors = [htmlSelector]; var defaultProperties = {}; for (var i = 0, prop; prop = goog.cssom.iframe.style.inheritedProperties_[i]; i++) { defaultProperties[prop] = computedStyle[goog.string.toCamelCase(prop)]; } defaultPropertiesRuleSet.setDeclarationTextFromObject(defaultProperties); ruleSets.push(defaultPropertiesRuleSet); var bodyRuleSet = new goog.cssom.iframe.style.CssRuleSet_(); var bodySelector = new goog.cssom.iframe.style.CssSelector_(); bodySelector.parts = [new goog.cssom.iframe.style.CssSelectorPart_('body')]; // Core set of sane property values for BODY, to prevent copied // styles from completely breaking the display. var bodyProperties = { position: 'relative', top: '0', left: '0', right: 'auto', // Override any existing right value so 'left' works. display: 'block', visibility: 'visible' }; // Text formatting property values, to keep text nodes directly under BODY // looking right. for (i = 0; prop = goog.cssom.iframe.style.textProperties_[i]; i++) { bodyProperties[prop] = computedStyle[goog.string.toCamelCase(prop)]; } if (opt_copyBackgroundContext && goog.cssom.iframe.style.isTransparentValue_( computedStyle['backgroundColor'])) { // opt_useAncestorBackgroundRules means that, if the original element // has a transparent backgorund, background properties rules should be // added to explicitly make the body have the same background appearance // as in the original element, even if its positioned somewhere else // in the DOM. var bgProperties = goog.cssom.iframe.style.getBackgroundContext(element); bodyProperties['background-color'] = bgProperties['backgroundColor']; var elementBgImage = computedStyle['backgroundImage']; if (!elementBgImage || elementBgImage == 'none') { bodyProperties['background-image'] = bgProperties['backgroundImage']; bodyProperties['background-repeat'] = bgProperties['backgroundRepeat']; bodyProperties['background-position'] = bgProperties['backgroundPosition']; } } bodyRuleSet.setDeclarationTextFromObject(bodyProperties, true); bodyRuleSet.selectors = [bodySelector]; ruleSets.push(bodyRuleSet); // Write outputTextParts to doc. var ruleSetStrings = []; ruleCount = ruleSets.length; for (i = 0; i < ruleCount; i++) { ruleSets[i].writeToArray(ruleSetStrings); } return ruleSetStrings.join(''); }; /** * Tests whether a value is equivalent to 'transparent'. * @param {string} colorValue The value to test. * @return {boolean} Whether the value is transparent. * @private */ goog.cssom.iframe.style.isTransparentValue_ = function(colorValue) { return colorValue == 'transparent' || colorValue == 'rgba(0, 0, 0, 0)'; }; /** * Returns an object containing the set of computedStyle/currentStyle * values for the given element. Note that this should be used with * caution as it ignores the fact that currentStyle and computedStyle * are not the same for certain properties. * * @param {Element} element The element whose computed style to return. * @return {Object} Object containing style properties and values. * @private */ goog.cssom.iframe.style.getComputedStyleObject_ = function(element) { // Return an object containing the element's computedStyle/currentStyle. // The resulting object can be re-used to read multiple properties, which // is faster than calling goog.style.getComputedStyle every time. return element.currentStyle || goog.dom.getOwnerDocument(element).defaultView.getComputedStyle( element, '') || {}; }; /** * RegExp that splits a value like "10px" or "-1em" into parts. * @private * @type {RegExp} */ goog.cssom.iframe.style.valueWithUnitsRegEx_ = /^(-?)([0-9]+)([a-z]*|%)/; /** * Given an object containing a set of styles, returns a two-element array * containing the values of background-position-x and background-position-y. * @param {Object} styleObject Object from which to read style properties. * @return {Array.<string>} The background-position values in the order [x, y]. * @private */ goog.cssom.iframe.style.getBackgroundXYValues_ = function(styleObject) { // Gecko only has backgroundPosition, containing both values. // IE has only backgroundPositionX/backgroundPositionY. // WebKit has both. if (styleObject['backgroundPositionY']) { return [styleObject['backgroundPositionX'], styleObject['backgroundPositionY']]; } else { return (styleObject['backgroundPosition'] || '0 0').split(' '); } }; /** * Generates a set of CSS properties that can be used to make another * element's background look like the background of a given element. * This is useful when you want to copy the CSS context of an element, * but the element's background is transparent. In the original context * you would see the ancestor's backround color/image showing through, * but in the new context there might be a something different underneath. * Note that this assumes the element you're copying context from has a * fairly standard positioning/layout - it assumes that when the element * has a transparent background what you're going to see through it is its * ancestors. * @param {Element} element The element from which to copy background styles. * @return {Object} Object containing background* properties. */ goog.cssom.iframe.style.getBackgroundContext = function(element) { var propertyValues = { 'backgroundImage': 'none' }; var ancestor = element; var currentIframeWindow; // Walk up the DOM tree to find the ancestor nodes whose backgrounds // may be visible underneath this element. Background-image and // background-color don't have to come from the same node, but as soon // an element with background-color is found there's no need to continue // because backgrounds farther up the chain won't be visible. // (This implementation is not sophisticated enough to handle opacity, // or multple layered partially-transparent background images.) while ((ancestor = ancestor.parentNode) && ancestor.nodeType == goog.dom.NodeType.ELEMENT) { var computedStyle = goog.cssom.iframe.style.getComputedStyleObject_( /** @type {Element} */ (ancestor)); // Copy background color if a non-transparent value is found. var backgroundColorValue = computedStyle['backgroundColor']; if (!goog.cssom.iframe.style.isTransparentValue_(backgroundColorValue)) { propertyValues['backgroundColor'] = backgroundColorValue; } // If a background image value is found, copy background-image, // background-repeat, and background-position. if (computedStyle['backgroundImage'] && computedStyle['backgroundImage'] != 'none') { propertyValues['backgroundImage'] = computedStyle['backgroundImage']; propertyValues['backgroundRepeat'] = computedStyle['backgroundRepeat']; // Calculate the offset between the original element and the element // providing the background image, so the background position can be // adjusted. var relativePosition; if (currentIframeWindow) { relativePosition = goog.style.getFramedPageOffset( element, currentIframeWindow); var frameElement = currentIframeWindow.frameElement; var iframeRelativePosition = goog.style.getRelativePosition( /** @type {Element} */ (frameElement), /** @type {Element} */ (ancestor)); var iframeBorders = goog.style.getBorderBox(frameElement); relativePosition.x += iframeRelativePosition.x + iframeBorders.left; relativePosition.y += iframeRelativePosition.y + iframeBorders.top; } else { relativePosition = goog.style.getRelativePosition( element, /** @type {Element} */ (ancestor)); } var backgroundXYValues = goog.cssom.iframe.style.getBackgroundXYValues_( computedStyle); // Parse background-repeat-* values in the form "10px", and adjust them. for (var i = 0; i < 2; i++) { var positionValue = backgroundXYValues[i]; var coordinate = i == 0 ? 'X' : 'Y'; var positionProperty = 'backgroundPosition' + coordinate; // relative position to its ancestor. var positionValueParts = goog.cssom.iframe.style.valueWithUnitsRegEx_.exec(positionValue); if (positionValueParts) { var value = parseInt( positionValueParts[1] + positionValueParts[2], 10); var units = positionValueParts[3]; // This only attempts to handle pixel values for now (plus // '0anything', which is equivalent to 0px). // TODO(user) Convert non-pixel values to pixels when possible. if (value == 0 || units == 'px') { value -= (coordinate == 'X' ? relativePosition.x : relativePosition.y); } positionValue = value + units; } propertyValues[positionProperty] = positionValue; } propertyValues['backgroundPosition'] = propertyValues['backgroundPositionX'] + ' ' + propertyValues['backgroundPositionY']; } if (propertyValues['backgroundColor']) { break; } if (ancestor.tagName == goog.dom.TagName.HTML) { try { currentIframeWindow = goog.dom.getWindow( /** @type {Document} */ (ancestor.parentNode)); // This could theoretically throw a security exception if the parent // iframe is in a different domain. ancestor = currentIframeWindow.frameElement; if (!ancestor) { // Loop has reached the top level window. break; } } catch (e) { // We don't have permission to go up to the parent window, stop here. break; } } } return propertyValues; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview CSS Object Model helper functions. * References: * - W3C: http://dev.w3.org/csswg/cssom/ * - MSDN: http://msdn.microsoft.com/en-us/library/ms531209(VS.85).aspx. * @supported in FF3, IE6, IE7, Safari 3.1.2, Chrome * TODO(user): Fix in Opera. * TODO(user): Consider hacking page, media, etc.. to work. * This would be pretty challenging. IE returns the text for any rule * regardless of whether or not the media is correct or not. Firefox at * least supports CSSRule.type to figure out if it's a media type and then * we could do something interesting, but IE offers no way for us to tell. */ goog.provide('goog.cssom'); goog.provide('goog.cssom.CssRuleType'); goog.require('goog.array'); goog.require('goog.dom'); /** * Enumeration of {@code CSSRule} types. * @enum {number} */ goog.cssom.CssRuleType = { STYLE: 1, IMPORT: 3, MEDIA: 4, FONT_FACE: 5, PAGE: 6, NAMESPACE: 7 }; /** * Recursively gets all CSS as text, optionally starting from a given * CSSStyleSheet. * @param {CSSStyleSheet=} opt_styleSheet The CSSStyleSheet. * @return {string} css text. */ goog.cssom.getAllCssText = function(opt_styleSheet) { var styleSheet = opt_styleSheet || document.styleSheets; return /** @type {string} */ (goog.cssom.getAllCss_(styleSheet, true)); }; /** * Recursively gets all CSSStyleRules, optionally starting from a given * CSSStyleSheet. * Note that this excludes any CSSImportRules, CSSMediaRules, etc.. * @param {CSSStyleSheet=} opt_styleSheet The CSSStyleSheet. * @return {Array.<CSSStyleRule>} A list of CSSStyleRules. */ goog.cssom.getAllCssStyleRules = function(opt_styleSheet) { var styleSheet = opt_styleSheet || document.styleSheets; return /** @type {Array.<CSSStyleRule>} */ ( goog.cssom.getAllCss_(styleSheet, false)); }; /** * Returns the CSSRules from a styleSheet. * Worth noting here is that IE and FF differ in terms of what they will return. * Firefox will return styleSheet.cssRules, which includes ImportRules and * anything which implements the CSSRules interface. IE returns simply a list of * CSSRules. * @param {CSSStyleSheet} styleSheet The CSSStyleSheet. * @throws {Error} If we cannot access the rules on a stylesheet object - this * can happen if a stylesheet object's rules are accessed before the rules * have been downloaded and parsed and are "ready". * @return {CSSRuleList} An array of CSSRules or null. */ goog.cssom.getCssRulesFromStyleSheet = function(styleSheet) { var cssRuleList = null; try { // IE is .rules, W3c is cssRules. cssRuleList = styleSheet.rules || styleSheet.cssRules; } catch (e) { // This can happen if we try to access the CSSOM before it's "ready". if (e.code == 15) { // Firefox throws an NS_ERROR_DOM_INVALID_ACCESS_ERR error if a stylesheet // is read before it has been fully parsed. Let the caller know which // stylesheet failed. e.styleSheet = styleSheet; throw e; } } return cssRuleList; }; /** * Gets all CSSStyleSheet objects starting from some CSSStyleSheet. Note that we * want to return the sheets in the order of the cascade, therefore if we * encounter an import, we will splice that CSSStyleSheet object in front of * the CSSStyleSheet that contains it in the returned array of CSSStyleSheets. * @param {CSSStyleSheet=} opt_styleSheet A CSSStyleSheet. * @param {boolean=} opt_includeDisabled If true, includes disabled stylesheets, * defaults to false. * @return {Array.<CSSStyleSheet>} A list of CSSStyleSheet objects. */ goog.cssom.getAllCssStyleSheets = function(opt_styleSheet, opt_includeDisabled) { var styleSheetsOutput = []; var styleSheet = opt_styleSheet || document.styleSheets; var includeDisabled = goog.isDef(opt_includeDisabled) ? opt_includeDisabled : false; // Imports need to go first. if (styleSheet.imports && styleSheet.imports.length) { for (var i = 0, n = styleSheet.imports.length; i < n; i++) { goog.array.extend(styleSheetsOutput, goog.cssom.getAllCssStyleSheets(styleSheet.imports[i])); } } else if (styleSheet.length) { // In case we get a StyleSheetList object. // http://dev.w3.org/csswg/cssom/#the-stylesheetlist for (var i = 0, n = styleSheet.length; i < n; i++) { goog.array.extend(styleSheetsOutput, goog.cssom.getAllCssStyleSheets(styleSheet[i])); } } else { // We need to walk through rules in browsers which implement .cssRules // to see if there are styleSheets buried in there. // If we have a CSSStyleSheet within CssRules. var cssRuleList = goog.cssom.getCssRulesFromStyleSheet(styleSheet); if (cssRuleList && cssRuleList.length) { // Chrome does not evaluate cssRuleList[i] to undefined when i >=n; // so we use a (i < n) check instead of cssRuleList[i] in the loop below // and in other places where we iterate over a rules list. // See issue # 5917 in Chromium. for (var i = 0, n = cssRuleList.length, cssRule; i < n; i++) { cssRule = cssRuleList[i]; // There are more stylesheets to get on this object.. if (cssRule.styleSheet) { goog.array.extend(styleSheetsOutput, goog.cssom.getAllCssStyleSheets(cssRule.styleSheet)); } } } } // This is a CSSStyleSheet. (IE uses .rules, W3c and Opera cssRules.) if ((styleSheet.type || styleSheet.rules || styleSheet.cssRules) && (!styleSheet.disabled || includeDisabled)) { styleSheetsOutput.push(styleSheet); } return styleSheetsOutput; }; /** * Gets the cssText from a CSSRule object cross-browserly. * @param {CSSRule} cssRule A CSSRule. * @return {string} cssText The text for the rule, including the selector. */ goog.cssom.getCssTextFromCssRule = function(cssRule) { var cssText = ''; if (cssRule.cssText) { // W3C. cssText = cssRule.cssText; } else if (cssRule.style && cssRule.style.cssText && cssRule.selectorText) { // IE: The spacing here is intended to make the result consistent with // FF and Webkit. // We also remove the special properties that we may have added in // getAllCssStyleRules since IE includes those in the cssText. var styleCssText = cssRule.style.cssText. replace(/\s*-closure-parent-stylesheet:\s*\[object\];?\s*/gi, ''). replace(/\s*-closure-rule-index:\s*[\d]+;?\s*/gi, ''); var thisCssText = cssRule.selectorText + ' { ' + styleCssText + ' }'; cssText = thisCssText; } return cssText; }; /** * Get the index of the CSSRule in it's CSSStyleSheet. * @param {CSSRule} cssRule A CSSRule. * @param {CSSStyleSheet=} opt_parentStyleSheet A reference to the stylesheet * object this cssRule belongs to. * @throws {Error} When we cannot get the parentStyleSheet. * @return {number} The index of the CSSRule, or -1. */ goog.cssom.getCssRuleIndexInParentStyleSheet = function(cssRule, opt_parentStyleSheet) { // Look for our special style.ruleIndex property from getAllCss. if (cssRule.style && cssRule.style['-closure-rule-index']) { return cssRule.style['-closure-rule-index']; } var parentStyleSheet = opt_parentStyleSheet || goog.cssom.getParentStyleSheet(cssRule); if (!parentStyleSheet) { // We could call getAllCssStyleRules() here to get our special indexes on // the style object, but that seems like it could be wasteful. throw Error('Cannot find a parentStyleSheet.'); } var cssRuleList = goog.cssom.getCssRulesFromStyleSheet(parentStyleSheet); if (cssRuleList && cssRuleList.length) { for (var i = 0, n = cssRuleList.length, thisCssRule; i < n; i++) { thisCssRule = cssRuleList[i]; if (thisCssRule == cssRule) { return i; } } } return -1; }; /** * We do some trickery in getAllCssStyleRules that hacks this in for IE. * If the cssRule object isn't coming from a result of that function call, this * method will return undefined in IE. * @param {CSSRule} cssRule The CSSRule. * @return {CSSStyleSheet} A styleSheet object. */ goog.cssom.getParentStyleSheet = function(cssRule) { return cssRule.parentStyleSheet || cssRule.style['-closure-parent-stylesheet']; }; /** * Replace a cssRule with some cssText for a new rule. * If the cssRule object is not one of objects returned by * getAllCssStyleRules, then you'll need to provide both the styleSheet and * possibly the index, since we can't infer them from the standard cssRule * object in IE. We do some trickery in getAllCssStyleRules to hack this in. * @param {CSSRule} cssRule A CSSRule. * @param {string} cssText The text for the new CSSRule. * @param {CSSStyleSheet=} opt_parentStyleSheet A reference to the stylesheet * object this cssRule belongs to. * @param {number=} opt_index The index of the cssRule in its parentStylesheet. * @throws {Error} If we cannot find a parentStyleSheet. * @throws {Error} If we cannot find a css rule index. */ goog.cssom.replaceCssRule = function(cssRule, cssText, opt_parentStyleSheet, opt_index) { var parentStyleSheet = opt_parentStyleSheet || goog.cssom.getParentStyleSheet(cssRule); if (parentStyleSheet) { var index = opt_index >= 0 ? opt_index : goog.cssom.getCssRuleIndexInParentStyleSheet(cssRule, parentStyleSheet); if (index >= 0) { goog.cssom.removeCssRule(parentStyleSheet, index); goog.cssom.addCssRule(parentStyleSheet, cssText, index); } else { throw Error('Cannot proceed without the index of the cssRule.'); } } else { throw Error('Cannot proceed without the parentStyleSheet.'); } }; /** * Cross browser function to add a CSSRule into a CSSStyleSheet, optionally * at a given index. * @param {CSSStyleSheet} cssStyleSheet The CSSRule's parentStyleSheet. * @param {string} cssText The text for the new CSSRule. * @param {number=} opt_index The index of the cssRule in its parentStylesheet. * @throws {Error} If the css rule text appears to be ill-formatted. * TODO(bowdidge): Inserting at index 0 fails on Firefox 2 and 3 with an * exception warning "Node cannot be inserted at the specified point in * the hierarchy." */ goog.cssom.addCssRule = function(cssStyleSheet, cssText, opt_index) { var index = opt_index; if (index < 0 || index == undefined) { // If no index specified, insert at the end of the current list // of rules. // If on IE, use rules property, otherwise use cssRules property. var rules = cssStyleSheet.rules || cssStyleSheet.cssRules; index = rules.length; } if (cssStyleSheet.insertRule) { // W3C. cssStyleSheet.insertRule(cssText, index); } else { // IE: We have to parse the cssRule text to get the selector separated // from the style text. // aka Everything that isn't a colon, followed by a colon, then // the rest is the style part. var matches = /^([^\{]+)\{([^\{]+)\}/.exec(cssText); if (matches.length == 3) { var selector = matches[1]; var style = matches[2]; cssStyleSheet.addRule(selector, style, index); } else { throw Error('Your CSSRule appears to be ill-formatted.'); } } }; /** * Cross browser function to remove a CSSRule in a CSSStyleSheet at an index. * @param {CSSStyleSheet} cssStyleSheet The CSSRule's parentStyleSheet. * @param {number} index The CSSRule's index in the parentStyleSheet. */ goog.cssom.removeCssRule = function(cssStyleSheet, index) { if (cssStyleSheet.deleteRule) { // W3C. cssStyleSheet.deleteRule(index); } else { // IE. cssStyleSheet.removeRule(index); } }; /** * Appends a DOM node to HEAD containing the css text that's passed in. * @param {string} cssText CSS to add to the end of the document. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper user for * document interactions. * @return {Element} The newly created STYLE element. */ goog.cssom.addCssText = function(cssText, opt_domHelper) { var document = opt_domHelper ? opt_domHelper.getDocument() : goog.dom.getDocument(); var cssNode = document.createElement('style'); cssNode.type = 'text/css'; var head = document.getElementsByTagName('head')[0]; head.appendChild(cssNode); if (cssNode.styleSheet) { // IE. cssNode.styleSheet.cssText = cssText; } else { // W3C. var cssTextNode = document.createTextNode(cssText); cssNode.appendChild(cssTextNode); } return cssNode; }; /** * Cross browser method to get the filename from the StyleSheet's href. * Explorer only returns the filename in the href, while other agents return * the full path. * @param {!StyleSheet} styleSheet Any valid StyleSheet object with an href. * @throws {Error} When there's no href property found. * @return {?string} filename The filename, or null if not an external * styleSheet. */ goog.cssom.getFileNameFromStyleSheet = function(styleSheet) { var href = styleSheet.href; // Another IE/FF difference. IE returns an empty string, while FF and others // return null for CSSStyleSheets not from an external file. if (!href) { return null; } // We need the regexp to ensure we get the filename minus any query params. var matches = /([^\/\?]+)[^\/]*$/.exec(href); var filename = matches[1]; return filename; }; /** * Recursively gets all CSS text or rules. * @param {CSSStyleSheet} styleSheet The CSSStyleSheet. * @param {boolean} isTextOutput If true, output is cssText, otherwise cssRules. * @return {string|Array.<CSSRule>} cssText or cssRules. * @private */ goog.cssom.getAllCss_ = function(styleSheet, isTextOutput) { var cssOut = []; var styleSheets = goog.cssom.getAllCssStyleSheets(styleSheet); for (var i = 0; styleSheet = styleSheets[i]; i++) { var cssRuleList = goog.cssom.getCssRulesFromStyleSheet(styleSheet); if (cssRuleList && cssRuleList.length) { // We're going to track cssRule index if we want rule output. if (!isTextOutput) { var ruleIndex = 0; } for (var j = 0, n = cssRuleList.length, cssRule; j < n; j++) { cssRule = cssRuleList[j]; // Gets cssText output, ignoring CSSImportRules. if (isTextOutput && !cssRule.href) { var res = goog.cssom.getCssTextFromCssRule(cssRule); cssOut.push(res); } else if (!cssRule.href) { // Gets cssRules output, ignoring CSSImportRules. if (cssRule.style) { // This is a fun little hack to get parentStyleSheet into the rule // object for IE since it failed to implement rule.parentStyleSheet. // We can later read this property when doing things like hunting // for indexes in order to delete a given CSSRule. // Unfortunately we have to use the style object to store these // pieces of info since the rule object is read-only. if (!cssRule.parentStyleSheet) { cssRule.style['-closure-parent-stylesheet'] = styleSheet; } // This is a hack to help with possible removal of the rule later, // where we just append the rule's index in its parentStyleSheet // onto the style object as a property. // Unfortunately we have to use the style object to store these // pieces of info since the rule object is read-only. cssRule.style['-closure-rule-index'] = ruleIndex; } cssOut.push(cssRule); } if (!isTextOutput) { ruleIndex++; } } } } return isTextOutput ? cssOut.join(' ') : cssOut; };
JavaScript
// Copyright 2010 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview HTML5 based history implementation, compatible with * goog.History. * * TODO(user): There should really be a history interface and multiple * implementations. * */ goog.provide('goog.history.Html5History'); goog.provide('goog.history.Html5History.TokenTransformer'); goog.require('goog.asserts'); goog.require('goog.events'); goog.require('goog.events.EventTarget'); goog.require('goog.events.EventType'); goog.require('goog.history.Event'); goog.require('goog.history.EventType'); /** * An implementation compatible with goog.History that uses the HTML5 * history APIs. * * @param {Window=} opt_win The window to listen/dispatch history events on. * @param {goog.history.Html5History.TokenTransformer=} opt_transformer * The token transformer that is used to create URL from the token * when storing token without using hash fragment. * @constructor * @extends {goog.events.EventTarget} */ goog.history.Html5History = function(opt_win, opt_transformer) { goog.events.EventTarget.call(this); goog.asserts.assert(goog.history.Html5History.isSupported(opt_win), 'HTML5 history is not supported.'); /** * The window object to use for history tokens. Typically the top window. * @type {Window} * @private */ this.window_ = opt_win || window; /** * The token transformer that is used to create URL from the token * when storing token without using hash fragment. * @type {goog.history.Html5History.TokenTransformer} * @private */ this.transformer_ = opt_transformer || null; goog.events.listen(this.window_, goog.events.EventType.POPSTATE, this.onHistoryEvent_, false, this); goog.events.listen(this.window_, goog.events.EventType.HASHCHANGE, this.onHistoryEvent_, false, this); }; goog.inherits(goog.history.Html5History, goog.events.EventTarget); /** * Returns whether Html5History is supported. * @param {Window=} opt_win Optional window to check. * @return {boolean} Whether html5 history is supported. */ goog.history.Html5History.isSupported = function(opt_win) { var win = opt_win || window; return !!(win.history && win.history.pushState); }; /** * Status of when the object is active and dispatching events. * @type {boolean} * @private */ goog.history.Html5History.prototype.enabled_ = false; /** * Whether to use the fragment to store the token, defaults to true. * @type {boolean} * @private */ goog.history.Html5History.prototype.useFragment_ = true; /** * If useFragment is false the path will be used, the path prefix will be * prepended to all tokens. Defaults to '/'. * @type {string} * @private */ goog.history.Html5History.prototype.pathPrefix_ = '/'; /** * Starts or stops the History. When enabled, the History object * will immediately fire an event for the current location. The caller can set * up event listeners between the call to the constructor and the call to * setEnabled. * * @param {boolean} enable Whether to enable history. */ goog.history.Html5History.prototype.setEnabled = function(enable) { if (enable == this.enabled_) { return; } this.enabled_ = enable; if (enable) { this.dispatchEvent(new goog.history.Event(this.getToken(), false)); } }; /** * Returns the current token. * @return {string} The current token. */ goog.history.Html5History.prototype.getToken = function() { if (this.useFragment_) { var loc = this.window_.location.href; var index = loc.indexOf('#'); return index < 0 ? '' : loc.substring(index + 1); } else { return this.transformer_ ? this.transformer_.retrieveToken( this.pathPrefix_, this.window_.location) : this.window_.location.pathname.substr(this.pathPrefix_.length); } }; /** * Sets the history state. * @param {string} token The history state identifier. * @param {string=} opt_title Optional title to associate with history entry. */ goog.history.Html5History.prototype.setToken = function(token, opt_title) { if (token == this.getToken()) { return; } // Per externs/gecko_dom.js document.title can be null. this.window_.history.pushState(null, opt_title || this.window_.document.title || '', this.getUrl_(token)); this.dispatchEvent(new goog.history.Event(token, false)); }; /** * Replaces the current history state without affecting the rest of the history * stack. * @param {string} token The history state identifier. * @param {string=} opt_title Optional title to associate with history entry. */ goog.history.Html5History.prototype.replaceToken = function(token, opt_title) { // Per externs/gecko_dom.js document.title can be null. this.window_.history.replaceState(null, opt_title || this.window_.document.title || '', this.getUrl_(token)); this.dispatchEvent(new goog.history.Event(token, false)); }; /** @override */ goog.history.Html5History.prototype.disposeInternal = function() { goog.events.unlisten(this.window_, goog.events.EventType.POPSTATE, this.onHistoryEvent_, false, this); if (this.useFragment_) { goog.events.unlisten(this.window_, goog.events.EventType.HASHCHANGE, this.onHistoryEvent_, false, this); } }; /** * Sets whether to use the fragment to store tokens. * @param {boolean} useFragment Whether to use the fragment. */ goog.history.Html5History.prototype.setUseFragment = function(useFragment) { if (this.useFragment_ != useFragment) { if (useFragment) { goog.events.listen(this.window_, goog.events.EventType.HASHCHANGE, this.onHistoryEvent_, false, this); } else { goog.events.unlisten(this.window_, goog.events.EventType.HASHCHANGE, this.onHistoryEvent_, false, this); } this.useFragment_ = useFragment; } }; /** * Sets the path prefix to use if storing tokens in the path. The path * prefix should start and end with slash. * @param {string} pathPrefix Sets the path prefix. */ goog.history.Html5History.prototype.setPathPrefix = function(pathPrefix) { this.pathPrefix_ = pathPrefix; }; /** * Gets the path prefix. * @return {string} The path prefix. */ goog.history.Html5History.prototype.getPathPrefix = function() { return this.pathPrefix_; }; /** * Gets the URL to set when calling history.pushState * @param {string} token The history token. * @return {string} The URL. * @private */ goog.history.Html5History.prototype.getUrl_ = function(token) { if (this.useFragment_) { return '#' + token; } else { return this.transformer_ ? this.transformer_.createUrl( token, this.pathPrefix_, this.window_.location) : this.pathPrefix_ + token + this.window_.location.search; } }; /** * Handles history events dispatched by the browser. * @param {goog.events.BrowserEvent} e The browser event object. * @private */ goog.history.Html5History.prototype.onHistoryEvent_ = function(e) { if (this.enabled_) { this.dispatchEvent(new goog.history.Event(this.getToken(), true)); } }; /** * A token transformer that can create a URL from a history * token. This is used by {@code goog.history.Html5History} to create * URL when storing token without the hash fragment. * * Given a {@code window.location} object containing the location * created by {@code createUrl}, the token transformer allows * retrieval of the token back via {@code retrieveToken}. * * @interface */ goog.history.Html5History.TokenTransformer = function() {}; /** * Retrieves a history token given the path prefix and * {@code window.location} object. * * @param {string} pathPrefix The path prefix to use when storing token * in a path; always begin with a slash. * @param {Location} location The {@code window.location} object. * Treat this object as read-only. * @return {string} token The history token. */ goog.history.Html5History.TokenTransformer.prototype.retrieveToken = function( pathPrefix, location) {}; /** * Creates a URL to be pushed into HTML5 history stack when storing * token without using hash fragment. * * @param {string} token The history token. * @param {string} pathPrefix The path prefix to use when storing token * in a path; always begin with a slash. * @param {Location} location The {@code window.location} object. * Treat this object as read-only. * @return {string} url The complete URL string from path onwards * (without {@code protocol://host:port} part); must begin with a * slash. */ goog.history.Html5History.TokenTransformer.prototype.createUrl = function( token, pathPrefix, location) {};
JavaScript
// Copyright 2013 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for goog.history.History. */ /** @suppress {extraProvide} */ goog.provide('goog.HistoryTest'); goog.require('goog.History'); goog.require('goog.testing.jsunit'); goog.require('goog.userAgent'); goog.setTestOnly('goog.HistoryTest'); // Mimimal function to exercise construction. function testCreation() { // Running goog.History in tests on older browsers simply hangs them in TAP. if (goog.userAgent.GECKO || (goog.userAgent.IE && !goog.userAgent.isVersion(9))) { return; } var history = new goog.History(); } function testIsHashChangeSupported() { // This is the policy currently implemented. var supportsOnHashChange = (goog.userAgent.IE ? document.documentMode >= 8 : 'onhashchange' in window); assertEquals( supportsOnHashChange, goog.History.isOnHashChangeSupported()); } // TODO(nnaze): Test additional behavior.
JavaScript
// Copyright 2010 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview The event object dispatched when the history changes. * */ goog.provide('goog.history.Event'); goog.require('goog.events.Event'); goog.require('goog.history.EventType'); /** * Event object dispatched after the history state has changed. * @param {string} token The string identifying the new history state. * @param {boolean} isNavigation True if the event was triggered by a browser * action, such as forward or back, clicking on a link, editing the URL, or * calling {@code window.history.(go|back|forward)}. * False if the token has been changed by a {@code setToken} or * {@code replaceToken} call. * @constructor * @extends {goog.events.Event} */ goog.history.Event = function(token, isNavigation) { goog.events.Event.call(this, goog.history.EventType.NAVIGATE); /** * The current history state. * @type {string} */ this.token = token; /** * Whether the event was triggered by browser navigation. * @type {boolean} */ this.isNavigation = isNavigation; }; goog.inherits(goog.history.Event, goog.events.Event);
JavaScript
// Copyright 2010 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Event types for goog.history. * */ goog.provide('goog.history.EventType'); /** * Event types for goog.history. * @enum {string} */ goog.history.EventType = { NAVIGATE: 'navigate' };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Browser history stack management class. * * The goog.History object allows a page to create history state without leaving * the current document. This allows users to, for example, hit the browser's * back button without leaving the current page. * * The history object can be instantiated in one of two modes. In user visible * mode, the current history state is shown in the browser address bar as a * document location fragment (the portion of the URL after the '#'). These * addresses can be bookmarked, copied and pasted into another browser, and * modified directly by the user like any other URL. * * If the history object is created in invisible mode, the user can still * affect the state using the browser forward and back buttons, but the current * state is not displayed in the browser address bar. These states are not * bookmarkable or editable. * * It is possible to use both types of history object on the same page, but not * currently recommended due to browser deficiencies. * * Tested to work in: * <ul> * <li>Firefox 1.0-4.0 * <li>Internet Explorer 5.5-9.0 * <li>Opera 9+ * <li>Safari 4+ * </ul> * * @author brenneman@google.com (Shawn Brenneman) * @see ../demos/history1.html * @see ../demos/history2.html */ /* Some browser specific implementation notes: * * Firefox (through version 2.0.0.1): * * Ideally, navigating inside the hidden iframe could be done using * about:blank#state instead of a real page on the server. Setting the hash on * about:blank creates history entries, but the hash is not recorded and is lost * when the user hits the back button. This is true in Opera as well. A blank * HTML page must be provided for invisible states to be recorded in the iframe * hash. * * After leaving the page with the History object and returning to it (by * hitting the back button from another site), the last state of the iframe is * overwritten. The most recent state is saved in a hidden input field so the * previous state can be restored. * * Firefox does not store the previous value of dynamically generated input * elements. To save the state, the hidden element must be in the HTML document, * either in the original source or added with document.write. If a reference * to the input element is not provided as a constructor argument, then the * history object creates one using document.write, in which case the history * object must be created from a script in the body element of the page. * * Manually editing the address field to a different hash link prevents further * updates to the address bar. The page continues to work as normal, but the * address shown will be incorrect until the page is reloaded. * * NOTE(user): It should be noted that Firefox will URL encode any non-regular * ascii character, along with |space|, ", <, and >, when added to the fragment. * If you expect these characters in your tokens you should consider that * setToken('<b>') would result in the history fragment "%3Cb%3E", and * "esp&eacute;re" would show "esp%E8re". (IE allows unicode characters in the * fragment) * * TODO(user): Should we encapsulate this escaping into the API for visible * history and encode all characters that aren't supported by Firefox? It also * needs to be optional so apps can elect to handle the escaping themselves. * * * Internet Explorer (through version 7.0): * * IE does not modify the history stack when the document fragment is changed. * We create history entries instead by using document.open and document.write * into a hidden iframe. * * IE destroys the history stack when navigating from /foo.html#someFragment to * /foo.html. The workaround is to always append the # to the URL. This is * somewhat unfortunate when loading the page without any # specified, because * a second "click" sound will play on load as the fragment is automatically * appended. If the hash is always present, this can be avoided. * * Manually editing the hash in the address bar in IE6 and then hitting the back * button can replace the page with a blank page. This is a Bad User Experience, * but probably not preventable. * * IE also has a bug when the page is loaded via a server redirect, setting * a new hash value on the window location will force a page reload. This will * happen the first time setToken is called with a new token. The only known * workaround is to force a client reload early, for example by setting * window.location.hash = window.location.hash, which will otherwise be a no-op. * * Internet Explorer 8.0, Webkit 532.1 and Gecko 1.9.2: * * IE8 has introduced the support to the HTML5 onhashchange event, which means * we don't have to do any polling to detect fragment changes. Chrome and * Firefox have added it on their newer builds, wekbit 532.1 and gecko 1.9.2. * http://www.w3.org/TR/html5/history.html * NOTE(goto): it is important to note that the document needs to have the * <!DOCTYPE html> tag to enable the IE8 HTML5 mode. If the tag is not present, * IE8 will enter IE7 compatibility mode (which can also be enabled manually). * * Opera (through version 9.02): * * Navigating through pages at a rate faster than some threshhold causes Opera * to cancel all outstanding timeouts and intervals, including the location * polling loop. Since this condition cannot be detected, common input events * are captured to cause the loop to restart. * * location.replace is adding a history entry inside setHash_, despite * documentation that suggests it should not. * * * Safari (through version 2.0.4): * * After hitting the back button, the location.hash property is no longer * readable from JavaScript. This is fixed in later WebKit builds, but not in * currently shipping Safari. For now, the only recourse is to disable history * states in Safari. Pages are still navigable via the History object, but the * back button cannot restore previous states. * * Safari sets history states on navigation to a hashlink, but doesn't allow * polling of the hash, so following actual anchor links in the page will create * useless history entries. Using location.replace does not seem to prevent * this. Not a terribly good user experience, but fixed in later Webkits. * * * WebKit (nightly version 420+): * * This almost works. Returning to a page with an invisible history object does * not restore the old state, however, and there is no pageshow event that fires * in this browser. Holding off on finding a solution for now. * * * HTML5 capable browsers (Firefox 4, Chrome, Safari 5) * * No known issues. The goog.history.Html5History class provides a simpler * implementation more suitable for recent browsers. These implementations * should be merged so the history class automatically invokes the correct * implementation. */ goog.provide('goog.History'); goog.provide('goog.History.Event'); goog.provide('goog.History.EventType'); goog.require('goog.Timer'); goog.require('goog.dom'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventTarget'); goog.require('goog.events.EventType'); goog.require('goog.history.Event'); goog.require('goog.history.EventType'); goog.require('goog.memoize'); goog.require('goog.string'); goog.require('goog.userAgent'); /** * A history management object. Can be instantiated in user-visible mode (uses * the address fragment to manage state) or in hidden mode. This object should * be created from a script in the document body before the document has * finished loading. * * To store the hidden states in browsers other than IE, a hidden iframe is * used. It must point to a valid html page on the same domain (which can and * probably should be blank.) * * Sample instantiation and usage: * * <pre> * // Instantiate history to use the address bar for state. * var h = new goog.History(); * goog.events.listen(h, goog.history.EventType.NAVIGATE, navCallback); * h.setEnabled(true); * * // Any changes to the location hash will call the following function. * function navCallback(e) { * alert('Navigated to state "' + e.token + '"'); * } * * // The history token can also be set from code directly. * h.setToken('foo'); * </pre> * * @param {boolean=} opt_invisible True to use hidden history states instead of * the user-visible location hash. * @param {string=} opt_blankPageUrl A URL to a blank page on the same server. * Required if opt_invisible is true. This URL is also used as the src * for the iframe used to track history state in IE (if not specified the * iframe is not given a src attribute). Access is Denied error may * occur in IE7 if the window's URL's scheme is https, and this URL is * not specified. * @param {HTMLInputElement=} opt_input The hidden input element to be used to * store the history token. If not provided, a hidden input element will * be created using document.write. * @param {HTMLIFrameElement=} opt_iframe The hidden iframe that will be used by * IE for pushing history state changes, or by all browsers if opt_invisible * is true. If not provided, a hidden iframe element will be created using * document.write. * @constructor * @extends {goog.events.EventTarget} */ goog.History = function(opt_invisible, opt_blankPageUrl, opt_input, opt_iframe) { goog.events.EventTarget.call(this); if (opt_invisible && !opt_blankPageUrl) { throw Error('Can\'t use invisible history without providing a blank page.'); } var input; if (opt_input) { input = opt_input; } else { var inputId = 'history_state' + goog.History.historyCount_; document.write(goog.string.subs(goog.History.INPUT_TEMPLATE_, inputId, inputId)); input = goog.dom.getElement(inputId); } /** * An input element that stores the current iframe state. Used to restore * the state when returning to the page on non-IE browsers. * @type {HTMLInputElement} * @private */ this.hiddenInput_ = /** @type {HTMLInputElement} */ (input); /** * The window whose location contains the history token fragment. This is * the window that contains the hidden input. It's typically the top window. * It is not necessarily the same window that the js code is loaded in. * @type {Window} * @private */ this.window_ = opt_input ? goog.dom.getWindow(goog.dom.getOwnerDocument(opt_input)) : window; /** * The initial page location with an empty hash component. If the page uses * a BASE element, setting location.hash directly will navigate away from the * current document. To prevent this, the full path is always specified. * @type {string} * @private */ this.baseUrl_ = this.window_.location.href.split('#')[0]; /** * The base URL for the hidden iframe. Must refer to a document in the * same domain as the main page. * @type {string|undefined} * @private */ this.iframeSrc_ = opt_blankPageUrl; if (goog.userAgent.IE && !opt_blankPageUrl) { this.iframeSrc_ = window.location.protocol == 'https' ? 'https:///' : 'javascript:""'; } /** * A timer for polling the current history state for changes. * @type {goog.Timer} * @private */ this.timer_ = new goog.Timer(goog.History.PollingType.NORMAL); this.registerDisposable(this.timer_); /** * True if the state tokens are displayed in the address bar, false for hidden * history states. * @type {boolean} * @private */ this.userVisible_ = !opt_invisible; /** * An object to keep track of the history event listeners. * @type {goog.events.EventHandler} * @private */ this.eventHandler_ = new goog.events.EventHandler(this); if (opt_invisible || goog.History.LEGACY_IE) { var iframe; if (opt_iframe) { iframe = opt_iframe; } else { var iframeId = 'history_iframe' + goog.History.historyCount_; var srcAttribute = this.iframeSrc_ ? 'src="' + goog.string.htmlEscape(this.iframeSrc_) + '"' : ''; document.write(goog.string.subs(goog.History.IFRAME_TEMPLATE_, iframeId, srcAttribute)); iframe = goog.dom.getElement(iframeId); } /** * Internet Explorer uses a hidden iframe for all history changes. Other * browsers use the iframe only for pushing invisible states. * @type {HTMLIFrameElement} * @private */ this.iframe_ = /** @type {HTMLIFrameElement} */ (iframe); /** * Whether the hidden iframe has had a document written to it yet in this * session. * @type {boolean} * @private */ this.unsetIframe_ = true; } if (goog.History.LEGACY_IE) { // IE relies on the hidden input to restore the history state from previous // sessions, but input values are only restored after window.onload. Set up // a callback to poll the value after the onload event. this.eventHandler_.listen(this.window_, goog.events.EventType.LOAD, this.onDocumentLoaded); /** * IE-only variable for determining if the document has loaded. * @type {boolean} * @protected */ this.documentLoaded = false; /** * IE-only variable for storing whether the history object should be enabled * once the document finishes loading. * @type {boolean} * @private */ this.shouldEnable_ = false; } // Set the initial history state. if (this.userVisible_) { this.setHash_(this.getToken(), true); } else { this.setIframeToken_(this.hiddenInput_.value); } goog.History.historyCount_++; }; goog.inherits(goog.History, goog.events.EventTarget); /** * Status of when the object is active and dispatching events. * @type {boolean} * @private */ goog.History.prototype.enabled_ = false; /** * Whether the object is performing polling with longer intervals. This can * occur for instance when setting the location of the iframe when in invisible * mode and the server that is hosting the blank html page is down. In FF, this * will cause the location of the iframe to no longer be accessible, with * permision denied exceptions being thrown on every access of the history * token. When this occurs, the polling interval is elongated. This causes * exceptions to be thrown at a lesser rate while allowing for the history * object to resurrect itself when the html page becomes accessible. * @type {boolean} * @private */ goog.History.prototype.longerPolling_ = false; /** * The last token set by the history object, used to poll for changes. * @type {?string} * @private */ goog.History.prototype.lastToken_ = null; /** * Whether the browser supports HTML5 history management's onhashchange event. * {@link http://www.w3.org/TR/html5/history.html}. IE 9 in compatibility mode * indicates that onhashchange is in window, but testing reveals the event * isn't actually fired. * @return {boolean} Whether onhashchange is supported. */ goog.History.isOnHashChangeSupported = goog.memoize(function() { return goog.userAgent.IE ? document.documentMode >= 8 : 'onhashchange' in goog.global; }); /** * Whether the current browser is Internet Explorer prior to version 8. Many IE * specific workarounds developed before version 8 are unnecessary in more * current versions. * @type {boolean} */ goog.History.LEGACY_IE = goog.userAgent.IE && !goog.userAgent.isDocumentMode(8); /** * Whether the browser always requires the hash to be present. Internet Explorer * before version 8 will reload the HTML page if the hash is omitted. * @type {boolean} */ goog.History.HASH_ALWAYS_REQUIRED = goog.History.LEGACY_IE; /** * If not null, polling in the user invisible mode will be disabled until this * token is seen. This is used to prevent a race condition where the iframe * hangs temporarily while the location is changed. * @type {?string} * @private */ goog.History.prototype.lockedToken_ = null; /** @override */ goog.History.prototype.disposeInternal = function() { goog.History.superClass_.disposeInternal.call(this); this.eventHandler_.dispose(); this.setEnabled(false); }; /** * Starts or stops the History polling loop. When enabled, the History object * will immediately fire an event for the current location. The caller can set * up event listeners between the call to the constructor and the call to * setEnabled. * * On IE, actual startup may be delayed until the iframe and hidden input * element have been loaded and can be polled. This behavior is transparent to * the caller. * * @param {boolean} enable Whether to enable the history polling loop. */ goog.History.prototype.setEnabled = function(enable) { if (enable == this.enabled_) { return; } if (goog.History.LEGACY_IE && !this.documentLoaded) { // Wait until the document has actually loaded before enabling the // object or any saved state from a previous session will be lost. this.shouldEnable_ = enable; return; } if (enable) { if (goog.userAgent.OPERA) { // Capture events for common user input so we can restart the timer in // Opera if it fails. Yes, this is distasteful. See operaDefibrillator_. this.eventHandler_.listen(this.window_.document, goog.History.INPUT_EVENTS_, this.operaDefibrillator_); } else if (goog.userAgent.GECKO) { // Firefox will not restore the correct state after navigating away from // and then back to the page with the history object. This can be fixed // by restarting the history object on the pageshow event. this.eventHandler_.listen(this.window_, 'pageshow', this.onShow_); } // TODO(user): make HTML5 and invisible history work by listening to the // iframe # changes instead of the window. if (goog.History.isOnHashChangeSupported() && this.userVisible_) { this.eventHandler_.listen( this.window_, goog.events.EventType.HASHCHANGE, this.onHashChange_); this.enabled_ = true; this.dispatchEvent(new goog.history.Event(this.getToken(), false)); } else if (!goog.userAgent.IE || this.documentLoaded) { // Start dispatching history events if all necessary loading has // completed (always true for browsers other than IE.) this.eventHandler_.listen(this.timer_, goog.Timer.TICK, goog.bind(this.check_, this, true)); this.enabled_ = true; // Initialize last token at startup except on IE < 8, where the last token // must only be set in conjunction with IFRAME updates, or the IFRAME will // start out of sync and remove any pre-existing URI fragment. if (!goog.History.LEGACY_IE) { this.lastToken_ = this.getToken(); this.dispatchEvent(new goog.history.Event(this.getToken(), false)); } this.timer_.start(); } } else { this.enabled_ = false; this.eventHandler_.removeAll(); this.timer_.stop(); } }; /** * Callback for the window onload event in IE. This is necessary to read the * value of the hidden input after restoring a history session. The value of * input elements is not viewable until after window onload for some reason (the * iframe state is similarly unavailable during the loading phase.) If * setEnabled is called before the iframe has completed loading, the history * object will actually be enabled at this point. * @protected */ goog.History.prototype.onDocumentLoaded = function() { this.documentLoaded = true; if (this.hiddenInput_.value) { // Any saved value in the hidden input can only be read after the document // has been loaded due to an IE limitation. Restore the previous state if // it has been set. this.setIframeToken_(this.hiddenInput_.value, true); } this.setEnabled(this.shouldEnable_); }; /** * Handler for the Gecko pageshow event. Restarts the history object so that the * correct state can be restored in the hash or iframe. * @param {goog.events.BrowserEvent} e The browser event. * @private */ goog.History.prototype.onShow_ = function(e) { // NOTE(user): persisted is a property passed in the pageshow event that // indicates whether the page is being persisted from the cache or is being // loaded for the first time. if (e.getBrowserEvent()['persisted']) { this.setEnabled(false); this.setEnabled(true); } }; /** * Handles HTML5 onhashchange events on browsers where it is supported. * This is very similar to {@link #check_}, except that it is not executed * continuously. It is only used when * {@code goog.History.isOnHashChangeSupported()} is true. * @param {goog.events.BrowserEvent} e The browser event. * @private */ goog.History.prototype.onHashChange_ = function(e) { var hash = this.getLocationFragment_(this.window_); if (hash != this.lastToken_) { this.update_(hash, true); } }; /** * @return {string} The current token. */ goog.History.prototype.getToken = function() { if (this.lockedToken_ != null) { return this.lockedToken_; } else if (this.userVisible_) { return this.getLocationFragment_(this.window_); } else { return this.getIframeToken_() || ''; } }; /** * Sets the history state. When user visible states are used, the URL fragment * will be set to the provided token. Sometimes it is necessary to set the * history token before the document title has changed, in this case IE's * history drop down can be out of sync with the token. To get around this * problem, the app can pass in a title to use with the hidden iframe. * @param {string} token The history state identifier. * @param {string=} opt_title Optional title used when setting the hidden iframe * title in IE. */ goog.History.prototype.setToken = function(token, opt_title) { this.setHistoryState_(token, false, opt_title); }; /** * Replaces the current history state without affecting the rest of the history * stack. * @param {string} token The history state identifier. * @param {string=} opt_title Optional title used when setting the hidden iframe * title in IE. */ goog.History.prototype.replaceToken = function(token, opt_title) { this.setHistoryState_(token, true, opt_title); }; /** * Gets the location fragment for the current URL. We don't use location.hash * directly as the browser helpfully urlDecodes the string for us which can * corrupt the tokens. For example, if we want to store: label/%2Froot it would * be returned as label//root. * @param {Window} win The window object to use. * @return {string} The fragment. * @private */ goog.History.prototype.getLocationFragment_ = function(win) { var href = win.location.href; var index = href.indexOf('#'); return index < 0 ? '' : href.substring(index + 1); }; /** * Sets the history state. When user visible states are used, the URL fragment * will be set to the provided token. Setting opt_replace to true will cause the * navigation to occur, but will replace the current history entry without * affecting the length of the stack. * * @param {string} token The history state identifier. * @param {boolean} replace Set to replace the current history entry instead of * appending a new history state. * @param {string=} opt_title Optional title used when setting the hidden iframe * title in IE. * @private */ goog.History.prototype.setHistoryState_ = function(token, replace, opt_title) { if (this.getToken() != token) { if (this.userVisible_) { this.setHash_(token, replace); if (!goog.History.isOnHashChangeSupported()) { if (goog.userAgent.IE) { // IE must save state using the iframe. this.setIframeToken_(token, replace, opt_title); } } // This condition needs to be called even if // goog.History.isOnHashChangeSupported() is true so the NAVIGATE event // fires sychronously. if (this.enabled_) { this.check_(false); } } else { // Fire the event immediately so that setting history is synchronous, but // set a suspendToken so that polling doesn't trigger a 'back'. this.setIframeToken_(token, replace); this.lockedToken_ = this.lastToken_ = this.hiddenInput_.value = token; this.dispatchEvent(new goog.history.Event(token, false)); } } }; /** * Sets or replaces the URL fragment. The token does not need to be URL encoded * according to the URL specification, though certain characters (like newline) * are automatically stripped. * * If opt_replace is not set, non-IE browsers will append a new entry to the * history list. Setting the hash does not affect the history stack in IE * (unless there is a pre-existing named anchor for that hash.) * * Older versions of Webkit cannot query the location hash, but it still can be * set. If we detect one of these versions, always replace instead of creating * new history entries. * * window.location.replace replaces the current state from the history stack. * http://www.whatwg.org/specs/web-apps/current-work/#dom-location-replace * http://www.whatwg.org/specs/web-apps/current-work/#replacement-enabled * * @param {string} token The new string to set. * @param {boolean=} opt_replace Set to true to replace the current token * without appending a history entry. * @private */ goog.History.prototype.setHash_ = function(token, opt_replace) { var loc = this.window_.location; var url = this.baseUrl_; // If a hash has already been set, then removing it programmatically will // reload the page. Once there is a hash, we won't remove it. var hasHash = goog.string.contains(loc.href, '#'); if (goog.History.HASH_ALWAYS_REQUIRED || hasHash || token) { url += '#' + token; } if (url != loc.href) { if (opt_replace) { loc.replace(url); } else { loc.href = url; } } }; /** * Sets the hidden iframe state. On IE, this is accomplished by writing a new * document into the iframe. In Firefox, the iframe's URL fragment stores the * state instead. * * Older versions of webkit cannot set the iframe, so ignore those browsers. * * @param {string} token The new string to set. * @param {boolean=} opt_replace Set to true to replace the current iframe state * without appending a new history entry. * @param {string=} opt_title Optional title used when setting the hidden iframe * title in IE. * @private */ goog.History.prototype.setIframeToken_ = function(token, opt_replace, opt_title) { if (this.unsetIframe_ || token != this.getIframeToken_()) { this.unsetIframe_ = false; token = goog.string.urlEncode(token); if (goog.userAgent.IE) { // Caching the iframe document results in document permission errors after // leaving the page and returning. Access it anew each time instead. var doc = goog.dom.getFrameContentDocument(this.iframe_); doc.open('text/html', opt_replace ? 'replace' : undefined); doc.write(goog.string.subs( goog.History.IFRAME_SOURCE_TEMPLATE_, goog.string.htmlEscape( /** @type {string} */ (opt_title || this.window_.document.title)), token)); doc.close(); } else { var url = this.iframeSrc_ + '#' + token; // In Safari, it is possible for the contentWindow of the iframe to not // be present when the page is loading after a reload. var contentWindow = this.iframe_.contentWindow; if (contentWindow) { if (opt_replace) { contentWindow.location.replace(url); } else { contentWindow.location.href = url; } } } } }; /** * Return the current state string from the hidden iframe. On internet explorer, * this is stored as a string in the document body. Other browsers use the * location hash of the hidden iframe. * * Older versions of webkit cannot access the iframe location, so always return * null in that case. * * @return {?string} The state token saved in the iframe (possibly null if the * iframe has never loaded.). * @private */ goog.History.prototype.getIframeToken_ = function() { if (goog.userAgent.IE) { var doc = goog.dom.getFrameContentDocument(this.iframe_); return doc.body ? goog.string.urlDecode(doc.body.innerHTML) : null; } else { // In Safari, it is possible for the contentWindow of the iframe to not // be present when the page is loading after a reload. var contentWindow = this.iframe_.contentWindow; if (contentWindow) { var hash; /** @preserveTry */ try { // Iframe tokens are urlEncoded hash = goog.string.urlDecode(this.getLocationFragment_(contentWindow)); } catch (e) { // An exception will be thrown if the location of the iframe can not be // accessed (permission denied). This can occur in FF if the the server // that is hosting the blank html page goes down and then a new history // token is set. The iframe will navigate to an error page, and the // location of the iframe can no longer be accessed. Due to the polling, // this will cause constant exceptions to be thrown. In this case, // we enable longer polling. We do not have to attempt to reset the // iframe token because (a) we already fired the NAVIGATE event when // setting the token, (b) we can rely on the locked token for current // state, and (c) the token is still in the history and // accesible on forward/back. if (!this.longerPolling_) { this.setLongerPolling_(true); } return null; } // There was no exception when getting the hash so turn off longer polling // if it is on. if (this.longerPolling_) { this.setLongerPolling_(false); } return hash || null; } else { return null; } } }; /** * Checks the state of the document fragment and the iframe title to detect * navigation changes. If {@code goog.HistoryisOnHashChangeSupported()} is * {@code false}, then this runs approximately twenty times per second. * @param {boolean} isNavigation True if the event was initiated by a browser * action, false if it was caused by a setToken call. See * {@link goog.history.Event}. * @private */ goog.History.prototype.check_ = function(isNavigation) { if (this.userVisible_) { var hash = this.getLocationFragment_(this.window_); if (hash != this.lastToken_) { this.update_(hash, isNavigation); } } // Old IE uses the iframe for both visible and non-visible versions. if (!this.userVisible_ || goog.History.LEGACY_IE) { var token = this.getIframeToken_() || ''; if (this.lockedToken_ == null || token == this.lockedToken_) { this.lockedToken_ = null; if (token != this.lastToken_) { this.update_(token, isNavigation); } } } }; /** * Updates the current history state with a given token. Called after a change * to the location or the iframe state is detected by poll_. * * @param {string} token The new history state. * @param {boolean} isNavigation True if the event was initiated by a browser * action, false if it was caused by a setToken call. See * {@link goog.history.Event}. * @private */ goog.History.prototype.update_ = function(token, isNavigation) { this.lastToken_ = this.hiddenInput_.value = token; if (this.userVisible_) { if (goog.History.LEGACY_IE) { this.setIframeToken_(token); } this.setHash_(token); } else { this.setIframeToken_(token); } this.dispatchEvent(new goog.history.Event(this.getToken(), isNavigation)); }; /** * Sets if the history oject should use longer intervals when polling. * * @param {boolean} longerPolling Whether to enable longer polling. * @private */ goog.History.prototype.setLongerPolling_ = function(longerPolling) { if (this.longerPolling_ != longerPolling) { this.timer_.setInterval(longerPolling ? goog.History.PollingType.LONG : goog.History.PollingType.NORMAL); } this.longerPolling_ = longerPolling; }; /** * Opera cancels all outstanding timeouts and intervals after any rapid * succession of navigation events, including the interval used to detect * navigation events. This function restarts the interval so that navigation can * continue. Ideally, only events which would be likely to cause a navigation * change (mousedown and keydown) would be bound to this function. Since Opera * seems to ignore keydown events while the alt key is pressed (such as * alt-left or right arrow), this function is also bound to the much more * frequent mousemove event. This way, when the update loop freezes, it will * unstick itself as the user wiggles the mouse in frustration. * @private */ goog.History.prototype.operaDefibrillator_ = function() { this.timer_.stop(); this.timer_.start(); }; /** * List of user input event types registered in Opera to restart the history * timer (@see goog.History#operaDefibrillator_). * @type {Array.<string>} * @private */ goog.History.INPUT_EVENTS_ = [ goog.events.EventType.MOUSEDOWN, goog.events.EventType.KEYDOWN, goog.events.EventType.MOUSEMOVE ]; /** * Minimal HTML page used to populate the iframe in Internet Explorer. The title * is visible in the history dropdown menu, the iframe state is stored as the * body innerHTML. * @type {string} * @private */ goog.History.IFRAME_SOURCE_TEMPLATE_ = '<title>%s</title><body>%s</body>'; /** * HTML template for an invisible iframe. * @type {string} * @private */ goog.History.IFRAME_TEMPLATE_ = '<iframe id="%s" style="display:none" %s></iframe>'; /** * HTML template for an invisible named input element. * @type {string} * @private */ goog.History.INPUT_TEMPLATE_ = '<input type="text" name="%s" id="%s" style="display:none">'; /** * Counter for the number of goog.History objects that have been instantiated. * Used to create unique IDs. * @type {number} * @private */ goog.History.historyCount_ = 0; /** * Types of polling. The values are in ms of the polling interval. * @enum {number} */ goog.History.PollingType = { NORMAL: 150, LONG: 10000 }; /** * Constant for the history change event type. * @enum {string} * @deprecated Use goog.history.EventType. */ goog.History.EventType = goog.history.EventType; /** * Constant for the history change event type. * @param {string} token The string identifying the new history state. * @extends {goog.events.Event} * @constructor * @deprecated Use goog.history.Event. */ goog.History.Event = goog.history.Event;
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview SHA-224 cryptographic hash. * * Usage: * var sha224 = new goog.crypt.Sha224(); * sha224.update(bytes); * var hash = sha224.digest(); * */ goog.provide('goog.crypt.Sha224'); goog.require('goog.crypt.Sha2'); /** * SHA-224 cryptographic hash constructor. * * @constructor * @extends {goog.crypt.Sha2} */ goog.crypt.Sha224 = function() { goog.base(this); }; goog.inherits(goog.crypt.Sha224, goog.crypt.Sha2); /** @override */ goog.crypt.Sha224.prototype.reset = function() { this.chunk = []; this.inChunk = 0; this.total = 0; this.hash = [ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4]; this.numHashBlocks = 7; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Namespace with crypto related helper functions. */ goog.provide('goog.crypt'); goog.require('goog.array'); /** * Turns a string into an array of bytes; a "byte" being a JS number in the * range 0-255. * @param {string} str String value to arrify. * @return {!Array.<number>} Array of numbers corresponding to the * UCS character codes of each character in str. */ goog.crypt.stringToByteArray = function(str) { var output = [], p = 0; for (var i = 0; i < str.length; i++) { var c = str.charCodeAt(i); while (c > 0xff) { output[p++] = c & 0xff; c >>= 8; } output[p++] = c; } return output; }; /** * Turns an array of numbers into the string given by the concatenation of the * characters to which the numbers correspond. * @param {Array} array Array of numbers representing characters. * @return {string} Stringification of the array. */ goog.crypt.byteArrayToString = function(array) { return String.fromCharCode.apply(null, array); }; /** * Turns an array of numbers into the hex string given by the concatenation of * the hex values to which the numbers correspond. * @param {Array} array Array of numbers representing characters. * @return {string} Hex string. */ goog.crypt.byteArrayToHex = function(array) { return goog.array.map(array, function(numByte) { var hexByte = numByte.toString(16); return hexByte.length > 1 ? hexByte : '0' + hexByte; }).join(''); }; /** * Converts a hex string into an integer array. * @param {string} hexString Hex string of 16-bit integers (two characters * per integer). * @return {!Array.<number>} Array of {0,255} integers for the given string. */ goog.crypt.hexToByteArray = function(hexString) { goog.asserts.assert(hexString.length % 2 == 0, 'Key string length must be multiple of 2'); var arr = []; for (var i = 0; i < hexString.length; i += 2) { arr.push(parseInt(hexString.substring(i, i + 2), 16)); } return arr; }; /** * Converts a JS string to a UTF-8 "byte" array. * @param {string} str 16-bit unicode string. * @return {Array.<number>} UTF-8 byte array. */ goog.crypt.stringToUtf8ByteArray = function(str) { // TODO(user): Use native implementations if/when available str = str.replace(/\r\n/g, '\n'); var out = [], p = 0; for (var i = 0; i < str.length; i++) { var c = str.charCodeAt(i); if (c < 128) { out[p++] = c; } else if (c < 2048) { out[p++] = (c >> 6) | 192; out[p++] = (c & 63) | 128; } else { out[p++] = (c >> 12) | 224; out[p++] = ((c >> 6) & 63) | 128; out[p++] = (c & 63) | 128; } } return out; }; /** * Converts a UTF-8 byte array to JavaScript's 16-bit Unicode. * @param {Array.<number>} bytes UTF-8 byte array. * @return {string} 16-bit Unicode string. */ goog.crypt.utf8ByteArrayToString = function(bytes) { // TODO(user): Use native implementations if/when available var out = [], pos = 0, c = 0; while (pos < bytes.length) { var c1 = bytes[pos++]; if (c1 < 128) { out[c++] = String.fromCharCode(c1); } else if (c1 > 191 && c1 < 224) { var c2 = bytes[pos++]; out[c++] = String.fromCharCode((c1 & 31) << 6 | c2 & 63); } else { var c2 = bytes[pos++]; var c3 = bytes[pos++]; out[c++] = String.fromCharCode( (c1 & 15) << 12 | (c2 & 63) << 6 | c3 & 63); } } return out.join(''); }; /** * XOR two byte arrays. * @param {!Array.<number>} bytes1 Byte array 1. * @param {!Array.<number>} bytes2 Byte array 2. * @return {!Array.<number>} Resulting XOR of the two byte arrays. */ goog.crypt.xorByteArray = function(bytes1, bytes2) { goog.asserts.assert( bytes1.length == bytes2.length, 'XOR array lengths must match'); var result = []; for (var i = 0; i < bytes1.length; i++) { result.push(bytes1[i] ^ bytes2[i]); } return result; };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Implementation of PBKDF2 in JavaScript. * @see http://en.wikipedia.org/wiki/PBKDF2 * * Currently we only support HMAC-SHA1 as the underlying hash function. To add a * new hash function, add a static method similar to deriveKeyFromPasswordSha1() * and implement the specific computeBlockCallback() using the hash function. * * Usage: * var key = pbkdf2.deriveKeySha1( * stringToByteArray('password'), stringToByteArray('salt'), 1000, 128); * */ goog.provide('goog.crypt.pbkdf2'); goog.require('goog.asserts'); goog.require('goog.crypt'); goog.require('goog.crypt.Hmac'); goog.require('goog.crypt.Sha1'); /** * Derives key from password using PBKDF2-SHA1 * @param {!Array.<number>} password Byte array representation of the password * from which the key is derived. * @param {!Array.<number>} initialSalt Byte array representation of the salt. * @param {number} iterations Number of interations when computing the key. * @param {number} keyLength Length of the output key in bits. * Must be multiple of 8. * @return {!Array.<number>} Byte array representation of the output key. */ goog.crypt.pbkdf2.deriveKeySha1 = function( password, initialSalt, iterations, keyLength) { // Length of the HMAC-SHA1 output in bits. var HASH_LENGTH = 160; /** * Compute each block of the key using HMAC-SHA1. * @param {!Array.<number>} index Byte array representation of the index of * the block to be computed. * @return {!Array.<number>} Byte array representation of the output block. */ var computeBlock = function(index) { // Initialize the result to be array of 0 such that its xor with the first // block would be the first block. var result = goog.array.repeat(0, HASH_LENGTH / 8); // Initialize the salt of the first iteration to initialSalt || i. var salt = initialSalt.concat(index); var hmac = new goog.crypt.Hmac(new goog.crypt.Sha1(), password, 64); // Compute and XOR each iteration. for (var i = 0; i < iterations; i++) { // The salt of the next iteration is the result of the current iteration. salt = hmac.getHmac(salt); result = goog.crypt.xorByteArray(result, salt); } return result; }; return goog.crypt.pbkdf2.deriveKeyFromPassword_( computeBlock, HASH_LENGTH, keyLength); }; /** * Compute each block of the key using PBKDF2. * @param {Function} computeBlock Function to compute each block of the output * key. * @param {number} hashLength Length of each block in bits. This is determined * by the specific hash function used. Must be multiple of 8. * @param {number} keyLength Length of the output key in bits. * Must be multiple of 8. * @return {!Array.<number>} Byte array representation of the output key. * @private */ goog.crypt.pbkdf2.deriveKeyFromPassword_ = function(computeBlock, hashLength, keyLength) { goog.asserts.assert(keyLength % 8 == 0, 'invalid output key length'); // Compute and concactate each block of the output key. var numBlocks = Math.ceil(keyLength / hashLength); goog.asserts.assert(numBlocks >= 1, 'invalid number of blocks'); var result = []; for (var i = 1; i <= numBlocks; i++) { var indexBytes = goog.crypt.pbkdf2.integerToByteArray_(i); result = result.concat(computeBlock(indexBytes)); } // Trim the last block if needed. var lastBlockSize = keyLength % hashLength; if (lastBlockSize != 0) { var desiredBytes = ((numBlocks - 1) * hashLength + lastBlockSize) / 8; result.splice(desiredBytes, (hashLength - lastBlockSize) / 8); } return result; }; /** * Converts an integer number to a 32-bit big endian byte array. * @param {number} n Integer number to be converted. * @return {!Array.<number>} Byte Array representation of the 32-bit big endian * encoding of n. * @private */ goog.crypt.pbkdf2.integerToByteArray_ = function(n) { var result = new Array(4); result[0] = n >> 24 & 0xFF; result[1] = n >> 16 & 0xFF; result[2] = n >> 8 & 0xFF; result[3] = n & 0xFF; return result; };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for CBC mode for block ciphers. * * @author nnaze@google.com (Nathan Naze) */ /** @suppress {extraProvide} */ goog.provide('goog.crypt.CbcTest'); goog.require('goog.crypt'); goog.require('goog.crypt.Aes'); goog.require('goog.crypt.Cbc'); goog.require('goog.testing.jsunit'); goog.setTestOnly('goog.crypt.CbcTest'); function stringToBytes(s) { var bytes = new Array(s.length); for (var i = 0; i < s.length; ++i) bytes[i] = s.charCodeAt(i) & 255; return bytes; } function runCbcAesTest(keyBytes, initialVectorBytes, plainTextBytes, cipherTextBytes) { var aes = new goog.crypt.Aes(keyBytes); var cbc = new goog.crypt.Cbc(aes); var encryptedBytes = cbc.encrypt(plainTextBytes, initialVectorBytes); assertEquals('Encrypted bytes should match cipher text.', goog.crypt.byteArrayToHex(cipherTextBytes), goog.crypt.byteArrayToHex(encryptedBytes)); var decryptedBytes = cbc.decrypt(cipherTextBytes, initialVectorBytes); assertEquals('Decrypted bytes should match plain text.', goog.crypt.byteArrayToHex(plainTextBytes), goog.crypt.byteArrayToHex(decryptedBytes)); } function testAesCbcCipherAlgorithm() { // Test values from http://www.ietf.org/rfc/rfc3602.txt // Case #1 runCbcAesTest( goog.crypt.hexToByteArray('06a9214036b8a15b512e03d534120006'), goog.crypt.hexToByteArray('3dafba429d9eb430b422da802c9fac41'), stringToBytes('Single block msg'), goog.crypt.hexToByteArray('e353779c1079aeb82708942dbe77181a')); // Case #2 runCbcAesTest( goog.crypt.hexToByteArray('c286696d887c9aa0611bbb3e2025a45a'), goog.crypt.hexToByteArray('562e17996d093d28ddb3ba695a2e6f58'), goog.crypt.hexToByteArray( '000102030405060708090a0b0c0d0e0f' + '101112131415161718191a1b1c1d1e1f'), goog.crypt.hexToByteArray( 'd296cd94c2cccf8a3a863028b5e1dc0a' + '7586602d253cfff91b8266bea6d61ab1')); // Case #3 runCbcAesTest( goog.crypt.hexToByteArray('6c3ea0477630ce21a2ce334aa746c2cd'), goog.crypt.hexToByteArray('c782dc4c098c66cbd9cd27d825682c81'), stringToBytes('This is a 48-byte message (exactly 3 AES blocks)'), goog.crypt.hexToByteArray( 'd0a02b3836451753d493665d33f0e886' + '2dea54cdb293abc7506939276772f8d5' + '021c19216bad525c8579695d83ba2684')); // Case #4 runCbcAesTest( goog.crypt.hexToByteArray('56e47a38c5598974bc46903dba290349'), goog.crypt.hexToByteArray('8ce82eefbea0da3c44699ed7db51b7d9'), goog.crypt.hexToByteArray( 'a0a1a2a3a4a5a6a7a8a9aaabacadaeaf' + 'b0b1b2b3b4b5b6b7b8b9babbbcbdbebf' + 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf' + 'd0d1d2d3d4d5d6d7d8d9dadbdcdddedf'), goog.crypt.hexToByteArray( 'c30e32ffedc0774e6aff6af0869f71aa' + '0f3af07a9a31a9c684db207eb0ef8e4e' + '35907aa632c3ffdf868bb7b29d3d46ad' + '83ce9f9a102ee99d49a53e87f4c3da55')); }
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Implementation of AES in JavaScript. * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard * */ goog.provide('goog.crypt.Aes'); goog.require('goog.asserts'); goog.require('goog.crypt.BlockCipher'); /** * Implementation of AES in JavaScript. * See http://en.wikipedia.org/wiki/Advanced_Encryption_Standard * * WARNING: This is ECB mode only. If you are encrypting something * longer than 16 bytes, or encrypting more than one value with the same key * (so basically, always) you need to use this with a block cipher mode of * operation. See goog.crypt.Cbc. * * See http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation for more * information. * * @constructor * @implements {goog.crypt.BlockCipher} * @param {!Array.<number>} key The key as an array of integers in {0, 255}. * The key must have lengths of 16, 24, or 32 integers for 128-, * 192-, or 256-bit encryption, respectively. */ goog.crypt.Aes = function(key) { goog.crypt.Aes.assertKeyArray_(key); /** * The AES key. * @type {!Array.<number>} * @private */ this.key_ = key; /** * Key length, in words. * @type {number} * @private */ this.keyLength_ = this.key_.length / 4; /** * Number of rounds. Based on key length per AES spec. * @type {number} * @private */ this.numberOfRounds_ = this.keyLength_ + 6; /** * 4x4 byte array containing the current state. * @type {!Array.<Array.<number>>} * @private */ this.state_ = [[], [], [], []]; /** * Scratch temporary array for calculation. * @type {!Array.<Array.<number>>} * @private */ this.temp_ = [[], [], [], []]; this.keyExpansion_(); }; /** * @define {boolean} Whether to call test method stubs. This can be enabled * for unit testing. */ goog.crypt.Aes.ENABLE_TEST_MODE = false; /** * @override */ goog.crypt.Aes.prototype.encrypt = function(input) { if (goog.crypt.Aes.ENABLE_TEST_MODE) { this.testKeySchedule_(0, this.keySchedule_, 0); } this.copyInput_(input); this.addRoundKey_(0); for (var round = 1; round < this.numberOfRounds_; ++round) { if (goog.crypt.Aes.ENABLE_TEST_MODE) { this.testKeySchedule_(round, this.keySchedule_, round); this.testStartRound_(round, this.state_); } this.subBytes_(goog.crypt.Aes.SBOX_); if (goog.crypt.Aes.ENABLE_TEST_MODE) { this.testAfterSubBytes_(round, this.state_); } this.shiftRows_(); if (goog.crypt.Aes.ENABLE_TEST_MODE) { this.testAfterShiftRows_(round, this.state_); } this.mixColumns_(); if (goog.crypt.Aes.ENABLE_TEST_MODE) { this.testAfterMixColumns_(round, this.state_); } this.addRoundKey_(round); } this.subBytes_(goog.crypt.Aes.SBOX_); if (goog.crypt.Aes.ENABLE_TEST_MODE) { this.testAfterSubBytes_(round, this.state_); } this.shiftRows_(); if (goog.crypt.Aes.ENABLE_TEST_MODE) { this.testAfterShiftRows_(round, this.state_); } this.addRoundKey_(this.numberOfRounds_); return this.generateOutput_(); }; /** * @override */ goog.crypt.Aes.prototype.decrypt = function(input) { if (goog.crypt.Aes.ENABLE_TEST_MODE) { this.testKeySchedule_(0, this.keySchedule_, this.numberOfRounds_); } this.copyInput_(input); this.addRoundKey_(this.numberOfRounds_); for (var round = 1; round < this.numberOfRounds_; ++round) { if (goog.crypt.Aes.ENABLE_TEST_MODE) { this.testKeySchedule_(round, this.keySchedule_, this.numberOfRounds_ - round); this.testStartRound_(round, this.state_); } this.invShiftRows_(); if (goog.crypt.Aes.ENABLE_TEST_MODE) { this.testAfterShiftRows_(round, this.state_); } this.subBytes_(goog.crypt.Aes.INV_SBOX_); if (goog.crypt.Aes.ENABLE_TEST_MODE) { this.testAfterSubBytes_(round, this.state_); } this.addRoundKey_(this.numberOfRounds_ - round); if (goog.crypt.Aes.ENABLE_TEST_MODE) { this.testAfterAddRoundKey_(round, this.state_); } this.invMixColumns_(); } this.invShiftRows_(); if (goog.crypt.Aes.ENABLE_TEST_MODE) { this.testAfterShiftRows_(round, this.state_); } this.subBytes_(goog.crypt.Aes.INV_SBOX_); if (goog.crypt.Aes.ENABLE_TEST_MODE) { this.testAfterSubBytes_(this.numberOfRounds_, this.state_); } if (goog.crypt.Aes.ENABLE_TEST_MODE) { this.testKeySchedule_(this.numberOfRounds_, this.keySchedule_, 0); } this.addRoundKey_(0); return this.generateOutput_(); }; /** * Block size, in words. Fixed at 4 per AES spec. * @type {number} * @private */ goog.crypt.Aes.BLOCK_SIZE_ = 4; /** * Asserts that the key's array of integers is in the correct format. * @param {!Array.<number>} arr AES key as array of integers. * @private */ goog.crypt.Aes.assertKeyArray_ = function(arr) { if (goog.asserts.ENABLE_ASSERTS) { goog.asserts.assert(arr.length == 16 || arr.length == 24 || arr.length == 32, 'Key must have length 16, 24, or 32.'); for (var i = 0; i < arr.length; i++) { goog.asserts.assertNumber(arr[i]); goog.asserts.assert(arr[i] >= 0 && arr[i] <= 255); } } }; /** * Tests can populate this with a callback, and that callback will get called * at the start of each round *in both functions encrypt() and decrypt()*. * @param {number} roundNum Round number. * @param {!Array.<Array.<number>>} Current state. * @private */ goog.crypt.Aes.prototype.testStartRound_ = goog.nullFunction; /** * Tests can populate this with a callback, and that callback will get called * each round right after the SubBytes step gets executed *in both functions * encrypt() and decrypt()*. * @param {number} roundNum Round number. * @param {!Array.<Array.<number>>} Current state. * @private */ goog.crypt.Aes.prototype.testAfterSubBytes_ = goog.nullFunction; /** * Tests can populate this with a callback, and that callback will get called * each round right after the ShiftRows step gets executed *in both functions * encrypt() and decrypt()*. * @param {number} roundNum Round number. * @param {!Array.<Array.<number>>} Current state. * @private */ goog.crypt.Aes.prototype.testAfterShiftRows_ = goog.nullFunction; /** * Tests can populate this with a callback, and that callback will get called * each round right after the MixColumns step gets executed *but only in the * decrypt() function*. * @param {number} roundNum Round number. * @param {!Array.<Array.<number>>} Current state. * @private */ goog.crypt.Aes.prototype.testAfterMixColumns_ = goog.nullFunction; /** * Tests can populate this with a callback, and that callback will get called * each round right after the AddRoundKey step gets executed encrypt(). * @param {number} roundNum Round number. * @param {!Array.<Array.<number>>} Current state. * @private */ goog.crypt.Aes.prototype.testAfterAddRoundKey_ = goog.nullFunction; /** * Tests can populate this with a callback, and that callback will get called * before each round on the round key. *Gets called in both the encrypt() and * decrypt() functions.* * @param {number} roundNum Round number. * @param {!Array.<number>} Computed key schedule. * @param {number} index The index into the key schedule to test. This is not * necessarily roundNum because the key schedule is used in reverse * in the case of decryption. * @private */ goog.crypt.Aes.prototype.testKeySchedule_ = goog.nullFunction; /** * Helper to copy input into the AES state matrix. * @param {!Array.<number>} input Byte array to copy into the state matrix. * @private */ goog.crypt.Aes.prototype.copyInput_ = function(input) { var v, p; goog.asserts.assert(input.length == goog.crypt.Aes.BLOCK_SIZE_ * 4, 'Expecting input of 4 times block size.'); for (var r = 0; r < goog.crypt.Aes.BLOCK_SIZE_; r++) { for (var c = 0; c < 4; c++) { p = c * 4 + r; v = input[p]; goog.asserts.assert( v <= 255 && v >= 0, 'Invalid input. Value %s at position %s is not a byte.', v, p); this.state_[r][c] = v; } } }; /** * Helper to copy the state matrix into an output array. * @return {!Array.<number>} Output byte array. * @private */ goog.crypt.Aes.prototype.generateOutput_ = function() { var output = []; for (var r = 0; r < goog.crypt.Aes.BLOCK_SIZE_; r++) { for (var c = 0; c < 4; c++) { output[c * 4 + r] = this.state_[r][c]; } } return output; }; /** * AES's AddRoundKey procedure. Add the current round key to the state. * @param {number} round The current round. * @private */ goog.crypt.Aes.prototype.addRoundKey_ = function(round) { for (var r = 0; r < 4; r++) { for (var c = 0; c < 4; c++) { this.state_[r][c] ^= this.keySchedule_[round * 4 + c][r]; } } }; /** * AES's SubBytes procedure. Substitute bytes from the precomputed SBox lookup * into the state. * @param {!Array.<number>} box The SBox or invSBox. * @private */ goog.crypt.Aes.prototype.subBytes_ = function(box) { for (var r = 0; r < 4; r++) { for (var c = 0; c < 4; c++) { this.state_[r][c] = box[this.state_[r][c]]; } } }; /** * AES's ShiftRows procedure. Shift the values in each row to the right. Each * row is shifted one more slot than the one above it. * @private */ goog.crypt.Aes.prototype.shiftRows_ = function() { for (var r = 1; r < 4; r++) { for (var c = 0; c < 4; c++) { this.temp_[r][c] = this.state_[r][c]; } } for (var r = 1; r < 4; r++) { for (var c = 0; c < 4; c++) { this.state_[r][c] = this.temp_[r][(c + r) % goog.crypt.Aes.BLOCK_SIZE_]; } } }; /** * AES's InvShiftRows procedure. Shift the values in each row to the right. * @private */ goog.crypt.Aes.prototype.invShiftRows_ = function() { for (var r = 1; r < 4; r++) { for (var c = 0; c < 4; c++) { this.temp_[r][(c + r) % goog.crypt.Aes.BLOCK_SIZE_] = this.state_[r][c]; } } for (var r = 1; r < 4; r++) { for (var c = 0; c < 4; c++) { this.state_[r][c] = this.temp_[r][c]; } } }; /** * AES's MixColumns procedure. Mix the columns of the state using magic. * @private */ goog.crypt.Aes.prototype.mixColumns_ = function() { var s = this.state_; var t = this.temp_[0]; for (var c = 0; c < 4; c++) { t[0] = s[0][c]; t[1] = s[1][c]; t[2] = s[2][c]; t[3] = s[3][c]; s[0][c] = (goog.crypt.Aes.MULT_2_[t[0]] ^ goog.crypt.Aes.MULT_3_[t[1]] ^ t[2] ^ t[3]); s[1][c] = (t[0] ^ goog.crypt.Aes.MULT_2_[t[1]] ^ goog.crypt.Aes.MULT_3_[t[2]] ^ t[3]); s[2][c] = (t[0] ^ t[1] ^ goog.crypt.Aes.MULT_2_[t[2]] ^ goog.crypt.Aes.MULT_3_[t[3]]); s[3][c] = (goog.crypt.Aes.MULT_3_[t[0]] ^ t[1] ^ t[2] ^ goog.crypt.Aes.MULT_2_[t[3]]); } }; /** * AES's InvMixColumns procedure. * @private */ goog.crypt.Aes.prototype.invMixColumns_ = function() { var s = this.state_; var t = this.temp_[0]; for (var c = 0; c < 4; c++) { t[0] = s[0][c]; t[1] = s[1][c]; t[2] = s[2][c]; t[3] = s[3][c]; s[0][c] = ( goog.crypt.Aes.MULT_E_[t[0]] ^ goog.crypt.Aes.MULT_B_[t[1]] ^ goog.crypt.Aes.MULT_D_[t[2]] ^ goog.crypt.Aes.MULT_9_[t[3]]); s[1][c] = ( goog.crypt.Aes.MULT_9_[t[0]] ^ goog.crypt.Aes.MULT_E_[t[1]] ^ goog.crypt.Aes.MULT_B_[t[2]] ^ goog.crypt.Aes.MULT_D_[t[3]]); s[2][c] = ( goog.crypt.Aes.MULT_D_[t[0]] ^ goog.crypt.Aes.MULT_9_[t[1]] ^ goog.crypt.Aes.MULT_E_[t[2]] ^ goog.crypt.Aes.MULT_B_[t[3]]); s[3][c] = ( goog.crypt.Aes.MULT_B_[t[0]] ^ goog.crypt.Aes.MULT_D_[t[1]] ^ goog.crypt.Aes.MULT_9_[t[2]] ^ goog.crypt.Aes.MULT_E_[t[3]]); } }; /** * AES's KeyExpansion procedure. Create the key schedule from the initial key. * @private */ goog.crypt.Aes.prototype.keyExpansion_ = function() { this.keySchedule_ = new Array(goog.crypt.Aes.BLOCK_SIZE_ * ( this.numberOfRounds_ + 1)); for (var rowNum = 0; rowNum < this.keyLength_; rowNum++) { this.keySchedule_[rowNum] = [ this.key_[4 * rowNum], this.key_[4 * rowNum + 1], this.key_[4 * rowNum + 2], this.key_[4 * rowNum + 3] ]; } var temp = new Array(4); for (var rowNum = this.keyLength_; rowNum < (goog.crypt.Aes.BLOCK_SIZE_ * (this.numberOfRounds_ + 1)); rowNum++) { temp[0] = this.keySchedule_[rowNum - 1][0]; temp[1] = this.keySchedule_[rowNum - 1][1]; temp[2] = this.keySchedule_[rowNum - 1][2]; temp[3] = this.keySchedule_[rowNum - 1][3]; if (rowNum % this.keyLength_ == 0) { this.rotWord_(temp); this.subWord_(temp); temp[0] ^= goog.crypt.Aes.RCON_[rowNum / this.keyLength_][0]; temp[1] ^= goog.crypt.Aes.RCON_[rowNum / this.keyLength_][1]; temp[2] ^= goog.crypt.Aes.RCON_[rowNum / this.keyLength_][2]; temp[3] ^= goog.crypt.Aes.RCON_[rowNum / this.keyLength_][3]; } else if (this.keyLength_ > 6 && rowNum % this.keyLength_ == 4) { this.subWord_(temp); } this.keySchedule_[rowNum] = new Array(4); this.keySchedule_[rowNum][0] = this.keySchedule_[rowNum - this.keyLength_][0] ^ temp[0]; this.keySchedule_[rowNum][1] = this.keySchedule_[rowNum - this.keyLength_][1] ^ temp[1]; this.keySchedule_[rowNum][2] = this.keySchedule_[rowNum - this.keyLength_][2] ^ temp[2]; this.keySchedule_[rowNum][3] = this.keySchedule_[rowNum - this.keyLength_][3] ^ temp[3]; } }; /** * AES's SubWord procedure. * @param {!Array.<number>} w Bytes to find the SBox substitution for. * @return {!Array.<number>} The substituted bytes. * @private */ goog.crypt.Aes.prototype.subWord_ = function(w) { w[0] = goog.crypt.Aes.SBOX_[w[0]]; w[1] = goog.crypt.Aes.SBOX_[w[1]]; w[2] = goog.crypt.Aes.SBOX_[w[2]]; w[3] = goog.crypt.Aes.SBOX_[w[3]]; return w; }; /** * AES's RotWord procedure. * @param {!Array.<number>} w Array of bytes to rotate. * @return {!Array.<number>} The rotated bytes. * @private */ goog.crypt.Aes.prototype.rotWord_ = function(w) { var temp = w[0]; w[0] = w[1]; w[1] = w[2]; w[2] = w[3]; w[3] = temp; return w; }; /** * The key schedule. * @type {!Array.<number>} * @private */ goog.crypt.Aes.prototype.keySchedule_; /** * Precomputed SBox lookup. * @type {!Array.<number>} * @private */ goog.crypt.Aes.SBOX_ = [ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 ]; /** * Precomputed InvSBox lookup. * @type {!Array.<number>} * @private */ goog.crypt.Aes.INV_SBOX_ = [ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d ]; /** * Precomputed RCon lookup. * @type {!Array.<number>} * @private */ goog.crypt.Aes.RCON_ = [ [0x00, 0x00, 0x00, 0x00], [0x01, 0x00, 0x00, 0x00], [0x02, 0x00, 0x00, 0x00], [0x04, 0x00, 0x00, 0x00], [0x08, 0x00, 0x00, 0x00], [0x10, 0x00, 0x00, 0x00], [0x20, 0x00, 0x00, 0x00], [0x40, 0x00, 0x00, 0x00], [0x80, 0x00, 0x00, 0x00], [0x1b, 0x00, 0x00, 0x00], [0x36, 0x00, 0x00, 0x00] ]; /** * Precomputed lookup of multiplication by 2 in GF(2^8) * @type {!Array.<number>} * @private */ goog.crypt.Aes.MULT_2_ = [ 0x00, 0x02, 0x04, 0x06, 0x08, 0x0A, 0x0C, 0x0E, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1A, 0x1C, 0x1E, 0x20, 0x22, 0x24, 0x26, 0x28, 0x2A, 0x2C, 0x2E, 0x30, 0x32, 0x34, 0x36, 0x38, 0x3A, 0x3C, 0x3E, 0x40, 0x42, 0x44, 0x46, 0x48, 0x4A, 0x4C, 0x4E, 0x50, 0x52, 0x54, 0x56, 0x58, 0x5A, 0x5C, 0x5E, 0x60, 0x62, 0x64, 0x66, 0x68, 0x6A, 0x6C, 0x6E, 0x70, 0x72, 0x74, 0x76, 0x78, 0x7A, 0x7C, 0x7E, 0x80, 0x82, 0x84, 0x86, 0x88, 0x8A, 0x8C, 0x8E, 0x90, 0x92, 0x94, 0x96, 0x98, 0x9A, 0x9C, 0x9E, 0xA0, 0xA2, 0xA4, 0xA6, 0xA8, 0xAA, 0xAC, 0xAE, 0xB0, 0xB2, 0xB4, 0xB6, 0xB8, 0xBA, 0xBC, 0xBE, 0xC0, 0xC2, 0xC4, 0xC6, 0xC8, 0xCA, 0xCC, 0xCE, 0xD0, 0xD2, 0xD4, 0xD6, 0xD8, 0xDA, 0xDC, 0xDE, 0xE0, 0xE2, 0xE4, 0xE6, 0xE8, 0xEA, 0xEC, 0xEE, 0xF0, 0xF2, 0xF4, 0xF6, 0xF8, 0xFA, 0xFC, 0xFE, 0x1B, 0x19, 0x1F, 0x1D, 0x13, 0x11, 0x17, 0x15, 0x0B, 0x09, 0x0F, 0x0D, 0x03, 0x01, 0x07, 0x05, 0x3B, 0x39, 0x3F, 0x3D, 0x33, 0x31, 0x37, 0x35, 0x2B, 0x29, 0x2F, 0x2D, 0x23, 0x21, 0x27, 0x25, 0x5B, 0x59, 0x5F, 0x5D, 0x53, 0x51, 0x57, 0x55, 0x4B, 0x49, 0x4F, 0x4D, 0x43, 0x41, 0x47, 0x45, 0x7B, 0x79, 0x7F, 0x7D, 0x73, 0x71, 0x77, 0x75, 0x6B, 0x69, 0x6F, 0x6D, 0x63, 0x61, 0x67, 0x65, 0x9B, 0x99, 0x9F, 0x9D, 0x93, 0x91, 0x97, 0x95, 0x8B, 0x89, 0x8F, 0x8D, 0x83, 0x81, 0x87, 0x85, 0xBB, 0xB9, 0xBF, 0xBD, 0xB3, 0xB1, 0xB7, 0xB5, 0xAB, 0xA9, 0xAF, 0xAD, 0xA3, 0xA1, 0xA7, 0xA5, 0xDB, 0xD9, 0xDF, 0xDD, 0xD3, 0xD1, 0xD7, 0xD5, 0xCB, 0xC9, 0xCF, 0xCD, 0xC3, 0xC1, 0xC7, 0xC5, 0xFB, 0xF9, 0xFF, 0xFD, 0xF3, 0xF1, 0xF7, 0xF5, 0xEB, 0xE9, 0xEF, 0xED, 0xE3, 0xE1, 0xE7, 0xE5 ]; /** * Precomputed lookup of multiplication by 3 in GF(2^8) * @type {!Array.<number>} * @private */ goog.crypt.Aes.MULT_3_ = [ 0x00, 0x03, 0x06, 0x05, 0x0C, 0x0F, 0x0A, 0x09, 0x18, 0x1B, 0x1E, 0x1D, 0x14, 0x17, 0x12, 0x11, 0x30, 0x33, 0x36, 0x35, 0x3C, 0x3F, 0x3A, 0x39, 0x28, 0x2B, 0x2E, 0x2D, 0x24, 0x27, 0x22, 0x21, 0x60, 0x63, 0x66, 0x65, 0x6C, 0x6F, 0x6A, 0x69, 0x78, 0x7B, 0x7E, 0x7D, 0x74, 0x77, 0x72, 0x71, 0x50, 0x53, 0x56, 0x55, 0x5C, 0x5F, 0x5A, 0x59, 0x48, 0x4B, 0x4E, 0x4D, 0x44, 0x47, 0x42, 0x41, 0xC0, 0xC3, 0xC6, 0xC5, 0xCC, 0xCF, 0xCA, 0xC9, 0xD8, 0xDB, 0xDE, 0xDD, 0xD4, 0xD7, 0xD2, 0xD1, 0xF0, 0xF3, 0xF6, 0xF5, 0xFC, 0xFF, 0xFA, 0xF9, 0xE8, 0xEB, 0xEE, 0xED, 0xE4, 0xE7, 0xE2, 0xE1, 0xA0, 0xA3, 0xA6, 0xA5, 0xAC, 0xAF, 0xAA, 0xA9, 0xB8, 0xBB, 0xBE, 0xBD, 0xB4, 0xB7, 0xB2, 0xB1, 0x90, 0x93, 0x96, 0x95, 0x9C, 0x9F, 0x9A, 0x99, 0x88, 0x8B, 0x8E, 0x8D, 0x84, 0x87, 0x82, 0x81, 0x9B, 0x98, 0x9D, 0x9E, 0x97, 0x94, 0x91, 0x92, 0x83, 0x80, 0x85, 0x86, 0x8F, 0x8C, 0x89, 0x8A, 0xAB, 0xA8, 0xAD, 0xAE, 0xA7, 0xA4, 0xA1, 0xA2, 0xB3, 0xB0, 0xB5, 0xB6, 0xBF, 0xBC, 0xB9, 0xBA, 0xFB, 0xF8, 0xFD, 0xFE, 0xF7, 0xF4, 0xF1, 0xF2, 0xE3, 0xE0, 0xE5, 0xE6, 0xEF, 0xEC, 0xE9, 0xEA, 0xCB, 0xC8, 0xCD, 0xCE, 0xC7, 0xC4, 0xC1, 0xC2, 0xD3, 0xD0, 0xD5, 0xD6, 0xDF, 0xDC, 0xD9, 0xDA, 0x5B, 0x58, 0x5D, 0x5E, 0x57, 0x54, 0x51, 0x52, 0x43, 0x40, 0x45, 0x46, 0x4F, 0x4C, 0x49, 0x4A, 0x6B, 0x68, 0x6D, 0x6E, 0x67, 0x64, 0x61, 0x62, 0x73, 0x70, 0x75, 0x76, 0x7F, 0x7C, 0x79, 0x7A, 0x3B, 0x38, 0x3D, 0x3E, 0x37, 0x34, 0x31, 0x32, 0x23, 0x20, 0x25, 0x26, 0x2F, 0x2C, 0x29, 0x2A, 0x0B, 0x08, 0x0D, 0x0E, 0x07, 0x04, 0x01, 0x02, 0x13, 0x10, 0x15, 0x16, 0x1F, 0x1C, 0x19, 0x1A ]; /** * Precomputed lookup of multiplication by 9 in GF(2^8) * @type {!Array.<number>} * @private */ goog.crypt.Aes.MULT_9_ = [ 0x00, 0x09, 0x12, 0x1B, 0x24, 0x2D, 0x36, 0x3F, 0x48, 0x41, 0x5A, 0x53, 0x6C, 0x65, 0x7E, 0x77, 0x90, 0x99, 0x82, 0x8B, 0xB4, 0xBD, 0xA6, 0xAF, 0xD8, 0xD1, 0xCA, 0xC3, 0xFC, 0xF5, 0xEE, 0xE7, 0x3B, 0x32, 0x29, 0x20, 0x1F, 0x16, 0x0D, 0x04, 0x73, 0x7A, 0x61, 0x68, 0x57, 0x5E, 0x45, 0x4C, 0xAB, 0xA2, 0xB9, 0xB0, 0x8F, 0x86, 0x9D, 0x94, 0xE3, 0xEA, 0xF1, 0xF8, 0xC7, 0xCE, 0xD5, 0xDC, 0x76, 0x7F, 0x64, 0x6D, 0x52, 0x5B, 0x40, 0x49, 0x3E, 0x37, 0x2C, 0x25, 0x1A, 0x13, 0x08, 0x01, 0xE6, 0xEF, 0xF4, 0xFD, 0xC2, 0xCB, 0xD0, 0xD9, 0xAE, 0xA7, 0xBC, 0xB5, 0x8A, 0x83, 0x98, 0x91, 0x4D, 0x44, 0x5F, 0x56, 0x69, 0x60, 0x7B, 0x72, 0x05, 0x0C, 0x17, 0x1E, 0x21, 0x28, 0x33, 0x3A, 0xDD, 0xD4, 0xCF, 0xC6, 0xF9, 0xF0, 0xEB, 0xE2, 0x95, 0x9C, 0x87, 0x8E, 0xB1, 0xB8, 0xA3, 0xAA, 0xEC, 0xE5, 0xFE, 0xF7, 0xC8, 0xC1, 0xDA, 0xD3, 0xA4, 0xAD, 0xB6, 0xBF, 0x80, 0x89, 0x92, 0x9B, 0x7C, 0x75, 0x6E, 0x67, 0x58, 0x51, 0x4A, 0x43, 0x34, 0x3D, 0x26, 0x2F, 0x10, 0x19, 0x02, 0x0B, 0xD7, 0xDE, 0xC5, 0xCC, 0xF3, 0xFA, 0xE1, 0xE8, 0x9F, 0x96, 0x8D, 0x84, 0xBB, 0xB2, 0xA9, 0xA0, 0x47, 0x4E, 0x55, 0x5C, 0x63, 0x6A, 0x71, 0x78, 0x0F, 0x06, 0x1D, 0x14, 0x2B, 0x22, 0x39, 0x30, 0x9A, 0x93, 0x88, 0x81, 0xBE, 0xB7, 0xAC, 0xA5, 0xD2, 0xDB, 0xC0, 0xC9, 0xF6, 0xFF, 0xE4, 0xED, 0x0A, 0x03, 0x18, 0x11, 0x2E, 0x27, 0x3C, 0x35, 0x42, 0x4B, 0x50, 0x59, 0x66, 0x6F, 0x74, 0x7D, 0xA1, 0xA8, 0xB3, 0xBA, 0x85, 0x8C, 0x97, 0x9E, 0xE9, 0xE0, 0xFB, 0xF2, 0xCD, 0xC4, 0xDF, 0xD6, 0x31, 0x38, 0x23, 0x2A, 0x15, 0x1C, 0x07, 0x0E, 0x79, 0x70, 0x6B, 0x62, 0x5D, 0x54, 0x4F, 0x46 ]; /** * Precomputed lookup of multiplication by 11 in GF(2^8) * @type {!Array.<number>} * @private */ goog.crypt.Aes.MULT_B_ = [ 0x00, 0x0B, 0x16, 0x1D, 0x2C, 0x27, 0x3A, 0x31, 0x58, 0x53, 0x4E, 0x45, 0x74, 0x7F, 0x62, 0x69, 0xB0, 0xBB, 0xA6, 0xAD, 0x9C, 0x97, 0x8A, 0x81, 0xE8, 0xE3, 0xFE, 0xF5, 0xC4, 0xCF, 0xD2, 0xD9, 0x7B, 0x70, 0x6D, 0x66, 0x57, 0x5C, 0x41, 0x4A, 0x23, 0x28, 0x35, 0x3E, 0x0F, 0x04, 0x19, 0x12, 0xCB, 0xC0, 0xDD, 0xD6, 0xE7, 0xEC, 0xF1, 0xFA, 0x93, 0x98, 0x85, 0x8E, 0xBF, 0xB4, 0xA9, 0xA2, 0xF6, 0xFD, 0xE0, 0xEB, 0xDA, 0xD1, 0xCC, 0xC7, 0xAE, 0xA5, 0xB8, 0xB3, 0x82, 0x89, 0x94, 0x9F, 0x46, 0x4D, 0x50, 0x5B, 0x6A, 0x61, 0x7C, 0x77, 0x1E, 0x15, 0x08, 0x03, 0x32, 0x39, 0x24, 0x2F, 0x8D, 0x86, 0x9B, 0x90, 0xA1, 0xAA, 0xB7, 0xBC, 0xD5, 0xDE, 0xC3, 0xC8, 0xF9, 0xF2, 0xEF, 0xE4, 0x3D, 0x36, 0x2B, 0x20, 0x11, 0x1A, 0x07, 0x0C, 0x65, 0x6E, 0x73, 0x78, 0x49, 0x42, 0x5F, 0x54, 0xF7, 0xFC, 0xE1, 0xEA, 0xDB, 0xD0, 0xCD, 0xC6, 0xAF, 0xA4, 0xB9, 0xB2, 0x83, 0x88, 0x95, 0x9E, 0x47, 0x4C, 0x51, 0x5A, 0x6B, 0x60, 0x7D, 0x76, 0x1F, 0x14, 0x09, 0x02, 0x33, 0x38, 0x25, 0x2E, 0x8C, 0x87, 0x9A, 0x91, 0xA0, 0xAB, 0xB6, 0xBD, 0xD4, 0xDF, 0xC2, 0xC9, 0xF8, 0xF3, 0xEE, 0xE5, 0x3C, 0x37, 0x2A, 0x21, 0x10, 0x1B, 0x06, 0x0D, 0x64, 0x6F, 0x72, 0x79, 0x48, 0x43, 0x5E, 0x55, 0x01, 0x0A, 0x17, 0x1C, 0x2D, 0x26, 0x3B, 0x30, 0x59, 0x52, 0x4F, 0x44, 0x75, 0x7E, 0x63, 0x68, 0xB1, 0xBA, 0xA7, 0xAC, 0x9D, 0x96, 0x8B, 0x80, 0xE9, 0xE2, 0xFF, 0xF4, 0xC5, 0xCE, 0xD3, 0xD8, 0x7A, 0x71, 0x6C, 0x67, 0x56, 0x5D, 0x40, 0x4B, 0x22, 0x29, 0x34, 0x3F, 0x0E, 0x05, 0x18, 0x13, 0xCA, 0xC1, 0xDC, 0xD7, 0xE6, 0xED, 0xF0, 0xFB, 0x92, 0x99, 0x84, 0x8F, 0xBE, 0xB5, 0xA8, 0xA3 ]; /** * Precomputed lookup of multiplication by 13 in GF(2^8) * @type {!Array.<number>} * @private */ goog.crypt.Aes.MULT_D_ = [ 0x00, 0x0D, 0x1A, 0x17, 0x34, 0x39, 0x2E, 0x23, 0x68, 0x65, 0x72, 0x7F, 0x5C, 0x51, 0x46, 0x4B, 0xD0, 0xDD, 0xCA, 0xC7, 0xE4, 0xE9, 0xFE, 0xF3, 0xB8, 0xB5, 0xA2, 0xAF, 0x8C, 0x81, 0x96, 0x9B, 0xBB, 0xB6, 0xA1, 0xAC, 0x8F, 0x82, 0x95, 0x98, 0xD3, 0xDE, 0xC9, 0xC4, 0xE7, 0xEA, 0xFD, 0xF0, 0x6B, 0x66, 0x71, 0x7C, 0x5F, 0x52, 0x45, 0x48, 0x03, 0x0E, 0x19, 0x14, 0x37, 0x3A, 0x2D, 0x20, 0x6D, 0x60, 0x77, 0x7A, 0x59, 0x54, 0x43, 0x4E, 0x05, 0x08, 0x1F, 0x12, 0x31, 0x3C, 0x2B, 0x26, 0xBD, 0xB0, 0xA7, 0xAA, 0x89, 0x84, 0x93, 0x9E, 0xD5, 0xD8, 0xCF, 0xC2, 0xE1, 0xEC, 0xFB, 0xF6, 0xD6, 0xDB, 0xCC, 0xC1, 0xE2, 0xEF, 0xF8, 0xF5, 0xBE, 0xB3, 0xA4, 0xA9, 0x8A, 0x87, 0x90, 0x9D, 0x06, 0x0B, 0x1C, 0x11, 0x32, 0x3F, 0x28, 0x25, 0x6E, 0x63, 0x74, 0x79, 0x5A, 0x57, 0x40, 0x4D, 0xDA, 0xD7, 0xC0, 0xCD, 0xEE, 0xE3, 0xF4, 0xF9, 0xB2, 0xBF, 0xA8, 0xA5, 0x86, 0x8B, 0x9C, 0x91, 0x0A, 0x07, 0x10, 0x1D, 0x3E, 0x33, 0x24, 0x29, 0x62, 0x6F, 0x78, 0x75, 0x56, 0x5B, 0x4C, 0x41, 0x61, 0x6C, 0x7B, 0x76, 0x55, 0x58, 0x4F, 0x42, 0x09, 0x04, 0x13, 0x1E, 0x3D, 0x30, 0x27, 0x2A, 0xB1, 0xBC, 0xAB, 0xA6, 0x85, 0x88, 0x9F, 0x92, 0xD9, 0xD4, 0xC3, 0xCE, 0xED, 0xE0, 0xF7, 0xFA, 0xB7, 0xBA, 0xAD, 0xA0, 0x83, 0x8E, 0x99, 0x94, 0xDF, 0xD2, 0xC5, 0xC8, 0xEB, 0xE6, 0xF1, 0xFC, 0x67, 0x6A, 0x7D, 0x70, 0x53, 0x5E, 0x49, 0x44, 0x0F, 0x02, 0x15, 0x18, 0x3B, 0x36, 0x21, 0x2C, 0x0C, 0x01, 0x16, 0x1B, 0x38, 0x35, 0x22, 0x2F, 0x64, 0x69, 0x7E, 0x73, 0x50, 0x5D, 0x4A, 0x47, 0xDC, 0xD1, 0xC6, 0xCB, 0xE8, 0xE5, 0xF2, 0xFF, 0xB4, 0xB9, 0xAE, 0xA3, 0x80, 0x8D, 0x9A, 0x97 ]; /** * Precomputed lookup of multiplication by 14 in GF(2^8) * @type {!Array.<number>} * @private */ goog.crypt.Aes.MULT_E_ = [ 0x00, 0x0E, 0x1C, 0x12, 0x38, 0x36, 0x24, 0x2A, 0x70, 0x7E, 0x6C, 0x62, 0x48, 0x46, 0x54, 0x5A, 0xE0, 0xEE, 0xFC, 0xF2, 0xD8, 0xD6, 0xC4, 0xCA, 0x90, 0x9E, 0x8C, 0x82, 0xA8, 0xA6, 0xB4, 0xBA, 0xDB, 0xD5, 0xC7, 0xC9, 0xE3, 0xED, 0xFF, 0xF1, 0xAB, 0xA5, 0xB7, 0xB9, 0x93, 0x9D, 0x8F, 0x81, 0x3B, 0x35, 0x27, 0x29, 0x03, 0x0D, 0x1F, 0x11, 0x4B, 0x45, 0x57, 0x59, 0x73, 0x7D, 0x6F, 0x61, 0xAD, 0xA3, 0xB1, 0xBF, 0x95, 0x9B, 0x89, 0x87, 0xDD, 0xD3, 0xC1, 0xCF, 0xE5, 0xEB, 0xF9, 0xF7, 0x4D, 0x43, 0x51, 0x5F, 0x75, 0x7B, 0x69, 0x67, 0x3D, 0x33, 0x21, 0x2F, 0x05, 0x0B, 0x19, 0x17, 0x76, 0x78, 0x6A, 0x64, 0x4E, 0x40, 0x52, 0x5C, 0x06, 0x08, 0x1A, 0x14, 0x3E, 0x30, 0x22, 0x2C, 0x96, 0x98, 0x8A, 0x84, 0xAE, 0xA0, 0xB2, 0xBC, 0xE6, 0xE8, 0xFA, 0xF4, 0xDE, 0xD0, 0xC2, 0xCC, 0x41, 0x4F, 0x5D, 0x53, 0x79, 0x77, 0x65, 0x6B, 0x31, 0x3F, 0x2D, 0x23, 0x09, 0x07, 0x15, 0x1B, 0xA1, 0xAF, 0xBD, 0xB3, 0x99, 0x97, 0x85, 0x8B, 0xD1, 0xDF, 0xCD, 0xC3, 0xE9, 0xE7, 0xF5, 0xFB, 0x9A, 0x94, 0x86, 0x88, 0xA2, 0xAC, 0xBE, 0xB0, 0xEA, 0xE4, 0xF6, 0xF8, 0xD2, 0xDC, 0xCE, 0xC0, 0x7A, 0x74, 0x66, 0x68, 0x42, 0x4C, 0x5E, 0x50, 0x0A, 0x04, 0x16, 0x18, 0x32, 0x3C, 0x2E, 0x20, 0xEC, 0xE2, 0xF0, 0xFE, 0xD4, 0xDA, 0xC8, 0xC6, 0x9C, 0x92, 0x80, 0x8E, 0xA4, 0xAA, 0xB8, 0xB6, 0x0C, 0x02, 0x10, 0x1E, 0x34, 0x3A, 0x28, 0x26, 0x7C, 0x72, 0x60, 0x6E, 0x44, 0x4A, 0x58, 0x56, 0x37, 0x39, 0x2B, 0x25, 0x0F, 0x01, 0x13, 0x1D, 0x47, 0x49, 0x5B, 0x55, 0x7F, 0x71, 0x63, 0x6D, 0xD7, 0xD9, 0xCB, 0xC5, 0xEF, 0xE1, 0xF3, 0xFD, 0xA7, 0xA9, 0xBB, 0xB5, 0x9F, 0x91, 0x83, 0x8D ];
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Base64 en/decoding. Not much to say here except that we * work with decoded values in arrays of bytes. By "byte" I mean a number * in [0, 255]. * * @author doughtie@google.com (Gavin Doughtie) * @author fschneider@google.com (Fritz Schneider) */ goog.provide('goog.crypt.base64'); goog.require('goog.crypt'); goog.require('goog.userAgent'); // Static lookup maps, lazily populated by init_() /** * Maps bytes to characters. * @type {Object} * @private */ goog.crypt.base64.byteToCharMap_ = null; /** * Maps characters to bytes. * @type {Object} * @private */ goog.crypt.base64.charToByteMap_ = null; /** * Maps bytes to websafe characters. * @type {Object} * @private */ goog.crypt.base64.byteToCharMapWebSafe_ = null; /** * Maps websafe characters to bytes. * @type {Object} * @private */ goog.crypt.base64.charToByteMapWebSafe_ = null; /** * Our default alphabet, shared between * ENCODED_VALS and ENCODED_VALS_WEBSAFE * @type {string} */ goog.crypt.base64.ENCODED_VALS_BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789'; /** * Our default alphabet. Value 64 (=) is special; it means "nothing." * @type {string} */ goog.crypt.base64.ENCODED_VALS = goog.crypt.base64.ENCODED_VALS_BASE + '+/='; /** * Our websafe alphabet. * @type {string} */ goog.crypt.base64.ENCODED_VALS_WEBSAFE = goog.crypt.base64.ENCODED_VALS_BASE + '-_.'; /** * Whether this browser supports the atob and btoa functions. This extension * started at Mozilla but is now implemented by many browsers. We use the * ASSUME_* variables to avoid pulling in the full useragent detection library * but still allowing the standard per-browser compilations. * * @type {boolean} */ goog.crypt.base64.HAS_NATIVE_SUPPORT = goog.userAgent.GECKO || goog.userAgent.WEBKIT || goog.userAgent.OPERA || typeof(goog.global.atob) == 'function'; /** * Base64-encode an array of bytes. * * @param {Array.<number>|Uint8Array} input An array of bytes (numbers with * value in [0, 255]) to encode. * @param {boolean=} opt_webSafe Boolean indicating we should use the * alternative alphabet. * @return {string} The base64 encoded string. */ goog.crypt.base64.encodeByteArray = function(input, opt_webSafe) { if (!goog.isArrayLike(input)) { throw Error('encodeByteArray takes an array as a parameter'); } goog.crypt.base64.init_(); var byteToCharMap = opt_webSafe ? goog.crypt.base64.byteToCharMapWebSafe_ : goog.crypt.base64.byteToCharMap_; var output = []; for (var i = 0; i < input.length; i += 3) { var byte1 = input[i]; var haveByte2 = i + 1 < input.length; var byte2 = haveByte2 ? input[i + 1] : 0; var haveByte3 = i + 2 < input.length; var byte3 = haveByte3 ? input[i + 2] : 0; var outByte1 = byte1 >> 2; var outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4); var outByte3 = ((byte2 & 0x0F) << 2) | (byte3 >> 6); var outByte4 = byte3 & 0x3F; if (!haveByte3) { outByte4 = 64; if (!haveByte2) { outByte3 = 64; } } output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]); } return output.join(''); }; /** * Base64-encode a string. * * @param {string} input A string to encode. * @param {boolean=} opt_webSafe If true, we should use the * alternative alphabet. * @return {string} The base64 encoded string. */ goog.crypt.base64.encodeString = function(input, opt_webSafe) { // Shortcut for Mozilla browsers that implement // a native base64 encoder in the form of "btoa/atob" if (goog.crypt.base64.HAS_NATIVE_SUPPORT && !opt_webSafe) { return goog.global.btoa(input); } return goog.crypt.base64.encodeByteArray( goog.crypt.stringToByteArray(input), opt_webSafe); }; /** * Base64-decode a string. * * @param {string} input to decode. * @param {boolean=} opt_webSafe True if we should use the * alternative alphabet. * @return {string} string representing the decoded value. */ goog.crypt.base64.decodeString = function(input, opt_webSafe) { // Shortcut for Mozilla browsers that implement // a native base64 encoder in the form of "btoa/atob" if (goog.crypt.base64.HAS_NATIVE_SUPPORT && !opt_webSafe) { return goog.global.atob(input); } return goog.crypt.byteArrayToString( goog.crypt.base64.decodeStringToByteArray(input, opt_webSafe)); }; /** * Base64-decode a string. * * @param {string} input to decode (length not required to be a multiple of 4). * @param {boolean=} opt_webSafe True if we should use the * alternative alphabet. * @return {Array} bytes representing the decoded value. */ goog.crypt.base64.decodeStringToByteArray = function(input, opt_webSafe) { goog.crypt.base64.init_(); var charToByteMap = opt_webSafe ? goog.crypt.base64.charToByteMapWebSafe_ : goog.crypt.base64.charToByteMap_; var output = []; for (var i = 0; i < input.length; ) { var byte1 = charToByteMap[input.charAt(i++)]; var haveByte2 = i < input.length; var byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0; ++i; var haveByte3 = i < input.length; var byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 0; ++i; var haveByte4 = i < input.length; var byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 0; ++i; if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) { throw Error(); } var outByte1 = (byte1 << 2) | (byte2 >> 4); output.push(outByte1); if (byte3 != 64) { var outByte2 = ((byte2 << 4) & 0xF0) | (byte3 >> 2); output.push(outByte2); if (byte4 != 64) { var outByte3 = ((byte3 << 6) & 0xC0) | byte4; output.push(outByte3); } } } return output; }; /** * Lazy static initialization function. Called before * accessing any of the static map variables. * @private */ goog.crypt.base64.init_ = function() { if (!goog.crypt.base64.byteToCharMap_) { goog.crypt.base64.byteToCharMap_ = {}; goog.crypt.base64.charToByteMap_ = {}; goog.crypt.base64.byteToCharMapWebSafe_ = {}; goog.crypt.base64.charToByteMapWebSafe_ = {}; // We want quick mappings back and forth, so we precompute two maps. for (var i = 0; i < goog.crypt.base64.ENCODED_VALS.length; i++) { goog.crypt.base64.byteToCharMap_[i] = goog.crypt.base64.ENCODED_VALS.charAt(i); goog.crypt.base64.charToByteMap_[goog.crypt.base64.byteToCharMap_[i]] = i; goog.crypt.base64.byteToCharMapWebSafe_[i] = goog.crypt.base64.ENCODED_VALS_WEBSAFE.charAt(i); goog.crypt.base64.charToByteMapWebSafe_[ goog.crypt.base64.byteToCharMapWebSafe_[i]] = i; } } };
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Abstract cryptographic hash interface. * * See goog.crypt.Sha1 and goog.crypt.Md5 for sample implementations. * */ goog.provide('goog.crypt.Hash'); /** * Create a cryptographic hash instance. * * @constructor */ goog.crypt.Hash = function() {}; /** * Resets the internal accumulator. */ goog.crypt.Hash.prototype.reset = goog.abstractMethod; /** * Adds a byte array (array with values in [0-255] range) or a string (might * only contain 8-bit, i.e., Latin1 characters) to the internal accumulator. * * Many hash functions operate on blocks of data and implement optimizations * when a full chunk of data is readily available. Hence it is often preferable * to provide large chunks of data (a kilobyte or more) than to repeatedly * call the update method with few tens of bytes. If this is not possible, or * not feasible, it might be good to provide data in multiplies of hash block * size (often 64 bytes). Please see the implementation and performance tests * of your favourite hash. * * @param {Array.<number>|Uint8Array|string} bytes Data used for the update. * @param {number=} opt_length Number of bytes to use. */ goog.crypt.Hash.prototype.update = goog.abstractMethod; /** * @return {!Array.<number>} The finalized hash computed * from the internal accumulator. */ goog.crypt.Hash.prototype.digest = goog.abstractMethod;
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Asynchronous hash computer for the Blob interface. * * The Blob interface, part of the HTML5 File API, is supported on Chrome 7+, * Firefox 4.0 and Opera 11. No Blob interface implementation is expected on * Internet Explorer 10. Chrome 11, Firefox 5.0 and the subsequent release of * Opera are supposed to use vendor prefixes due to evolving API, see * http://dev.w3.org/2006/webapi/FileAPI/ for details. * * This implementation currently uses upcoming Chrome and Firefox prefixes, * plus the original Blob.slice specification, as implemented on Chrome 10 * and Firefox 4.0. * */ goog.provide('goog.crypt.BlobHasher'); goog.provide('goog.crypt.BlobHasher.EventType'); goog.require('goog.asserts'); goog.require('goog.crypt'); goog.require('goog.crypt.Hash'); goog.require('goog.debug.Logger'); goog.require('goog.events.EventTarget'); goog.require('goog.fs'); /** * Construct the hash computer. * * @param {!goog.crypt.Hash} hashFn The hash function to use. * @param {number=} opt_blockSize Processing block size. * @constructor * @extends {goog.events.EventTarget} */ goog.crypt.BlobHasher = function(hashFn, opt_blockSize) { goog.base(this); /** * The actual hash function. * @type {!goog.crypt.Hash} * @private */ this.hashFn_ = hashFn; /** * The blob being processed. * @type {Blob} * @private */ this.blob_ = null; /** * Computed hash value. * @type {Array.<number>} * @private */ this.hashVal_ = null; /** * Number of bytes already processed. * @type {number} * @private */ this.bytesProcessed_ = 0; /** * Processing block size. * @type {number} * @private */ this.blockSize_ = opt_blockSize || 5000000; /** * File reader object. * @type {FileReader} * @private */ this.fileReader_ = null; /** * The logger used by this object. * @type {!goog.debug.Logger} * @private */ this.logger_ = goog.debug.Logger.getLogger('goog.crypt.BlobHasher'); }; goog.inherits(goog.crypt.BlobHasher, goog.events.EventTarget); /** * Event names for hash computation events * @enum {string} */ goog.crypt.BlobHasher.EventType = { STARTED: 'started', PROGRESS: 'progress', COMPLETE: 'complete', ABORT: 'abort', ERROR: 'error' }; /** * Start the hash computation. * @param {!Blob} blob The blob of data to compute the hash for. */ goog.crypt.BlobHasher.prototype.hash = function(blob) { this.abort(); this.hashFn_.reset(); this.blob_ = blob; this.hashVal_ = null; this.bytesProcessed_ = 0; this.dispatchEvent(goog.crypt.BlobHasher.EventType.STARTED); this.processNextBlock_(); }; /** * Abort hash computation. */ goog.crypt.BlobHasher.prototype.abort = function() { if (this.fileReader_ && this.fileReader_.readyState != this.fileReader_.DONE) { this.fileReader_.abort(); } }; /** * @return {number} Number of bytes processed so far. */ goog.crypt.BlobHasher.prototype.getBytesProcessed = function() { return this.bytesProcessed_; }; /** * @return {Array.<number>} The computed hash value or null if not ready. */ goog.crypt.BlobHasher.prototype.getHash = function() { return this.hashVal_; }; /** * Helper function setting up the processing for the next block, or finalizing * the computation if all blocks were processed. * @private */ goog.crypt.BlobHasher.prototype.processNextBlock_ = function() { goog.asserts.assert(this.blob_, 'The blob has disappeared during processing'); if (this.bytesProcessed_ < this.blob_.size) { // We have to reset the FileReader every time, otherwise it fails on // Chrome, including the latest Chrome 12 beta. // http://code.google.com/p/chromium/issues/detail?id=82346 this.fileReader_ = new FileReader(); this.fileReader_.onload = goog.bind(this.onLoad_, this); this.fileReader_.onabort = goog.bind(this.dispatchEvent, this, goog.crypt.BlobHasher.EventType.ABORT); this.fileReader_.onerror = goog.bind(this.dispatchEvent, this, goog.crypt.BlobHasher.EventType.ERROR); var size = Math.min(this.blob_.size - this.bytesProcessed_, this.blockSize_); var chunk = goog.fs.sliceBlob(this.blob_, this.bytesProcessed_, this.bytesProcessed_ + size); if (!chunk || chunk.size != size) { this.logger_.severe('Failed slicing the blob'); this.dispatchEvent(goog.crypt.BlobHasher.EventType.ERROR); return; } if (this.fileReader_.readAsArrayBuffer) { this.fileReader_.readAsArrayBuffer(chunk); } else if (this.fileReader_.readAsBinaryString) { this.fileReader_.readAsBinaryString(chunk); } else { this.logger_.severe('Failed calling the chunk reader'); this.dispatchEvent(goog.crypt.BlobHasher.EventType.ERROR); } } else { this.hashVal_ = this.hashFn_.digest(); this.dispatchEvent(goog.crypt.BlobHasher.EventType.COMPLETE); } }; /** * Handle processing block loaded. * @private */ goog.crypt.BlobHasher.prototype.onLoad_ = function() { this.logger_.info('Successfully loaded a chunk'); var array = null; if (this.fileReader_.result instanceof Array || goog.isString(this.fileReader_.result)) { array = this.fileReader_.result; } else if (goog.global['ArrayBuffer'] && goog.global['Uint8Array'] && this.fileReader_.result instanceof ArrayBuffer) { array = new Uint8Array(this.fileReader_.result); } if (!array) { this.logger_.severe('Failed reading the chunk'); this.dispatchEvent(goog.crypt.BlobHasher.EventType.ERROR); return; } this.hashFn_.update(array); this.bytesProcessed_ += array.length; this.dispatchEvent(goog.crypt.BlobHasher.EventType.PROGRESS); this.processNextBlock_(); };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Implementation of CBC mode for block ciphers. See * http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation * #Cipher-block_chaining_.28CBC.29. for description. * * @author nnaze@google.com (Nathan Naze) */ goog.provide('goog.crypt.Cbc'); goog.require('goog.array'); goog.require('goog.crypt'); /** * Implements the CBC mode for block ciphers. See * http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation * #Cipher-block_chaining_.28CBC.29 * * @param {!goog.crypt.BlockCipher} cipher The block cipher to use. * @param {number=} opt_blockSize The block size of the cipher in bytes. * Defaults to 16 bytes. * @constructor */ goog.crypt.Cbc = function(cipher, opt_blockSize) { /** * Block cipher. * @type {!goog.crypt.BlockCipher} * @private */ this.cipher_ = cipher; /** * Block size in bytes. * @type {number} * @private */ this.blockSize_ = opt_blockSize || 16; }; /** * Encrypt a message. * * @param {!Array.<number>} plainText Message to encrypt. An array of bytes. * The length should be a multiple of the block size. * @param {!Array.<number>} initialVector Initial vector for the CBC mode. * An array of bytes with the same length as the block size. * @return {!Array.<number>} Encrypted message. */ goog.crypt.Cbc.prototype.encrypt = function(plainText, initialVector) { goog.asserts.assert( plainText.length % this.blockSize_ == 0, 'Data\'s length must be multiple of block size.'); goog.asserts.assert( initialVector.length == this.blockSize_, 'Initial vector must be size of one block.'); // Implementation of // http://en.wikipedia.org/wiki/File:Cbc_encryption.png var cipherText = []; var vector = initialVector; // Generate each block of the encrypted cypher text. for (var blockStartIndex = 0; blockStartIndex < plainText.length; blockStartIndex += this.blockSize_) { // Takes one block from the input message. var plainTextBlock = goog.array.slice( plainText, blockStartIndex, blockStartIndex + this.blockSize_); var input = goog.crypt.xorByteArray(plainTextBlock, vector); var resultBlock = this.cipher_.encrypt(input); goog.array.extend(cipherText, resultBlock); vector = resultBlock; } return cipherText; }; /** * Decrypt a message. * * @param {!Array.<number>} cipherText Message to decrypt. An array of bytes. * The length should be a multiple of the block size. * @param {!Array.<number>} initialVector Initial vector for the CBC mode. * An array of bytes with the same length as the block size. * @return {!Array.<number>} Decrypted message. */ goog.crypt.Cbc.prototype.decrypt = function(cipherText, initialVector) { goog.asserts.assert( cipherText.length % this.blockSize_ == 0, 'Data\'s length must be multiple of block size.'); goog.asserts.assert( initialVector.length == this.blockSize_, 'Initial vector must be size of one block.'); // Implementation of // http://en.wikipedia.org/wiki/File:Cbc_decryption.png var plainText = []; var blockStartIndex = 0; var vector = initialVector; // Generate each block of the decrypted plain text. while (blockStartIndex < cipherText.length) { // Takes one block. var cipherTextBlock = goog.array.slice( cipherText, blockStartIndex, blockStartIndex + this.blockSize_); var resultBlock = this.cipher_.decrypt(cipherTextBlock); var plainTextBlock = goog.crypt.xorByteArray(vector, resultBlock); goog.array.extend(plainText, plainTextBlock); vector = cipherTextBlock; blockStartIndex += this.blockSize_; } return plainText; };
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Implementation of HMAC in JavaScript. * * Usage: * var hmac = new goog.crypt.Hmac(new goog.crypt.sha1(), key, 64); * var digest = hmac.getHmac(bytes); * */ goog.provide('goog.crypt.Hmac'); goog.require('goog.asserts'); goog.require('goog.crypt.Hash'); /** * @constructor * @param {!goog.crypt.Hash} hasher An object to serve as a hash function. * @param {Array.<number>} key The secret key to use to calculate the hmac. * Should be an array of not more than {@code blockSize} integers in {0, 255}. * @param {number=} opt_blockSize Optional. The block size {@code hasher} uses. * If not specified, 16. * @extends {goog.crypt.Hash} */ goog.crypt.Hmac = function(hasher, key, opt_blockSize) { goog.base(this); /** * The underlying hasher to calculate hash. * * @type {!goog.crypt.Hash} * @private */ this.hasher_ = hasher; /** * The block size. * * @type {number} * @private */ this.blockSize_ = opt_blockSize || 16; /** * The outer padding array of hmac * * @type {!Array.<number>} * @private */ this.keyO_ = new Array(this.blockSize_); /** * The inner padding array of hmac * * @type {!Array.<number>} * @private */ this.keyI_ = new Array(this.blockSize_); this.initialize_(key); }; goog.inherits(goog.crypt.Hmac, goog.crypt.Hash); /** * Outer padding byte of HMAC algorith, per http://en.wikipedia.org/wiki/HMAC * * @type {number} * @private */ goog.crypt.Hmac.OPAD_ = 0x5c; /** * Inner padding byte of HMAC algorith, per http://en.wikipedia.org/wiki/HMAC * * @type {number} * @private */ goog.crypt.Hmac.IPAD_ = 0x36; /** * Initializes Hmac by precalculating the inner and outer paddings. * * @param {Array.<number>} key The secret key to use to calculate the hmac. * Should be an array of not more than {@code blockSize} integers in {0, 255}. * @private */ goog.crypt.Hmac.prototype.initialize_ = function(key) { if (key.length > this.blockSize_) { this.hasher_.update(key); key = this.hasher_.digest(); } // Precalculate padded and xor'd keys. var keyByte; for (var i = 0; i < this.blockSize_; i++) { if (i < key.length) { keyByte = key[i]; } else { keyByte = 0; } this.keyO_[i] = keyByte ^ goog.crypt.Hmac.OPAD_; this.keyI_[i] = keyByte ^ goog.crypt.Hmac.IPAD_; } // Be ready for an immediate update. this.hasher_.update(this.keyI_); }; /** @override */ goog.crypt.Hmac.prototype.reset = function() { this.hasher_.reset(); this.hasher_.update(this.keyI_); }; /** @override */ goog.crypt.Hmac.prototype.update = function(bytes, opt_length) { this.hasher_.update(bytes, opt_length); }; /** @override */ goog.crypt.Hmac.prototype.digest = function() { var temp = this.hasher_.digest(); this.hasher_.reset(); this.hasher_.update(this.keyO_); this.hasher_.update(temp); return this.hasher_.digest(); }; /** * Calculates an HMAC for a given message. * * @param {Array.<number>} message An array of integers in {0, 255}. * @return {!Array.<number>} the digest of the given message. */ goog.crypt.Hmac.prototype.getHmac = function(message) { this.reset(); this.update(message); return this.digest(); };
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for the abstract cryptographic hash interface. * */ goog.provide('goog.crypt.hashTester'); goog.require('goog.array'); goog.require('goog.crypt'); goog.require('goog.testing.PerformanceTable'); goog.require('goog.testing.PseudoRandom'); goog.require('goog.testing.asserts'); goog.setTestOnly('hashTester'); /** * Runs basic tests. * * @param {!goog.crypt.Hash} hash A hash instance. */ goog.crypt.hashTester.runBasicTests = function(hash) { // Compute first hash. hash.update([97, 158]); var golden1 = hash.digest(); // Compute second hash. hash.reset(); hash.update('aB'); var golden2 = hash.digest(); assertTrue('Two different inputs resulted in a hash collision', !!goog.testing.asserts.findDifferences(golden1, golden2)); // Empty hash. hash.reset(); var empty = hash.digest(); assertTrue('Empty hash collided with a non-trivial one', !!goog.testing.asserts.findDifferences(golden1, empty) && !!goog.testing.asserts.findDifferences(golden2, empty)); // Zero-length array update. hash.reset(); hash.update([]); assertArrayEquals('Updating with an empty array did not give an empty hash', empty, hash.digest()); // Zero-length string update. hash.reset(); hash.update(''); assertArrayEquals('Updating with an empty string did not give an empty hash', empty, hash.digest()); // Recompute the first hash. hash.reset(); hash.update([97, 158]); assertArrayEquals('The reset did not produce the initial state', golden1, hash.digest()); // Check for a trivial collision. hash.reset(); hash.update([158, 97]); assertTrue('Swapping bytes resulted in a hash collision', !!goog.testing.asserts.findDifferences(golden1, hash.digest())); // Compare array and string input. hash.reset(); hash.update([97, 66]); assertArrayEquals('String and array inputs should give the same result', golden2, hash.digest()); // Compute in parts. hash.reset(); hash.update('a'); hash.update([158]); assertArrayEquals('Partial updates resulted in a different hash', golden1, hash.digest()); // Test update with specified length. hash.reset(); hash.update('aB', 0); hash.update([97, 158, 32], 2); assertArrayEquals('Updating with an explicit buffer length did not work', golden1, hash.digest()); }; /** * Runs block tests. * * @param {!goog.crypt.Hash} hash A hash instance. * @param {number} blockBytes Size of the hash block. */ goog.crypt.hashTester.runBlockTests = function(hash, blockBytes) { // Compute a message which is 1 byte shorter than hash block size. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var message = ''; for (var i = 0; i < blockBytes - 1; i++) { message += chars.charAt(i % chars.length); } // Compute golden hash for 1 block + 2 bytes. hash.update(message + '123'); var golden1 = hash.digest(); // Compute golden hash for 2 blocks + 1 byte. hash.reset(); hash.update(message + message + '123'); var golden2 = hash.digest(); // Almost fill a block, then overflow. hash.reset(); hash.update(message); hash.update('123'); assertArrayEquals(golden1, hash.digest()); // Fill a block. hash.reset(); hash.update(message + '1'); hash.update('23'); assertArrayEquals(golden1, hash.digest()); // Overflow a block. hash.reset(); hash.update(message + '12'); hash.update('3'); assertArrayEquals(golden1, hash.digest()); // Test single overflow with an array. hash.reset(); hash.update(goog.crypt.stringToByteArray(message + '123')); assertArrayEquals(golden1, hash.digest()); // Almost fill a block, then overflow this and the next block. hash.reset(); hash.update(message); hash.update(message + '123'); assertArrayEquals(golden2, hash.digest()); // Fill two blocks. hash.reset(); hash.update(message + message + '12'); hash.update('3'); assertArrayEquals(golden2, hash.digest()); // Test double overflow with an array. hash.reset(); hash.update(goog.crypt.stringToByteArray(message)); hash.update(goog.crypt.stringToByteArray(message + '123')); assertArrayEquals(golden2, hash.digest()); }; /** * Runs performance tests. * * @param {function():!goog.crypt.Hash} hashFactory A hash factory. * @param {string} hashName Name of the hashing function. */ goog.crypt.hashTester.runPerfTests = function(hashFactory, hashName) { var body = goog.dom.getDocument().body; var perfTable = goog.dom.createElement('div'); goog.dom.appendChild(body, perfTable); var table = new goog.testing.PerformanceTable(perfTable); function runPerfTest(byteLength, updateCount) { var label = (hashName + ': ' + updateCount + ' update(s) of ' + byteLength + ' bytes'); function run(data, dataType) { table.run(function() { var hash = hashFactory(); for (var i = 0; i < updateCount; i++) { hash.update(data, byteLength); } var digest = hash.digest(); }, label + ' (' + dataType + ')'); } var byteArray = goog.crypt.hashTester.createRandomByteArray_(byteLength); var byteString = goog.crypt.hashTester.createByteString_(byteArray); run(byteArray, 'byte array'); run(byteString, 'byte string'); } var MESSAGE_LENGTH_LONG = 10000000; // 10 Mbytes var MESSAGE_LENGTH_SHORT = 10; // 10 bytes var MESSAGE_COUNT_SHORT = MESSAGE_LENGTH_LONG / MESSAGE_LENGTH_SHORT; runPerfTest(MESSAGE_LENGTH_LONG, 1); runPerfTest(MESSAGE_LENGTH_SHORT, MESSAGE_COUNT_SHORT); }; /** * Creates and returns a random byte array. * * @param {number} length Length of the byte array. * @return {!Array.<number>} An array of bytes. * @private */ goog.crypt.hashTester.createRandomByteArray_ = function(length) { var random = new goog.testing.PseudoRandom(0); var bytes = []; for (var i = 0; i < length; ++i) { // Generates an integer from 0 to 255. var b = Math.floor(random.random() * 0x100); bytes.push(b); } return bytes; }; /** * Creates a string from an array of bytes. * * @param {!Array.<number>} bytes An array of bytes. * @return {string} The string encoded by the bytes. * @private */ goog.crypt.hashTester.createByteString_ = function(bytes) { var str = ''; goog.array.forEach(bytes, function(b) { str += String.fromCharCode(b); }); return str; };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview SHA-256 cryptographic hash. * * Usage: * var sha256 = new goog.crypt.Sha256(); * sha256.update(bytes); * var hash = sha256.digest(); * */ goog.provide('goog.crypt.Sha256'); goog.require('goog.crypt.Sha2'); /** * SHA-256 cryptographic hash constructor. * * @constructor * @extends {goog.crypt.Sha2} */ goog.crypt.Sha256 = function() { goog.base(this); }; goog.inherits(goog.crypt.Sha256, goog.crypt.Sha2); /** @override */ goog.crypt.Sha256.prototype.reset = function() { this.chunk = []; this.inChunk = 0; this.total = 0; this.hash = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]; this.numHashBlocks = 8; };
JavaScript
// Copyright 2005 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview SHA-1 cryptographic hash. * Variable names follow the notation in FIPS PUB 180-3: * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf. * * Usage: * var sha1 = new goog.crypt.sha1(); * sha1.update(bytes); * var hash = sha1.digest(); * * Performance: * Chrome 23: ~400 Mbit/s * Firefox 16: ~250 Mbit/s * */ goog.provide('goog.crypt.Sha1'); goog.require('goog.crypt.Hash'); /** * SHA-1 cryptographic hash constructor. * * The properties declared here are discussed in the above algorithm document. * @constructor * @extends {goog.crypt.Hash} */ goog.crypt.Sha1 = function() { goog.base(this); /** * Holds the previous values of accumulated variables a-e in the compress_ * function. * @type {Array.<number>} * @private */ this.chain_ = []; /** * A buffer holding the partially computed hash result. * @type {Array.<number>} * @private */ this.buf_ = []; /** * An array of 80 bytes, each a part of the message to be hashed. Referred to * as the message schedule in the docs. * @type {Array.<number>} * @private */ this.W_ = []; /** * Contains data needed to pad messages less than 64 bytes. * @type {Array.<number>} * @private */ this.pad_ = []; this.pad_[0] = 128; for (var i = 1; i < 64; ++i) { this.pad_[i] = 0; } this.reset(); }; goog.inherits(goog.crypt.Sha1, goog.crypt.Hash); /** @override */ goog.crypt.Sha1.prototype.reset = function() { this.chain_[0] = 0x67452301; this.chain_[1] = 0xefcdab89; this.chain_[2] = 0x98badcfe; this.chain_[3] = 0x10325476; this.chain_[4] = 0xc3d2e1f0; this.inbuf_ = 0; this.total_ = 0; }; /** * Internal compress helper function. * @param {Array.<number>|Uint8Array|string} buf Block to compress. * @param {number=} opt_offset Offset of the block in the buffer. * @private */ goog.crypt.Sha1.prototype.compress_ = function(buf, opt_offset) { if (!opt_offset) { opt_offset = 0; } var W = this.W_; // get 16 big endian words if (goog.isString(buf)) { for (var i = 0; i < 16; i++) { // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS // have a bug that turns the post-increment ++ operator into pre-increment // during JIT compilation. We have code that depends heavily on SHA-1 for // correctness and which is affected by this bug, so I've removed all uses // of post-increment ++ in which the result value is used. We can revert // this change once the Safari bug // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and // most clients have been updated. W[i] = (buf.charCodeAt(opt_offset) << 24) | (buf.charCodeAt(opt_offset + 1) << 16) | (buf.charCodeAt(opt_offset + 2) << 8) | (buf.charCodeAt(opt_offset + 3)); opt_offset += 4; } } else { for (var i = 0; i < 16; i++) { W[i] = (buf[opt_offset] << 24) | (buf[opt_offset + 1] << 16) | (buf[opt_offset + 2] << 8) | (buf[opt_offset + 3]); opt_offset += 4; } } // expand to 80 words for (var i = 16; i < 80; i++) { var t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff; } var a = this.chain_[0]; var b = this.chain_[1]; var c = this.chain_[2]; var d = this.chain_[3]; var e = this.chain_[4]; var f, k; // TODO(user): Try to unroll this loop to speed up the computation. for (var i = 0; i < 80; i++) { if (i < 40) { if (i < 20) { f = d ^ (b & (c ^ d)); k = 0x5a827999; } else { f = b ^ c ^ d; k = 0x6ed9eba1; } } else { if (i < 60) { f = (b & c) | (d & (b | c)); k = 0x8f1bbcdc; } else { f = b ^ c ^ d; k = 0xca62c1d6; } } var t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff; e = d; d = c; c = ((b << 30) | (b >>> 2)) & 0xffffffff; b = a; a = t; } this.chain_[0] = (this.chain_[0] + a) & 0xffffffff; this.chain_[1] = (this.chain_[1] + b) & 0xffffffff; this.chain_[2] = (this.chain_[2] + c) & 0xffffffff; this.chain_[3] = (this.chain_[3] + d) & 0xffffffff; this.chain_[4] = (this.chain_[4] + e) & 0xffffffff; }; /** @override */ goog.crypt.Sha1.prototype.update = function(bytes, opt_length) { if (!goog.isDef(opt_length)) { opt_length = bytes.length; } var lengthMinusBlock = opt_length - 64; var n = 0; // Using local instead of member variables gives ~5% speedup on Firefox 16. var buf = this.buf_; var inbuf = this.inbuf_; // The outer while loop should execute at most twice. while (n < opt_length) { // When we have no data in the block to top up, we can directly process the // input buffer (assuming it contains sufficient data). This gives ~25% // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that // the data is provided in large chunks (or in multiples of 64 bytes). if (inbuf == 0) { while (n <= lengthMinusBlock) { this.compress_(bytes, n); n += 64; } } if (goog.isString(bytes)) { while (n < opt_length) { buf[inbuf] = bytes.charCodeAt(n); ++inbuf; ++n; if (inbuf == 64) { this.compress_(buf); inbuf = 0; // Jump to the outer loop so we use the full-block optimization. break; } } } else { while (n < opt_length) { buf[inbuf] = bytes[n]; ++inbuf; ++n; if (inbuf == 64) { this.compress_(buf); inbuf = 0; // Jump to the outer loop so we use the full-block optimization. break; } } } } this.inbuf_ = inbuf; this.total_ += opt_length; }; /** @override */ goog.crypt.Sha1.prototype.digest = function() { var digest = []; var totalBits = this.total_ * 8; // Add pad 0x80 0x00*. if (this.inbuf_ < 56) { this.update(this.pad_, 56 - this.inbuf_); } else { this.update(this.pad_, 64 - (this.inbuf_ - 56)); } // Add # bits. for (var i = 63; i >= 56; i--) { this.buf_[i] = totalBits & 255; totalBits /= 256; // Don't use bit-shifting here! } this.compress_(this.buf_); var n = 0; for (var i = 0; i < 5; i++) { for (var j = 24; j >= 0; j -= 8) { digest[n] = (this.chain_[i] >> j) & 255; ++n; } } return digest; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Implementation of 32-bit hashing functions. * * This is a direct port from the Google Java Hash class * */ goog.provide('goog.crypt.hash32'); goog.require('goog.crypt'); /** * Default seed used during hashing, digits of pie. * See SEED32 in http://go/base.hash.java * @type {number} */ goog.crypt.hash32.SEED32 = 314159265; /** * Arbitrary constant used during hashing. * See CONSTANT32 in http://go/base.hash.java * @type {number} */ goog.crypt.hash32.CONSTANT32 = -1640531527; /** * Hashes a string to a 32-bit value. * @param {string} str String to hash. * @return {number} 32-bit hash. */ goog.crypt.hash32.encodeString = function(str) { return goog.crypt.hash32.encodeByteArray(goog.crypt.stringToByteArray(str)); }; /** * Hashes a string to a 32-bit value, converting the string to UTF-8 before * doing the encoding. * @param {string} str String to hash. * @return {number} 32-bit hash. */ goog.crypt.hash32.encodeStringUtf8 = function(str) { return goog.crypt.hash32.encodeByteArray( goog.crypt.stringToUtf8ByteArray(str)); }; /** * Hashes an integer to a 32-bit value. * @param {number} value Number to hash. * @return {number} 32-bit hash. */ goog.crypt.hash32.encodeInteger = function(value) { // TODO(user): Does this make sense in JavaScript with doubles? Should we // force the value to be in the correct range? return goog.crypt.hash32.mix32_({ a: value, b: goog.crypt.hash32.CONSTANT32, c: goog.crypt.hash32.SEED32 }); }; /** * Hashes a "byte" array to a 32-bit value using the supplied seed. * @param {Array.<number>} bytes Array of bytes. * @param {number=} opt_offset The starting position to use for hash * computation. * @param {number=} opt_length Number of bytes that are used for hashing. * @param {number=} opt_seed The seed. * @return {number} 32-bit hash. */ goog.crypt.hash32.encodeByteArray = function( bytes, opt_offset, opt_length, opt_seed) { var offset = opt_offset || 0; var length = opt_length || bytes.length; var seed = opt_seed || goog.crypt.hash32.SEED32; var mix = { a: goog.crypt.hash32.CONSTANT32, b: goog.crypt.hash32.CONSTANT32, c: seed }; var keylen; for (keylen = length; keylen >= 12; keylen -= 12, offset += 12) { mix.a += goog.crypt.hash32.wordAt_(bytes, offset); mix.b += goog.crypt.hash32.wordAt_(bytes, offset + 4); mix.c += goog.crypt.hash32.wordAt_(bytes, offset + 8); goog.crypt.hash32.mix32_(mix); } // Hash any remaining bytes mix.c += length; switch (keylen) { // deal with rest. Some cases fall through case 11: mix.c += (bytes[offset + 10]) << 24; case 10: mix.c += (bytes[offset + 9] & 0xff) << 16; case 9 : mix.c += (bytes[offset + 8] & 0xff) << 8; // the first byte of c is reserved for the length case 8 : mix.b += goog.crypt.hash32.wordAt_(bytes, offset + 4); mix.a += goog.crypt.hash32.wordAt_(bytes, offset); break; case 7 : mix.b += (bytes[offset + 6] & 0xff) << 16; case 6 : mix.b += (bytes[offset + 5] & 0xff) << 8; case 5 : mix.b += (bytes[offset + 4] & 0xff); case 4 : mix.a += goog.crypt.hash32.wordAt_(bytes, offset); break; case 3 : mix.a += (bytes[offset + 2] & 0xff) << 16; case 2 : mix.a += (bytes[offset + 1] & 0xff) << 8; case 1 : mix.a += (bytes[offset + 0] & 0xff); // case 0 : nothing left to add } return goog.crypt.hash32.mix32_(mix); }; /** * Performs an inplace mix of an object with the integer properties (a, b, c) * and returns the final value of c. * @param {Object} mix Object with properties, a, b, and c. * @return {number} The end c-value for the mixing. * @private */ goog.crypt.hash32.mix32_ = function(mix) { var a = mix.a, b = mix.b, c = mix.c; a -= b; a -= c; a ^= c >>> 13; b -= c; b -= a; b ^= a << 8; c -= a; c -= b; c ^= b >>> 13; a -= b; a -= c; a ^= c >>> 12; b -= c; b -= a; b ^= a << 16; c -= a; c -= b; c ^= b >>> 5; a -= b; a -= c; a ^= c >>> 3; b -= c; b -= a; b ^= a << 10; c -= a; c -= b; c ^= b >>> 15; mix.a = a; mix.b = b; mix.c = c; return c; }; /** * Returns the word at a given offset. Treating an array of bytes a word at a * time is far more efficient than byte-by-byte. * @param {Array.<number>} bytes Array of bytes. * @param {number} offset Offset in the byte array. * @return {number} Integer value for the word. * @private */ goog.crypt.hash32.wordAt_ = function(bytes, offset) { var a = goog.crypt.hash32.toSigned_(bytes[offset + 0]); var b = goog.crypt.hash32.toSigned_(bytes[offset + 1]); var c = goog.crypt.hash32.toSigned_(bytes[offset + 2]); var d = goog.crypt.hash32.toSigned_(bytes[offset + 3]); return a + (b << 8) + (c << 16) + (d << 24); }; /** * Converts an unsigned "byte" to signed, that is, convert a value in the range * (0, 2^8-1) to (-2^7, 2^7-1) in order to be compatible with Java's byte type. * @param {number} n Unsigned "byte" value. * @return {number} Signed "byte" value. * @private */ goog.crypt.hash32.toSigned_ = function(n) { return n > 127 ? n - 256 : n; };
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview MD5 cryptographic hash. * Implementation of http://tools.ietf.org/html/rfc1321 with common * optimizations and tweaks (see http://en.wikipedia.org/wiki/MD5). * * Usage: * var md5 = new goog.crypt.Md5(); * md5.update(bytes); * var hash = md5.digest(); * * Performance: * Chrome 23 ~680 Mbit/s * Chrome 13 (in a VM) ~250 Mbit/s * Firefox 6.0 (in a VM) ~100 Mbit/s * IE9 (in a VM) ~27 Mbit/s * Firefox 3.6 ~15 Mbit/s * IE8 (in a VM) ~13 Mbit/s * */ goog.provide('goog.crypt.Md5'); goog.require('goog.crypt.Hash'); /** * MD5 cryptographic hash constructor. * @constructor * @extends {goog.crypt.Hash} */ goog.crypt.Md5 = function() { goog.base(this); /** * Holds the current values of accumulated A-D variables (MD buffer). * @type {Array.<number>} * @private */ this.chain_ = new Array(4); /** * A buffer holding the data until the whole block can be processed. * @type {Array.<number>} * @private */ this.block_ = new Array(64); /** * The length of yet-unprocessed data as collected in the block. * @type {number} * @private */ this.blockLength_ = 0; /** * The total length of the message so far. * @type {number} * @private */ this.totalLength_ = 0; this.reset(); }; goog.inherits(goog.crypt.Md5, goog.crypt.Hash); /** * Integer rotation constants used by the abbreviated implementation. * They are hardcoded in the unrolled implementation, so it is left * here commented out. * @type {Array.<number>} * @private * goog.crypt.Md5.S_ = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 ]; */ /** * Sine function constants used by the abbreviated implementation. * They are hardcoded in the unrolled implementation, so it is left * here commented out. * @type {Array.<number>} * @private * goog.crypt.Md5.T_ = [ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 ]; */ /** @override */ goog.crypt.Md5.prototype.reset = function() { this.chain_[0] = 0x67452301; this.chain_[1] = 0xefcdab89; this.chain_[2] = 0x98badcfe; this.chain_[3] = 0x10325476; this.blockLength_ = 0; this.totalLength_ = 0; }; /** * Internal compress helper function. It takes a block of data (64 bytes) * and updates the accumulator. * @param {Array.<number>|Uint8Array|string} buf The block to compress. * @param {number=} opt_offset Offset of the block in the buffer. * @private */ goog.crypt.Md5.prototype.compress_ = function(buf, opt_offset) { if (!opt_offset) { opt_offset = 0; } // We allocate the array every time, but it's cheap in practice. var X = new Array(16); // Get 16 little endian words. It is not worth unrolling this for Chrome 11. if (goog.isString(buf)) { for (var i = 0; i < 16; ++i) { X[i] = (buf.charCodeAt(opt_offset++)) | (buf.charCodeAt(opt_offset++) << 8) | (buf.charCodeAt(opt_offset++) << 16) | (buf.charCodeAt(opt_offset++) << 24); } } else { for (var i = 0; i < 16; ++i) { X[i] = (buf[opt_offset++]) | (buf[opt_offset++] << 8) | (buf[opt_offset++] << 16) | (buf[opt_offset++] << 24); } } var A = this.chain_[0]; var B = this.chain_[1]; var C = this.chain_[2]; var D = this.chain_[3]; var sum = 0; /* * This is an abbreviated implementation, it is left here commented out for * reference purposes. See below for an unrolled version in use. * var f, n, tmp; for (var i = 0; i < 64; ++i) { if (i < 16) { f = (D ^ (B & (C ^ D))); n = i; } else if (i < 32) { f = (C ^ (D & (B ^ C))); n = (5 * i + 1) % 16; } else if (i < 48) { f = (B ^ C ^ D); n = (3 * i + 5) % 16; } else { f = (C ^ (B | (~D))); n = (7 * i) % 16; } tmp = D; D = C; C = B; sum = (A + f + goog.crypt.Md5.T_[i] + X[n]) & 0xffffffff; B += ((sum << goog.crypt.Md5.S_[i]) & 0xffffffff) | (sum >>> (32 - goog.crypt.Md5.S_[i])); A = tmp; } */ /* * This is an unrolled MD5 implementation, which gives ~30% speedup compared * to the abbreviated implementation above, as measured on Chrome 11. It is * important to keep 32-bit croppings to minimum and inline the integer * rotation. */ sum = (A + (D ^ (B & (C ^ D))) + X[0] + 0xd76aa478) & 0xffffffff; A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25)); sum = (D + (C ^ (A & (B ^ C))) + X[1] + 0xe8c7b756) & 0xffffffff; D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20)); sum = (C + (B ^ (D & (A ^ B))) + X[2] + 0x242070db) & 0xffffffff; C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15)); sum = (B + (A ^ (C & (D ^ A))) + X[3] + 0xc1bdceee) & 0xffffffff; B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10)); sum = (A + (D ^ (B & (C ^ D))) + X[4] + 0xf57c0faf) & 0xffffffff; A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25)); sum = (D + (C ^ (A & (B ^ C))) + X[5] + 0x4787c62a) & 0xffffffff; D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20)); sum = (C + (B ^ (D & (A ^ B))) + X[6] + 0xa8304613) & 0xffffffff; C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15)); sum = (B + (A ^ (C & (D ^ A))) + X[7] + 0xfd469501) & 0xffffffff; B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10)); sum = (A + (D ^ (B & (C ^ D))) + X[8] + 0x698098d8) & 0xffffffff; A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25)); sum = (D + (C ^ (A & (B ^ C))) + X[9] + 0x8b44f7af) & 0xffffffff; D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20)); sum = (C + (B ^ (D & (A ^ B))) + X[10] + 0xffff5bb1) & 0xffffffff; C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15)); sum = (B + (A ^ (C & (D ^ A))) + X[11] + 0x895cd7be) & 0xffffffff; B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10)); sum = (A + (D ^ (B & (C ^ D))) + X[12] + 0x6b901122) & 0xffffffff; A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25)); sum = (D + (C ^ (A & (B ^ C))) + X[13] + 0xfd987193) & 0xffffffff; D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20)); sum = (C + (B ^ (D & (A ^ B))) + X[14] + 0xa679438e) & 0xffffffff; C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15)); sum = (B + (A ^ (C & (D ^ A))) + X[15] + 0x49b40821) & 0xffffffff; B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10)); sum = (A + (C ^ (D & (B ^ C))) + X[1] + 0xf61e2562) & 0xffffffff; A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27)); sum = (D + (B ^ (C & (A ^ B))) + X[6] + 0xc040b340) & 0xffffffff; D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23)); sum = (C + (A ^ (B & (D ^ A))) + X[11] + 0x265e5a51) & 0xffffffff; C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18)); sum = (B + (D ^ (A & (C ^ D))) + X[0] + 0xe9b6c7aa) & 0xffffffff; B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12)); sum = (A + (C ^ (D & (B ^ C))) + X[5] + 0xd62f105d) & 0xffffffff; A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27)); sum = (D + (B ^ (C & (A ^ B))) + X[10] + 0x02441453) & 0xffffffff; D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23)); sum = (C + (A ^ (B & (D ^ A))) + X[15] + 0xd8a1e681) & 0xffffffff; C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18)); sum = (B + (D ^ (A & (C ^ D))) + X[4] + 0xe7d3fbc8) & 0xffffffff; B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12)); sum = (A + (C ^ (D & (B ^ C))) + X[9] + 0x21e1cde6) & 0xffffffff; A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27)); sum = (D + (B ^ (C & (A ^ B))) + X[14] + 0xc33707d6) & 0xffffffff; D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23)); sum = (C + (A ^ (B & (D ^ A))) + X[3] + 0xf4d50d87) & 0xffffffff; C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18)); sum = (B + (D ^ (A & (C ^ D))) + X[8] + 0x455a14ed) & 0xffffffff; B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12)); sum = (A + (C ^ (D & (B ^ C))) + X[13] + 0xa9e3e905) & 0xffffffff; A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27)); sum = (D + (B ^ (C & (A ^ B))) + X[2] + 0xfcefa3f8) & 0xffffffff; D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23)); sum = (C + (A ^ (B & (D ^ A))) + X[7] + 0x676f02d9) & 0xffffffff; C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18)); sum = (B + (D ^ (A & (C ^ D))) + X[12] + 0x8d2a4c8a) & 0xffffffff; B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12)); sum = (A + (B ^ C ^ D) + X[5] + 0xfffa3942) & 0xffffffff; A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28)); sum = (D + (A ^ B ^ C) + X[8] + 0x8771f681) & 0xffffffff; D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21)); sum = (C + (D ^ A ^ B) + X[11] + 0x6d9d6122) & 0xffffffff; C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16)); sum = (B + (C ^ D ^ A) + X[14] + 0xfde5380c) & 0xffffffff; B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9)); sum = (A + (B ^ C ^ D) + X[1] + 0xa4beea44) & 0xffffffff; A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28)); sum = (D + (A ^ B ^ C) + X[4] + 0x4bdecfa9) & 0xffffffff; D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21)); sum = (C + (D ^ A ^ B) + X[7] + 0xf6bb4b60) & 0xffffffff; C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16)); sum = (B + (C ^ D ^ A) + X[10] + 0xbebfbc70) & 0xffffffff; B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9)); sum = (A + (B ^ C ^ D) + X[13] + 0x289b7ec6) & 0xffffffff; A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28)); sum = (D + (A ^ B ^ C) + X[0] + 0xeaa127fa) & 0xffffffff; D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21)); sum = (C + (D ^ A ^ B) + X[3] + 0xd4ef3085) & 0xffffffff; C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16)); sum = (B + (C ^ D ^ A) + X[6] + 0x04881d05) & 0xffffffff; B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9)); sum = (A + (B ^ C ^ D) + X[9] + 0xd9d4d039) & 0xffffffff; A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28)); sum = (D + (A ^ B ^ C) + X[12] + 0xe6db99e5) & 0xffffffff; D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21)); sum = (C + (D ^ A ^ B) + X[15] + 0x1fa27cf8) & 0xffffffff; C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16)); sum = (B + (C ^ D ^ A) + X[2] + 0xc4ac5665) & 0xffffffff; B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9)); sum = (A + (C ^ (B | (~D))) + X[0] + 0xf4292244) & 0xffffffff; A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26)); sum = (D + (B ^ (A | (~C))) + X[7] + 0x432aff97) & 0xffffffff; D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22)); sum = (C + (A ^ (D | (~B))) + X[14] + 0xab9423a7) & 0xffffffff; C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17)); sum = (B + (D ^ (C | (~A))) + X[5] + 0xfc93a039) & 0xffffffff; B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11)); sum = (A + (C ^ (B | (~D))) + X[12] + 0x655b59c3) & 0xffffffff; A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26)); sum = (D + (B ^ (A | (~C))) + X[3] + 0x8f0ccc92) & 0xffffffff; D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22)); sum = (C + (A ^ (D | (~B))) + X[10] + 0xffeff47d) & 0xffffffff; C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17)); sum = (B + (D ^ (C | (~A))) + X[1] + 0x85845dd1) & 0xffffffff; B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11)); sum = (A + (C ^ (B | (~D))) + X[8] + 0x6fa87e4f) & 0xffffffff; A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26)); sum = (D + (B ^ (A | (~C))) + X[15] + 0xfe2ce6e0) & 0xffffffff; D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22)); sum = (C + (A ^ (D | (~B))) + X[6] + 0xa3014314) & 0xffffffff; C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17)); sum = (B + (D ^ (C | (~A))) + X[13] + 0x4e0811a1) & 0xffffffff; B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11)); sum = (A + (C ^ (B | (~D))) + X[4] + 0xf7537e82) & 0xffffffff; A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26)); sum = (D + (B ^ (A | (~C))) + X[11] + 0xbd3af235) & 0xffffffff; D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22)); sum = (C + (A ^ (D | (~B))) + X[2] + 0x2ad7d2bb) & 0xffffffff; C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17)); sum = (B + (D ^ (C | (~A))) + X[9] + 0xeb86d391) & 0xffffffff; B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11)); this.chain_[0] = (this.chain_[0] + A) & 0xffffffff; this.chain_[1] = (this.chain_[1] + B) & 0xffffffff; this.chain_[2] = (this.chain_[2] + C) & 0xffffffff; this.chain_[3] = (this.chain_[3] + D) & 0xffffffff; }; /** @override */ goog.crypt.Md5.prototype.update = function(bytes, opt_length) { if (!goog.isDef(opt_length)) { opt_length = bytes.length; } var lengthMinusBlock = opt_length - 64; // Copy some object properties to local variables in order to save on access // time from inside the loop (~10% speedup was observed on Chrome 11). var block = this.block_; var blockLength = this.blockLength_; var i = 0; // The outer while loop should execute at most twice. while (i < opt_length) { // When we have no data in the block to top up, we can directly process the // input buffer (assuming it contains sufficient data). This gives ~30% // speedup on Chrome 14 and ~70% speedup on Firefox 6.0, but requires that // the data is provided in large chunks (or in multiples of 64 bytes). if (blockLength == 0) { while (i <= lengthMinusBlock) { this.compress_(bytes, i); i += 64; } } if (goog.isString(bytes)) { while (i < opt_length) { block[blockLength++] = bytes.charCodeAt(i++); if (blockLength == 64) { this.compress_(block); blockLength = 0; // Jump to the outer loop so we use the full-block optimization. break; } } } else { while (i < opt_length) { block[blockLength++] = bytes[i++]; if (blockLength == 64) { this.compress_(block); blockLength = 0; // Jump to the outer loop so we use the full-block optimization. break; } } } } this.blockLength_ = blockLength; this.totalLength_ += opt_length; }; /** @override */ goog.crypt.Md5.prototype.digest = function() { // This must accommodate at least 1 padding byte (0x80), 8 bytes of // total bitlength, and must end at a 64-byte boundary. var pad = new Array((this.blockLength_ < 56 ? 64 : 128) - this.blockLength_); // Add padding: 0x80 0x00* pad[0] = 0x80; for (var i = 1; i < pad.length - 8; ++i) { pad[i] = 0; } // Add the total number of bits, little endian 64-bit integer. var totalBits = this.totalLength_ * 8; for (var i = pad.length - 8; i < pad.length; ++i) { pad[i] = totalBits & 0xff; totalBits /= 0x100; // Don't use bit-shifting here! } this.update(pad); var digest = new Array(16); var n = 0; for (var i = 0; i < 4; ++i) { for (var j = 0; j < 32; j += 8) { digest[n++] = (this.chain_[i] >>> j) & 0xff; } } return digest; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Numeric base conversion library. Works for arbitrary bases and * arbitrary length numbers. * * For base-64 conversion use base64.js because it is optimized for the specific * conversion to base-64 while this module is generic. Base-64 is defined here * mostly for demonstration purpose. * * TODO: Make base64 and baseN classes that have common interface. (Perhaps...) * */ goog.provide('goog.crypt.baseN'); /** * Base-2, i.e. '01'. * @type {string} */ goog.crypt.baseN.BASE_BINARY = '01'; /** * Base-8, i.e. '01234567'. * @type {string} */ goog.crypt.baseN.BASE_OCTAL = '01234567'; /** * Base-10, i.e. '0123456789'. * @type {string} */ goog.crypt.baseN.BASE_DECIMAL = '0123456789'; /** * Base-16 using lower case, i.e. '0123456789abcdef'. * @type {string} */ goog.crypt.baseN.BASE_LOWERCASE_HEXADECIMAL = '0123456789abcdef'; /** * Base-16 using upper case, i.e. '0123456789ABCDEF'. * @type {string} */ goog.crypt.baseN.BASE_UPPERCASE_HEXADECIMAL = '0123456789ABCDEF'; /** * The more-known version of the BASE-64 encoding. Uses + and / characters. * @type {string} */ goog.crypt.baseN.BASE_64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; /** * URL-safe version of the BASE-64 encoding. * @type {string} */ goog.crypt.baseN.BASE_64_URL_SAFE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; /** * Converts a number from one numeric base to another. * * The bases are represented as strings, which list allowed digits. Each digit * should be unique. The bases can either be user defined, or any of * goog.crypt.baseN.BASE_xxx. * * The number is in human-readable format, most significant digit first, and is * a non-negative integer. Base designators such as $, 0x, d, b or h (at end) * will be interpreted as digits, so avoid them. Leading zeros will be trimmed. * * Note: for huge bases the result may be inaccurate because of overflowing * 64-bit doubles used by JavaScript for integer calculus. This may happen * if the product of the number of digits in the input and output bases comes * close to 10^16, which is VERY unlikely (100M digits in each base), but * may be possible in the future unicode world. (Unicode 3.2 has less than 100K * characters. However, it reserves some more, close to 1M.) * * @param {string} number The number to convert. * @param {string} inputBase The numeric base the number is in (all digits). * @param {string} outputBase Requested numeric base. * @return {string} The converted number. */ goog.crypt.baseN.recodeString = function(number, inputBase, outputBase) { if (outputBase == '') { throw Error('Empty output base'); } // Check if number is 0 (special case when we don't want to return ''). var isZero = true; for (var i = 0, n = number.length; i < n; i++) { if (number.charAt(i) != inputBase.charAt(0)) { isZero = false; break; } } if (isZero) { return outputBase.charAt(0); } var numberDigits = goog.crypt.baseN.stringToArray_(number, inputBase); var inputBaseSize = inputBase.length; var outputBaseSize = outputBase.length; // result = 0. var result = []; // For all digits of number, starting with the most significant ... for (var i = numberDigits.length - 1; i >= 0; i--) { // result *= number.base. var carry = 0; for (var j = 0, n = result.length; j < n; j++) { var digit = result[j]; // This may overflow for huge bases. See function comment. digit = digit * inputBaseSize + carry; if (digit >= outputBaseSize) { var remainder = digit % outputBaseSize; carry = (digit - remainder) / outputBaseSize; digit = remainder; } else { carry = 0; } result[j] = digit; } while (carry) { var remainder = carry % outputBaseSize; result.push(remainder); carry = (carry - remainder) / outputBaseSize; } // result += number[i]. carry = numberDigits[i]; var j = 0; while (carry) { if (j >= result.length) { // Extend result with a leading zero which will be overwritten below. result.push(0); } var digit = result[j]; digit += carry; if (digit >= outputBaseSize) { var remainder = digit % outputBaseSize; carry = (digit - remainder) / outputBaseSize; digit = remainder; } else { carry = 0; } result[j] = digit; j++; } } return goog.crypt.baseN.arrayToString_(result, outputBase); }; /** * Converts a string representation of a number to an array of digit values. * * More precisely, the digit values are indices into the number base, which * is represented as a string, which can either be user defined or one of the * BASE_xxx constants. * * Throws an Error if the number contains a digit not found in the base. * * @param {string} number The string to convert, most significant digit first. * @param {string} base Digits in the base. * @return {Array.<number>} Array of digit values, least significant digit * first. * @private */ goog.crypt.baseN.stringToArray_ = function(number, base) { var index = {}; for (var i = 0, n = base.length; i < n; i++) { index[base.charAt(i)] = i; } var result = []; for (var i = number.length - 1; i >= 0; i--) { var character = number.charAt(i); var digit = index[character]; if (typeof digit == 'undefined') { throw Error('Number ' + number + ' contains a character not found in base ' + base + ', which is ' + character); } result.push(digit); } return result; }; /** * Converts an array representation of a number to a string. * * More precisely, the elements of the input array are indices into the base, * which is represented as a string, which can either be user defined or one of * the BASE_xxx constants. * * Throws an Error if the number contains a digit which is outside the range * 0 ... base.length - 1. * * @param {Array.<number>} number Array of digit values, least significant * first. * @param {string} base Digits in the base. * @return {string} Number as a string, most significant digit first. * @private */ goog.crypt.baseN.arrayToString_ = function(number, base) { var n = number.length; var chars = []; var baseSize = base.length; for (var i = n - 1; i >= 0; i--) { var digit = number[i]; if (digit >= baseSize || digit < 0) { throw Error('Number ' + number + ' contains an invalid digit: ' + digit); } chars.push(base.charAt(digit)); } return chars.join(''); };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Interface definition of a block cipher. A block cipher is a * pair of algorithms that implement encryption and decryption of input bytes. * * @see http://en.wikipedia.org/wiki/Block_cipher * * @author nnaze@google.com (Nathan Naze) */ goog.provide('goog.crypt.BlockCipher'); /** * Interface definition for a block cipher. * @interface */ goog.crypt.BlockCipher = function() {}; /** * Encrypt a plaintext block. The implementation may expect (and assert) * a particular block length. * @param {!Array.<number>} input Plaintext array of input bytes. * @return {!Array.<number>} Encrypted ciphertext array of bytes. Should be the * same length as input. */ goog.crypt.BlockCipher.prototype.encrypt; /** * Decrypt a plaintext block. The implementation may expect (and assert) * a particular block length. * @param {!Array.<number>} input Ciphertext. Array of input bytes. * @return {!Array.<number>} Decrypted plaintext array of bytes. Should be the * same length as input. */ goog.crypt.BlockCipher.prototype.decrypt;
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Base class for SHA-2 cryptographic hash. * * Variable names follow the notation in FIPS PUB 180-3: * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf. * * To implement specific SHA-2 such as SHA-256, create a sub-class with * overridded reset(). See sha256.js for an example. * * TODO(user): SHA-512/384 are not currently implemented. Could be added * if needed. * * Some code similar to SHA1 are borrowed from sha1.js written by mschilder@. * */ goog.provide('goog.crypt.Sha2'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.crypt.Hash'); /** * SHA-2 cryptographic hash constructor. * This constructor should not be used directly to create the object. Rather, * one should use the constructor of the sub-classes. * @constructor * @extends {goog.crypt.Hash} */ goog.crypt.Sha2 = function() { goog.base(this); /** * A chunk holding the currently processed message bytes. Once the chunk has * 64 bytes, we feed it into computeChunk_ function and reset this.chunk_. * Sub-class needs to reset it when overriding reset(). * @type {!Array.<number>} * @protected */ this.chunk = []; /** * Current number of bytes in this.chunk_. * Sub-class needs to reset it when overriding reset(). * @type {number} * @protected */ this.inChunk = 0; /** * Total number of bytes in currently processed message. * Sub-class needs to reset it when overriding reset(). * @type {number} * @protected */ this.total = 0; /** * Contains data needed to pad messages less than 64 bytes. * @type {!Array.<number>} * @private */ this.pad_ = goog.array.repeat(0, 64); this.pad_[0] = 128; /** * Holds the previous values of accumulated hash a-h in the computeChunk_ * function. * It is a subclass-dependent value. Sub-class needs to explicitly set it * when overriding reset(). * @type {!Array.<number>} * @protected */ this.hash = []; /** * The number of output hash blocks (each block is 4 bytes long). * It is a subclass-dependent value. Sub-class needs to explicitly set it * when overriding reset(). * @type {number} * @protected */ this.numHashBlocks = 0; this.reset(); }; goog.inherits(goog.crypt.Sha2, goog.crypt.Hash); /** @override */ goog.crypt.Sha2.prototype.reset = goog.abstractMethod; /** * Helper function to compute the hashes for a given 512-bit message chunk. * @param {!Array.<number>} chunk A 512-bit message chunk to be processed. * @private */ goog.crypt.Sha2.prototype.computeChunk_ = function(chunk) { goog.asserts.assert(chunk.length == 64); // Divide the chunk into 16 32-bit-words. var w = []; var index = 0; var offset = 0; while (offset < chunk.length) { w[index++] = (chunk[offset] << 24) | (chunk[offset + 1] << 16) | (chunk[offset + 2] << 8) | (chunk[offset + 3]); offset = index * 4; } // Expand to 64 32-bit-words for (var i = 16; i < 64; i++) { var s0 = ((w[i - 15] >>> 7) | (w[i - 15] << 25)) ^ ((w[i - 15] >>> 18) | (w[i - 15] << 14)) ^ (w[i - 15] >>> 3); var s1 = ((w[i - 2] >>> 17) | (w[i - 2] << 15)) ^ ((w[i - 2] >>> 19) | (w[i - 2] << 13)) ^ (w[i - 2] >>> 10); w[i] = (w[i - 16] + s0 + w[i - 7] + s1) & 0xffffffff; } var a = this.hash[0]; var b = this.hash[1]; var c = this.hash[2]; var d = this.hash[3]; var e = this.hash[4]; var f = this.hash[5]; var g = this.hash[6]; var h = this.hash[7]; for (var i = 0; i < 64; i++) { var S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10)); var maj = ((a & b) ^ (a & c) ^ (b & c)); var t2 = (S0 + maj) & 0xffffffff; var S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7)); var ch = ((e & f) ^ ((~ e) & g)); var t1 = (h + S1 + ch + this.K_[i] + w[i]) & 0xffffffff; h = g; g = f; f = e; e = (d + t1) & 0xffffffff; d = c; c = b; b = a; a = (t1 + t2) & 0xffffffff; } this.hash[0] = (this.hash[0] + a) & 0xffffffff; this.hash[1] = (this.hash[1] + b) & 0xffffffff; this.hash[2] = (this.hash[2] + c) & 0xffffffff; this.hash[3] = (this.hash[3] + d) & 0xffffffff; this.hash[4] = (this.hash[4] + e) & 0xffffffff; this.hash[5] = (this.hash[5] + f) & 0xffffffff; this.hash[6] = (this.hash[6] + g) & 0xffffffff; this.hash[7] = (this.hash[7] + h) & 0xffffffff; }; /** @override */ goog.crypt.Sha2.prototype.update = function(message, opt_length) { if (!goog.isDef(opt_length)) { opt_length = message.length; } // Process the message from left to right up to |opt_length| bytes. // When we get a 512-bit chunk, compute the hash of it and reset // this.chunk_. The message might not be multiple of 512 bits so we // might end up with a chunk that is less than 512 bits. We store // such partial chunk in this.chunk_ and it will be filled up later // in digest(). var n = 0; var inChunk = this.inChunk; // The input message could be either byte array of string. if (goog.isString(message)) { while (n < opt_length) { this.chunk[inChunk++] = message.charCodeAt(n++); if (inChunk == 64) { this.computeChunk_(this.chunk); inChunk = 0; } } } else { while (n < opt_length) { this.chunk[inChunk++] = message[n++]; if (inChunk == 64) { this.computeChunk_(this.chunk); inChunk = 0; } } } // Record the current bytes in chunk to support partial update. this.inChunk = inChunk; // Record total message bytes we have processed so far. this.total += opt_length; }; /** @override */ goog.crypt.Sha2.prototype.digest = function() { var digest = []; var totalBits = this.total * 8; // Append pad 0x80 0x00*. if (this.inChunk < 56) { this.update(this.pad_, 56 - this.inChunk); } else { this.update(this.pad_, 64 - (this.inChunk - 56)); } // Append # bits in the 64-bit big-endian format. for (var i = 63; i >= 56; i--) { this.chunk[i] = totalBits & 255; totalBits /= 256; // Don't use bit-shifting here! } this.computeChunk_(this.chunk); // Finally, output the result digest. var n = 0; for (var i = 0; i < this.numHashBlocks; i++) { for (var j = 24; j >= 0; j -= 8) { digest[n++] = ((this.hash[i] >> j) & 255); } } return digest; }; /** * Constants used in SHA-2. * @const * @private */ goog.crypt.Sha2.prototype.K_ = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];
JavaScript
// Copyright 2005 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview ARC4 streamcipher implementation. A description of the * algorithm can be found at: * http://www.mozilla.org/projects/security/pki/nss/draft-kaukonen-cipher-arcfour-03.txt. * * Usage: * <code> * var arc4 = new goog.crypt.Arc4(); * arc4.setKey(key); * arc4.discard(1536); * arc4.crypt(bytes); * </code> * * Note: For converting between strings and byte arrays, goog.crypt.base64 may * be useful. * */ goog.provide('goog.crypt.Arc4'); goog.require('goog.asserts'); /** * ARC4 streamcipher implementation. * @constructor */ goog.crypt.Arc4 = function() { /** * A permutation of all 256 possible bytes. * @type {Array.<number>} * @private */ this.state_ = []; /** * 8 bit index pointer into this.state_. * @type {number} * @private */ this.index1_ = 0; /** * 8 bit index pointer into this.state_. * @type {number} * @private */ this.index2_ = 0; }; /** * Initialize the cipher for use with new key. * @param {Array.<number>} key A byte array containing the key. * @param {number=} opt_length Indicates # of bytes to take from the key. */ goog.crypt.Arc4.prototype.setKey = function(key, opt_length) { goog.asserts.assertArray(key, 'Key parameter must be a byte array'); if (!opt_length) { opt_length = key.length; } var state = this.state_; for (var i = 0; i < 256; ++i) { state[i] = i; } var j = 0; for (var i = 0; i < 256; ++i) { j = (j + state[i] + key[i % opt_length]) & 255; var tmp = state[i]; state[i] = state[j]; state[j] = tmp; } this.index1_ = 0; this.index2_ = 0; }; /** * Discards n bytes of the keystream. * These days 1536 is considered a decent amount to drop to get the key state * warmed-up enough for secure usage. This is not done in the constructor to * preserve efficiency for use cases that do not need this. * NOTE: Discard is identical to crypt without actually xoring any data. It's * unfortunate to have this code duplicated, but this was done for performance * reasons. Alternatives which were attempted: * 1. Create a temp array of the correct length and pass it to crypt. This * works but needlessly allocates an array. But more importantly this * requires choosing an array type (Array or Uint8Array) in discard, and * choosing a different type than will be passed to crypt by the client * code hurts the javascript engines ability to optimize crypt (7x hit in * v8). * 2. Make data option in crypt so discard can pass null, this has a huge * perf hit for crypt. * @param {number} length Number of bytes to disregard from the stream. */ goog.crypt.Arc4.prototype.discard = function(length) { var i = this.index1_; var j = this.index2_; var state = this.state_; for (var n = 0; n < length; ++n) { i = (i + 1) & 255; j = (j + state[i]) & 255; var tmp = state[i]; state[i] = state[j]; state[j] = tmp; } this.index1_ = i; this.index2_ = j; }; /** * En- or decrypt (same operation for streamciphers like ARC4) * @param {Array.<number>|Uint8Array} data The data to be xor-ed in place. * @param {number=} opt_length The number of bytes to crypt. */ goog.crypt.Arc4.prototype.crypt = function(data, opt_length) { if (!opt_length) { opt_length = data.length; } var i = this.index1_; var j = this.index2_; var state = this.state_; for (var n = 0; n < opt_length; ++n) { i = (i + 1) & 255; j = (j + state[i]) & 255; var tmp = state[i]; state[i] = state[j]; state[j] = tmp; data[n] ^= state[(state[i] + state[j]) & 255]; } this.index1_ = i; this.index2_ = j; };
JavaScript
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Useful compiler idioms. * */ goog.provide('goog.reflect'); /** * Syntax for object literal casts. * @see http://go/jscompiler-renaming * @see http://code.google.com/p/closure-compiler/wiki/ * ExperimentalTypeBasedPropertyRenaming * * Use this if you have an object literal whose keys need to have the same names * as the properties of some class even after they are renamed by the compiler. * * @param {!Function} type Type to cast to. * @param {Object} object Object literal to cast. * @return {Object} The object literal. */ goog.reflect.object = function(type, object) { return object; }; /** * To assert to the compiler that an operation is needed when it would * otherwise be stripped. For example: * <code> * // Force a layout * goog.reflect.sinkValue(dialog.offsetHeight); * </code> * @type {!Function} */ goog.reflect.sinkValue = function(x) { goog.reflect.sinkValue[' '](x); return x; }; /** * The compiler should optimize this function away iff no one ever uses * goog.reflect.sinkValue. */ goog.reflect.sinkValue[' '] = goog.nullFunction; /** * Check if a property can be accessed without throwing an exception. * @param {Object} obj The owner of the property. * @param {string} prop The property name. * @return {boolean} Whether the property is accessible. Will also return true * if obj is null. */ goog.reflect.canAccessProperty = function(obj, prop) { /** @preserveTry */ try { goog.reflect.sinkValue(obj[prop]); return true; } catch (e) {} return false; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Python style iteration utilities. * @author arv@google.com (Erik Arvidsson) */ goog.provide('goog.iter'); goog.provide('goog.iter.Iterator'); goog.provide('goog.iter.StopIteration'); goog.require('goog.array'); goog.require('goog.asserts'); // TODO(nnaze): Add more functions from Python's itertools. // http://docs.python.org/library/itertools.html /** * @typedef {goog.iter.Iterator|{length:number}|{__iterator__}} */ goog.iter.Iterable; // For script engines that already support iterators. if ('StopIteration' in goog.global) { /** * Singleton Error object that is used to terminate iterations. * @type {Error} */ goog.iter.StopIteration = goog.global['StopIteration']; } else { /** * Singleton Error object that is used to terminate iterations. * @type {Error} * @suppress {duplicate} */ goog.iter.StopIteration = Error('StopIteration'); } /** * Class/interface for iterators. An iterator needs to implement a {@code next} * method and it needs to throw a {@code goog.iter.StopIteration} when the * iteration passes beyond the end. Iterators have no {@code hasNext} method. * It is recommended to always use the helper functions to iterate over the * iterator or in case you are only targeting JavaScript 1.7 for in loops. * @constructor */ goog.iter.Iterator = function() {}; /** * Returns the next value of the iteration. This will throw the object * {@see goog.iter#StopIteration} when the iteration passes the end. * @return {*} Any object or value. */ goog.iter.Iterator.prototype.next = function() { throw goog.iter.StopIteration; }; /** * Returns the {@code Iterator} object itself. This is used to implement * the iterator protocol in JavaScript 1.7 * @param {boolean=} opt_keys Whether to return the keys or values. Default is * to only return the values. This is being used by the for-in loop (true) * and the for-each-in loop (false). Even though the param gives a hint * about what the iterator will return there is no guarantee that it will * return the keys when true is passed. * @return {!goog.iter.Iterator} The object itself. */ goog.iter.Iterator.prototype.__iterator__ = function(opt_keys) { return this; }; /** * Returns an iterator that knows how to iterate over the values in the object. * @param {goog.iter.Iterable} iterable If the object is an iterator it * will be returned as is. If the object has a {@code __iterator__} method * that will be called to get the value iterator. If the object is an * array-like object we create an iterator for that. * @return {!goog.iter.Iterator} An iterator that knows how to iterate over the * values in {@code iterable}. */ goog.iter.toIterator = function(iterable) { if (iterable instanceof goog.iter.Iterator) { return iterable; } if (typeof iterable.__iterator__ == 'function') { return iterable.__iterator__(false); } if (goog.isArrayLike(iterable)) { var i = 0; var newIter = new goog.iter.Iterator; newIter.next = function() { while (true) { if (i >= iterable.length) { throw goog.iter.StopIteration; } // Don't include deleted elements. if (!(i in iterable)) { i++; continue; } return iterable[i++]; } }; return newIter; } // TODO(arv): Should we fall back on goog.structs.getValues()? throw Error('Not implemented'); }; /** * Calls a function for each element in the iterator with the element of the * iterator passed as argument. * * @param {goog.iter.Iterable} iterable The iterator to iterate * over. If the iterable is an object {@code toIterator} will be called on * it. * @param {function(this:T,?,?,?):?} f The function to call for every * element. This function * takes 3 arguments (the element, undefined, and the iterator) and the * return value is irrelevant. The reason for passing undefined as the * second argument is so that the same function can be used in * {@see goog.array#forEach} as well as others. * @param {T=} opt_obj The object to be used as the value of 'this' within * {@code f}. * @template T */ goog.iter.forEach = function(iterable, f, opt_obj) { if (goog.isArrayLike(iterable)) { /** @preserveTry */ try { // NOTES: this passes the index number to the second parameter // of the callback contrary to the documentation above. goog.array.forEach(/** @type {goog.array.ArrayLike} */(iterable), f, opt_obj); } catch (ex) { if (ex !== goog.iter.StopIteration) { throw ex; } } } else { iterable = goog.iter.toIterator(iterable); /** @preserveTry */ try { while (true) { f.call(opt_obj, iterable.next(), undefined, iterable); } } catch (ex) { if (ex !== goog.iter.StopIteration) { throw ex; } } } }; /** * Calls a function for every element in the iterator, and if the function * returns true adds the element to a new iterator. * * @param {goog.iter.Iterable} iterable The iterator to iterate over. * @param {function(this:T,?,undefined,?):boolean} f The function to call for * every element. This function * takes 3 arguments (the element, undefined, and the iterator) and should * return a boolean. If the return value is true the element will be * included in the returned iteror. If it is false the element is not * included. * @param {T=} opt_obj The object to be used as the value of 'this' within * {@code f}. * @return {!goog.iter.Iterator} A new iterator in which only elements that * passed the test are present. * @template T */ goog.iter.filter = function(iterable, f, opt_obj) { var iterator = goog.iter.toIterator(iterable); var newIter = new goog.iter.Iterator; newIter.next = function() { while (true) { var val = iterator.next(); if (f.call(opt_obj, val, undefined, iterator)) { return val; } } }; return newIter; }; /** * Creates a new iterator that returns the values in a range. This function * can take 1, 2 or 3 arguments: * <pre> * range(5) same as range(0, 5, 1) * range(2, 5) same as range(2, 5, 1) * </pre> * * @param {number} startOrStop The stop value if only one argument is provided. * The start value if 2 or more arguments are provided. If only one * argument is used the start value is 0. * @param {number=} opt_stop The stop value. If left out then the first * argument is used as the stop value. * @param {number=} opt_step The number to increment with between each call to * next. This can be negative. * @return {!goog.iter.Iterator} A new iterator that returns the values in the * range. */ goog.iter.range = function(startOrStop, opt_stop, opt_step) { var start = 0; var stop = startOrStop; var step = opt_step || 1; if (arguments.length > 1) { start = startOrStop; stop = opt_stop; } if (step == 0) { throw Error('Range step argument must not be zero'); } var newIter = new goog.iter.Iterator; newIter.next = function() { if (step > 0 && start >= stop || step < 0 && start <= stop) { throw goog.iter.StopIteration; } var rv = start; start += step; return rv; }; return newIter; }; /** * Joins the values in a iterator with a delimiter. * @param {goog.iter.Iterable} iterable The iterator to get the values from. * @param {string} deliminator The text to put between the values. * @return {string} The joined value string. */ goog.iter.join = function(iterable, deliminator) { return goog.iter.toArray(iterable).join(deliminator); }; /** * For every element in the iterator call a function and return a new iterator * with that value. * * @param {goog.iter.Iterable} iterable The iterator to iterate over. * @param {function(this:T,?,undefined,?):?} f The function to call for every * element. This function * takes 3 arguments (the element, undefined, and the iterator) and should * return a new value. * @param {T=} opt_obj The object to be used as the value of 'this' within * {@code f}. * @return {!goog.iter.Iterator} A new iterator that returns the results of * applying the function to each element in the original iterator. * @template T */ goog.iter.map = function(iterable, f, opt_obj) { var iterator = goog.iter.toIterator(iterable); var newIter = new goog.iter.Iterator; newIter.next = function() { while (true) { var val = iterator.next(); return f.call(opt_obj, val, undefined, iterator); } }; return newIter; }; /** * Passes every element of an iterator into a function and accumulates the * result. * * @param {goog.iter.Iterable} iterable The iterator to iterate over. * @param {function(this:T,V,?):V} f The function to call for every * element. This function takes 2 arguments (the function's previous result * or the initial value, and the value of the current element). * function(previousValue, currentElement) : newValue. * @param {V} val The initial value to pass into the function on the first call. * @param {T=} opt_obj The object to be used as the value of 'this' * within f. * @return {V} Result of evaluating f repeatedly across the values of * the iterator. * @template T,V */ goog.iter.reduce = function(iterable, f, val, opt_obj) { var rval = val; goog.iter.forEach(iterable, function(val) { rval = f.call(opt_obj, rval, val); }); return rval; }; /** * Goes through the values in the iterator. Calls f for each these and if any of * them returns true, this returns true (without checking the rest). If all * return false this will return false. * * @param {goog.iter.Iterable} iterable The iterator object. * @param {function(this:T,?,undefined,?):boolean} f The function to call for * every value. This function * takes 3 arguments (the value, undefined, and the iterator) and should * return a boolean. * @param {T=} opt_obj The object to be used as the value of 'this' within * {@code f}. * @return {boolean} true if any value passes the test. * @template T */ goog.iter.some = function(iterable, f, opt_obj) { iterable = goog.iter.toIterator(iterable); /** @preserveTry */ try { while (true) { if (f.call(opt_obj, iterable.next(), undefined, iterable)) { return true; } } } catch (ex) { if (ex !== goog.iter.StopIteration) { throw ex; } } return false; }; /** * Goes through the values in the iterator. Calls f for each these and if any of * them returns false this returns false (without checking the rest). If all * return true this will return true. * * @param {goog.iter.Iterable} iterable The iterator object. * @param {function(this:T,?,undefined,?):boolean} f The function to call for * every value. This function * takes 3 arguments (the value, undefined, and the iterator) and should * return a boolean. * @param {T=} opt_obj The object to be used as the value of 'this' within * {@code f}. * @return {boolean} true if every value passes the test. * @template T */ goog.iter.every = function(iterable, f, opt_obj) { iterable = goog.iter.toIterator(iterable); /** @preserveTry */ try { while (true) { if (!f.call(opt_obj, iterable.next(), undefined, iterable)) { return false; } } } catch (ex) { if (ex !== goog.iter.StopIteration) { throw ex; } } return true; }; /** * Takes zero or more iterators and returns one iterator that will iterate over * them in the order chained. * @param {...goog.iter.Iterator} var_args Any number of iterator objects. * @return {!goog.iter.Iterator} Returns a new iterator that will iterate over * all the given iterators' contents. */ goog.iter.chain = function(var_args) { var args = arguments; var length = args.length; var i = 0; var newIter = new goog.iter.Iterator; /** * @return {*} The next item in the iteration. * @this {goog.iter.Iterator} */ newIter.next = function() { /** @preserveTry */ try { if (i >= length) { throw goog.iter.StopIteration; } var current = goog.iter.toIterator(args[i]); return current.next(); } catch (ex) { if (ex !== goog.iter.StopIteration || i >= length) { throw ex; } else { // In case we got a StopIteration increment counter and try again. i++; return this.next(); } } }; return newIter; }; /** * Builds a new iterator that iterates over the original, but skips elements as * long as a supplied function returns true. * @param {goog.iter.Iterable} iterable The iterator object. * @param {function(this:T,?,undefined,?):boolean} f The function to call for * every value. This function * takes 3 arguments (the value, undefined, and the iterator) and should * return a boolean. * @param {T=} opt_obj The object to be used as the value of 'this' within * {@code f}. * @return {!goog.iter.Iterator} A new iterator that drops elements from the * original iterator as long as {@code f} is true. * @template T */ goog.iter.dropWhile = function(iterable, f, opt_obj) { var iterator = goog.iter.toIterator(iterable); var newIter = new goog.iter.Iterator; var dropping = true; newIter.next = function() { while (true) { var val = iterator.next(); if (dropping && f.call(opt_obj, val, undefined, iterator)) { continue; } else { dropping = false; } return val; } }; return newIter; }; /** * Builds a new iterator that iterates over the original, but only as long as a * supplied function returns true. * @param {goog.iter.Iterable} iterable The iterator object. * @param {function(this:T,?,undefined,?):boolean} f The function to call for * every value. This function * takes 3 arguments (the value, undefined, and the iterator) and should * return a boolean. * @param {T=} opt_obj This is used as the 'this' object in f when called. * @return {!goog.iter.Iterator} A new iterator that keeps elements in the * original iterator as long as the function is true. * @template T */ goog.iter.takeWhile = function(iterable, f, opt_obj) { var iterator = goog.iter.toIterator(iterable); var newIter = new goog.iter.Iterator; var taking = true; newIter.next = function() { while (true) { if (taking) { var val = iterator.next(); if (f.call(opt_obj, val, undefined, iterator)) { return val; } else { taking = false; } } else { throw goog.iter.StopIteration; } } }; return newIter; }; /** * Converts the iterator to an array * @param {goog.iter.Iterable} iterable The iterator to convert to an array. * @return {!Array} An array of the elements the iterator iterates over. */ goog.iter.toArray = function(iterable) { // Fast path for array-like. if (goog.isArrayLike(iterable)) { return goog.array.toArray(/** @type {!goog.array.ArrayLike} */(iterable)); } iterable = goog.iter.toIterator(iterable); var array = []; goog.iter.forEach(iterable, function(val) { array.push(val); }); return array; }; /** * Iterates over 2 iterators and returns true if they contain the same sequence * of elements and have the same length. * @param {goog.iter.Iterable} iterable1 The first iterable object. * @param {goog.iter.Iterable} iterable2 The second iterable object. * @return {boolean} true if the iterators contain the same sequence of * elements and have the same length. */ goog.iter.equals = function(iterable1, iterable2) { iterable1 = goog.iter.toIterator(iterable1); iterable2 = goog.iter.toIterator(iterable2); var b1, b2; /** @preserveTry */ try { while (true) { b1 = b2 = false; var val1 = iterable1.next(); b1 = true; var val2 = iterable2.next(); b2 = true; if (val1 != val2) { return false; } } } catch (ex) { if (ex !== goog.iter.StopIteration) { throw ex; } else { if (b1 && !b2) { // iterable1 done but iterable2 is not done. return false; } if (!b2) { /** @preserveTry */ try { // iterable2 not done? val2 = iterable2.next(); // iterable2 not done but iterable1 is done return false; } catch (ex1) { if (ex1 !== goog.iter.StopIteration) { throw ex1; } // iterable2 done as well... They are equal return true; } } } } return false; }; /** * Advances the iterator to the next position, returning the given default value * instead of throwing an exception if the iterator has no more entries. * @param {goog.iter.Iterable} iterable The iterable object. * @param {*} defaultValue The value to return if the iterator is empty. * @return {*} The next item in the iteration, or defaultValue if the iterator * was empty. */ goog.iter.nextOrValue = function(iterable, defaultValue) { try { return goog.iter.toIterator(iterable).next(); } catch (e) { if (e != goog.iter.StopIteration) { throw e; } return defaultValue; } }; /** * Cartesian product of zero or more sets. Gives an iterator that gives every * combination of one element chosen from each set. For example, * ([1, 2], [3, 4]) gives ([1, 3], [1, 4], [2, 3], [2, 4]). * @see http://docs.python.org/library/itertools.html#itertools.product * @param {...!goog.array.ArrayLike.<*>} var_args Zero or more sets, as arrays. * @return {!goog.iter.Iterator} An iterator that gives each n-tuple (as an * array). */ goog.iter.product = function(var_args) { var someArrayEmpty = goog.array.some(arguments, function(arr) { return !arr.length; }); // An empty set in a cartesian product gives an empty set. if (someArrayEmpty || !arguments.length) { return new goog.iter.Iterator(); } var iter = new goog.iter.Iterator(); var arrays = arguments; // The first indicies are [0, 0, ...] var indicies = goog.array.repeat(0, arrays.length); iter.next = function() { if (indicies) { var retVal = goog.array.map(indicies, function(valueIndex, arrayIndex) { return arrays[arrayIndex][valueIndex]; }); // Generate the next-largest indicies for the next call. // Increase the rightmost index. If it goes over, increase the next // rightmost (like carry-over addition). for (var i = indicies.length - 1; i >= 0; i--) { // Assertion prevents compiler warning below. goog.asserts.assert(indicies); if (indicies[i] < arrays[i].length - 1) { indicies[i]++; break; } // We're at the last indicies (the last element of every array), so // the iteration is over on the next call. if (i == 0) { indicies = null; break; } // Reset the index in this column and loop back to increment the // next one. indicies[i] = 0; } return retVal; } throw goog.iter.StopIteration; }; return iter; }; /** * Create an iterator to cycle over the iterable's elements indefinitely. * For example, ([1, 2, 3]) would return : 1, 2, 3, 1, 2, 3, ... * @see: http://docs.python.org/library/itertools.html#itertools.cycle. * @param {!goog.iter.Iterable} iterable The iterable object. * @return {!goog.iter.Iterator} An iterator that iterates indefinitely over * the values in {@code iterable}. */ goog.iter.cycle = function(iterable) { var baseIterator = goog.iter.toIterator(iterable); // We maintain a cache to store the iterable elements as we iterate // over them. The cache is used to return elements once we have // iterated over the iterable once. var cache = []; var cacheIndex = 0; var iter = new goog.iter.Iterator(); // This flag is set after the iterable is iterated over once var useCache = false; iter.next = function() { var returnElement = null; // Pull elements off the original iterator if not using cache if (!useCache) { try { // Return the element from the iterable returnElement = baseIterator.next(); cache.push(returnElement); return returnElement; } catch (e) { // If an exception other than StopIteration is thrown // or if there are no elements to iterate over (the iterable was empty) // throw an exception if (e != goog.iter.StopIteration || goog.array.isEmpty(cache)) { throw e; } // set useCache to true after we know that a 'StopIteration' exception // was thrown and the cache is not empty (to handle the 'empty iterable' // use case) useCache = true; } } returnElement = cache[cacheIndex]; cacheIndex = (cacheIndex + 1) % cache.length; return returnElement; }; return iter; };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Experimental observer-observable API. This is * intended as super lightweight replacement of * goog.events.EventTarget when w3c event model bubble/capture * behavior is not required. * * This is similar to {@code goog.pubsub.PubSub} but with different * intent and naming so that it is more discoverable. The API is * tighter while allowing for more flexibility offered by the * interface {@code Observable}. * * WARNING: This is still highly experimental. Please contact author * before using this. * */ goog.provide('goog.labs.observe.Observable'); goog.require('goog.disposable.IDisposable'); /** * Interface for an observable object. * @interface * @extends {goog.disposable.IDisposable} */ goog.labs.observe.Observable = function() {}; /** * Registers an observer on the observable. * * Note that no guarantee is provided on order of execution of the * observers. For a single notification, one Notice object is reused * across all invoked observers. * * Note that if an observation with the same observer is already * registered, it will not be registered again. Comparison is done via * observer's {@code equals} method. * * @param {!goog.labs.observe.Observer} observer The observer to add. * @return {boolean} Whether the observer was successfully added. */ goog.labs.observe.Observable.prototype.observe = function(observer) {}; /** * Unregisters an observer from the observable. The parameter must be * the same as those passed to {@code observe} method. Comparison is * done via observer's {@code equals} method. * @param {!goog.labs.observe.Observer} observer The observer to remove. * @return {boolean} Whether the observer is removed. */ goog.labs.observe.Observable.prototype.unobserve = function(observer) {}; /** * Notifies observers by invoking them. Optionally, a data object may be * given to be passed to each observer. * @param {*=} opt_data An optional data object. */ goog.labs.observe.Observable.prototype.notify = function(opt_data) {};
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview An implementation of {@code Observable} that can be * used as base class or composed into another class that wants to * implement {@code Observable}. */ goog.provide('goog.labs.observe.SimpleObservable'); goog.require('goog.Disposable'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.labs.observe.Notice'); goog.require('goog.labs.observe.Observable'); goog.require('goog.labs.observe.Observer'); goog.require('goog.object'); /** * A simple implementation of {@code goog.labs.observe.Observable} that can * be used as a standalone observable or as a base class for other * observable object. * * When another class wants to implement observable without extending * {@code SimpleObservable}, they can create an instance of * {@code SimpleObservable}, specifying {@code opt_actualObservable}, * and delegate to the instance. Here is a trivial example: * * <pre> * ClassA = function() { * goog.base(this); * this.observable_ = new SimpleObservable(this); * this.registerDisposable(this.observable_); * }; * goog.inherits(ClassA, goog.Disposable); * * ClassA.prototype.observe = function(observer) { * this.observable_.observe(observer); * }; * * ClassA.prototype.unobserve = function(observer) { * this.observable_.unobserve(observer); * }; * * ClassA.prototype.notify = function(opt_data) { * this.observable_.notify(opt_data); * }; * </pre> * * @param {!goog.labs.observe.Observable=} opt_actualObservable * Optional observable object. Defaults to 'this'. When used as * base class, the parameter need not be given. It is only useful * when using this class to implement implement {@code Observable} * interface on another object, see example above. * @constructor * @implements {goog.labs.observe.Observable} * @extends {goog.Disposable} */ goog.labs.observe.SimpleObservable = function(opt_actualObservable) { goog.base(this); /** * @type {!goog.labs.observe.Observable} * @private */ this.actualObservable_ = opt_actualObservable || this; /** * Observers registered on this object. * @type {!Array.<!goog.labs.observe.Observer>} * @private */ this.observers_ = []; }; goog.inherits(goog.labs.observe.SimpleObservable, goog.Disposable); /** @override */ goog.labs.observe.SimpleObservable.prototype.observe = function(observer) { goog.asserts.assert(!this.isDisposed()); // Registers the (type, observer) only if it has not been previously // registered. var shouldRegisterObserver = !goog.array.some(this.observers_, goog.partial( goog.labs.observe.Observer.equals, observer)); if (shouldRegisterObserver) { this.observers_.push(observer); } return shouldRegisterObserver; }; /** @override */ goog.labs.observe.SimpleObservable.prototype.unobserve = function(observer) { goog.asserts.assert(!this.isDisposed()); return goog.array.removeIf(this.observers_, goog.partial( goog.labs.observe.Observer.equals, observer)); }; /** @override */ goog.labs.observe.SimpleObservable.prototype.notify = function(opt_data) { goog.asserts.assert(!this.isDisposed()); var notice = new goog.labs.observe.Notice(this.actualObservable_, opt_data); goog.array.forEach( goog.array.clone(this.observers_), function(observer) { observer.notify(notice); }); }; /** @override */ goog.labs.observe.SimpleObservable.prototype.disposeInternal = function() { this.observers_.length = 0; };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A set of {@code goog.labs.observe.Observable}s that * allow registering and removing observers to all of the observables * in the set. */ goog.provide('goog.labs.observe.ObservableSet'); goog.require('goog.array'); goog.require('goog.labs.observe.Observer'); /** * Creates a set of observables. * * An ObservableSet is a collection of observables. Observers may be * reigstered and will receive notifications when any of the * observables notify. This class is meant to simplify management of * observations on multiple observables of the same nature. * * @constructor */ goog.labs.observe.ObservableSet = function() { /** * The observers registered with this set. * @type {!Array.<!goog.labs.observe.Observer>} * @private */ this.observers_ = []; /** * The observables in this set. * @type {!Array.<!goog.labs.observe.Observable>} * @private */ this.observables_ = []; }; /** * Adds an observer that observes all observables in the set. If new * observables are added to or removed from the set, the observer will * be registered or unregistered accordingly. * * The observer will not be added if there is already an equivalent * observer. * * @param {!goog.labs.observe.Observer} observer The observer to invoke. * @return {boolean} Whether the observer is actually added. */ goog.labs.observe.ObservableSet.prototype.addObserver = function(observer) { // Check whether the observer already exists. if (goog.array.find(this.observers_, goog.partial( goog.labs.observe.Observer.equals, observer))) { return false; } this.observers_.push(observer); goog.array.forEach(this.observables_, function(o) { o.observe(observer); }); return true; }; /** * Removes an observer from the set. The observer will be removed from * all observables in the set. Does nothing if the observer is not in * the set. * @param {!goog.labs.observe.Observer} observer The observer to remove. * @return {boolean} Whether the observer is actually removed. */ goog.labs.observe.ObservableSet.prototype.removeObserver = function(observer) { // Check that the observer exists before removing. var removed = goog.array.removeIf(this.observers_, goog.partial( goog.labs.observe.Observer.equals, observer)); if (removed) { goog.array.forEach(this.observables_, function(o) { o.unobserve(observer); }); } return removed; }; /** * Removes all registered observers. */ goog.labs.observe.ObservableSet.prototype.removeAllObservers = function() { this.unregisterAll_(); this.observers_.length = 0; }; /** * Adds an observable to the set. All previously added and future * observers will be added to the new observable as well. * * The observable will not be added if it is already registered in the * set. * * @param {!goog.labs.observe.Observable} observable The observable to add. * @return {boolean} Whether the observable is actually added. */ goog.labs.observe.ObservableSet.prototype.addObservable = function(observable) { if (goog.array.contains(this.observables_, observable)) { return false; } this.observables_.push(observable); goog.array.forEach(this.observers_, function(observer) { observable.observe(observer); }); return true; }; /** * Removes an observable from the set. All observers registered on the * set will be removed from the observable as well. * @param {!goog.labs.observe.Observable} observable The observable to remove. * @return {boolean} Whether the observable is actually removed. */ goog.labs.observe.ObservableSet.prototype.removeObservable = function( observable) { var removed = goog.array.remove(this.observables_, observable); if (removed) { goog.array.forEach(this.observers_, function(observer) { observable.unobserve(observer); }); } return removed; }; /** * Removes all registered observables. */ goog.labs.observe.ObservableSet.prototype.removeAllObservables = function() { this.unregisterAll_(); this.observables_.length = 0; }; /** * Removes all registered observations and observables. */ goog.labs.observe.ObservableSet.prototype.removeAll = function() { this.removeAllObservers(); this.observables_.length = 0; }; /** * Unregisters all registered observers from all registered observables. * @private */ goog.labs.observe.ObservableSet.prototype.unregisterAll_ = function() { goog.array.forEach(this.observers_, function(observer) { goog.array.forEach(this.observables_, function(o) { o.unobserve(observer); }); }, this); };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provide definition of an observer. This is meant to * be used with {@code goog.labs.observe.Observable}. * * This file also provides convenient functions to compare and create * Observer objects. * */ goog.provide('goog.labs.observe.Observer'); /** * A class implementing {@code Observer} may be informed of changes in * observable object. * @see {goog.labs.observe.Observable} * @interface */ goog.labs.observe.Observer = function() {}; /** * Notifies the observer of changes to the observable object. * @param {!goog.labs.observe.Notice} notice The notice object. */ goog.labs.observe.Observer.prototype.notify; /** * Whether this observer is equal to the given observer. * @param {!goog.labs.observe.Observer} observer The observer to compare with. * @return {boolean} Whether the two observers are equal. */ goog.labs.observe.Observer.prototype.equals; /** * @param {!goog.labs.observe.Observer} observer1 Observer to compare. * @param {!goog.labs.observe.Observer} observer2 Observer to compare. * @return {boolean} Whether observer1 and observer2 are equal, as * determined by the first observer1's {@code equals} method. */ goog.labs.observe.Observer.equals = function(observer1, observer2) { return observer1 == observer2 || observer1.equals(observer2); }; /** * Creates an observer that calls the given function. * @param {function(!goog.labs.observe.Notice)} fn Function to be converted. * @param {!Object=} opt_scope Optional scope to execute the function. * @return {!goog.labs.observe.Observer} An observer object. */ goog.labs.observe.Observer.fromFunction = function(fn, opt_scope) { return new goog.labs.observe.Observer.FunctionObserver_(fn, opt_scope); }; /** * An observer that calls the given function on {@code notify}. * @param {function(!goog.labs.observe.Notice)} fn Function to delegate to. * @param {!Object=} opt_scope Optional scope to execute the function. * @constructor * @implements {goog.labs.observe.Observer} * @private */ goog.labs.observe.Observer.FunctionObserver_ = function(fn, opt_scope) { this.fn_ = fn; this.scope_ = opt_scope; }; /** @override */ goog.labs.observe.Observer.FunctionObserver_.prototype.notify = function( notice) { this.fn_.call(this.scope_, notice); }; /** @override */ goog.labs.observe.Observer.FunctionObserver_.prototype.equals = function( observer) { return this.fn_ === observer.fn_ && this.scope_ === observer.scope_; };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides a notice object that is used to encapsulates * information about a particular change/notification on an observable * object. */ goog.provide('goog.labs.observe.Notice'); /** * A notice object encapsulates information about a notification fired * by an observable. * @param {!goog.labs.observe.Observable} observable The observable * object that fires this notice. * @param {*=} opt_data The optional data associated with this notice. * @constructor */ goog.labs.observe.Notice = function(observable, opt_data) { /** * @type {!goog.labs.observe.Observable} * @private */ this.observable_ = observable; /** * @type {*} * @private */ this.data_ = opt_data; }; /** * @return {!goog.labs.observe.Observable} The observable object that * fires this notice. */ goog.labs.observe.Notice.prototype.getObservable = function() { return this.observable_; }; /** * @return {*} The optional data associated with this notice. May be * null/undefined. */ goog.labs.observe.Notice.prototype.getData = function() { return this.data_; };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A set of observations. This set provides a convenient * means of observing many observables at once. * * This is similar in purpose to {@code goog.events.EventHandler}. * */ goog.provide('goog.labs.observe.ObservationSet'); goog.require('goog.array'); goog.require('goog.labs.observe.Observer'); /** * A set of observations. An observation is defined by an observable * and an observer. The set keeps track of observations and * allows their removal. * @param {!Object=} opt_defaultScope Optional function scope to use * when using {@code observeWithFunction} and * {@code unobserveWithFunction}. * @constructor */ goog.labs.observe.ObservationSet = function(opt_defaultScope) { /** * @type {!Array.<!goog.labs.observe.ObservationSet.Observation_>} * @private */ this.storedObservations_ = []; /** * @type {!Object|undefined} * @private */ this.defaultScope_ = opt_defaultScope; }; /** * Observes the given observer on the observable. * @param {!goog.labs.observe.Observable} observable The observable to * observe on. * @param {!goog.labs.observe.Observer} observer The observer. * @return {boolean} True if the observer is successfully registered. */ goog.labs.observe.ObservationSet.prototype.observe = function( observable, observer) { var success = observable.observe(observer); if (success) { this.storedObservations_.push( new goog.labs.observe.ObservationSet.Observation_( observable, observer)); } return success; }; /** * Observes the given function on the observable. * @param {!goog.labs.observe.Observable} observable The observable to * observe on. * @param {function(!goog.labs.observe.Notice)} fn The handler function. * @param {!Object=} opt_scope Optional scope. * @return {goog.labs.observe.Observer} The registered observer object. * If the observer is not successfully registered, this will be null. */ goog.labs.observe.ObservationSet.prototype.observeWithFunction = function( observable, fn, opt_scope) { var observer = goog.labs.observe.Observer.fromFunction( fn, opt_scope || this.defaultScope_); if (this.observe(observable, observer)) { return observer; } return null; }; /** * Unobserves the given observer from the observable. * @param {!goog.labs.observe.Observable} observable The observable to * unobserve from. * @param {!goog.labs.observe.Observer} observer The observer. * @return {boolean} True if the observer is successfully removed. */ goog.labs.observe.ObservationSet.prototype.unobserve = function( observable, observer) { var removed = goog.array.removeIf( this.storedObservations_, function(o) { return o.observable == observable && goog.labs.observe.Observer.equals(o.observer, observer); }); if (removed) { observable.unobserve(observer); } return removed; }; /** * Unobserves the given function from the observable. * @param {!goog.labs.observe.Observable} observable The observable to * unobserve from. * @param {function(!goog.labs.observe.Notice)} fn The handler function. * @param {!Object=} opt_scope Optional scope. * @return {boolean} True if the observer is successfully removed. */ goog.labs.observe.ObservationSet.prototype.unobserveWithFunction = function( observable, fn, opt_scope) { var observer = goog.labs.observe.Observer.fromFunction( fn, opt_scope || this.defaultScope_); return this.unobserve(observable, observer); }; /** * Removes all observations registered through this set. */ goog.labs.observe.ObservationSet.prototype.removeAll = function() { goog.array.forEach(this.storedObservations_, function(observation) { var observable = observation.observable; var observer = observation.observer; observable.unobserve(observer); }); }; /** * A representation of an observation, which is defined uniquely by * the observable and observer. * @param {!goog.labs.observe.Observable} observable The observable. * @param {!goog.labs.observe.Observer} observer The observer. * @constructor * @private */ goog.labs.observe.ObservationSet.Observation_ = function( observable, observer) { this.observable = observable; this.observer = observer; };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Restricted class definitions for Closure. * * @author johnlenz@google.com (John Lenz) */ goog.provide('goog.labs.classdef'); /** @typedef { {constructor:!Function}| {constructor:!Function, statics:(Object|function(Function):void)}} */ goog.labs.classdef.ClassDescriptor; /** * Creates a restricted form of a Closure "class": * - from the compiler's perspective, the instance returned from the * constructor is sealed (no new properties may be added). This enables * better type checking. * - the compiler will rewrite this definition to a form that is optimal * for type checking and optimization (initially this will be a more * traditional form). * * @param {Function} superClass The superclass or null. * @param {goog.labs.classdef.ClassDescriptor} def * An object literal describing the * the class. It may have the following properties: * "constructor": the constructor function * "statics": an object literal containing methods to add to the constructor * as "static" methods or a function that will recieve the constructor * function as its only parameter to which static properties can * be added. * all other properties are added to the prototype. * @return {!Function} The class constructor. */ goog.labs.classdef.defineClass = function(superClass, def) { // TODO(johnlenz): consider making the superClass an optional parameter. var constructor = def.constructor; var statics = def.statics; // Wrap the constructor prior to setting up the prototype and static methods. if (!constructor || constructor == Object.prototype.constructor) { throw Error('constructor property is required.'); } var cls = goog.labs.classdef.createSealingConstructor_(constructor); if (superClass) { goog.inherits(cls, superClass); } // Remove all the properties that should not be copied to the prototype. delete def.constructor; delete def.statics; goog.labs.classdef.applyProperties_(cls.prototype, def); if (statics != null) { if (statics instanceof Function) { statics(cls); } else { goog.labs.classdef.applyProperties_(cls, statics); } } return cls; }; /** * @define {boolean} Whether the instances returned by * goog.labs.classdef.defineClass should be sealed when possible. */ goog.labs.classdef.SEAL_CLASS_INSTANCES = goog.DEBUG; /** * If goog.labs.classdef.SEAL_CLASS_INSTANCES is enabled and Object.seal is * defined, this function will wrap the constructor in a function that seals the * results of the provided constructor function. * * @param {!Function} ctr The constructor whose results maybe be sealed. * @return {!Function} The replacement constructor. * @private */ goog.labs.classdef.createSealingConstructor_ = function(ctr) { if (goog.labs.classdef.SEAL_CLASS_INSTANCES && Object.seal instanceof Function) { /** @this {*} */ var wrappedCtr = function() { // Don't seal an instance of a subclass when it calls the constructor of // its super class as there is most likely still setup to do. var instance = ctr.apply(this, arguments) || this; if (this.constructor === wrappedCtr) { Object.seal(instance); } return instance; }; return wrappedCtr; } return ctr; }; // TODO(johnlenz): share these values with the goog.object /** * The names of the fields that are defined on Object.prototype. * @type {!Array.<string>} * @private * @const */ goog.labs.classdef.OBJECT_PROTOTYPE_FIELDS_ = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; // TODO(johnlenz): share this function with the goog.object /** * @param {!Object} target The object to add properties to. * @param {!Object} source The object to copy properites from. * @private */ goog.labs.classdef.applyProperties_ = function(target, source) { // TODO(johnlenz): update this to support ES5 getters/setters var key; for (key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } // For IE the for-in-loop does not contain any properties that are not // enumerable on the prototype object (for example isPrototypeOf from // Object.prototype) and it will also not include 'replace' on objects that // extend String and change 'replace' (not that it is common for anyone to // extend anything except Object). for (var i = 0; i < goog.labs.classdef.OBJECT_PROTOTYPE_FIELDS_.length; i++) { key = goog.labs.classdef.OBJECT_PROTOTYPE_FIELDS_[i]; if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for goog.labs.net.Image. * * @author nnaze@google.com (Nathan Naze) */ /** @suppress {extraProvide} */ goog.provide('goog.labs.net.imageTest'); goog.require('goog.events'); goog.require('goog.labs.net.image'); goog.require('goog.result'); goog.require('goog.result.Result'); goog.require('goog.string'); goog.require('goog.testing.AsyncTestCase'); goog.require('goog.testing.jsunit'); goog.require('goog.testing.recordFunction'); goog.setTestOnly('goog.labs.net.ImageTest'); var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall(); function testValidImage() { var url = 'testdata/cleardot.gif'; asyncTestCase.waitForAsync('image load'); assertEquals(0, goog.events.getTotalListenerCount()); var result = goog.labs.net.image.load(url); goog.result.waitOnSuccess(result, function(value) { assertEquals(goog.result.Result.State.SUCCESS, result.getState()); assertEquals('IMG', value.tagName); assertTrue(goog.string.endsWith(value.src, url)); assertUndefined(result.getError()); assertEquals('Listeners should have been cleaned up.', 0, goog.events.getTotalListenerCount()); asyncTestCase.continueTesting(); }); } function testInvalidImage() { var url = 'testdata/invalid.gif'; // This file does not exist. asyncTestCase.waitForAsync('image load'); assertEquals(0, goog.events.getTotalListenerCount()); var result = goog.labs.net.image.load(url); goog.result.wait(result, function(result) { assertEquals(goog.result.Result.State.ERROR, result.getState()); assertUndefined(result.getValue()); assertUndefined(result.getError()); assertEquals('Listeners should have been cleaned up.', 0, goog.events.getTotalListenerCount()); asyncTestCase.continueTesting(); }); } function testImageFactory() { var returnedImage = new Image(); var factory = function() { return returnedImage; }; var countedFactory = goog.testing.recordFunction(factory); var url = 'testdata/cleardot.gif'; asyncTestCase.waitForAsync('image load'); assertEquals(0, goog.events.getTotalListenerCount()); var result = goog.labs.net.image.load(url, countedFactory); goog.result.waitOnSuccess(result, function(value) { assertEquals(goog.result.Result.State.SUCCESS, result.getState()); assertEquals(returnedImage, value); assertEquals(1, countedFactory.getCallCount()); assertUndefined(result.getError()); assertEquals('Listeners should have been cleaned up.', 0, goog.events.getTotalListenerCount()); asyncTestCase.continueTesting(); }); } function testExistingImage() { var image = new Image(); var url = 'testdata/cleardot.gif'; asyncTestCase.waitForAsync('image load'); assertEquals(0, goog.events.getTotalListenerCount()); var result = goog.labs.net.image.load(url, image); goog.result.waitOnSuccess(result, function(value) { assertEquals(goog.result.Result.State.SUCCESS, result.getState()); assertEquals(image, value); assertUndefined(result.getError()); assertEquals('Listeners should have been cleaned up.', 0, goog.events.getTotalListenerCount()); asyncTestCase.continueTesting(); }); }
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Offered as an alternative to XhrIo as a way for making requests * via XMLHttpRequest. Instead of mirroring the XHR interface and exposing * events, results are used as a way to pass a "promise" of the response to * interested parties. * */ goog.provide('goog.labs.net.xhr'); goog.provide('goog.labs.net.xhr.Error'); goog.provide('goog.labs.net.xhr.HttpError'); goog.provide('goog.labs.net.xhr.TimeoutError'); goog.require('goog.debug.Error'); goog.require('goog.json'); goog.require('goog.net.HttpStatus'); goog.require('goog.net.XmlHttp'); goog.require('goog.result'); goog.require('goog.result.SimpleResult'); goog.require('goog.string'); goog.require('goog.uri.utils'); goog.scope(function() { var _ = goog.labs.net.xhr; var Result = goog.result.Result; var SimpleResult = goog.result.SimpleResult; var Wait = goog.result.wait; var HttpStatus = goog.net.HttpStatus; /** * Configuration options for an XMLHttpRequest. * - headers: map of header key/value pairs. * - timeoutMs: number of milliseconds after which the request will be timed * out by the client. Default is to allow the browser to handle timeouts. * - withCredentials: whether user credentials are to be included in a * cross-origin request. See: * http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#the-withcredentials-attribute * - mimeType: allows the caller to override the content-type and charset for * the request, which is useful when requesting binary data. See: * http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#dom-xmlhttprequest-overridemimetype * - xssiPrefix: Prefix used for protecting against XSSI attacks, which should * be removed before parsing the response as JSON. * * @typedef {{ * headers: (Object.<string>|undefined), * timeoutMs: (number|undefined), * withCredentials: (boolean|undefined), * mimeType: (string|undefined), * xssiPrefix: (string|undefined) * }} */ _.Options; /** * Defines the types that are allowed as post data. * @typedef {(ArrayBuffer|Blob|Document|FormData|null|string|undefined)} */ _.PostData; /** * The Content-Type HTTP header name. * @type {string} */ _.CONTENT_TYPE_HEADER = 'Content-Type'; /** * The Content-Type HTTP header value for a url-encoded form. * @type {string} */ _.FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded;charset=utf-8'; /** * Sends a get request, returning a transformed result which will be resolved * with the response text once the request completes. * * @param {string} url The URL to request. * @param {_.Options=} opt_options Configuration options for the request. * @return {!Result} A result object that will be resolved * with the response text once the request finishes. */ _.get = function(url, opt_options) { var result = _.send('GET', url, null, opt_options); var transformedResult = goog.result.transform(result, _.getResponseText_); return transformedResult; }; /** * Sends a post request, returning a transformed result which will be resolved * with the response text once the request completes. * * @param {string} url The URL to request. * @param {_.PostData} data The body of the post request. * @param {_.Options=} opt_options Configuration options for the request. * @return {!Result} A result object that will be resolved * with the response text once the request finishes. */ _.post = function(url, data, opt_options) { var result = _.send('POST', url, data, opt_options); var transformedResult = goog.result.transform(result, _.getResponseText_); return transformedResult; }; /** * Sends a get request, returning a result which will be resolved with * the parsed response text once the request completes. * * @param {string} url The URL to request. * @param {_.Options=} opt_options Configuration options for the request. * @return {!Result} A result object that will be resolved * with the response JSON once the request finishes. */ _.getJson = function(url, opt_options) { var result = _.send('GET', url, null, opt_options); var transformedResult = _.addJsonParsingCallbacks_(result, opt_options); return transformedResult; }; /** * Sends a post request, returning a result which will be resolved with * the parsed response text once the request completes. * * @param {string} url The URL to request. * @param {_.PostData} data The body of the post request. * @param {_.Options=} opt_options Configuration options for the request. * @return {!Result} A result object that will be resolved * with the response JSON once the request finishes. */ _.postJson = function(url, data, opt_options) { var result = _.send('POST', url, data, opt_options); var transformedResult = _.addJsonParsingCallbacks_(result, opt_options); return transformedResult; }; /** * Sends a request using XMLHttpRequest and returns a result. * * @param {string} method The HTTP method for the request. * @param {string} url The URL to request. * @param {_.PostData} data The body of the post request. * @param {_.Options=} opt_options Configuration options for the request. * @return {!Result} A result object that will be resolved * with the XHR object as it's value when the request finishes. */ _.send = function(method, url, data, opt_options) { var result = new SimpleResult(); // When the deferred is cancelled, we abort the XHR. We want to make sure // the readystatechange event still fires, so it can do the timeout // cleanup, however we don't want the callback or errback to be called // again. Thus the slight ugliness here. If results were pushed into // makeRequest, this could become a lot cleaner but we want an option for // people not to include goog.result.Result. goog.result.waitOnError(result, function(error, result) { if (result.isCanceled()) { xhr.abort(); xhr.onreadystatechange = goog.nullFunction; } }); function callback(data) { result.setValue(data); } function errback(err) { result.setError(err); } var xhr = _.makeRequest(method, url, data, opt_options, callback, errback); return result; }; /** * Creates a new XMLHttpRequest and initiates a request. * * @param {string} method The HTTP method for the request. * @param {string} url The URL to request. * @param {_.PostData} data The body of the post request, unless the content * type is explicitly set in the Options, then it will default to form * urlencoded. * @param {_.Options=} opt_options Configuration options for the request. * @param {function(XMLHttpRequest)=} opt_callback Optional callback to call * when the request completes. * @param {function(Error)=} opt_errback Optional callback to call * when there is an error. * @return {!XMLHttpRequest} The new XMLHttpRequest. */ _.makeRequest = function( method, url, data, opt_options, opt_callback, opt_errback) { var options = opt_options || {}; var callback = opt_callback || goog.nullFunction; var errback = opt_errback || goog.nullFunction; var timer; var xhr = /** @type {!XMLHttpRequest} */ (goog.net.XmlHttp()); try { xhr.open(method, url, true); } catch (e) { // XMLHttpRequest.open may throw when 'open' is called, for example, IE7 // throws "Access Denied" for cross-origin requests. errback(new _.Error('Error opening XHR: ' + e.message, url, xhr)); return xhr; } // So sad that IE doesn't support onload and onerror. xhr.onreadystatechange = function() { if (xhr.readyState == goog.net.XmlHttp.ReadyState.COMPLETE) { window.clearTimeout(timer); // Note: When developing locally, XHRs to file:// schemes return a status // code of 0. We mark that case as a success too. if (HttpStatus.isSuccess(xhr.status) || xhr.status === 0 && !_.isEffectiveSchemeHttp_(url)) { callback(xhr); } else { errback(new _.HttpError(xhr.status, url, xhr)); } } }; // Set the headers. var contentTypeIsSet = false; if (options.headers) { for (var key in options.headers) { xhr.setRequestHeader(key, options.headers[key]); } contentTypeIsSet = _.CONTENT_TYPE_HEADER in options.headers; } // If a content type hasn't been set, default to form-urlencoded/UTF8 for // POSTs. This is because some proxies have been known to reject posts // without a content-type. if (method == 'POST' && !contentTypeIsSet) { xhr.setRequestHeader(_.CONTENT_TYPE_HEADER, _.FORM_CONTENT_TYPE); } // Set whether to pass cookies on cross-domain requests (if applicable). // @see http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#the-withcredentials-attribute if (options.withCredentials) { xhr.withCredentials = options.withCredentials; } // Allow the request to override the mime type, useful for getting binary // data from the server. e.g. 'text/plain; charset=x-user-defined'. // @see http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#dom-xmlhttprequest-overridemimetype if (options.mimeType) { xhr.overrideMimeType(options.mimeType); } // Handle timeouts, if requested. if (options.timeoutMs > 0) { timer = window.setTimeout(function() { // Clear event listener before aborting so the errback will not be // called twice. xhr.onreadystatechange = goog.nullFunction; xhr.abort(); errback(new _.TimeoutError(url, xhr)); }, options.timeoutMs); } // Trigger the send. try { xhr.send(data); } catch (e) { // XMLHttpRequest.send is known to throw on some versions of FF, for example // if a cross-origin request is disallowed. xhr.onreadystatechange = goog.nullFunction; window.clearTimeout(timer); errback(new _.Error('Error sending XHR: ' + e.message, url, xhr)); } return xhr; }; /** * @param {string} url The URL to test. * @return {boolean} Whether the effective scheme is HTTP or HTTPs. * @private */ _.isEffectiveSchemeHttp_ = function(url) { var scheme = goog.uri.utils.getEffectiveScheme(url); // NOTE(user): Empty-string is for the case under FF3.5 when the location // is not defined inside a web worker. return scheme == 'http' || scheme == 'https' || scheme == ''; }; /** * Returns the response text of an XHR object. Intended to be called when * the result resolves. * * @param {!XMLHttpRequest} xhr The XHR object. * @return {string} The response text. * @private */ _.getResponseText_ = function(xhr) { return xhr.responseText; }; /** * Transforms a result, parsing the JSON in the original result value's * responseText. The transformed result's value is a javascript object. * Parse errors resolve the transformed result in an error. * * @param {!Result} result The result to wait on. * @param {_.Options|undefined} options The options object. * * @return {!Result} The transformed result. * @private */ _.addJsonParsingCallbacks_ = function(result, options) { var resultWithResponseText = goog.result.transform(result, _.getResponseText_); var prefixStrippedResult = resultWithResponseText; if (options && options.xssiPrefix) { prefixStrippedResult = goog.result.transform(resultWithResponseText, goog.partial(_.stripXssiPrefix_, options.xssiPrefix)); } var jsonParsedResult = goog.result.transform(prefixStrippedResult, goog.json.parse); return jsonParsedResult; }; /** * Strips the XSSI prefix from the input string. * * @param {string} prefix The XSSI prefix. * @param {string} string The string to strip the prefix from. * @return {string} The input string without the prefix. * @private */ _.stripXssiPrefix_ = function(prefix, string) { if (goog.string.startsWith(string, prefix)) { string = string.substring(prefix.length); } return string; }; /** * Generic error that may occur during a request. * * @param {string} message The error message. * @param {string} url The URL that was being requested. * @param {!XMLHttpRequest} xhr The XMLHttpRequest that failed. * @extends {goog.debug.Error} * @constructor */ _.Error = function(message, url, xhr) { goog.base(this, message + ', url=' + url); /** * The URL that was requested. * @type {string} */ this.url = url; /** * The XMLHttpRequest corresponding with the failed request. * @type {!XMLHttpRequest} */ this.xhr = xhr; }; goog.inherits(_.Error, goog.debug.Error); /** @override */ _.Error.prototype.name = 'XhrError'; /** * Class for HTTP errors. * * @param {number} status The HTTP status code of the response. * @param {string} url The URL that was being requested. * @param {!XMLHttpRequest} xhr The XMLHttpRequest that failed. * @extends {_.Error} * @constructor */ _.HttpError = function(status, url, xhr) { goog.base(this, 'Request Failed, status=' + status, url, xhr); /** * The HTTP status code for the error. * @type {number} */ this.status = status; }; goog.inherits(_.HttpError, _.Error); /** @override */ _.HttpError.prototype.name = 'XhrHttpError'; /** * Class for Timeout errors. * * @param {string} url The URL that timed out. * @param {!XMLHttpRequest} xhr The XMLHttpRequest that failed. * @extends {_.Error} * @constructor */ _.TimeoutError = function(url, xhr) { goog.base(this, 'Request timed out', url, xhr); }; goog.inherits(_.TimeoutError, _.Error); /** @override */ _.TimeoutError.prototype.name = 'XhrTimeoutError'; }); // goog.scope
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Simple image loader, used for preloading. * @author nnaze@google.com (Nathan Naze) */ goog.provide('goog.labs.net.image'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventType'); goog.require('goog.net.EventType'); goog.require('goog.result.SimpleResult'); goog.require('goog.userAgent'); /** * Loads a single image. Useful for preloading images. May be combined with * goog.result.combine to preload many images. * * @param {string} uri URI of the image. * @param {(Image|function(): !Image)=} opt_image If present, instead of * creating a new Image instance the function will use the passed Image * instance or the result of calling the Image factory respectively. This * can be used to control exactly how Image instances are created, for * example if they should be created in a particular document element, or * have fields that will trigger CORS image fetches. * @return {!goog.result.Result} An asyncronous result that will succeed * if the image successfully loads or error if the image load fails. */ goog.labs.net.image.load = function(uri, opt_image) { var image; if (!goog.isDef(opt_image)) { image = new Image(); } else if (goog.isFunction(opt_image)) { image = opt_image(); } else { image = opt_image; } // IE's load event on images can be buggy. Instead, we wait for // readystatechange events and check if readyState is 'complete'. // See: // http://msdn.microsoft.com/en-us/library/ie/ms536957(v=vs.85).aspx // http://msdn.microsoft.com/en-us/library/ie/ms534359(v=vs.85).aspx var loadEvent = goog.userAgent.IE ? goog.net.EventType.READY_STATE_CHANGE : goog.events.EventType.LOAD; var result = new goog.result.SimpleResult(); var handler = new goog.events.EventHandler(); handler.listen( image, [loadEvent, goog.net.EventType.ABORT, goog.net.EventType.ERROR], function(e) { // We only registered listeners for READY_STATE_CHANGE for IE. // If readyState is now COMPLETE, the image has loaded. // See related comment above. if (e.type == goog.net.EventType.READY_STATE_CHANGE && image.readyState != goog.net.EventType.COMPLETE) { return; } // At this point, we know whether the image load was successful // and no longer care about image events. goog.dispose(handler); // Whether the image successfully loaded. if (e.type == loadEvent) { result.setValue(image); } else { result.setError(); } }); // Initiate the image request. image.src = uri; return result; };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A labs location for functions destined for Closure's * {@code goog.object} namespace. */ goog.provide('goog.labs.object'); /** * Whether two values are not observably distinguishable. This * correctly detects that 0 is not the same as -0 and two NaNs are * practically equivalent. * * The implementation is as suggested by harmony:egal proposal. * * @param {*} v The first value to compare. * @param {*} v2 The second value to compare. * @return {boolean} Whether two values are not observably distinguishable. * @see http://wiki.ecmascript.org/doku.php?id=harmony:egal */ goog.labs.object.is = function(v, v2) { if (v === v2) { // 0 === -0, but they are not identical. // We need the cast because the compiler requires that v2 is a // number (although 1/v2 works with non-number). We cast to ? to // stop the compiler from type-checking this statement. return v !== 0 || 1 / v === 1 / /** @type {?} */ (v2); } // NaN is non-reflexive: NaN !== NaN, although they are identical. return v !== v && v2 !== v2; };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides the built-in string matchers like containsString, * startsWith, endsWith, etc. */ goog.provide('goog.labs.testing.ContainsStringMatcher'); goog.provide('goog.labs.testing.EndsWithMatcher'); goog.provide('goog.labs.testing.EqualToIgnoringCaseMatcher'); goog.provide('goog.labs.testing.EqualToIgnoringWhitespaceMatcher'); goog.provide('goog.labs.testing.EqualsMatcher'); goog.provide('goog.labs.testing.RegexMatcher'); goog.provide('goog.labs.testing.StartsWithMatcher'); goog.provide('goog.labs.testing.StringContainsInOrderMatcher'); goog.require('goog.asserts'); goog.require('goog.labs.testing.Matcher'); goog.require('goog.string'); /** * The ContainsString matcher. * * @param {string} value The expected string. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.ContainsStringMatcher = function(value) { /** * @type {string} * @private */ this.value_ = value; }; /** * Determines if input string contains the expected string. * * @override */ goog.labs.testing.ContainsStringMatcher.prototype.matches = function(actualValue) { goog.asserts.assertString(actualValue); return goog.string.contains(actualValue, this.value_); }; /** * @override */ goog.labs.testing.ContainsStringMatcher.prototype.describe = function(actualValue) { return actualValue + ' does not contain ' + this.value_; }; /** * The EndsWith matcher. * * @param {string} value The expected string. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.EndsWithMatcher = function(value) { /** * @type {string} * @private */ this.value_ = value; }; /** * Determines if input string ends with the expected string. * * @override */ goog.labs.testing.EndsWithMatcher.prototype.matches = function(actualValue) { goog.asserts.assertString(actualValue); return goog.string.endsWith(actualValue, this.value_); }; /** * @override */ goog.labs.testing.EndsWithMatcher.prototype.describe = function(actualValue) { return actualValue + ' does not end with ' + this.value_; }; /** * The EqualToIgnoringWhitespace matcher. * * @param {string} value The expected string. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.EqualToIgnoringWhitespaceMatcher = function(value) { /** * @type {string} * @private */ this.value_ = value; }; /** * Determines if input string contains the expected string. * * @override */ goog.labs.testing.EqualToIgnoringWhitespaceMatcher.prototype.matches = function(actualValue) { goog.asserts.assertString(actualValue); var string1 = goog.string.collapseWhitespace(actualValue); return goog.string.caseInsensitiveCompare(this.value_, string1) === 0; }; /** * @override */ goog.labs.testing.EqualToIgnoringWhitespaceMatcher.prototype.describe = function(actualValue) { return actualValue + ' is not equal(ignoring whitespace) to ' + this.value_; }; /** * The Equals matcher. * * @param {string} value The expected string. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.EqualsMatcher = function(value) { /** * @type {string} * @private */ this.value_ = value; }; /** * Determines if input string is equal to the expected string. * * @override */ goog.labs.testing.EqualsMatcher.prototype.matches = function(actualValue) { goog.asserts.assertString(actualValue); return this.value_ === actualValue; }; /** * @override */ goog.labs.testing.EqualsMatcher.prototype.describe = function(actualValue) { return actualValue + ' is not equal to ' + this.value_; }; /** * The MatchesRegex matcher. * * @param {!RegExp} regex The expected regex. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.RegexMatcher = function(regex) { /** * @type {!RegExp} * @private */ this.regex_ = regex; }; /** * Determines if input string is equal to the expected string. * * @override */ goog.labs.testing.RegexMatcher.prototype.matches = function( actualValue) { goog.asserts.assertString(actualValue); return this.regex_.test(actualValue); }; /** * @override */ goog.labs.testing.RegexMatcher.prototype.describe = function(actualValue) { return actualValue + ' does not match ' + this.regex_; }; /** * The StartsWith matcher. * * @param {string} value The expected string. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.StartsWithMatcher = function(value) { /** * @type {string} * @private */ this.value_ = value; }; /** * Determines if input string starts with the expected string. * * @override */ goog.labs.testing.StartsWithMatcher.prototype.matches = function(actualValue) { goog.asserts.assertString(actualValue); return goog.string.startsWith(actualValue, this.value_); }; /** * @override */ goog.labs.testing.StartsWithMatcher.prototype.describe = function(actualValue) { return actualValue + ' does not start with ' + this.value_; }; /** * The StringContainsInOrdermatcher. * * @param {Array.<string>} values The expected string values. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.StringContainsInOrderMatcher = function(values) { /** * @type {Array.<string>} * @private */ this.values_ = values; }; /** * Determines if input string contains, in order, the expected array of strings. * * @override */ goog.labs.testing.StringContainsInOrderMatcher.prototype.matches = function(actualValue) { goog.asserts.assertString(actualValue); var currentIndex, previousIndex = 0; for (var i = 0; i < this.values_.length; i++) { currentIndex = goog.string.contains(actualValue, this.values_[i]); if (currentIndex < 0 || currentIndex < previousIndex) { return false; } previousIndex = currentIndex; } return true; }; /** * @override */ goog.labs.testing.StringContainsInOrderMatcher.prototype.describe = function(actualValue) { return actualValue + ' does not contain the expected values in order.'; }; /** * Matches a string containing the given string. * * @param {string} value The expected value. * * @return {!goog.labs.testing.ContainsStringMatcher} A * ContainsStringMatcher. */ function containsString(value) { return new goog.labs.testing.ContainsStringMatcher(value); } /** * Matches a string that ends with the given string. * * @param {string} value The expected value. * * @return {!goog.labs.testing.EndsWithMatcher} A * EndsWithMatcher. */ function endsWith(value) { return new goog.labs.testing.EndsWithMatcher(value); } /** * Matches a string that equals (ignoring whitespace) the given string. * * @param {string} value The expected value. * * @return {!goog.labs.testing.EqualToIgnoringWhitespaceMatcher} A * EqualToIgnoringWhitespaceMatcher. */ function equalToIgnoringWhitespace(value) { return new goog.labs.testing.EqualToIgnoringWhitespaceMatcher(value); } /** * Matches a string that equals the given string. * * @param {string} value The expected value. * * @return {!goog.labs.testing.EqualsMatcher} A EqualsMatcher. */ function equals(value) { return new goog.labs.testing.EqualsMatcher(value); } /** * Matches a string against a regular expression. * * @param {!RegExp} regex The expected regex. * * @return {!goog.labs.testing.RegexMatcher} A RegexMatcher. */ function matchesRegex(regex) { return new goog.labs.testing.RegexMatcher(regex); } /** * Matches a string that starts with the given string. * * @param {string} value The expected value. * * @return {!goog.labs.testing.StartsWithMatcher} A * StartsWithMatcher. */ function startsWith(value) { return new goog.labs.testing.StartsWithMatcher(value); } /** * Matches a string that contains the given strings in order. * * @param {Array.<string>} values The expected value. * * @return {!goog.labs.testing.StringContainsInOrderMatcher} A * StringContainsInOrderMatcher. */ function stringContainsInOrder(values) { return new goog.labs.testing.StringContainsInOrderMatcher(values); }
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides main functionality of assertThat. assertThat calls the * matcher's matches method to test if a matcher matches assertThat's arguments. */ goog.provide('goog.labs.testing.MatcherError'); goog.provide('goog.labs.testing.assertThat'); goog.require('goog.asserts'); goog.require('goog.debug.Error'); goog.require('goog.labs.testing.Matcher'); /** * Asserts that the actual value evaluated by the matcher is true. * * @param {*} actual The object to assert by the matcher. * @param {!goog.labs.testing.Matcher} matcher A matcher to verify values. * @param {string=} opt_reason Description of what is asserted. * */ goog.labs.testing.assertThat = function(actual, matcher, opt_reason) { if (!matcher.matches(actual)) { // Prefix the error description with a reason from the assert ? var prefix = opt_reason ? opt_reason + ': ' : ''; var desc = prefix + matcher.describe(actual); // some sort of failure here throw new goog.labs.testing.MatcherError(desc); } }; /** * Error thrown when a Matcher fails to match the input value. * @param {string=} opt_message The error message. * @constructor * @extends {goog.debug.Error} */ goog.labs.testing.MatcherError = function(opt_message) { goog.base(this, opt_message); }; goog.inherits(goog.labs.testing.MatcherError, goog.debug.Error);
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides the built-in logic matchers: anyOf, allOf, and isNot. * */ goog.provide('goog.labs.testing.AllOfMatcher'); goog.provide('goog.labs.testing.AnyOfMatcher'); goog.provide('goog.labs.testing.IsNotMatcher'); goog.require('goog.array'); goog.require('goog.labs.testing.Matcher'); /** * The AllOf matcher. * * @param {!Array.<!goog.labs.testing.Matcher>} matchers Input matchers. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.AllOfMatcher = function(matchers) { /** * @type {!Array.<!goog.labs.testing.Matcher>} * @private */ this.matchers_ = matchers; }; /** * Determines if all of the matchers match the input value. * * @override */ goog.labs.testing.AllOfMatcher.prototype.matches = function(actualValue) { return goog.array.every(this.matchers_, function(matcher) { return matcher.matches(actualValue); }); }; /** * Describes why the matcher failed. The returned string is a concatenation of * all the failed matchers' error strings. * * @override */ goog.labs.testing.AllOfMatcher.prototype.describe = function(actualValue) { // TODO(user) : Optimize this to remove duplication with matches ? var errorString = ''; goog.array.forEach(this.matchers_, function(matcher) { if (!matcher.matches(actualValue)) { errorString += matcher.describe(actualValue) + '\n'; } }); return errorString; }; /** * The AnyOf matcher. * * @param {!Array.<!goog.labs.testing.Matcher>} matchers Input matchers. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.AnyOfMatcher = function(matchers) { /** * @type {!Array.<!goog.labs.testing.Matcher>} * @private */ this.matchers_ = matchers; }; /** * Determines if any of the matchers matches the input value. * * @override */ goog.labs.testing.AnyOfMatcher.prototype.matches = function(actualValue) { return goog.array.some(this.matchers_, function(matcher) { return matcher.matches(actualValue); }); }; /** * Describes why the matcher failed. * * @override */ goog.labs.testing.AnyOfMatcher.prototype.describe = function(actualValue) { // TODO(user) : Optimize this to remove duplication with matches ? var errorString = ''; goog.array.forEach(this.matchers_, function(matcher) { if (!matcher.matches(actualValue)) { errorString += matcher.describe(actualValue) + '\n'; } }); return errorString; }; /** * The IsNot matcher. * * @param {!goog.labs.testing.Matcher} matcher The matcher to negate. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.IsNotMatcher = function(matcher) { /** * @type {!goog.labs.testing.Matcher} * @private */ this.matcher_ = matcher; }; /** * Determines if the input value doesn't satisfy a matcher. * * @override */ goog.labs.testing.IsNotMatcher.prototype.matches = function(actualValue) { return !this.matcher_.matches(actualValue); }; /** * Describes why the matcher failed. * * @override */ goog.labs.testing.IsNotMatcher.prototype.describe = function(actualValue) { return 'The following is false: ' + this.matcher_.describe(actualValue); }; /** * Creates a matcher that will succeed only if all of the given matchers * succeed. * * @param {...goog.labs.testing.Matcher} var_args The matchers to test * against. * * @return {!goog.labs.testing.AllOfMatcher} The AllOf matcher. */ function allOf(var_args) { var matchers = goog.array.toArray(arguments); return new goog.labs.testing.AllOfMatcher(matchers); } /** * Accepts a set of matchers and returns a matcher which matches * values which satisfy the constraints of any of the given matchers. * * @param {...goog.labs.testing.Matcher} var_args The matchers to test * against. * * @return {!goog.labs.testing.AnyOfMatcher} The AnyOf matcher. */ function anyOf(var_args) { var matchers = goog.array.toArray(arguments); return new goog.labs.testing.AnyOfMatcher(matchers); } /** * Returns a matcher that negates the input matcher. The returned * matcher matches the values not matched by the input matcher and vice-versa. * * @param {!goog.labs.testing.Matcher} matcher The matcher to test against. * * @return {!goog.labs.testing.IsNotMatcher} The IsNot matcher. */ function isNot(matcher) { return new goog.labs.testing.IsNotMatcher(matcher); }
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides the built-in decorators: is, describedAs, anything. */ goog.provide('goog.labs.testing.AnythingMatcher'); goog.require('goog.labs.testing.Matcher'); /** * The Anything matcher. Matches all possible inputs. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.AnythingMatcher = function() {}; /** * Matches anything. Useful if one doesn't care what the object under test is. * * @override */ goog.labs.testing.AnythingMatcher.prototype.matches = function(actualObject) { return true; }; /** * This method is never called but is needed so AnythingMatcher implements the * Matcher interface. * * @override */ goog.labs.testing.AnythingMatcher.prototype.describe = function(actualObject) { throw Error('AnythingMatcher should never fail!'); }; /** * Returns a matcher that matches anything. * * @return {!goog.labs.testing.AnythingMatcher} A AnythingMatcher. */ function anything() { return new goog.labs.testing.AnythingMatcher(); } /** * Returnes any matcher that is passed to it (aids readability). * * @param {!goog.labs.testing.Matcher} matcher A matcher. * @return {!goog.labs.testing.Matcher} The wrapped matcher. */ function is(matcher) { return matcher; } /** * Returns a matcher with a customized description for the given matcher. * * @param {string} description The custom description for the matcher. * @param {!goog.labs.testing.Matcher} matcher The matcher. * * @return {!goog.labs.testing.Matcher} The matcher with custom description. */ function describedAs(description, matcher) { matcher.describe = function(value) { return description; }; return matcher; }
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides the built-in dictionary matcher methods like * hasEntry, hasEntries, hasKey, hasValue, etc. */ goog.provide('goog.labs.testing.HasEntriesMatcher'); goog.provide('goog.labs.testing.HasEntryMatcher'); goog.provide('goog.labs.testing.HasKeyMatcher'); goog.provide('goog.labs.testing.HasValueMatcher'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.labs.testing.Matcher'); goog.require('goog.string'); /** * The HasEntries matcher. * * @param {!Object} entries The entries to check in the object. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.HasEntriesMatcher = function(entries) { /** * @type {Object} * @private */ this.entries_ = entries; }; /** * Determines if an object has particular entries. * * @override */ goog.labs.testing.HasEntriesMatcher.prototype.matches = function(actualObject) { goog.asserts.assertObject(actualObject, 'Expected an Object'); var object = /** @type {!Object} */(actualObject); return goog.object.every(this.entries_, function(value, key) { return goog.object.containsKey(object, key) && object[key] === value; }); }; /** * @override */ goog.labs.testing.HasEntriesMatcher.prototype.describe = function(actualObject) { goog.asserts.assertObject(actualObject, 'Expected an Object'); var object = /** @type {!Object} */(actualObject); var errorString = 'Input object did not contain the following entries:\n'; goog.object.forEach(this.entries_, function(value, key) { if (!goog.object.containsKey(object, key) || object[key] !== value) { errorString += key + ': ' + value + '\n'; } }); return errorString; }; /** * The HasEntry matcher. * * @param {string} key The key for the entry. * @param {*} value The value for the key. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.HasEntryMatcher = function(key, value) { /** * @type {string} * @private */ this.key_ = key; /** * @type {*} * @private */ this.value_ = value; }; /** * Determines if an object has a particular entry. * * @override */ goog.labs.testing.HasEntryMatcher.prototype.matches = function(actualObject) { goog.asserts.assertObject(actualObject); return goog.object.containsKey(actualObject, this.key_) && actualObject[this.key_] === this.value_; }; /** * @override */ goog.labs.testing.HasEntryMatcher.prototype.describe = function(actualObject) { goog.asserts.assertObject(actualObject); var errorMsg; if (goog.object.containsKey(actualObject, this.key_)) { errorMsg = 'Input object did not contain key: ' + this.key_; } else { errorMsg = 'Value for key did not match value: ' + this.value_; } return errorMsg; }; /** * The HasKey matcher. * * @param {string} key The key to check in the object. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.HasKeyMatcher = function(key) { /** * @type {string} * @private */ this.key_ = key; }; /** * Determines if an object has a key. * * @override */ goog.labs.testing.HasKeyMatcher.prototype.matches = function(actualObject) { goog.asserts.assertObject(actualObject); return goog.object.containsKey(actualObject, this.key_); }; /** * @override */ goog.labs.testing.HasKeyMatcher.prototype.describe = function(actualObject) { goog.asserts.assertObject(actualObject); return 'Input object did not contain the key: ' + this.key_; }; /** * The HasValue matcher. * * @param {*} value The value to check in the object. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.HasValueMatcher = function(value) { /** * @type {*} * @private */ this.value_ = value; }; /** * Determines if an object contains a value * * @override */ goog.labs.testing.HasValueMatcher.prototype.matches = function(actualObject) { goog.asserts.assertObject(actualObject, 'Expected an Object'); var object = /** @type {!Object} */(actualObject); return goog.object.containsValue(object, this.value_); }; /** * @override */ goog.labs.testing.HasValueMatcher.prototype.describe = function(actualObject) { return 'Input object did not contain the value: ' + this.value_; }; /** * Gives a matcher that asserts an object contains all the given key-value pairs * in the input object. * * @param {!Object} entries The entries to check for presence in the object. * * @return {!goog.labs.testing.HasEntriesMatcher} A HasEntriesMatcher. */ function hasEntries(entries) { return new goog.labs.testing.HasEntriesMatcher(entries); } /** * Gives a matcher that asserts an object contains the given key-value pair. * * @param {string} key The key to check for presence in the object. * @param {*} value The value to check for presence in the object. * * @return {!goog.labs.testing.HasEntryMatcher} A HasEntryMatcher. */ function hasEntry(key, value) { return new goog.labs.testing.HasEntryMatcher(key, value); } /** * Gives a matcher that asserts an object contains the given key. * * @param {string} key The key to check for presence in the object. * * @return {!goog.labs.testing.HasKeyMatcher} A HasKeyMatcher. */ function hasKey(key) { return new goog.labs.testing.HasKeyMatcher(key); } /** * Gives a matcher that asserts an object contains the given value. * * @param {*} value The value to check for presence in the object. * * @return {!goog.labs.testing.HasValueMatcher} A HasValueMatcher. */ function hasValue(value) { return new goog.labs.testing.HasValueMatcher(value); }
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides the built-in number matchers like lessThan, * greaterThan, etc. */ goog.provide('goog.labs.testing.CloseToMatcher'); goog.provide('goog.labs.testing.EqualToMatcher'); goog.provide('goog.labs.testing.GreaterThanEqualToMatcher'); goog.provide('goog.labs.testing.GreaterThanMatcher'); goog.provide('goog.labs.testing.LessThanEqualToMatcher'); goog.provide('goog.labs.testing.LessThanMatcher'); goog.require('goog.asserts'); goog.require('goog.labs.testing.Matcher'); /** * The GreaterThan matcher. * * @param {number} value The value to compare. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.GreaterThanMatcher = function(value) { /** * @type {number} * @private */ this.value_ = value; }; /** * Determines if input value is greater than the expected value. * * @override */ goog.labs.testing.GreaterThanMatcher.prototype.matches = function(actualValue) { goog.asserts.assertNumber(actualValue); return actualValue > this.value_; }; /** * @override */ goog.labs.testing.GreaterThanMatcher.prototype.describe = function(actualValue) { goog.asserts.assertNumber(actualValue); return actualValue + ' is not greater than ' + this.value_; }; /** * The lessThan matcher. * * @param {number} value The value to compare. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.LessThanMatcher = function(value) { /** * @type {number} * @private */ this.value_ = value; }; /** * Determines if the input value is less than the expected value. * * @override */ goog.labs.testing.LessThanMatcher.prototype.matches = function(actualValue) { goog.asserts.assertNumber(actualValue); return actualValue < this.value_; }; /** * @override */ goog.labs.testing.LessThanMatcher.prototype.describe = function(actualValue) { goog.asserts.assertNumber(actualValue); return actualValue + ' is not less than ' + this.value_; }; /** * The GreaterThanEqualTo matcher. * * @param {number} value The value to compare. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.GreaterThanEqualToMatcher = function(value) { /** * @type {number} * @private */ this.value_ = value; }; /** * Determines if the input value is greater than equal to the expected value. * * @override */ goog.labs.testing.GreaterThanEqualToMatcher.prototype.matches = function(actualValue) { goog.asserts.assertNumber(actualValue); return actualValue >= this.value_; }; /** * @override */ goog.labs.testing.GreaterThanEqualToMatcher.prototype.describe = function(actualValue) { goog.asserts.assertNumber(actualValue); return actualValue + ' is not greater than equal to ' + this.value_; }; /** * The LessThanEqualTo matcher. * * @param {number} value The value to compare. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.LessThanEqualToMatcher = function(value) { /** * @type {number} * @private */ this.value_ = value; }; /** * Determines if the input value is less than or equal to the expected value. * * @override */ goog.labs.testing.LessThanEqualToMatcher.prototype.matches = function(actualValue) { goog.asserts.assertNumber(actualValue); return actualValue <= this.value_; }; /** * @override */ goog.labs.testing.LessThanEqualToMatcher.prototype.describe = function(actualValue) { goog.asserts.assertNumber(actualValue); return actualValue + ' is not less than equal to ' + this.value_; }; /** * The EqualTo matcher. * * @param {number} value The value to compare. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.EqualToMatcher = function(value) { /** * @type {number} * @private */ this.value_ = value; }; /** * Determines if the input value is equal to the expected value. * * @override */ goog.labs.testing.EqualToMatcher.prototype.matches = function(actualValue) { goog.asserts.assertNumber(actualValue); return actualValue === this.value_; }; /** * @override */ goog.labs.testing.EqualToMatcher.prototype.describe = function(actualValue) { goog.asserts.assertNumber(actualValue); return actualValue + ' is not equal to ' + this.value_; }; /** * The CloseTo matcher. * * @param {number} value The value to compare. * @param {number} range The range to check within. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.CloseToMatcher = function(value, range) { /** * @type {number} * @private */ this.value_ = value; /** * @type {number} * @private */ this.range_ = range; }; /** * Determines if input value is within a certain range of the expected value. * * @override */ goog.labs.testing.CloseToMatcher.prototype.matches = function(actualValue) { goog.asserts.assertNumber(actualValue); return Math.abs(this.value_ - actualValue) < this.range_; }; /** * @override */ goog.labs.testing.CloseToMatcher.prototype.describe = function(actualValue) { goog.asserts.assertNumber(actualValue); return actualValue + ' is not close to(' + this.range_ + ') ' + this.value_; }; /** * @param {number} value The expected value. * * @return {!goog.labs.testing.GreaterThanMatcher} A GreaterThanMatcher. */ function greaterThan(value) { return new goog.labs.testing.GreaterThanMatcher(value); } /** * @param {number} value The expected value. * * @return {!goog.labs.testing.GreaterThanEqualToMatcher} A * GreaterThanEqualToMatcher. */ function greaterThanEqualTo(value) { return new goog.labs.testing.GreaterThanEqualToMatcher(value); } /** * @param {number} value The expected value. * * @return {!goog.labs.testing.LessThanMatcher} A LessThanMatcher. */ function lessThan(value) { return new goog.labs.testing.LessThanMatcher(value); } /** * @param {number} value The expected value. * * @return {!goog.labs.testing.LessThanEqualToMatcher} A LessThanEqualToMatcher. */ function lessThanEqualTo(value) { return new goog.labs.testing.LessThanEqualToMatcher(value); } /** * @param {number} value The expected value. * * @return {!goog.labs.testing.EqualToMatcher} An EqualToMatcher. */ function equalTo(value) { return new goog.labs.testing.EqualToMatcher(value); } /** * @param {number} value The expected value. * @param {number} range The maximum allowed difference from the expected value. * * @return {!goog.labs.testing.CloseToMatcher} A CloseToMatcher. */ function closeTo(value, range) { return new goog.labs.testing.CloseToMatcher(value, range); }
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides the built-in object matchers like equalsObject, * hasProperty, instanceOf, etc. */ goog.provide('goog.labs.testing.HasPropertyMatcher'); goog.provide('goog.labs.testing.InstanceOfMatcher'); goog.provide('goog.labs.testing.IsNullMatcher'); goog.provide('goog.labs.testing.IsNullOrUndefinedMatcher'); goog.provide('goog.labs.testing.IsUndefinedMatcher'); goog.provide('goog.labs.testing.ObjectEqualsMatcher'); goog.require('goog.labs.testing.Matcher'); goog.require('goog.string'); /** * The Equals matcher. * * @param {!Object} expectedObject The expected object. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.ObjectEqualsMatcher = function(expectedObject) { /** * @type {!Object} * @private */ this.object_ = expectedObject; }; /** * Determines if two objects are the same. * * @override */ goog.labs.testing.ObjectEqualsMatcher.prototype.matches = function(actualObject) { return actualObject === this.object_; }; /** * @override */ goog.labs.testing.ObjectEqualsMatcher.prototype.describe = function(actualObject) { return 'Input object is not the same as the expected object.'; }; /** * The HasProperty matcher. * * @param {string} property Name of the property to test. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.HasPropertyMatcher = function(property) { /** * @type {string} * @private */ this.property_ = property; }; /** * Determines if an object has a property. * * @override */ goog.labs.testing.HasPropertyMatcher.prototype.matches = function(actualObject) { return this.property_ in actualObject; }; /** * @override */ goog.labs.testing.HasPropertyMatcher.prototype.describe = function(actualObject) { return 'Object does not have property: ' + this.property_; }; /** * The InstanceOf matcher. * * @param {!Object} object The expected class object. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.InstanceOfMatcher = function(object) { /** * @type {!Object} * @private */ this.object_ = object; }; /** * Determines if an object is an instance of another object. * * @override */ goog.labs.testing.InstanceOfMatcher.prototype.matches = function(actualObject) { return actualObject instanceof this.object_; }; /** * @override */ goog.labs.testing.InstanceOfMatcher.prototype.describe = function(actualObject) { return 'Input object is not an instance of the expected object'; }; /** * The IsNullOrUndefined matcher. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.IsNullOrUndefinedMatcher = function() {}; /** * Determines if input value is null or undefined. * * @override */ goog.labs.testing.IsNullOrUndefinedMatcher.prototype.matches = function(actualValue) { return !goog.isDefAndNotNull(actualValue); }; /** * @override */ goog.labs.testing.IsNullOrUndefinedMatcher.prototype.describe = function(actualValue) { return actualValue + ' is not null or undefined.'; }; /** * The IsNull matcher. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.IsNullMatcher = function() {}; /** * Determines if input value is null. * * @override */ goog.labs.testing.IsNullMatcher.prototype.matches = function(actualValue) { return goog.isNull(actualValue); }; /** * @override */ goog.labs.testing.IsNullMatcher.prototype.describe = function(actualValue) { return actualValue + ' is not null.'; }; /** * The IsUndefined matcher. * * @constructor * @implements {goog.labs.testing.Matcher} */ goog.labs.testing.IsUndefinedMatcher = function() {}; /** * Determines if input value is undefined. * * @override */ goog.labs.testing.IsUndefinedMatcher.prototype.matches = function(actualValue) { return !goog.isDef(actualValue); }; /** * @override */ goog.labs.testing.IsUndefinedMatcher.prototype.describe = function(actualValue) { return actualValue + ' is not undefined.'; }; /** * Returns a matcher that matches objects that are equal to the input object. * Equality in this case means the two objects are references to the same * object. * * @param {!Object} object The expected object. * * @return {!goog.labs.testing.ObjectEqualsMatcher} A * ObjectEqualsMatcher. */ function equalsObject(object) { return new goog.labs.testing.ObjectEqualsMatcher(object); } /** * Returns a matcher that matches objects that contain the input property. * * @param {string} property The property name to check. * * @return {!goog.labs.testing.HasPropertyMatcher} A HasPropertyMatcher. */ function hasProperty(property) { return new goog.labs.testing.HasPropertyMatcher(property); } /** * Returns a matcher that matches instances of the input class. * * @param {!Object} object The class object. * * @return {!goog.labs.testing.InstanceOfMatcher} A * InstanceOfMatcher. */ function instanceOfClass(object) { return new goog.labs.testing.InstanceOfMatcher(object); } /** * Returns a matcher that matches all null values. * * @return {!goog.labs.testing.IsNullMatcher} A IsNullMatcher. */ function isNull() { return new goog.labs.testing.IsNullMatcher(); } /** * Returns a matcher that matches all null and undefined values. * * @return {!goog.labs.testing.IsNullOrUndefinedMatcher} A * IsNullOrUndefinedMatcher. */ function isNullOrUndefined() { return new goog.labs.testing.IsNullOrUndefinedMatcher(); } /** * Returns a matcher that matches undefined values. * * @return {!goog.labs.testing.IsUndefinedMatcher} A IsUndefinedMatcher. */ function isUndefined() { return new goog.labs.testing.IsUndefinedMatcher(); }
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides the base Matcher interface. User code should use the * matchers through assertThat statements and not directly. */ goog.provide('goog.labs.testing.Matcher'); /** * A matcher object to be used in assertThat statements. * @interface */ goog.labs.testing.Matcher = function() {}; /** * Determines whether a value matches the constraints of the match. * * @param {*} value The object to match. * @return {boolean} Whether the input value matches this matcher. */ goog.labs.testing.Matcher.prototype.matches = function(value) {}; /** * Describes why the matcher failed. * * @param {*} value The value that didn't match. * @param {string=} opt_description A partial description to which the reason * will be appended. * * @return {string} Description of why the matcher failed. */ goog.labs.testing.Matcher.prototype.describe = function(value, opt_description) {};
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A collection similar to * {@code goog.labs.structs.Map}, but also allows associating multiple * values with a single key. * * This implementation ensures that you can use any string keys. * */ goog.provide('goog.labs.structs.Multimap'); goog.require('goog.array'); goog.require('goog.labs.object'); goog.require('goog.labs.structs.Map'); /** * Creates a new multimap. * @constructor */ goog.labs.structs.Multimap = function() { this.clear(); }; /** * The backing map. * @type {!goog.labs.structs.Map} * @private */ goog.labs.structs.Multimap.prototype.map_; /** * @type {number} * @private */ goog.labs.structs.Multimap.prototype.count_ = 0; /** * Clears the multimap. */ goog.labs.structs.Multimap.prototype.clear = function() { this.count_ = 0; this.map_ = new goog.labs.structs.Map(); }; /** * Clones this multimap. * @return {!goog.labs.structs.Multimap} A multimap that contains all * the mapping this multimap has. */ goog.labs.structs.Multimap.prototype.clone = function() { var map = new goog.labs.structs.Multimap(); map.addAllFromMultimap(this); return map; }; /** * Adds the given (key, value) pair to the map. The (key, value) pair * is guaranteed to be added. * @param {string} key The key to add. * @param {*} value The value to add. */ goog.labs.structs.Multimap.prototype.add = function(key, value) { var values = this.map_.get(key); if (!values) { this.map_.set(key, (values = [])); } values.push(value); this.count_++; }; /** * Stores a collection of values to the given key. Does not replace * existing (key, value) pairs. * @param {string} key The key to add. * @param {!Array.<*>} values The values to add. */ goog.labs.structs.Multimap.prototype.addAllValues = function(key, values) { goog.array.forEach(values, function(v) { this.add(key, v); }, this); }; /** * Adds the contents of the given map/multimap to this multimap. * @param {!(goog.labs.structs.Map|goog.labs.structs.Multimap)} map The * map to add. */ goog.labs.structs.Multimap.prototype.addAllFromMultimap = function(map) { goog.array.forEach(map.getEntries(), function(entry) { this.add(entry[0], entry[1]); }, this); }; /** * Replaces all the values for the given key with the given values. * @param {string} key The key whose values are to be replaced. * @param {!Array.<*>} values The new values. If empty, this is * equivalent to {@code removaAll(key)}. */ goog.labs.structs.Multimap.prototype.replaceValues = function(key, values) { this.removeAll(key); this.addAllValues(key, values); }; /** * Gets the values correspond to the given key. * @param {string} key The key to retrieve. * @return {!Array.<*>} An array of values corresponding to the given * key. May be empty. Note that the ordering of values are not * guaranteed to be consistent. */ goog.labs.structs.Multimap.prototype.get = function(key) { var values = /** @type {Array.<string>} */ (this.map_.get(key)); return values ? goog.array.clone(values) : []; }; /** * Removes a single occurrence of (key, value) pair. * @param {string} key The key to remove. * @param {*} value The value to remove. * @return {boolean} Whether any matching (key, value) pair is removed. */ goog.labs.structs.Multimap.prototype.remove = function(key, value) { var values = /** @type {Array.<string>} */ (this.map_.get(key)); if (!values) { return false; } var removed = goog.array.removeIf(values, function(v) { return goog.labs.object.is(value, v); }); if (removed) { this.count_--; if (values.length == 0) { this.map_.remove(key); } } return removed; }; /** * Removes all values corresponding to the given key. * @param {string} key The key whose values are to be removed. * @return {boolean} Whether any value is removed. */ goog.labs.structs.Multimap.prototype.removeAll = function(key) { // We have to first retrieve the values from the backing map because // we need to keep track of count (and correctly calculates the // return value). values may be undefined. var values = this.map_.get(key); if (this.map_.remove(key)) { this.count_ -= values.length; return true; } return false; }; /** * @return {boolean} Whether the multimap is empty. */ goog.labs.structs.Multimap.prototype.isEmpty = function() { return !this.count_; }; /** * @return {number} The count of (key, value) pairs in the map. */ goog.labs.structs.Multimap.prototype.getCount = function() { return this.count_; }; /** * @param {string} key The key to check. * @param {string} value The value to check. * @return {boolean} Whether the (key, value) pair exists in the multimap. */ goog.labs.structs.Multimap.prototype.containsEntry = function(key, value) { var values = /** @type {Array.<string>} */ (this.map_.get(key)); if (!values) { return false; } var index = goog.array.findIndex(values, function(v) { return goog.labs.object.is(v, value); }); return index >= 0; }; /** * @param {string} key The key to check. * @return {boolean} Whether the multimap contains at least one (key, * value) pair with the given key. */ goog.labs.structs.Multimap.prototype.containsKey = function(key) { return this.map_.containsKey(key); }; /** * @param {*} value The value to check. * @return {boolean} Whether the multimap contains at least one (key, * value) pair with the given value. */ goog.labs.structs.Multimap.prototype.containsValue = function(value) { return goog.array.some(this.map_.getValues(), function(values) { return goog.array.some(/** @type {Array} */ (values), function(v) { return goog.labs.object.is(v, value); }); }); }; /** * @return {!Array.<string>} An array of unique keys. */ goog.labs.structs.Multimap.prototype.getKeys = function() { return this.map_.getKeys(); }; /** * @return {!Array.<*>} An array of values. There may be duplicates. */ goog.labs.structs.Multimap.prototype.getValues = function() { return goog.array.flatten(this.map_.getValues()); }; /** * @return {!Array.<!Array>} An array of entries. Each entry is of the * form [key, value]. */ goog.labs.structs.Multimap.prototype.getEntries = function() { var keys = this.getKeys(); var entries = []; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var values = this.get(key); for (var j = 0; j < values.length; j++) { entries.push([key, values[j]]); } } return entries; };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A map data structure that offers a convenient API to * manipulate a key, value map. The key must be a string. * * This implementation also ensure that you can use keys that would * not be usable using a normal object literal {}. Some examples * include __proto__ (all newer browsers), toString/hasOwnProperty (IE * <= 8). */ goog.provide('goog.labs.structs.Map'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.labs.object'); goog.require('goog.object'); /** * Creates a new map. * @constructor */ goog.labs.structs.Map = function() { // clear() initializes the map to the empty state. this.clear(); }; /** * @type {function(this: Object, string): boolean} * @private */ goog.labs.structs.Map.objectPropertyIsEnumerable_ = Object.prototype.propertyIsEnumerable; /** * @type {function(this: Object, string): boolean} * @private */ goog.labs.structs.Map.objectHasOwnProperty_ = Object.prototype.hasOwnProperty; /** * Primary backing store of this map. * @type {!Object} * @private */ goog.labs.structs.Map.prototype.map_; /** * Secondary backing store for keys. The index corresponds to the * index for secondaryStoreValues_. * @type {!Array.<string>} * @private */ goog.labs.structs.Map.prototype.secondaryStoreKeys_; /** * Secondary backing store for keys. The index corresponds to the * index for secondaryStoreValues_. * @type {!Array.<*>} * @private */ goog.labs.structs.Map.prototype.secondaryStoreValues_; /** * Adds the (key, value) pair, overriding previous entry with the same * key, if any. * @param {string} key The key. * @param {*} value The value. */ goog.labs.structs.Map.prototype.set = function(key, value) { this.assertKeyIsString_(key); var newKey = !this.hasKeyInPrimaryStore_(key); this.map_[key] = value; // __proto__ is not settable on object. if (key == '__proto__' || // Shadows for built-in properties are not enumerable in IE <= 8 . (!goog.labs.structs.Map.BrowserFeature.OBJECT_CREATE_SUPPORTED && !goog.labs.structs.Map.objectPropertyIsEnumerable_.call( this.map_, key))) { delete this.map_[key]; var index = goog.array.indexOf(this.secondaryStoreKeys_, key); if ((newKey = index < 0)) { index = this.secondaryStoreKeys_.length; } this.secondaryStoreKeys_[index] = key; this.secondaryStoreValues_[index] = value; } if (newKey) this.count_++; }; /** * Gets the value for the given key. * @param {string} key The key whose value we want to retrieve. * @param {*=} opt_default The default value to return if the key does * not exist in the map, default to undefined. * @return {*} The value corresponding to the given key, or opt_default * if the key does not exist in this map. */ goog.labs.structs.Map.prototype.get = function(key, opt_default) { this.assertKeyIsString_(key); if (this.hasKeyInPrimaryStore_(key)) { return this.map_[key]; } var index = goog.array.indexOf(this.secondaryStoreKeys_, key); return index >= 0 ? this.secondaryStoreValues_[index] : opt_default; }; /** * Removes the map entry with the given key. * @param {string} key The key to remove. * @return {boolean} True if the entry is removed. */ goog.labs.structs.Map.prototype.remove = function(key) { this.assertKeyIsString_(key); if (this.hasKeyInPrimaryStore_(key)) { this.count_--; delete this.map_[key]; return true; } else { var index = goog.array.indexOf(this.secondaryStoreKeys_, key); if (index >= 0) { this.count_--; goog.array.removeAt(this.secondaryStoreKeys_, index); goog.array.removeAt(this.secondaryStoreValues_, index); return true; } } return false; }; /** * Adds the content of the map to this map. If a new entry uses a key * that already exists in this map, the existing key is replaced. * @param {!goog.labs.structs.Map} map The map to add. */ goog.labs.structs.Map.prototype.addAll = function(map) { goog.array.forEach(map.getKeys(), function(key) { this.set(key, map.get(key)); }, this); }; /** * @return {boolean} True if the map is empty. */ goog.labs.structs.Map.prototype.isEmpty = function() { return !this.count_; }; /** * @return {number} The number of the entries in this map. */ goog.labs.structs.Map.prototype.getCount = function() { return this.count_; }; /** * @param {string} key The key to check. * @return {boolean} True if the map contains the given key. */ goog.labs.structs.Map.prototype.containsKey = function(key) { this.assertKeyIsString_(key); return this.hasKeyInPrimaryStore_(key) || goog.array.contains(this.secondaryStoreKeys_, key); }; /** * Whether the map contains the given value. The comparison is done * using !== comparator. Also returns true if the passed value is NaN * and a NaN value exists in the map. * @param {*} value Value to check. * @return {boolean} True if the map contains the given value. */ goog.labs.structs.Map.prototype.containsValue = function(value) { var found = goog.object.some(this.map_, function(v, k) { return this.hasKeyInPrimaryStore_(k) && goog.labs.object.is(v, value); }, this); return found || goog.array.contains(this.secondaryStoreValues_, value); }; /** * @return {!Array.<string>} An array of all the keys contained in this map. */ goog.labs.structs.Map.prototype.getKeys = function() { var keys; if (goog.labs.structs.Map.BrowserFeature.OBJECT_KEYS_SUPPORTED) { keys = goog.array.clone(Object.keys(this.map_)); } else { keys = []; for (var key in this.map_) { if (goog.labs.structs.Map.objectHasOwnProperty_.call(this.map_, key)) { keys.push(key); } } } goog.array.extend(keys, this.secondaryStoreKeys_); return keys; }; /** * @return {!Array.<*>} An array of all the values contained in this map. * There may be duplicates. */ goog.labs.structs.Map.prototype.getValues = function() { var values = []; var keys = this.getKeys(); for (var i = 0; i < keys.length; i++) { values.push(this.get(keys[i])); } return values; }; /** * @return {!Array.<Array>} An array of entries. Each entry is of the * form [key, value]. Do not rely on consistent ordering of entries. */ goog.labs.structs.Map.prototype.getEntries = function() { var entries = []; var keys = this.getKeys(); for (var i = 0; i < keys.length; i++) { var key = keys[i]; entries.push([key, this.get(key)]); } return entries; }; /** * Clears the map to the initial state. */ goog.labs.structs.Map.prototype.clear = function() { this.map_ = goog.labs.structs.Map.BrowserFeature.OBJECT_CREATE_SUPPORTED ? Object.create(null) : {}; this.secondaryStoreKeys_ = []; this.secondaryStoreValues_ = []; this.count_ = 0; }; /** * Clones this map. * @return {!goog.labs.structs.Map} The clone of this map. */ goog.labs.structs.Map.prototype.clone = function() { var map = new goog.labs.structs.Map(); map.addAll(this); return map; }; /** * @param {string} key The key to check. * @return {boolean} True if the given key has been added successfully * to the primary store. * @private */ goog.labs.structs.Map.prototype.hasKeyInPrimaryStore_ = function(key) { // New browsers that support Object.create do not allow setting of // __proto__. In other browsers, hasOwnProperty will return true for // __proto__ for object created with literal {}, so we need to // special case it. if (key == '__proto__') { return false; } if (goog.labs.structs.Map.BrowserFeature.OBJECT_CREATE_SUPPORTED) { return key in this.map_; } return goog.labs.structs.Map.objectHasOwnProperty_.call(this.map_, key); }; /** * Asserts that the given key is a string. * @param {string} key The key to check. * @private */ goog.labs.structs.Map.prototype.assertKeyIsString_ = function(key) { goog.asserts.assert(goog.isString(key), 'key must be a string.'); }; /** * Browser feature enum necessary for map. * @enum {boolean} */ goog.labs.structs.Map.BrowserFeature = { // TODO(user): Replace with goog.userAgent detection. /** * Whether Object.create method is supported. */ OBJECT_CREATE_SUPPORTED: !!Object.create, /** * Whether Object.keys method is supported. */ OBJECT_KEYS_SUPPORTED: !!Object.keys };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Performance test for goog.structs.Map and * goog.labs.structs.Map. To run this test fairly, you would have to * compile this via JsCompiler (with --export_test_functions), and * pull the compiled JS into an empty HTML file. */ goog.provide('goog.labs.structs.mapPerf'); goog.require('goog.dom'); goog.require('goog.labs.structs.Map'); goog.require('goog.structs.Map'); goog.require('goog.testing.PerformanceTable'); goog.require('goog.testing.jsunit'); goog.scope(function() { var mapPerf = goog.labs.structs.mapPerf; /** * @typedef {goog.labs.structs.Map|goog.structs.Map} */ mapPerf.MapType; /** * @type {goog.testing.PerformanceTable} */ mapPerf.perfTable; /** * A key list. This maps loop index to key name to be used during * benchmark. This ensure that we do not need to pay the cost of * string concatenation/GC whenever we derive a key from loop index. * * This is filled once in setUpPage and then remain unchanged for the * rest of the test case. * * @type {Array} */ mapPerf.keyList = []; /** * Maxium number of keys in keyList (and, by extension, the map under * test). * @type {number} */ mapPerf.MAX_NUM_KEY = 10000; /** * Fills the given map with generated key-value pair. * @param {mapPerf.MapType} map The map to fill. * @param {number} numKeys The number of key-value pair to fill. */ mapPerf.fillMap = function(map, numKeys) { goog.asserts.assert(numKeys <= mapPerf.MAX_NUM_KEY); for (var i = 0; i < numKeys; ++i) { map.set(mapPerf.keyList[i], i); } }; /** * Primes the given map with deletion of keys. * @param {mapPerf.MapType} map The map to prime. * @return {mapPerf.MapType} The primed map (for chaining). */ mapPerf.primeMapWithDeletion = function(map) { for (var i = 0; i < 1000; ++i) { map.set(mapPerf.keyList[i], i); } for (var i = 0; i < 1000; ++i) { map.remove(mapPerf.keyList[i]); } return map; }; /** * Runs performance test for Map#get with the given map. * @param {mapPerf.MapType} map The map to stress. * @param {string} message Message to be put in performance table. */ mapPerf.runPerformanceTestForMapGet = function(map, message) { mapPerf.fillMap(map, 10000); mapPerf.perfTable.run( function() { // Creates local alias for map and keyList. var localMap = map; var localKeyList = mapPerf.keyList; for (var i = 0; i < 500; ++i) { var sum = 0; for (var j = 0; j < 10000; ++j) { sum += localMap.get(localKeyList[j]); } } }, message); }; /** * Runs performance test for Map#set with the given map. * @param {mapPerf.MapType} map The map to stress. * @param {string} message Message to be put in performance table. */ mapPerf.runPerformanceTestForMapSet = function(map, message) { mapPerf.perfTable.run( function() { // Creates local alias for map and keyList. var localMap = map; var localKeyList = mapPerf.keyList; for (var i = 0; i < 500; ++i) { for (var j = 0; j < 10000; ++j) { localMap.set(localKeyList[i], i); } } }, message); }; goog.global['setUpPage'] = function() { var content = goog.dom.createDom('div'); goog.dom.insertChildAt(document.body, content, 0); var ua = navigator.userAgent; content.innerHTML = '<h1>Closure Performance Tests - Map</h1>' + '<p><strong>User-agent: </strong><span id="ua">' + ua + '</span></p>' + '<div id="perf-table"></div>' + '<hr>'; mapPerf.perfTable = new goog.testing.PerformanceTable( goog.dom.getElement('perf-table')); // Fills keyList. for (var i = 0; i < mapPerf.MAX_NUM_KEY; ++i) { mapPerf.keyList.push('k' + i); } }; goog.global['testGetFromLabsMap'] = function() { mapPerf.runPerformanceTestForMapGet( new goog.labs.structs.Map(), '#get: no previous deletion (Labs)'); }; goog.global['testGetFromOriginalMap'] = function() { mapPerf.runPerformanceTestForMapGet( new goog.structs.Map(), '#get: no previous deletion (Original)'); }; goog.global['testGetWithPreviousDeletionFromLabsMap'] = function() { mapPerf.runPerformanceTestForMapGet( mapPerf.primeMapWithDeletion(new goog.labs.structs.Map()), '#get: with previous deletion (Labs)'); }; goog.global['testGetWithPreviousDeletionFromOriginalMap'] = function() { mapPerf.runPerformanceTestForMapGet( mapPerf.primeMapWithDeletion(new goog.structs.Map()), '#get: with previous deletion (Original)'); }; goog.global['testSetFromLabsMap'] = function() { mapPerf.runPerformanceTestForMapSet( new goog.labs.structs.Map(), '#set: no previous deletion (Labs)'); }; goog.global['testSetFromOriginalMap'] = function() { mapPerf.runPerformanceTestForMapSet( new goog.structs.Map(), '#set: no previous deletion (Original)'); }; }); // goog.scope
JavaScript