### Draw a Triangle with WebGPU Source: https://webkit.org/wp-content/uploads/webgpu-api-proposal.html This example demonstrates the basic setup for drawing a triangle using the WebGPU API. It involves creating a library, defining vertex data, setting up a render pipeline, and issuing draw commands. ```javascript let canvas = document.querySelector("canvas"); canvas.width = 500; canvas.height = 500; let gpu = canvas.getContext("Webgpu"); let library = gpu.createLibrary(loadShaderFromScript("library")); library.label = "Example label"; let vertexF = library.functionWithName("vertex_main"); let fragmentF = library.functionWithName("fragment_main"); let vertexData = new Float32Array([ // x y z 1 r g b 1 0, 0.75, 0, 1, 1, 0, 0, 1, -0.75, -0.75, 0, 1, 0, 1, 0, 1, 0.75, -0.75, 0, 1, 0, 0, 1, 1 ]); let vertexBuffer = gpu.createBuffer(vertexData); let pipelineDescriptor = new WebGPURenderPipelineDescriptor(); pipelineDescriptor.vertexFunction = vertexF; pipelineDescriptor.fragmentFunction = fragmentF; pipelineDescriptor.colorAttachments[0].pixelFormat = "BGRA8Unorm"; let pipelineState = gpu.createRenderPipelineState(pipelineDescriptor); let drawable = gpu.nextDrawable(); let passDescriptor = new WebGPURenderPassDescriptor(); passDescriptor.colorAttachments[0].loadAction = "clear"; passDescriptor.colorAttachments[0].storeAction = "store"; passDescriptor.colorAttachments[0].clearColor = [0.8, 0.8, 0.8, 1.0]; passDescriptor.colorAttachments[0].texture = drawable.texture; let commandQueue = gpu.createCommandQueue(); let commandBuffer = commandQueue.createCommandBuffer(); let commandEncoder = commandBuffer.createRenderCommandEncoder(passDescriptor); commandEncoder.setRenderPipelineState(pipelineState); commandEncoder.setVertexBuffer(vertexBuffer, 0, 0); commandEncoder.drawPrimitives("triangle", 0, 3); commandEncoder.endEncoding(); commandBuffer.presentDrawable(drawable); commandBuffer.commit(); ``` -------------------------------- ### Establish a Typical Audio-Video WebRTC Call Source: https://webkit.org/blog/7763/a-closer-look-into-webrtc This example shows how to initiate a standard audio-video WebRTC call using the latest APIs. It includes getting user media, adding tracks to the peer connection, and creating an offer. ```javascript var stream = await navigator.mediaDevices.getUserMedia({audio: true, video: true}); var pc = new RTCPeerConnection(); var audioSender = pc.addTrack(stream.getAudioTracks()[0], stream); var videoSender = pc.addTrack(stream.getVideoTracks()[0], stream); var offer = await pc.createOffer(); await pc.setLocalDescription(offer); // send offer to the other party ... ``` -------------------------------- ### Basic CSS Grid Container Setup Source: https://webkit.org/blog/17474/css-grid-a-helpful-mental-model-and-the-power-of-grid-lines Sets up a grid container with three columns and two rows, and applies a gap between grid items. This is the starting point for grid layout. ```css .products { display: grid; grid-template-columns: 1fr 1fr 1fr; grid-template-rows: 1fr 1fr; grid-gap: 2em; } ``` -------------------------------- ### Example Program for DFG JIT Analysis Source: https://webkit.org/blog/3362/introducing-the-webkit-ftl-jit This simple program is used as an example to illustrate how the DFG JIT analyzes data flow and performs optimizations based on type predictions. ```javascript function add(a, b) { return a + b; } ``` -------------------------------- ### JavaScript Set toString() Example Source: https://webkit.org/blog/6756/es6-feature-complete Demonstrates creating a Set and logging its string representation. This example illustrates a scenario where Object Property Conditions would be applied for optimizing access to the toString method. ```javascript function foo() { let r = new Set(); console.log(r.toString()); } ``` -------------------------------- ### JIT Logging Output Example Source: https://webkit.org/blog/6411/javascriptcore-csi-a-crash-site-investigation-story Example log output from JavaScriptCore's JIT compiler, showing function calls and register state during execution. Useful for tracing program flow and identifying potential corruption points. ```text ENTRY[0x10a92d280:<0x00000002 2>] AH::copyCalleeSavesFromFrameOrRegisterToVMCalleeSavesBuffer set the saved %rbx to ebx:<0x7fff59f212e0 140734702424800> ENTRY[0x10a92d280:<0x00000002 2>] AH::copyCalleeSavesFromFrameOrRegisterToVMCalleeSavesBuffer set the saved %rbx to ebx:<0x7fff59f212e0 140734702424800> ENTRY[0x10a92d280:<0x00000002 2>] AH::copyCalleeSavesFromFrameOrRegisterToVMCalleeSavesBuffer set the saved %rbx to ebx:<0x7fff59f212e0 140734702424800> ENTRY[1] uncaughtException ENTER: rbx=0x7fff59f25100 rsp=0x7fff59f24f20 ENTRY[1] uncaughtException EXIT: rbx=0x7fff59f212e0 rsp=0x7fff59f24fd0 ASAN:SIGSEGV ``` -------------------------------- ### JSC Sampling Profiler Start Sampling Algorithm Source: https://webkit.org/blog/6539/introducing-jscs-new-sampling-profiler This pseudocode outlines the core logic for starting and running JSC's sampling profiler. It highlights the need for conservative stack traces and careful lock management to avoid deadlocks. ```cpp void SamplingProfiler::startSampling() { VM& vm = getCurrentVM(); MachineThread* jscThread = getJSCExecutionThread(); while (true) { std::sleep_for(std::chrono::microseconds(1000)); if (vm.isIdle()) continue; // Note that the sampling thread doesn't control the state in // which the execution thread pauses. This means it can be holding // arbitrary locks such as the malloc lock when it gets paused. // Therefore, the sampling thread can't malloc until the execution // is resumed or the sampling thread may deadlock. jscThread->pause(); // Get interesting register values from the paused execution thread. void* machinePC = thread->PC(); void* machineFramePointer = thread->framePointer(); // JSC designates a machine register to hold the bytecode PC when // executing interpreter code. This register is only used when the // sampling thread pauses the top frame inside the interpreter. void* interpreterPC = thread->interpreterPC(); void* framePointer = machineFramePointer; if (!isMachinePCInsideJITCode(machinePC) && !isMachinePCInsideTheInterpreter(machinePC)) { // When JSC's JIT code calls back into the C runtime, it will // store the frame pointer for the current JavaScript upon // entry into the runtime. This is needed for many reasons. // Because JSC does this, the sampling profiler can use that frame // as the top frame in a stack trace. framePointer = vm.topCallFrame; } bool success = takeConservativeStackTrace(framePointer, machinePC, interpreterPC); if (!success) continue; jscThread->resume(); // The sampling thread can now malloc and do interesting things with // other locks again. completeStackTrace(); } } ``` -------------------------------- ### CSS Radial Gradient Example Source: https://webkit.org/blog/175/introducing-css-gradients Example of a radial gradient. The first two points define a start circle and the next two define an end circle. If the start and end circles are identical, the gradient renders nothing. ```css -webkit-gradient(radial, center center, 0px, center center, 100px, color-stop(0, red), color-stop(1, blue)) ``` -------------------------------- ### Record Camera and Microphone to MP4 Source: https://webkit.org/blog/11353/mediarecorder-api This example demonstrates how to record audio and video from the camera and microphone, store the recordings as blobs, and preview them. It utilizes `navigator.mediaDevices.getUserMedia` to access the stream and `MediaRecorder` to handle the recording process. ```html
``` -------------------------------- ### Initialize Media Source and Load Video Segments Source: https://webkit.org/blog/15036/how-to-use-media-source-extensions-with-airplay Sets up the video playback by checking media type support, waiting for the MediaSource to open, adding a source buffer, and loading the initial video segment. It handles segment loading either immediately or via an 'onstartstreaming' event. ```javascript document.onload = async () => { if (!MediaSource.isTypeSupported(mediaType)) { return console.log('Media type is not supported.'); } await new Promise((resolve) => { source.addEventListener("sourceopen", resolve, { once: true }); document.body.appendChild(video); }); const sourceBuffer = source.addSourceBuffer(mediaType); async function loadSegment() { const response = await fetch(videoURL); const buffer = await response.arrayBuffer(); await new Promise((resolve) => { sourceBuffer.addEventListener("updateend", resolve, { once: true }); sourceBuffer.appendBuffer(buffer); }); } if (typeof(source.onstartstreaming) !== 'undefined') { source.onstartstreaming = async () => { loadSegment(); }; } else loadSegment(); }); ``` -------------------------------- ### Example A: Option 3 - Non-letter Start Source: https://webkit.org/blog/13607/help-choose-from-options-for-css-nesting-syntax Shows Option 3, where nested rules can be added directly but cannot start with a letter. ```css article { font-family: avenir; & aside { font-size: 1rem; } } ``` -------------------------------- ### CSS Linear Gradient Example Source: https://webkit.org/blog/175/introducing-css-gradients Example of a linear gradient. The points define a line, and colors are interpolated along this line. If the start and end points are identical, the gradient renders nothing. ```css -webkit-gradient(linear, left top, right bottom, color-stop(0, red), color-stop(1, blue)) ``` -------------------------------- ### WebGPU Bind Group Setup Source: https://webkit.org/blog/9528/webgpu-and-wsl-in-safari Demonstrates how WebGPU batches resources into bind groups for a more efficient and concise way to manage resources compared to WebGL. ```javascript encoder.setBindGroup(0, bindGroup); ``` -------------------------------- ### Conditional Breakpoint Example Source: https://webkit.org/blog/5435/breakpoint-options Demonstrates a conditional breakpoint within a loop. The breakpoint is triggered for odd values of 'i', starting with the sixth iteration. ```javascript for (var i = 0; i < 10; ++i) { // do some work } ``` -------------------------------- ### Run build-webkit Script with Help Option Source: https://webkit.org/building-webkit/script-tools Execute the `build-webkit` script with the `--help` option to view its usage instructions. This is useful for understanding script parameters. ```bash WebKit/Tools/Scripts/build-webkit --help ``` -------------------------------- ### Basic Grid Lanes Layout Source: https://webkit.org/demos/grid3/photos Utilize `display: grid-lanes` for a basic grid lanes setup. This example uses `repeat(auto-fill, minmax(14rem, 1fr))` to create responsive columns. ```css main { display: grid-lanes; grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr)); gap: 1rem; } ``` -------------------------------- ### WebGL Pipeline State Setup Source: https://webkit.org/blog/9528/webgpu-and-wsl-in-safari Demonstrates the verbose state-changing calls required to render a single object in WebGL. This highlights the complexity WebGPU aims to simplify. ```javascript gl.UseProgram(program1); gl.frontFace(gl.CW); gl.cullFace(gl.FRONT); gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_MIN); gl.blendFuncSeparate(gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA, gl.ZERO); gl.colorMask(true, false, true, true); gl.depthMask(true); gl.stencilMask(1); gl.depthFunc(gl.GREATER); gl.drawArrays(gl.TRIANGLES, 0, count); ``` -------------------------------- ### Update Uniforms in WebGPU Source: https://webkit.org/wp-content/uploads/webgpu-api-proposal.html This example shows how to update uniform buffer data per frame. It assumes the initial setup from drawing a triangle is complete and focuses on modifying and binding the uniform buffer before drawing. ```javascript // Setup let uniformData = new Float32Array([ 0.5 ]); let uniformBuffer = gpu.createBuffer(uniformData); // Each frame let uniformBufferView = new Float32Array(uniformBuffer.contents); uniformBufferView[0] = frameId * 10; // Some per-frame value let commandEncoder = commandBuffer.createRenderCommandEncoder(passDescriptor); commandEncoder.setRenderPipelineState(pipelineState); commandEncoder.setVertexBuffer(vertexBuffer, 0, 0); commandEncoder.setVertexBuffer(uniformBuffer, 0, 1); commandEncoder.drawPrimitives("triangle", 0, 3); commandEncoder.endEncoding(); commandBuffer.presentDrawable(drawable); commandBuffer.commit(); ``` -------------------------------- ### Run build-webkit Script with Help (Path Added) Source: https://webkit.org/building-webkit/script-tools Execute the `build-webkit` script with the `--help` option directly after adding `WebKit/Tools/Scripts` to your shell's PATH. This allows for quick access to script help. ```bash build-webkit --help ``` -------------------------------- ### WebGPU Pipeline State Setup Source: https://webkit.org/blog/9528/webgpu-and-wsl-in-safari Shows the simplified approach to rendering a single object in WebGPU using a pipeline state object. This reduces JavaScript-to-C++ communication overhead. ```javascript encoder.setPipeline(renderPipeline); encoder.draw(count, 1, 0, 0); ``` -------------------------------- ### Getting raw pointers/references from Ref/RefPtr Source: https://webkit.org/blog/5381/refptr-basics Use `get()` on a `Ref` to get a raw reference, and `ptr()` on a `RefPtr` to get a raw pointer. ```cpp printString(stderr, a.get().caption()); printNode(stderr, a.ptr()); ``` -------------------------------- ### Open Database and Execute SQL Queries Source: https://webkit.org/blog/126/webkit-does-html5-client-side-database-storage Demonstrates how to open a named database and execute SQL queries asynchronously. Callback functions are used to handle query results. ```javascript var database = openDatabase("Database Name", "Database Version"); database.executeSql("SELECT * FROM test", function(result1) { // do something with the results database.executeSql("DROP TABLE test", function(result2) { // do some more stuff alert("My second database query finished executing!"); }); }); ``` -------------------------------- ### Get Object Keys and Values Source: https://webkit.org/web-inspector/console-command-line-api Use keys() to get an array of an object's own enumerable property names and values() to get an array of an object's own enumerable property values. ```javascript keys({a: 1, b: 2}) values({a: 1, b: 2}) ``` -------------------------------- ### Initialize Video Element and URLs for AirPlay/MSE Demo Source: https://webkit.org/blog/15036/how-to-use-media-source-extensions-with-airplay Sets up the AirPlay URL, video URL, and media type. Creates and configures a video element for playback, enabling controls, loop, mute, and autoplay. ```javascript const airplayURL = './video/demo.m3u8'; const videoURL = './video/demo.mp4'; const mediaType = 'video/mp4; codecs="avc1.640028"'; // Create a video element const video = document.createElement('video'); // Set video element properties for the demo video.controls = true; video.loop = true; video.muted = true; video.autoplay = true; ``` -------------------------------- ### Unnested CSS Example C Source: https://webkit.org/blog/13607/help-choose-from-options-for-css-nesting-syntax Standard unnested CSS for re-nesting example. ```css a:hover { color: hotpink; } aside a:hover { color: red; } ``` -------------------------------- ### Build WebKit Source: https://webkit.org/getting-a-crash-log/webkit-on-windows Initiate the build process for WebKit using the provided script. ```bash > perl Tools/Scripts/build-webkit ``` -------------------------------- ### Unnested CSS Example F Source: https://webkit.org/blog/13607/help-choose-from-options-for-css-nesting-syntax Unnested CSS with media query for integration example. ```css ol, ul { padding-left: 1em; } @media (max-width: 30em){ .type ul, .type ol { padding-left: 0; } } ``` -------------------------------- ### WHLSL Pixel Shader Example Source: https://webkit.org/blog/8482/web-high-level-shading-language This pixel shader example is compatible with WHLSL without any modifications. ```whsl float intensity = 0.5f - length(float2(0.5f, 0.5f) - input.tex); intensity = clamp(intensity, 0.0f, 0.5f) * 2.0f; return float4(input.color.xyz, intensity); ``` -------------------------------- ### Create a Whitelist File for Function Signatures Source: https://webkit.org/blog/6411/javascriptcore-csi-a-crash-site-investigation-story Create a whitelist.txt file to specify function signatures for compilation. Each signature should be on a new line, and C++ style comments (//) are supported. ```bash $ vi whitelist.txt isSymbol#BTGpXV // toString#D57Jzo // _isHTMLAllCollection#BlkszW ``` -------------------------------- ### WHLSL Vertex Shader Example Source: https://webkit.org/blog/8482/web-high-level-shading-language This vertex shader example from Microsoft's DirectX-Graphics-Samples repository works unmodified as a WHLSL shader. ```whsl VSParticleDrawOut output; output.pos = g_bufPosVelo[input.id].pos.xyz; float mag = g_bufPosVelo[input.id].velo.w / 9; output.color = lerp(float4(1.0f, 0.1f, 0.1f, 1.0f), input.color, mag); return output; ``` -------------------------------- ### Run WebKit Build Script Source: https://webkit.org/running-webkit/script-tools Execute the `build-webkit` script from the command line using its full path. This is the standard way to initiate a build. ```bash WebKit/Tools/Scripts/build-webkit ``` -------------------------------- ### Domain-Bound Security Code Example Source: https://webkit.org/blog/10875/release-notes-for-safari-technology-preview-109-with-safari-14-features Example of a domain-bound security code for 2FA SMS. Safari will only offer to fill the code on example.com. ```text Your Example code is 123446. @example.com #123446 ``` -------------------------------- ### HTML Dialog Element Example Source: https://webkit.org/blog/12445/new-webkit-features-in-safari-15-4 Use the `` element to create overlays and modals. This example shows a basic structure for a confirmation dialog. ```html

Do you want to delete everything?

You will lose all your data.

``` -------------------------------- ### Correct Objective-C Block Spacing Source: https://webkit.org/bug-life-cycle/code-style-guidelines No space between block start and arguments, or block start and opening brace. Space between argument list and opening brace. ```objective-c block = ^{ ... }; block = ^(int, int) { ... }; ``` -------------------------------- ### Example A: Option 5 - Top-level @nest Source: https://webkit.org/blog/13607/help-choose-from-options-for-css-nesting-syntax Demonstrates Option 5, which uses a dedicated @nest at-rule for nested styles. ```css @nest article { & { font-family: avenir; } aside { font-size: 1rem; } } ``` -------------------------------- ### Add32 Instruction Example Source: https://webkit.org/docs/b3/assembly-intermediate-representation.html Demonstrates the AT&T style syntax for an Add32 instruction, where the destination is the last argument. This specific example loads from a memory location and adds to a register. ```assembly Add32 42(%rax), %rcx ```