### Basic WebGL Setup and Rendering Source: https://web.dev/articles/webgl-fundamentals.md.txt This snippet shows the fundamental setup for WebGL, including getting a context, creating and using shaders, setting up vertex data, and drawing a simple rectangle using clipspace coordinates. ```javascript // Get A WebGL context var canvas = document.getElementById("canvas"); var gl = canvas.getContext("experimental-webgl"); // setup a GLSL program var vertexShader = createShaderFromScriptElement(gl, "2d-vertex-shader"); var fragmentShader = createShaderFromScriptElement(gl, "2d-fragment-shader"); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); // look up where the vertex data needs to go. var positionLocation = gl.getAttribLocation(program, "a_position"); // Create a buffer and put a single clipspace rectangle in // it (2 triangles) var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData( gl.ARRAY_BUFFER, new Float32Array([ -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0]), gl.STATIC_DRAW); gl.enableVertexAttribArray(positionLocation); gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0); // draw gl.drawArrays(gl.TRIANGLES, 0, 6); ``` -------------------------------- ### Example Bug Description Source: https://web.dev/articles/how-to-file-a-good-bug.md.txt Provide a concise summary of the problem. This example highlights an issue with PWA installation event timing. ```text When installing a PWA using the `beforeinstallprompt.prompt()`, the `appinstalled` event fires before the call to `prompt()` resolves. ``` -------------------------------- ### Install build tools Source: https://web.dev/articles/webrtc-infrastructure.md.txt Install make and gcc for building software on Ubuntu. ```shell sudo apt-get install make sudo apt-get install gcc ``` -------------------------------- ### Start an XR Session and Set Up Rendering Source: https://web.dev/articles/vr-comes-to-the-web.md.txt This function initializes an XR session, sets up an event listener for session end, creates a canvas for rendering, gets an XR-compatible WebGL context, and configures the session's render state with an XRWebGLLayer. It then requests a 'local-floor' reference space and starts the animation frame loop. ```javascript function onSessionStarted(xrSession) { xrSession.addEventListener('end', onSessionEnded); let canvas = document.createElement('canvas'); webGLRenContext = canvas.getContext('webgl', { xrCompatible: true }); xrSession.updateRenderState({ baseLayer: new XRWebGLLayer(xrSession, webGLRenContext) }); xrSession.requestReferenceSpace('local-floor') .then((refSpace) => { xrRefSpace = refSpace; xrSession.requestAnimationFrame(onXRFrame); }); } ``` -------------------------------- ### Handle In-App Installation Click Source: https://web.dev/articles/customize-install.md.txt When a user clicks the install button, hide the promotion and show the install prompt. Wait for the user's response and then clear the deferred prompt. ```javascript buttonInstall.addEventListener('click', async () => { // Hide the app provided install promotion hideInstallPromotion(); // Show the install prompt deferredPrompt.prompt(); // Wait for the user to respond to the prompt const { outcome } = await deferredPrompt.userChoice; // Optionally, send analytics event with outcome of user choice console.log(`User response to the install prompt: ${outcome}`); // We've used the prompt and can't use it again, throw it away deferredPrompt = null; }); ``` -------------------------------- ### Listen for beforeinstallprompt event Source: https://web.dev/articles/codelab-make-installable.md.txt Capture the `beforeinstallprompt` event to enable the web app to be installed. This event fires when the app meets the installability criteria. Stash the event and unhide the install button. ```javascript window.addEventListener('beforeinstallprompt', (event) => { // Prevent the mini-infobar from appearing on mobile. event.preventDefault(); console.log('👍', 'beforeinstallprompt', event); // Stash the event so it can be triggered later. window.deferredPrompt = event; // Remove the 'hidden' class from the install button container. divInstall.classList.toggle('hidden', false); }); ``` -------------------------------- ### Install react-snap Source: https://web.dev/articles/prerender-with-react-snap.md.txt Install react-snap as a development dependency using npm. ```bash npm install --save-dev react-snap ``` -------------------------------- ### Install mkbitmap locally Source: https://web.dev/articles/compiling-mkbitmap-to-webassembly.md.txt Run 'sudo make install' to install the compiled mkbitmap executables and related files. This command requires root privileges for system-wide installation. ```bash $ sudo make install Password: Making install in src .././install-sh -c -d '/usr/local/bin' /bin/sh ../libtool --mode=install /usr/bin/install -c potrace mkbitmap '/usr/local/bin' [...] make[2]: Nothing to be done for `install-data-am'. ``` -------------------------------- ### Install Socket.io and node-static Source: https://web.dev/articles/webrtc-infrastructure.md.txt Commands to install necessary Node.js packages for the signaling server. ```bash npm install socket.io npm install node-static ``` -------------------------------- ### Install Lighthouse Bot Source: https://web.dev/articles/using-lighthouse-bot-to-set-a-performance-budget.md.txt Install Lighthouse Bot as a development dependency using npm. ```bash npm i --save-dev https://github.com/ebidel/lighthousebot ``` -------------------------------- ### Initialize and Build kbone Project Source: https://web.dev/articles/mini-apps/mini-app-open-source-projects.md.txt Use the kbone-cli to initialize a new project and then build it for mini app, web, or production. ```bash npx kbone-cli init my-app cd my-app npm run mp npm run web npm run build ``` -------------------------------- ### Install Polymer Standalone with Bower Source: https://web.dev/articles/yeoman.md.txt Install the Polymer library standalone using Bower for a lighter start. This command adds Polymer to your bower_components directory. ```bash bower install polymer ``` -------------------------------- ### Basic MediaSource Setup and Segment Appending Source: https://web.dev/articles/mse-seamless-playback.md.txt This snippet demonstrates the initial setup of a MediaSource instance, attaching it to an audio element, and appending audio segments upon receiving the 'sourceopen' event. It shows how to create a SourceBuffer and load media data. ```javascript var audio = document.createElement('audio'); var mediaSource = new MediaSource(); var SEGMENTS = 5; mediaSource.addEventListener('sourceopen', function () { var sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg'); function onAudioLoaded(data, index) { // Append the ArrayBuffer data into our new SourceBuffer. sourceBuffer.appendBuffer(data); } // Retrieve an audio segment via XHR. For simplicity, we're retrieving the // entire segment at once, but we could also retrieve it in chunks and append // each chunk separately. MSE will take care of assembling the pieces. GET('sintel/sintel_0.mp3', function (data) { onAudioLoaded(data, 0); }); }); audio.src = URL.createObjectURL(mediaSource); ``` -------------------------------- ### Get Current High-Resolution Time Source: https://web.dev/articles/usertiming.md.txt Call the `now()` method on the `performance` interface to get the current high-resolution timestamp. This value is relative to the navigation start time. ```javascript var myTime = window.performance.now(); ``` -------------------------------- ### Start webpkgserver Source: https://web.dev/articles/signed-exchanges-webpackager.md.txt Execute this command in your terminal to start the webpkgserver. Check the log messages for successful startup and cache status. ```shell ./webpkgserver ``` -------------------------------- ### JavaScript Canvas API Example Source: https://web.dev/articles/drawing-to-canvas-in-emscripten.md.txt This is a standard JavaScript example demonstrating how to get a canvas context and draw a filled rectangle. It serves as a reference for the C++ Embind equivalent. ```javascript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.fillStyle = 'green'; ctx.fillRect(10, 10, 150, 100); ``` -------------------------------- ### Example Usage of mapRange Source: https://web.dev/articles/building-chrometober.md.txt Demonstrates how to use the `mapRange` function to get a mapped value. This specific example maps 50 from a 0-100 range to a 250-1000 range, resulting in 625. ```javascript mapRange(0, 100, 250, 1000, 50) // 625 ``` -------------------------------- ### Start Nginx and Fetch SXG (Source-built) Source: https://web.dev/articles/how-to-set-up-signed-http-exchanges.md.txt Commands to start a source-built Nginx server and then fetch an SXG resource. The output is saved to index.html.sxg and can be viewed with less. ```bash cd /opt/nginx/sbin sudo ./nginx curl -H "Accept: application/signed-exchange;v=b3" https://website.test/ > index.html.sxg less index.html.sxg ``` -------------------------------- ### TransformStream Transformer Methods Source: https://web.dev/articles/streams.md.txt Defines the `start`, `transform`, and `flush` methods for a `TransformStream` transformer object. Use `start` for initial setup, `transform` for processing chunks, and `flush` for finalization. ```javascript const transformStream = new TransformStream({ start(controller) { /* ... */ }, transform(chunk, controller) { /* ... */ }, flush(controller) { /* ... */ }, }); ``` -------------------------------- ### Handle install button click Source: https://web.dev/articles/codelab-make-installable.md.txt Display the install prompt by calling `prompt()` on the saved `beforeinstallprompt` event. This must be called from a user gesture. Reset the deferred prompt and hide the install button after the prompt is shown. ```javascript butInstall.addEventListener('click', async () => { console.log('👍', 'butInstall-clicked'); const promptEvent = window.deferredPrompt; if (!promptEvent) { // The deferred prompt isn't available. return; } // Show the install prompt. promptEvent.prompt(); // Log the result const result = await promptEvent.userChoice; console.log('👍', 'userChoice', result); // Reset the deferred prompt variable, since // prompt() can only be called once. window.deferredPrompt = null; // Hide the install button. divInstall.classList.toggle('hidden', true); }); ``` -------------------------------- ### Conditional app install prompt logic Source: https://web.dev/articles/define-install-strategy.md.txt Implement logic to display different app install prompts based on the determined device category. This example shows a basic conditional check. ```javascript if (isDeviceMidOrLowEnd()) { // show "Lite app" install banner or PWA A2HS prompt } else { // show "Core app" install banner } ``` -------------------------------- ### XMLHttpRequest Example Source: https://web.dev/articles/introduction-to-fetch.md.txt Demonstrates making a GET request and handling JSON response using XMLHttpRequest. ```javascript function reqListener () { const data = JSON.parse(this.responseText); console.log(data); } function reqError (err) { console.log('Fetch Error :-S', err); } const oReq = new XMLHttpRequest(); oReq.onload = reqListener; oReq.onerror = reqError; oReq.open('get', './api/some.json', true); oReq.send(); ``` -------------------------------- ### Navigate and Start a React Application Source: https://web.dev/articles/get-started-optimize-react.md.txt After creating your app, navigate into the project directory and start the development server. This command is used to run the application locally. ```bash cd new-app npm start ``` -------------------------------- ### Shadow DOM Style Encapsulation Example Source: https://web.dev/articles/shadowdom-201.md.txt This example demonstrates style encapsulation in Shadow DOM. CSS styles defined within the ShadowRoot are scoped to it and do not affect or get affected by styles outside the shadow boundary. ```javascript var root = document.querySelector('div').createShadowRoot(); root.innerHTML = "

