### Starting a Simple HTTP Server (sh) Source: https://github.com/google/closure-library/blob/master/doc/develop/get-started.md Provides example commands for starting a simple local HTTP server using either Node.js (`npx http-server`) or Python (`python -m SimpleHTTPServer` or `python -m http.server`) to serve the application files for testing. ```sh # Node.js npx http-server # Python 2 python -m SimpleHTTPServer 8080 # Python 3 python -m http.server 8080 ``` -------------------------------- ### Initializing npm and Installing Closure Library (sh) Source: https://github.com/google/closure-library/blob/master/doc/develop/get-started.md Initializes a new npm package and installs the Google Closure Library as a project dependency. This sets up the basic project structure and downloads the library files. ```sh npm init -y npm install google-closure-library ``` -------------------------------- ### Installing google-closure-deps (sh) Source: https://github.com/google/closure-library/blob/master/doc/develop/get-started.md Installs the `google-closure-deps` package as a development dependency. This package provides command-line tools necessary for generating dependency files (`deps.js`) for uncompiled Closure code. ```sh npm install --save-dev google-closure-deps ``` -------------------------------- ### Installing Closure Compiler via npm (Development Dependency) Source: https://github.com/google/closure-library/blob/master/doc/develop/get-started.md This command installs the Google Closure Compiler command-line tool using npm, saving it as a development dependency in your project's package.json file. ```sh npm install --save-dev google-closure-compiler ``` -------------------------------- ### Getting Help for closure-make-deps (sh) Source: https://github.com/google/closure-library/blob/master/doc/develop/get-started.md Executes the `closure-make-deps` command with the `--help` flag to display usage information and available options for the dependency generation tool. ```sh $(npm bin)/closure-make-deps --help ``` -------------------------------- ### Compiling Multiple JavaScript Files with Closure Compiler (Shell) Source: https://github.com/google/closure-library/blob/master/doc/develop/get-started.md This provides a simplified example of using Closure Compiler to combine and compile multiple input JavaScript files into a single output file. ```sh $(npm bin)/google-closure-compiler --js_output_file=out.js in1.js in2.js in3.js ... ``` -------------------------------- ### Creating an HTML File for Closure App (html) Source: https://github.com/google/closure-library/blob/master/doc/develop/get-started.md Sets up a basic HTML page that includes the Closure Library base file (`base.js`), the generated dependency file (`deps.js`), and a script tag that uses `goog.require('hello')` to load the application's main module and its dependencies. ```html
Content to be rendered below
``` -------------------------------- ### Setting up Logging with Closure Library Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/toolbar.html Initializes the Closure Library logging system, sets the root logger level, creates a DivConsole for displaying logs in an HTML element, and starts capturing logs. It also retrieves component event types for logging. ```javascript var timer; // Set up a logger. goog.log.setLevel(goog.log.getRootLogger(), goog.log.Level.ALL); var logger = goog.log.getLogger('demo'); var logconsole = new goog.debug.DivConsole(goog.dom.getElement('log')); logconsole.setCapturing(true); var EVENTS = goog.object.getValues(goog.ui.Component.EventType); goog.log.fine(logger, 'Listening for: ' + EVENTS.join(', ') + '.'); ``` -------------------------------- ### Generating deps.js with closure-make-deps (sh) Source: https://github.com/google/closure-library/blob/master/doc/develop/get-started.md Uses the `closure-make-deps` tool to generate a `deps.js` file. This command includes the application's source file (`hello.js`), Closure Library's own `deps.js`, and specifies the path to the Closure Library, mapping dependencies for the debug loader. ```sh $(npm bin)/closure-make-deps \ -f hello.js \ -f node_modules/google-closure-library/closure/goog/deps.js \ --closure-path node_modules/google-closure-library/closure/goog \ > deps.js ``` -------------------------------- ### Creating a Simple Closure JavaScript File (js) Source: https://github.com/google/closure-library/blob/master/doc/develop/get-started.md Defines a Closure module named 'hello'. It requires the `goog.dom` namespace and defines a function `sayHi` that creates an `h1` element using `goog.dom.createDom` and appends it to the document body. The function is then called. ```js /** * @fileoverview Closure getting started tutorial code example. */ goog.module('hello'); const {TagName, createDom} = goog.require('goog.dom'); /** * Appends an `h1` tag to the body with the message "Hello world!". */ function sayHi() { const newHeader = createDom(TagName.H1, {'style': 'background-color:#EEE'}, 'Hello world!'); document.body.appendChild(newHeader); } sayHi(); ``` -------------------------------- ### Compiling a Closure Library Application with Dependencies (Shell) Source: https://github.com/google/closure-library/blob/master/doc/develop/get-started.md This shell command executes the Closure Compiler to compile a Closure Library application. It specifies the main entry point, includes the Closure Library source files, uses dependency pruning, and outputs the compiled code to a single file. ```sh $(npm bin)/google-closure-compiler \ --js hello.js \ --js node_modules/google-closure-library/**/*.js \ --dependency_mode=PRUNE \ --entry_point=goog:hello \ --js_output_file hello_compiled.js ``` -------------------------------- ### Initializing Closure Component Examples (JavaScript) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/samplecomponent.html Initializes and renders/decorates multiple instances of a sample Closure Component. Demonstrates rendering a new component, decorating an existing DOM element, and updating a component's label based on a timer event. Requires goog.ui.Component, goog.Timer, and goog.events. ```JavaScript goog.require('goog.ui.Component'); goog.require('goog.Timer'); function initPage() { // Shows default initial label var box1 = new goog.demos.SampleComponent(); box1.render(goog.dom.getElement('target1')); // Shows label taken from DIV text var box2 = new goog.demos.SampleComponent(); box2.decorate(goog.dom.getElement('target2')); // Shows initial Label + setting label var box3 = new goog.demos.SampleComponent('Counting...'); box3.decorate(goog.dom.getElement('target3')); var t = new goog.Timer(2000); var value = 0; goog.events.listen(t, goog.Timer.TICK, function (e) { box3.setLabelText((++value).toString()); }); t.start(); } goog.events.listen(window, goog.events.EventType.LOAD, initPage); ``` -------------------------------- ### Demonstrating Normal Tracing with goog.debug.Trace (JavaScript) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/tracer.html Initializes a trace, starts and stops nested tracers within loops, adds a comment, and outputs the trace results to an HTML element. ```JavaScript function normalTracer() { goog.debug.Trace.initCurrentTrace(0); var tracer = goog.debug.Trace.startTracer('Outer Loop'); var sum = 0; for (var i = 0; i < 15; i++) { sum = 0; var t2 = goog.debug.Trace.startTracer('Run ' + i); for (var j = 0; j < 50000; j++) { sum += j * i; } goog.debug.Trace.addComment('after'); goog.debug.Trace.stopTracer(t2); } goog.debug.Trace.stopTracer(tracer); var s = goog.debug.Trace.toString(); var outputElt = document.getElementById('output'); outputElt.innerHTML = goog.string.whitespaceEscape( goog.string.htmlEscape(s)); } ``` -------------------------------- ### Initialize Jekyll Data and Start Analytics (JavaScript) Source: https://github.com/google/closure-library/blob/master/doc/_layouts/empty.html This JavaScript snippet assigns an object containing Jekyll site and page data (serialized as JSON) to the global variable `window['_JEKYLL_DATA']`. It then calls the `startAnalytics()` method on the `closure.docs` object, presumably to begin tracking user activity. ```javascript window['_JEKYLL_DATA'] = { 'site': {{site|jsonify}}, 'page': {{page|jsonify}}, }; closure.docs.startAnalytics(); ``` -------------------------------- ### Start goog.Timer - JavaScript Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/timers.html Creates and starts a goog.Timer instance with a specified interval. Disposes of any existing timer and sets up a listener for the TICK event. ```javascript /** * Start a timer. */ var doTimerStart = function() { var seconds = getSeconds('timerSeconds'); if (typeof seconds !== 'number') { return; } if (timer) { timer.dispose(); tickCount = 0; } // A timer can be created with no callback object, // listen for the TICK event. timer = new goog.Timer(inMs(seconds)); timer.start(); goog.events.listen(timer, goog.Timer.TICK, tickAction); }; ``` -------------------------------- ### Setting up goog.messaging.PortChannel in JavaScript Source: https://github.com/google/closure-library/blob/master/closure/goog/messaging/testdata/portchannel_wrong_origin_inner.html Initializes Closure Library defines, requires the PortChannel module, creates a channel instance connected to a specific origin, and registers a 'ping' service that responds with 'pong'. ```JavaScript var CLOSURE_DEFINES = CLOSURE_DEFINES || {}; CLOSURE_DEFINES["goog.ENABLE_DEBUG_LOADER"]=true; goog.require('goog.messaging.PortChannel'); var channel = goog.messaging.PortChannel.forGlobalWindow( 'http://somewhere-else.com' ); channel.registerService('ping', function(msg) { channel.send('pong', msg); }); ``` -------------------------------- ### Executing the Debug Demonstration (JavaScript) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/debug.html Calls the demoDebug function to run the debugging examples and output results to the configured debug window or console. ```javascript demoDebug(); ``` -------------------------------- ### Importing Closure Library Modules Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/toolbar.html This JavaScript snippet lists the Closure Library modules required for the toolbar examples on this page. It includes core utilities, event handling, logging, DOM manipulation, styling, and various UI components like buttons, menus, and the toolbar itself. ```JavaScript goog.require('goog.array'); goog.require('goog.debug.DivConsole'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('goog.log'); goog.require('goog.object'); goog.require('goog.style'); goog.require('goog.ui.Button'); goog.require('goog.ui.ButtonSide'); goog.require('goog.ui.Component.EventType'); goog.require('goog.ui.Component.State'); goog.require('goog.ui.Menu'); goog.require('goog.ui.MenuItem'); goog.require('goog.ui.Option'); goog.require('goog.ui.SelectionModel'); goog.require('goog.ui.Separator'); goog.require('goog.ui.Toolbar'); goog.require('goog.ui.ToolbarButton'); goog.require('goog.ui.ToolbarMenuButton'); goog.require('goog.ui.ToolbarRenderer'); goog.require('goog.ui.ToolbarSelect'); goog.require('goog.ui.ToolbarSeparator'); goog.require('goog.ui.ToolbarToggleButton'); goog.require('goog.dom.TagName'); ``` -------------------------------- ### Importing Dependencies and Defining Base Styles (Closure Library) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/button.html Imports necessary Google Closure Library modules for UI components and defines base CSS classes for icons and a default button style used in the examples. ```JavaScript goog.require('goog.array'); goog.require('goog.debug.DivConsole'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('goog.log'); goog.require('goog.object'); goog.require('goog.ui.Button'); goog.require('goog.ui.ButtonRenderer'); goog.require('goog.ui.ButtonSide'); goog.require('goog.ui.CustomButton'); goog.require('goog.ui.CustomButtonRenderer'); goog.require('goog.ui.FlatButtonRenderer'); goog.require('goog.ui.LinkButtonRenderer'); goog.require('goog.ui.ToggleButton'); goog.require('goog.ui.decorate'); goog.require('goog.dom.TagName'); ``` ```CSS /* Base class for all icon elements. */ .icon { height: 16px; width: 16px; margin: 0 1px; background-image: url(../images/toolbar_icons.gif); background-repeat: no-repeat; vertical-align: middle; } /* "Highlight" icon. */ .highlight-icon{ background-position: -64px; } /* "Insert Image" icon. */ .insert-image-icon { background-position: -80px; } /* Custom style for the "default" button. */ .default-button { font-weight: bold; } ``` -------------------------------- ### Execute Simple GET Request (JavaScript) Source: https://github.com/google/closure-library/blob/master/closure/goog/net/iframeio_test_dom.html Calls the `simpleGet` function, likely initiating a basic GET request using IframeIo for testing purposes. ```JavaScript simpleGet() ``` -------------------------------- ### Implementing Generic CSS3 Fade (JavaScript) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/fx/css3/transition.html Defines a function to initiate a generic CSS3 fade transition using `goog.fx.css3.fade`. It reads duration, timing function, start opacity, and end opacity from user input, attaches an event listener for logging, and starts the transition. ```JavaScript function fade() { var duration = parseFloat(getValue_('FadeDuration')); var timingFn = getValue_('FadeTimingFn'); var startOpacity = parseFloat(getValue_('FadeStartingOpacity')); var endOpacity = parseFloat(getValue_('FadeEndingOpacity')); transition = goog.fx.css3.fade( animatedBox, duration, timingFn, startOpacity, endOpacity); installListener_(transition); transition.play(); } ``` -------------------------------- ### Start goog.async.Delay - JavaScript Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/timers.html Initiates a goog.async.Delay instance with a specified timeout. Prevents starting a new delay if one is already active. ```javascript /** * Start the delay, on the button press. */ var doDelay = function() { if (delay) { goog.dom.setTextContent(delayStatus, 'Delay already set.'); return; } var seconds = getSeconds('delaySeconds'); if (typeof seconds !== 'number') { return; } delay = new goog.async.Delay(delayedAction, inMs(seconds)); delay.start(); goog.dom.setTextContent(delayStatus, 'Delay for: ' + seconds + ' seconds.'); }; ``` -------------------------------- ### Executing Gauge Setup Function (JavaScript) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/gauge.html Calls the setupGauges function to initialize and render all the defined gauge instances on the page. ```javascript setupGauges(); ``` -------------------------------- ### Importing Zippy and Dependencies (JavaScript) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/zippy.html Imports the necessary modules from the Google Closure Library for using Zippy components, logging, and event handling. ```JavaScript goog.require('goog.debug.DivConsole'); goog.require('goog.events'); goog.require('goog.log'); goog.require('goog.ui.AnimatedZippy'); goog.require('goog.ui.Zippy'); goog.require('goog.ui.ZippyEvent'); ``` -------------------------------- ### Creating Collapsible TweakUi (JavaScript) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/tweakui.html Demonstrates how to create an instance of the TweakUi that starts in a collapsed state and append it to an HTML element. ```JavaScript document.getElementById('menu1').appendChild( goog.tweak.TweakUi.createCollapsible()); ``` -------------------------------- ### Styling Elements with Borders and Margins (CSS) Source: https://github.com/google/closure-library/blob/master/closure/goog/editor/plugins/enterhandler_test_dom.html These CSS rules define styles for elements with classes 'tr-field' and 'tr_bq'. 'tr-field' gets a thin blue border, and 'tr_bq' gets a thin red left border and a left margin. ```CSS .tr-field { border: thin solid blue; } .tr\_bq { border-left: thin solid red; margin-left: 5px; } ``` -------------------------------- ### Initializing goog.ui.HsvPalette (Normal Size) - JavaScript Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/hsvpalette.html Creates a default instance of the goog.ui.HsvPalette component using its constructor and renders it to the DOM. This example uses the standard size and appearance. ```javascript var p = new goog.ui.HsvPalette; p.render(); ``` -------------------------------- ### Decorating and Setting Up Second Toolbar - Closure Library JavaScript Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/toolbar.html Initializes a new `goog.ui.Toolbar` instance, decorates the HTML element with ID 't2', measures decoration performance, attaches a generic event listener (`logEvent`) to all toolbar events, and hooks up click listeners for show/enable actions on the toolbar and a specific menu button. ```JavaScript timer = goog.now(); var t2 = new goog.ui.Toolbar(); t2.decorate(goog.dom.getElement('t2')); showPerf('perf2', timer); goog.events.listen(t2, EVENTS, logEvent); // Hook up checkboxes. goog.events.listen(goog.dom.getElement('t2_show'), goog.events.EventType.CLICK, handleShow, false, t2); goog.events.listen(goog.dom.getElement('t2_enable'), goog.events.EventType.CLICK, handleEnable, false, t2); goog.events.listen(goog.dom.getElement('menuButton_enable'), goog.events.EventType.CLICK, handleEnable, false, t2.getChild('menuButton')); ``` -------------------------------- ### Displaying Performance Time Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/toolbar.html Calculates the time elapsed since a given start timestamp using goog.now() and updates the text content of an HTML element with the calculated duration in milliseconds. ```javascript function showPerf(id, start) { goog.dom.setTextContent(goog.dom.getElement(id), (goog.now() - start) + 'ms'); } ``` -------------------------------- ### Initialize Closure PortChannel and Register Service - JavaScript Source: https://github.com/google/closure-library/blob/master/closure/goog/messaging/testdata/portchannel_inner.html Initializes the Closure Library environment, requires the PortChannel module, determines the peer window's origin, creates a PortChannel instance, and registers a 'ping' service that responds with 'pong'. ```javascript var CLOSURE_DEFINES = CLOSURE_DEFINES || {}; CLOSURE_DEFINES["goog.ENABLE_DEBUG_LOADER"]=true; goog.require('goog.messaging.PortChannel'); var peerOrigin = window.location.protocol + '//' + window.location.host; var channel = goog.messaging.PortChannel.forGlobalWindow(peerOrigin); channel.registerService('ping', function(msg) { channel.send('pong', msg); }); ``` -------------------------------- ### Initializing and Connecting Cross-Page Channel (Closure Library) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/xpc/minimal/inner.html Sets up a Closure Library `CrossPageChannel` on window load. It parses configuration from a URI parameter named 'xpc', registers a 'log' service using the `log` function, and connects the channel, logging a message upon successful connection. ```JavaScript goog.events.listen(window, 'load', function() { // Get the channel configuration from the URI parameter. var cfg = goog.json.parse( (new goog.Uri(window.location.href)).getParameterValue('xpc')); // Create the channel. channel = new goog.net.xpc.CrossPageChannel(cfg); channel.registerService('log', log); channel.connect(function() { log('Channel connected.'); }); }); ``` -------------------------------- ### Demonstrating Unstopped Tracers with goog.debug.Trace (JavaScript) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/tracer.html Initializes a trace and starts nested tracers within a loop, intentionally leaving one tracer unstopped to illustrate how the tracing mechanism handles such cases. ```JavaScript function unstoppedTracers() { goog.debug.Trace.initCurrentTrace(0); var tracer = goog.debug.Trace.startTracer('Outer Loop'); var sum = 0; for (var i = 0; i < 10; i++) { var t2 = goog.debug.Trace.startTracer('Run ' + i); if (i != 5) { goog.debug.Trace.stopTracer(t2); } } goog.debug.Trace.stopTracer(tracer); var s = goog.debug.Trace.toString(); var outputElt = document.getElementById('output'); outputElt.innerHTML = goog.string.whitespaceEscape( goog.string.htmlEscape(s)); } ``` -------------------------------- ### Get Seconds from Input Element - JavaScript Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/timers.html Retrieves a numeric value from an HTML input element specified by its ID, validates it, and returns the number of seconds. Alerts the user if the input is not a valid number. ```javascript /** * Get the seconds from a document element. * @param {string} id The id of the element * @return {number} */ var getSeconds = function (id) { var time = Number(goog.dom.getElement(id).value); if (isNaN(time)) { alert('Please enter a Number'); return null; } else { return time; } }; ``` -------------------------------- ### Initializing Demo Variables and Logging Source: https://github.com/google/closure-library/blob/master/closure/goog/labs/pubsub/broadcastpubsub_demo.html This code initializes variables to reference DOM elements and sets up a logger with a DivConsole to display log messages on the page. It also logs an initial message indicating the start of local storage initialization. ```javascript var logger = goog.log.getLogger('demo'); var logConsole = new goog.debug.DivConsole(goog.dom.getElement('log')); logConsole.setCapturing(true); var broadcastPubSub1Value = goog.dom.getElement('broadcastPubSub1Value'); var broadcastPubSub2Value = goog.dom.getElement('broadcastPubSub2Value'); var broadcastPubSub1Display = goog.dom.getElement('broadcastPubSub1Display'); var broadcastPubSub2Display = goog.dom.getElement('broadcastPubSub2Display'); goog.log.info(logger, 'initializing local storage'); ``` -------------------------------- ### Handle Drag Start Event (JavaScript) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/dragdrop.html This function is triggered when a drag operation begins. It uses `goog.style.setOpacity` to reduce the opacity of the dragged element, providing visual feedback to the user that the element is being dragged. ```javascript function dragStart(event) { goog.style.setOpacity(event.dragSourceItem.element, 0.5); } ``` -------------------------------- ### Decorating Element as Closure ToggleButton (`toggleEnable`) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/button.html Gets the DOM element with ID 'toggleEnable', decorates it as a Closure Library button, configures transition events, and adds generic event listeners (EVENTS). ```javascript var toggleEnableElem = goog.dom.getElement('toggleEnable'); var toggleEnable = goog.ui.decorate(toggleEnableElem); toggleEnable.setDispatchTransitionEvents(goog.ui.Component.State.ALL, true); goog.events.listen(toggleEnable, EVENTS, logEvent); ``` -------------------------------- ### Writing Modified Location to Document (JavaScript) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/xpc/minimal/inner.html Writes the current window location's href to the document, after replacing any query string (starting with '?') with '...'. This is likely used for displaying a simplified version of the URL. ```JavaScript document.write(location.href.replace(/\?.*/,'?...')) ``` -------------------------------- ### Demonstrating Google Closure Library Button Usage (JavaScript) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/button.html This script initializes logging and showcases the creation, decoration, event handling, and interaction with various Google Closure Library button types, including standard, flat, and custom buttons, demonstrating programmatic creation and element decoration. ```JavaScript var timer = goog.now(); // Set up a logger. goog.log.setLevel(goog.log.getRootLogger(), goog.log.Level.ALL); var logger = goog.log.getLogger('demo'); var logconsole = new goog.debug.DivConsole(goog.dom.getElement('log')); logconsole.setCapturing(true); var EVENTS = goog.object.getValues(goog.ui.Component.EventType); goog.log.fine(logger, 'Listening for: ' + EVENTS.join(', ') + '.'); function logEvent(e) { goog.log.info(logger, '"' + e.target.getCaption() + '" dispatched: ' + e.type); } // Create the first button programmatically. var b1 = new goog.ui.Button('Hello!'); b1.render(goog.dom.getElement('b1')); b1.setTooltip('I changed the tooltip using setTooltip() ' + 'after the button was rendered.'); goog.events.listen(b1, EVENTS, logEvent); goog.events.listen(goog.dom.getElement('b1_enable'), goog.events.EventType.CLICK, function(e) { b1.setEnabled(e.target.checked); }); goog.events.listen(b1, goog.ui.Component.EventType.ACTION, function(e) { var newCaption = window.prompt('Enter new caption for button:'); b1.setCaption(newCaption || 'Empty'); }); // Create the second button by decorating an element. var b2 = new goog.ui.Button(); b2.decorate(goog.dom.getElement('b2')); goog.events.listen(b2, EVENTS, logEvent); goog.events.listen(goog.dom.getElement('b2_enable'), goog.events.EventType.CLICK, function(e) { b2.setEnabled(e.target.checked); }); goog.events.listen(b2, goog.ui.Component.EventType.ACTION, function(e) { alert('The value of the button is: ' + b2.getValue()); }); // Create flat buttons that use divs instead of button or input elements. // Render 1st flat button. var fb1 = new goog.ui.Button('Hello!', goog.ui.FlatButtonRenderer.getInstance()); fb1.render(goog.dom.getElement('fb1')); fb1.setTooltip('I changed the tooltip using setTooltip() ' + 'after the button was rendered.'); goog.events.listen(fb1, EVENTS, logEvent); goog.events.listen(goog.dom.getElement('fb1_enable'), goog.events.EventType.CLICK, function(e) { fb1.setEnabled(e.target.checked); }); goog.events.listen(fb1, goog.ui.Component.EventType.ACTION, function(e) { var newCaption = window.prompt('Enter new caption for button:'); fb1.setCaption(newCaption || 'Empty'); }); // Decorate 2nd flat button. var fb2 = goog.ui.decorate(goog.dom.getElement('fb2')); goog.events.listen(fb2, EVENTS, logEvent); goog.events.listen(goog.dom.getElement('fb2_enable'), goog.events.EventType.CLICK, function(e) { fb2.setEnabled(e.target.checked); }); goog.events.listen(fb2, goog.ui.Component.EventType.ACTION, function(e) { alert('The caption of the button is: ' + fb2.getCaption()); }); ``` -------------------------------- ### Displaying Performance Measurement Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/button.html Gets the DOM element with ID 'perf' and sets its text content to display the elapsed time calculated by subtracting a timer value from the current time (goog.now()), appended with 'ms'. ```javascript goog.dom.setTextContent(goog.dom.getElement('perf'), (goog.now() - timer) + 'ms'); ``` -------------------------------- ### Create, Render, and Listen to Events for c7 (BiDi) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/control.html Instantiates a new goog.ui.Control with 'Hello, world' text, adds the 'goog-inline-block' class, renders it into the element with ID 'bidi', and attaches a listener for specified 'EVENTS'. This is part of the BiDi examples. ```JavaScript var c7 = new goog.ui.Control('Hello, world'); c7.addClassName('goog-inline-block'); c7.render(goog.dom.getElement('bidi')); goog.events.listen(c7, EVENTS, logEvent); ``` -------------------------------- ### Importing Dependencies and Declaring Variables (Closure Library) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/xpc/minimal/inner.html Imports necessary Closure Library modules (goog.dom, goog.dom.TagName, goog.events, goog.net.xpc.CrossPageChannel) and declares variables (channel, logEl) used for the cross-page communication setup and logging. ```JavaScript goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.events'); goog.require('goog.net.xpc.CrossPageChannel'); var channel; var logEl; ``` -------------------------------- ### Demonstrating goog.ui.ColorMenuButton and ToolbarColorMenuButton (JavaScript) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/colormenubutton.html JavaScript code demonstrating the creation, decoration, configuration, and event handling for goog.ui.ColorMenuButton and goog.ui.ToolbarColorMenuButton components. It includes setting up logging, creating custom color menus, decorating toolbars, and measuring initialization performance. ```JavaScript var timer = goog.now(); // Set up a logger. goog.log.setLevel(goog.log.getRootLogger(), goog.log.Level.ALL); var logger = goog.log.getLogger('demo'); var logConsole = new goog.debug.DivConsole(goog.dom.getElement('log')); logConsole.setCapturing(true); var EVENTS = goog.object.getValues(goog.ui.Component.EventType); goog.log.fine(logger, 'Listening for: ' + EVENTS.join(', ') + '.'); function logEvent(e) { var component = e.target; var caption = (typeof component.getCaption == 'function' && component.getCaption()) || component.getId(); goog.log.info(logger, '"' + caption + '" dispatched: ' + e.type); } // Create the first ColorMenuButton programmatically. var cmb1 = new goog.ui.ColorMenuButton('Color'); cmb1.setTooltip('Click to select color'); cmb1.setSelectedColor('#FF0000'); cmb1.render(goog.dom.getElement('cmb1')); goog.events.listen(cmb1, EVENTS, logEvent); // Decorate the second ColorMenuButton. var cmb2 = goog.ui.decorate(goog.dom.getElement('cmb2')); cmb2.setSelectedColor('#0000FF'); goog.events.listen(cmb2, EVENTS, logEvent); // Create a custom palette and add it to a menu. var customColorPalette = new goog.ui.CustomColorPalette( ['#FE1', '#ACD', '#119']); customColorPalette.setSize(8); var customColorMenu = new goog.ui.Menu(); customColorMenu.addItem(new goog.ui.MenuItem( 'None', goog.ui.ColorMenuButton.NO_COLOR)); customColorMenu.addItem(new goog.ui.Separator()); customColorMenu.addItem(customColorPalette); // Create a ColorMenuButton with a custom menu. var cmb3 = new goog.ui.ColorMenuButton('Custom', customColorMenu); cmb3.setTooltip('Click to select a custom color'); // Currently, the "add custom color" dialog created by CustomColorPalette // blurs the button unless we set it to non-focusable. cmb3.setSupportedState(goog.ui.Component.State.FOCUSED, false); cmb3.render(goog.dom.getElement('cmb3')); goog.events.listen(cmb3, EVENTS, logEvent); // Create the first toolbar-style ColorMenuButton programmatically. var tcmb1 = new goog.ui.ColorMenuButton('Color', goog.ui.ColorMenuButton.newColorMenu(), goog.ui.ToolbarColorMenuButtonRenderer.getInstance()); tcmb1.render(goog.dom.getElement('tcmb1')); tcmb1.setTooltip('Click to select color'); tcmb1.setSelectedColor('#FF00FF'); goog.events.listen(tcmb1, EVENTS, logEvent); // Decorate the second toolbar-style ColorMenuButton. var tcmb2 = goog.ui.decorate(goog.dom.getElement('tcmb2')); tcmb2.setSelectedColor('#FFFF00'); goog.events.listen(tcmb2, EVENTS, logEvent); // Decorate the sample toolbar. var tb = new goog.ui.Toolbar(); tb.decorate(goog.dom.getElement('tb')); goog.events.listen(tb, EVENTS, logEvent); // Decorate the BiDi toolbar. var tbRtl = new goog.ui.Toolbar(); tbRtl.decorate(goog.dom.getElement('tbRtl')); goog.events.listen(tbRtl, EVENTS, logEvent); // Perf and clean up goog.dom.setTextContent(goog.dom.getElement('perf'), (goog.now() - timer) + 'ms'); ``` -------------------------------- ### Decorating and Setting Up Second RTL Toolbar - Closure Library JavaScript Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/toolbar.html Initializes a new `goog.ui.Toolbar` for Right-to-Left (RTL) layout, decorates the HTML element with ID 't2rtl', measures decoration performance, attaches a generic event listener (`logEvent`), and hooks up click listeners for show/enable actions on the toolbar and a specific RTL menu button. ```JavaScript // Decorate the second toolbar. timer = goog.now(); var t2rtl = new goog.ui.Toolbar(); t2rtl.decorate(goog.dom.getElement('t2rtl')); showPerf('perf2rtl', timer); goog.events.listen(t2rtl, EVENTS, logEvent); // Hook up checkboxes. goog.events.listen(goog.dom.getElement('t2rtl_show'), goog.events.EventType.CLICK, handleShow, false, t2rtl); goog.events.listen(goog.dom.getElement('t2rtl_enable'), goog.events.EventType.CLICK, handleEnable, false, t2rtl); goog.events.listen(goog.dom.getElement('rtlMenuButton_enable'), goog.events.EventType.CLICK, handleEnable, false, t2rtl.getChild('rtlMenuButton')); ``` -------------------------------- ### Referencing Compiled JavaScript File in HTML Source: https://github.com/google/closure-library/blob/master/doc/develop/get-started.md This HTML snippet shows how to include the compiled JavaScript file in your web page using a script tag. The compiled file contains all necessary code and dependencies, eliminating the need for base.js. ```html
Content to be rendered below
``` -------------------------------- ### Initializing Animation Setup - JavaScript Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/animationqueue.html Calls the 'createAnimations' function to set up the parallel and serial animation queues and populate them with slide animations for the block elements. This prepares the animations for playback. ```JavaScript createAnimations(); ``` -------------------------------- ### Initializing and Configuring Zippy Instances (JavaScript) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/zippy.html Sets up logging, creates instances of goog.ui.Zippy and goog.ui.AnimatedZippy, attaches event listeners to log state changes, expands the first zippy, and sets up a toggle relationship between the second and third animated zippies. ```JavaScript // Set up a logger. goog.log.setLevel(goog.log.getRootLogger(), goog.log.Level.ALL); var logger = goog.log.getLogger('zippy'); var logconsole = new goog.debug.DivConsole(goog.dom.getElement('log')); logconsole.setCapturing(true); var EVENTS = goog.object.getValues(goog.ui.Zippy.Events); goog.log.fine(logger, 'Listening for: ' + EVENTS.join(', ') + '.'); function logEvent(e) { var caption = e.target.elHeader_.id; goog.log.info(logger, '"' + caption + '" dispatched: ' + e.type); } var z1 = new goog.ui.Zippy('header1', 'content1'); goog.events.listen(z1, EVENTS, logEvent); var z2 = new goog.ui.AnimatedZippy('header2', 'content2', true); goog.events.listen(z2, EVENTS, logEvent); var z3 = new goog.ui.AnimatedZippy('header3', 'content3', false); goog.events.listen(z3, EVENTS, logEvent); z1.expand(); function zippyToggle(event) { z3.setExpanded(!event.expanded); } goog.events.listen(z2, goog.ui.Zippy.Events.TOGGLE, zippyToggle); ``` -------------------------------- ### Decorating Elements as Closure Combined Toggle Buttons Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/button.html Gets DOM elements with specific IDs ('btn4', 'btn5', 'btn6'), iterates through them, decorates each as a Closure Library button, configures transition events, stores instances in cb3, and adds generic event listeners. ```javascript var cb3 = []; var combinedButtons = goog.array.map(['btn4', 'btn5', 'btn6'], goog.dom.getElement); goog.array.forEach(combinedButtons, function(element) { var button = goog.ui.decorate(element); button.setDispatchTransitionEvents(goog.ui.Component.State.ALL, true); cb3.push(button); goog.events.listen(button, EVENTS, logEvent); }); ``` -------------------------------- ### Decorating Elements as Closure CustomButtons Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/button.html Gets DOM elements with specific IDs, iterates through them, decorates each element as a Closure Library button using goog.ui.decorate, configures transition events, stores the decorated button instances in the cb2 array, and adds generic event listeners. ```javascript var cb2 = []; var decoratedButtons = goog.array.map( ['foo', 'bar', 'fee', 'btn1', 'btn2', 'btn3'], goog.dom.getElement); goog.array.forEach(decoratedButtons, function(element) { // Since the elements to be decorated each have the correct "marker" CSS // class ("goog-custom-button"), we can use the renderer registry to get // the appropriate control instance to decorate them. var button = goog.ui.decorate(element); button.setDispatchTransitionEvents(goog.ui.Component.State.ALL, true); cb2.push(button); goog.events.listen(button, EVENTS, logEvent); }); ``` -------------------------------- ### Execute Tree Initialization - JavaScript Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/index_nav.html Calls the main initialization function `initTree` to start the process of setting up and rendering the demo navigation tree when the script runs. ```JavaScript initTree(); ``` -------------------------------- ### Creating and Rendering a Toolbar (LTR) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/toolbar.html Demonstrates programmatic creation of a standard Left-to-Right (LTR) Closure Library Toolbar (`goog.ui.Toolbar`). It adds various button types (`ToolbarButton`, `ToolbarSeparator`, `ToolbarToggleButton`) with tooltips and initial states, then renders the toolbar into a specified DOM element and attaches event listeners. ```javascript // Create first toolbar programmatically. timer = goog.now(); var t1 = new goog.ui.Toolbar(); t1.addChild(new goog.ui.ToolbarButton('Button'), true); t1.getChildAt(0).setTooltip('This is a tooltip for a button'); t1.addChild(new goog.ui.ToolbarButton('AnotherButton'), true); t1.addChild(new goog.ui.ToolbarSeparator(), true); t1.addChild(new goog.ui.ToolbarButton('Disabled'), true); t1.getChildAt(3).setEnabled(false); t1.addChild(new goog.ui.ToolbarButton('YetAnotherButton'), true); var toggleButton = new goog.ui.ToolbarToggleButton(goog.dom.createDom(goog.dom.TagName.DIV, 'icon goog-edit-bold')); toggleButton.setChecked(true); t1.addChild(toggleButton, true); var btnLeft = new goog.ui.ToolbarButton('Left'); btnLeft.setCollapsed(goog.ui.ButtonSide.END); t1.addChild(btnLeft, true); var btnCenter = new goog.ui.ToolbarButton('Center'); btnCenter.setCollapsed(goog.ui.ButtonSide.END | goog.ui.ButtonSide.START); t1.addChild(btnCenter, true); var btnRight = new goog.ui.ToolbarButton('Right'); btnRight.setCollapsed(goog.ui.ButtonSide.START); t1.addChild(btnRight, true); t1.render(goog.dom.getElement('t1')); showPerf('perf1', timer); goog.events.listen(t1, EVENTS, logEvent); ``` -------------------------------- ### Initializing and Configuring goog.ui.Select Components JavaScript Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/select.html This script initializes multiple goog.ui.Select instances with different options and configurations, sets up event listeners for user actions and logging, and demonstrates decorating an existing HTML element into a select control. ```JavaScript var timer = goog.now(); // Set up a logger. goog.log.setLevel(goog.log.getRootLogger(), goog.log.Level.ALL); var logger = goog.log.getLogger('demo'); var logconsole = new goog.debug.DivConsole(goog.dom.getElement('log')); logconsole.setCapturing(true); var EVENTS = goog.object.getValues(goog.ui.Component.EventType); goog.log.fine(logger, 'Listening for: ' + EVENTS.join(', ') + '.'); function logEvent(e) { var component = e.target; var caption = (typeof component.getCaption == 'function') ? component.getCaption() : component.getId(); goog.log.info(logger, '"' + caption + '" dispatched: ' + e.type); } var select1 = new goog.ui.Select(); select1.addItem(new goog.ui.MenuItem('Blade Runner')); select1.addItem(new goog.ui.MenuItem('Godfather Part II')); select1.addItem(new goog.ui.MenuItem('Citizen Kane')); select1.setSelectedIndex(0); select1.render(goog.dom.getElement('select1')); var select2 = new goog.ui.Select(); var disabledItem; select2.addItem(new goog.ui.Option('Transformers')); select2.addItem(new goog.ui.Option('Spider-Man 3')); select2.addItem(disabledItem = new goog.ui.Option('Howard the Duck')); select2.addItem(new goog.ui.Option('Catwoman')); disabledItem.setEnabled(false); select2.setValue('Spider-Man 3'); select2.render(goog.dom.getElement('select2')); var select3 = new goog.ui.Select('Click to select'); // Turn off auto-highlighting, just for fun. select3.setAutoStates(goog.ui.Component.State.HOVER, false); select3.addItem(new goog.ui.Option('enabled', true)); select3.addItem(new goog.ui.Option('disabled', false)); select3.render(goog.dom.getElement('select3')); select3.setSelectedIndex(0); goog.events.listen(select1, goog.ui.Component.EventType.ACTION, function(e) { var select = e.target; var value = 'Yay ' + select.getValue() + '!'; goog.dom.setTextContent(goog.dom.getElement('value1'), value); goog.dom.setTextContent(goog.dom.getElement('value2'), ''); }); goog.events.listen(select2, goog.ui.Component.EventType.ACTION, function(e) { var select = e.target; var value = 'Boo ' + select.getValue() + '...'; goog.dom.setTextContent(goog.dom.getElement('value2'), value); goog.dom.setTextContent(goog.dom.getElement('value1'), ''); }); goog.events.listen(select3, goog.ui.Component.EventType.ACTION, function(e) { var select = e.target; select2.setEnabled(select.getValue()); }); goog.events.listen(goog.dom.getElement('add'), goog.events.EventType.CLICK, function(e) { var good = prompt('What\'s another good movie...?'); if (select1.getItemCount() == 3) { select1.addItem(new goog.ui.Separator()); } select1.addItem(new goog.ui.MenuItem(good)); }); goog.events.listen(goog.dom.getElement('hide'), goog.events.EventType.CLICK, function(e) { select1.setVisible(!select1.isVisible()); }); goog.events.listen(goog.dom.getElement('worst'), goog.events.EventType.CLICK, function(e) { select2.setValue('Catwoman'); }); // Decorate an element with a Select control. var select4 = goog.ui.decorate(goog.dom.getElement('spaghetti')); goog.events.listen(select1, EVENTS, logEvent); goog.events.listen(select2, EVENTS, logEvent) ``` -------------------------------- ### Decorating Element as Closure ToggleButton (`hideShow`) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/button.html Gets the DOM element with ID 'hideShow', decorates it as a Closure Library button, configures transition events, and adds generic event listeners (EVENTS). Note: new goog.ui.decorate is unusual, goog.ui.decorate usually returns the instance directly. ```javascript var hideShowElem = goog.dom.getElement('hideShow'); var hideShow = new goog.ui.decorate(hideShowElem); hideShow.setDispatchTransitionEvents(goog.ui.Component.State.ALL, true); goog.events.listen(hideShow, EVENTS, logEvent); ``` -------------------------------- ### Handling Online/Offline Events with Closure (JavaScript) Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/onlinehandler.html Initializes a Closure Library OnlineHandler, gets a reference to an output element, defines a function to update the element's text and class based on the online status, listens for online/offline events from the handler, disposes the handler on window unload, and performs an initial status update. ```JavaScript var out = document.getElementById('out'); var oh = new goog.events.OnlineHandler; function updateText() { out.innerHTML = 'Is online: ' + oh.isOnline(); out.className = oh.isOnline() ? 'online' : 'offline'; } goog.events.listen(oh, [goog.net.NetworkStatusMonitor.EventType.ONLINE, goog.net.NetworkStatusMonitor.EventType.OFFLINE], updateText); goog.events.listen(window, 'unload', function() { oh.dispose(); }); updateText(); ``` -------------------------------- ### Creating and Rendering a Closure LinkButton Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/button.html Creates a new Closure Library button instance that looks like a link using goog.ui.LinkButtonRenderer, renders it into the element with ID 'lb', and sets its tooltip. ```javascript var lb = new goog.ui.Button('Hello!', goog.ui.LinkButtonRenderer.getInstance()); lb.render(goog.dom.getElement('lb')); lb.setTooltip('I changed the tooltip using setTooltip() ' + 'after the button was rendered.'); ``` -------------------------------- ### Setting up Google Closure Library Logging Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/container.html Initializes the Google Closure Library logging system, sets the root logger level to ALL, creates a specific logger instance, and sets up a DivConsole to capture and display log messages in an HTML element with the ID 'log'. ```javascript var timer = goog.now(); // Set up a logger. goog.log.setLevel(goog.log.getRootLogger(), goog.log.Level.ALL); var logger = goog.log.getLogger('demo'); var logconsole = new goog.debug.DivConsole(goog.dom.getElement('log')); logconsole.setCapturing(true); var EVENTS = goog.object.getValues(goog.ui.Component.EventType); goog.log.fine(logger, 'Listening for: ' + EVENTS.join(', ') + '.'); ``` -------------------------------- ### Execute JSON Echo GET Request (JavaScript) Source: https://github.com/google/closure-library/blob/master/closure/goog/net/iframeio_test_dom.html Calls the `jsonEcho` function with 'GET' as an argument, intended to test JSON echoing functionality via a GET request. ```JavaScript jsonEcho('GET') ``` -------------------------------- ### Trigger Random Button Click with Bubble - JavaScript Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/bubble.html Implements functions doRandom and doRandomClick to periodically simulate clicks on randomly selected buttons (excluding button 5). doRandom starts or stops an interval timer, while doRandomClick selects a random button ID, finds the button element, temporarily changes the default timeout, triggers the click (which calls clickButton), and restores the timeout. ```JavaScript var timer = null; function doRandom() { if (timer) { window.clearInterval(timer); timer = null; return; } doRandomClick(); timer = window.setInterval(doRandomClick, 2000); } function doRandomClick() { for ( ; ; ) { var number=Math.floor(Math.random()*9) + 1; if (number != 5) { break; } } var button = document.getElementById("button" + number); if (button) { var defaultTimeoutSav = defaultTimeout; defaultTimeout = 2000; button.click (); defaultTimeout = defaultTimeoutSav; } } ``` -------------------------------- ### Initialize and Connect CrossPageChannel - JavaScript Source: https://github.com/google/closure-library/blob/master/closure/goog/demos/xpc/minimal/index.html Sets up the configuration for a CrossPageChannel based on the current window's location and parameters, creates the channel, embeds the peer iframe, registers a 'log' service, and connects the channel upon window load. ```JavaScript goog.events.listen(window, 'load', function() { // Build the channel configuration. var cfg = {}; var ownUri = new goog.Uri(window.location.href); var peerDomain = ownUri.getParameterValue('peerdomain') || ownUri.getDomain(); var peerUri = ownUri.clone().setDomain(peerDomain); var localRelayUri = ownUri.resolve(new goog.Uri('relay.html')); var peerRelayUri = peerUri.resolve(new goog.Uri('relay.html')); var localPollUri = ownUri.resolve(new goog.Uri('blank.html')); var peerPollUri = peerUri.resolve(new goog.Uri('blank.html')); cfg[goog.net.xpc.CfgFields.LOCAL_RELAY_URI] = localRelayUri.toString(); cfg[goog.net.xpc.CfgFields.PEER_RELAY_URI] = peerRelayUri.toString(); cfg[goog.net.xpc.CfgFields.LOCAL_POLL_URI] = localPollUri.toString(); cfg[goog.net.xpc.CfgFields.PEER_POLL_URI] = peerPollUri.toString(); // Set the URI of the peer page. var peerUri = ownUri.resolve( new goog.Uri('inner.html')).setDomain(peerDomain); cfg[goog.net.xpc.CfgFields.PEER_URI] = peerUri; // Create the channel. channel = new goog.net.xpc.CrossPageChannel(cfg); // Create the peer iframe. channel.createPeerIframe( goog.dom.getElement('iframeContainer')); channel.registerService('log', log); channel.connect(function() { log('Channel connected.'); }); }); ```