Shadow DOM

"; ``` -------------------------------- ### Copy Web Packager Server Configuration Example Source: https://web.dev/articles/signed-exchanges-webpackager.md.txt Copies the example configuration file for `webpkgserver` to create a new configuration file named `webpkgserver.toml`. This file will be used to customize server settings. ```bash cp ./webpkgserver.example.toml ./webpkgserver.toml ``` -------------------------------- ### Setup: Get Stories Element and Median Source: https://web.dev/articles/codelab-building-a-stories-component.md.txt Grabs a reference to the stories element and calculates its horizontal midpoint for click detection. ```javascript const stories = document.querySelector('.stories') const median = stories.offsetLeft + (stories.clientWidth / 2) ``` -------------------------------- ### Navigate and Start Development Server Source: https://web.dev/articles/performance-as-a-default-with-nextjs.md.txt After creating a Next.js app, navigate into the project directory and start the local development server using npm run dev. ```bash cd new-app npm run dev ``` -------------------------------- ### Interactive Address Form Example Source: https://web.dev/articles/payment-and-address-form-best-practices.md.txt Explore a live demonstration of an address form designed with best practices to enhance user experience and streamline the data entry process. This example serves as a practical guide for implementing effective address form design. ```html ``` -------------------------------- ### Initial Request Example Source: https://web.dev/articles/user-preference-media-features-headers.md.txt The client makes an initial request to the server. ```bash GET / HTTP/2 Host: example.com ``` -------------------------------- ### Basic Prompt for Product Review Rating Source: https://web.dev/articles/practical-prompt-engineering.md.txt A simple prompt to get a product rating from a user review. This is a starting point for prompt engineering. ```text Based on a user review, provide a product rating as an integer between 1 and 5. Only output the integer. Review: "${review}" Rating: ``` -------------------------------- ### Example Steps to Reproduce Source: https://web.dev/articles/how-to-file-a-good-bug.md.txt Detail the exact steps needed to trigger the bug. This includes navigating to a specific URL and interacting with UI elements. ```text What steps will reproduce the problem? 1. Go to https://basic-pwa.glitch.me/, open DevTools and look at the console tab. 2. Click the Install button in the page, you might need to interact with the page a bit before it becomes enabled. 3. Click Install on the browser modal install confirmation. ``` -------------------------------- ### Using DistilBERT with Transformers.js Source: https://web.dev/articles/llm-sizes This example demonstrates how to use the DistilBERT model with the Transformers.js library for NLP tasks in the browser. Ensure Transformers.js is installed or imported. ```javascript import { pipeline } from '@xenova/transformers'; // Create a pipeline for sentiment analysis const classifier = await pipeline('sentiment-analysis'); // Classify a text const result = await classifier('I love Transformers.js!'); console.log(result); ``` -------------------------------- ### Display Web Packager Server Help Information Source: https://web.dev/articles/signed-exchanges-webpackager.md.txt Verifies the correct installation of `webpkgserver` by displaying its help information. This command helps troubleshoot installation issues, potentially related to GOPATH configuration. ```bash ./webpkgserver --help ``` -------------------------------- ### Get all items from the 'foods' object store Source: https://web.dev/articles/indexeddb.md.txt This example demonstrates calling `getAll()` on the 'foods' object store to retrieve all objects, ordered by their primary key. ```javascript import {openDB} from 'idb'; async function getAllItemsFromStore () { const db = await openDB('test-db4', 1); // Get all values from the designated object store: const allValues = await db.getAll('foods'); console.dir(allValues); } getAllItemsFromStore(); ``` -------------------------------- ### Setting Color Uniform and Buffer Setup Source: https://web.dev/articles/webgl-fundamentals.md.txt JavaScript code demonstrating how to get the location of the 'u_color' uniform and set up the vertex buffer and pointer for drawing. ```javascript var colorLocation = gl.getUniformLocation(program, "u_color"); ... // Create a buffer var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.enableVertexAttribArray(positionLocation); gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0); ``` -------------------------------- ### Configure Server Start Command Source: https://web.dev/articles/lighthouse-ci.md.txt Provide the command to start your development server for dynamic sites. ```javascript collect: { startServerCommand: 'npm run start', } ``` -------------------------------- ### Full Writable Stream Example Source: https://web.dev/articles/streams.md.txt Demonstrates the complete lifecycle of a writable stream, including start, write, close, and abort operations, along with writing data in chunks. ```javascript const writableStream = new WritableStream({ start(controller) { console.log('[start]'); }, async write(chunk, controller) { console.log('[write]', chunk); // Wait for next write. await new Promise((resolve) => setTimeout(() => { document.body.textContent += chunk; resolve(); }, 1_000)); }, close(controller) { console.log('[close]'); }, abort(reason) { console.log('[abort]', reason); }, }); const writer = writableStream.getWriter(); const start = Date.now(); for (const char of 'abcdefghijklmnopqrstuvwxyz') { // Wait to add to the write queue. await writer.ready; console.log('[ready]', Date.now() - start, 'ms'); // The Promise is resolved after the write finishes. writer.write(char); } await writer.close(); ``` -------------------------------- ### Setup Basic Audio Nodes and Load Sound Source: https://web.dev/articles/webaudio-positional-audio.md.txt Creates a gain node for main volume control, a sound source, and its own gain node. It then loads a sound file and decodes it into an audio buffer. ```javascript // Create a AudioGainNode to control the main volume. var mainVolume = ctx.createGain(); // Connect the main volume node to the context destination. mainVolume.connect(ctx.destination); // Create an object with a sound source and a volume control. var sound = {}; sound.source = ctx.createBufferSource(); sound.volume = ctx.createGain(); // Connect the sound source to the volume control. sound.source.connect(sound.volume); // Hook up the sound volume control to the main volume. sound.volume.connect(mainVolume); // Make the sound source loop. sound.source.loop = true; // Load a sound file using an ArrayBuffer XMLHttpRequest. var request = new XMLHttpRequest(); request.open("GET", soundFileName, true); request.responseType = "arraybuffer"; request.onload = function(e) { // Create a buffer from the response ArrayBuffer. ctx.decodeAudioData(this.response, function onSuccess(buffer) { sound.buffer = buffer; // Make the sound source use the buffer and start playing it. sound.source.buffer = sound.buffer; sound.source.start(ctx.currentTime); }, function onFailure() { alert("Decoding the audio buffer failed"); }); }; request.send(); ``` -------------------------------- ### Run Lighthouse with performance budgets Source: https://web.dev/articles/use-lighthouse-for-performance-budgets.md.txt Execute Lighthouse and specify the path to your budget configuration file using the --budget-path flag. ```bash lighthouse https://example.com --budget-path=./budget.json ``` -------------------------------- ### Margin Inline Shorthand Example Source: https://web.dev/articles/logical-property-shorthands.md.txt Use `margin-inline` to set both `margin-inline-start` and `margin-inline-end` with a single declaration. Providing two values allows for different start and end margins. ```css margin-inline-start: 4ch; margin-inline-end: 2ch; ``` ```css margin-inline: 4ch 2ch; ``` -------------------------------- ### Receive Device-Memory in Request Header Source: https://web.dev/articles/define-install-strategy.md.txt Once the Accept-CH header is set, the browser will include the Device-Memory information in subsequent requests. This example shows how it might appear in a GET request. ```http GET /main.js HTTP/1.1 Device-Memory: 0.5 ``` -------------------------------- ### Using mkbitmap command-line tool Source: https://web.dev/articles/compiling-mkbitmap-to-webassembly.md.txt This is an example of how to use the mkbitmap command-line tool with options and filenames. Refer to the tool's man page for all details. ```bash mkbitmap [options] [filename...] ``` -------------------------------- ### Setting Scale Uniform in WebGL JavaScript Source: https://web.dev/articles/webgl-transforms.md.txt This JavaScript code demonstrates how to get the location of the 'u_scale' uniform and set its value before drawing. This is part of the setup for applying scale transformations. ```javascript var scaleLocation = gl.getUniformLocation(program, "u_scale"); var scale = [1, 1]; // Draw the scene. function drawScene() { // Clear the canvas. gl.clear(gl.COLOR_BUFFER_BIT); // Set the translation. gl.uniform2fv(translationLocation, translation); // Set the rotation. gl.uniform2fv(rotationLocation, rotation); // Set the scale. gl.uniform2fv(scaleLocation, scale); // Draw the rectangle. gl.drawArrays(gl.TRIANGLES, 0, 18); } ``` -------------------------------- ### Example Client Hints for User Preferences Source: https://web.dev/articles/user-preference-media-features-headers.md.txt Demonstrates how to convey user preferences for color scheme and reduced motion using client hint headers. These headers are sent by the client to the server. ```http GET / HTTP/2 Host: example.com Sec-CH-Prefers-Color-Scheme: "dark" Sec-CH-Prefers-Reduced-Motion: "reduce" ``` -------------------------------- ### Basic Node.js Server Setup Source: https://web.dev/articles/codelab-text-compression.md.txt This snippet shows the basic setup for a Node.js server using Express to serve static files. ```javascript const express = require('express'); const app = express(); app.use(express.static('public')); const listener = app.listen(process.env.PORT, function() { console.log('Your app is listening on port ' + listener.address().port); }); ``` -------------------------------- ### Padding Inline Shorthand Example Source: https://web.dev/articles/logical-property-shorthands.md.txt Use `padding-inline` to set both `padding-inline-start` and `padding-inline-end` with a single declaration. This shorthand allows for setting distinct padding values for the start and end inline edges. ```css padding-inline-start: 4ch; padding-inline-end: 2ch; ``` ```css padding-inline: 4ch 2ch; ``` -------------------------------- ### Install mkcert on macOS (Quick Reference) Source: https://web.dev/articles/how-to-use-local-https.md.txt Installs mkcert using Homebrew on macOS as part of the quick reference. ```bash brew install mkcert ``` -------------------------------- ### Determine device category with JavaScript Source: https://web.dev/articles/define-install-strategy.md.txt Use JavaScript properties like navigator.hardwareConcurrency, navigator.deviceMemory, and navigator.connection to get device information. This example shows how to infer device category based on device memory. ```javascript const deviceCategory = req.get('Device-Memory') < 1 ? 'lite' : 'full'; ``` -------------------------------- ### Render a Fixed-Size List with React Window Source: https://web.dev/articles/virtualize-long-lists-react-window.md.txt This example shows how to render a list of 1000 items using react-window's FixedSizeList component. Ensure you have react-window installed. This component is suitable for lists where all items have the same height. ```javascript import React from 'react'; import { FixedSizeList as List } from 'react-window'; const Row = ({ index, style }) => (
Row {index}
); const App = () => ( {Row} ); export default App; ``` -------------------------------- ### Running a Basic Python Web Server Source: https://web.dev/articles/webgl-globe.md.txt Use this command to start a simple HTTP server in your current directory. Navigate to http://localhost:8000/globe/globe.html to view the WebGL Globe. ```bash python -m SimpleHTTPServer ``` -------------------------------- ### Basic Express Server Setup Source: https://web.dev/articles/codelab-text-compression-brotli.md.txt Sets up a basic Node.js server using Express to serve static files from the 'public' directory. ```javascript const express = require('express'); const app = express(); app.use(express.static('public')); const listener = app.listen(process.env.PORT, function() { console.log(`Your app is listening on port ${listener.address().port}`); }); ``` -------------------------------- ### Apply Styles Based on Display Mode Source: https://web.dev/articles/customize-install.md.txt Use conditional CSS with the `display-mode` media query to apply different styles when a PWA is launched as an installed application. This example sets a yellow background for standalone mode. ```css @media all and (display-mode: standalone) { body { background-color: yellow; } } ``` -------------------------------- ### Get a specific item from a named store in IndexedDB Source: https://web.dev/articles/indexeddb.md.txt This example demonstrates retrieving a specific record ('Sandwich') from the 'foods' object store within the 'test-db4' database using its primary key. The retrieved value is then logged to the console. ```javascript import {openDB} from 'idb'; async function getItemFromStore () { const db = await openDB('test-db4', 1); const value = await db.get('foods', 'Sandwich'); console.dir(value); } getItemFromStore(); ``` -------------------------------- ### Requesting and Setting Up Media Keys Source: https://web.dev/articles/media-eme.md.txt This snippet shows how to request a MediaKeySystemAccess for a specific key system and configuration, create MediaKeys, and set them on a video element. It handles potential errors during these operations. ```javascript var video = document.querySelector('video'); var config = [{initDataTypes: ['webm'], videoCapabilities: [{contentType: 'video/webm; codecs="vp09.00.10.08"'}]}]; if (!video.mediaKeys) { navigator.requestMediaKeySystemAccess('org.w3.clearkey', config).then( function(keySystemAccess) { var promise = keySystemAccess.createMediaKeys(); promise.catch( console.error.bind(console, 'Unable to create MediaKeys') ); promise.then( function(createdMediaKeys) { return video.setMediaKeys(createdMediaKeys); } ).catch( console.error.bind(console, 'Unable to set MediaKeys') ); promise.then( function(createdMediaKeys) { var initData = new Uint8Array([...]); var keySession = createdMediaKeys.createSession(); keySession.addEventListener('message', handleMessage, false); return keySession.generateRequest('webm', initData); } ).catch( console.error.bind(console, 'Unable to create or initialize key session') ); } ); } ``` -------------------------------- ### Control Embedded WordPress with JavaScript Client Source: https://web.dev/articles/wordpress-playground.md.txt Use the @wp-playground/client npm package to connect to an embedded WordPress Playground instance and control it programmatically. This example shows connecting, logging in, navigating, running PHP code, and installing a plugin. ```javascript import { connectPlayground, login, installPlugin } from '@wp-playground/client'; const client = await connectPlayground( document.getElementById('wp'), // An iframe { loadRemote: 'https://playground.wordpress.net/remote.html' }, ); await client.isReady(); // Login the user as admin and go to the post editor: await login(client, 'admin', 'password'); await client.goTo('/wp-admin/post-new.php'); // Run arbitrary PHP code: await client.run({ code: '' }); // Install a plugin: const plugin = await fetchZipFile(); await installPlugin(client, plugin); ``` -------------------------------- ### Setup Vertex Attribute for Color Source: https://web.dev/articles/webgl-orthographic-3d.md.txt Configures a WebGL vertex attribute pointer for color data. This involves getting the attribute location, creating a buffer, binding it, enabling the attribute array, and specifying the data format (RGB bytes). ```javascript // ... var colorLocation = gl.getAttribLocation(program, "a_color"); // ... // Create a buffer for colors. var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.enableVertexAttribArray(colorLocation); // We'll supply RGB as bytes. gl.vertexAttribPointer(colorLocation, 3, gl.UNSIGNED_BYTE, true, 0, 0); // Set Colors. setColors(gl); // ... ``` -------------------------------- ### Full Credential Management API Example Source: https://web.dev/articles/security-credential-management-retrieve-credentials.md.txt A comprehensive example demonstrating the entire flow: checking sign-in status, retrieving credentials (password or federated), handling the response, authenticating the user, updating the UI, and catching potential errors. ```javascript if (window.PasswordCredential || window.FederatedCredential) { if (!user.isSignedIn()) { navigator.credentials .get({ password: true, federated: { providers: ['https://accounts.google.com'], }, mediation: 'silent', }) .then((c) => { if (c) { switch (c.type) { case 'password': return sendRequest(c); break; case 'federated': return gSignIn(c); break; } } else { return Promise.resolve(); } }) .then((profile) => { if (profile) { updateUI(profile); } }) .catch((error) => { showError('Sign-in Failed'); }); } } ``` -------------------------------- ### Compress JPEG images with Imagemin npm module Source: https://web.dev/articles/use-imagemin-to-compress-images.md.txt Compresses JPEG files from specified source directories to a destination directory using the imagemin-mozjpeg plugin with a quality setting of 50. This example requires Node.js and the 'imagemin' and 'imagemin-mozjpeg' packages to be installed. ```javascript const imagemin = require('imagemin'); const imageminMozjpeg = require('imagemin-mozjpeg'); (async() => { const files = await imagemin( ['source_dir/*.jpg', 'another_dir/*.jpg'], { destination: 'destination_dir', plugins: [ imageminMozjpeg({quality: 50}) ] } ); console.log(files); })(); ``` -------------------------------- ### Set up and Begin Observing Changes Source: https://web.dev/articles/es7-observe.md.txt Sets up an observer function to log changes and then begins observing changes on model.a using Object.observe. ```javascript // Set up our observer function observer(changes) { changes.forEach(function (change, i) { console.log(change); }) } // Begin observing model.a for changes Object.observe(model.a, observer); ```