### Install Loki and Initialize Project Source: https://github.com/oblador/loki/blob/master/docs/getting-started.md Installs Loki as a development dependency using Yarn and initializes the project with default configurations, setting up the necessary files for visual regression testing. ```bash yarn add loki --dev yarn loki init ``` -------------------------------- ### Start Storybook and Emulators for Loki Testing Source: https://github.com/oblador/loki/blob/master/docs/getting-started.md Commands to start the Storybook server, which is essential for Loki to access your stories. If testing against mobile platforms, commands to start the respective iOS simulator or Android emulator are also provided. ```bash yarn storybook react-native run-ios react-native run-android ``` -------------------------------- ### Configure Loki for Web/Other React Storybook Projects Source: https://github.com/oblador/loki/blob/master/docs/getting-started.md Integrates Loki with a web-based or general React Storybook setup by adding the necessary import statement to your `.storybook/preview.js` file. This step is typically needed for older Storybook versions. ```javascript import 'loki/configure-react' ``` -------------------------------- ### Run Loki Visual Regression Tests Source: https://github.com/oblador/loki/blob/master/docs/getting-started.md Executes Loki in test mode, comparing current screenshots against the stored reference images. You can test a subset of your configurations by providing a regular expression as a second argument. ```bash yarn loki test yarn loki test laptop ``` -------------------------------- ### Configure Loki for React Native Storybook Source: https://github.com/oblador/loki/blob/master/docs/getting-started.md Integrates Loki with a React Native Storybook setup by adding the necessary import statement to your `storybook/storybook.js` file, enabling Loki to capture screenshots from your React Native components. ```javascript import 'loki/configure-react-native' ``` -------------------------------- ### Generate Initial Loki Reference Images Source: https://github.com/oblador/loki/blob/master/docs/getting-started.md Creates the baseline reference images for visual regression testing. These images are stored in the `loki` folder and should be checked into your version control system, optionally using `git-lfs`. ```bash yarn loki update ``` -------------------------------- ### Loki Development and Testing Commands Source: https://github.com/oblador/loki/blob/master/README.md This section details commands for developers working on Loki itself. It includes installing project dependencies, running example Storybook instances, executing visual tests for examples, and running both unit and CLI integration tests. ```bash yarn yarn workspace @loki/example-react run storybook yarn workspace @loki/example-react run test yarn test cd test/cli && yarn test ``` -------------------------------- ### Install and Initialize Loki Source: https://github.com/oblador/loki/blob/master/README.md This snippet provides the commands to install Loki as a development dependency using Yarn and then initialize its configuration, setting up the project for visual regression testing. ```bash yarn add loki --dev yarn loki init ``` -------------------------------- ### Approve Loki Test Changes and Update References Source: https://github.com/oblador/loki/blob/master/docs/getting-started.md Approves visual changes detected by Loki, updating the reference images to reflect the new desired state. This command is used after reviewing changes and confirming they are correct, and should be followed by committing the new reference images. ```bash yarn loki approve ``` -------------------------------- ### Install Docusaurus Website Dependencies with Yarn Source: https://github.com/oblador/loki/blob/master/website/README.md This command installs all necessary Node.js dependencies for a Docusaurus website using Yarn. It should be executed once after cloning the repository to ensure the project has all required packages for development and building. ```sh # Install dependencies yarn ``` -------------------------------- ### Start Docusaurus Development Server with Yarn Source: https://github.com/oblador/loki/blob/master/website/README.md This command launches the local development server for a Docusaurus website. It enables developers to preview changes in real-time, facilitating an efficient development workflow by automatically reloading the site on content modifications. ```sh # Start the site yarn start ``` -------------------------------- ### Initialize a new project for Loki Lambda renderer Source: https://github.com/oblador/loki/blob/master/docs/serverless.md This command sequence creates a new directory for the Loki Lambda renderer project, navigates into it, and initializes a new Yarn project with default settings, preparing the environment for further development. ```sh mkdir loki-lambda-renderer cd loki-lambda-renderer yarn init -y ``` -------------------------------- ### Loki Installation and Initialization Source: https://github.com/oblador/loki/blob/master/packages/loki/README.md This snippet provides the commands to install Loki as a development dependency using Yarn and then initialize its configuration. It sets up the project to use Loki for visual regression testing. ```bash yarn add loki --dev yarn loki init ``` -------------------------------- ### Loki Visual Regression Testing Workflow Source: https://github.com/oblador/loki/blob/master/README.md These commands outline the typical workflow for using Loki: starting the Storybook server, adding initial reference files, testing components against existing references, and finally approving any visual changes to update the references. ```bash yarn storybook yarn loki update yarn loki test yarn loki approve ``` -------------------------------- ### Prepare Lambda deployment package Source: https://github.com/oblador/loki/blob/master/docs/serverless.md These shell commands first install only the production dependencies of the project using Yarn. Subsequently, they create a zip archive named `loki-lambda-renderer.zip` containing all necessary files, which is a required format for deploying the Lambda function to AWS. ```sh yarn --production zip -r loki-lambda-renderer.zip . ``` -------------------------------- ### Install Loki Lambda renderer and Chromium dependencies Source: https://github.com/oblador/loki/blob/master/docs/serverless.md This command installs the necessary npm packages for the Loki AWS Lambda renderer (`@loki/renderer-aws-lambda`) and a Chromium binary (`@sparticuz/chromium`) specifically designed to be compatible with AWS Lambda environments, using Yarn. ```sh yarn add @loki/renderer-aws-lambda @sparticuz/chromium ``` -------------------------------- ### Loki Project Development and Testing Source: https://github.com/oblador/loki/blob/master/packages/loki/README.md This set of commands is used for developing and testing the Loki project itself. It covers installing dependencies, running example Storybook and visual tests, and executing both unit and CLI integration tests. ```bash yarn yarn workspace @loki/example-react run storybook yarn workspace @loki/example-react run test yarn test cd test/cli && yarn test ``` -------------------------------- ### Start Local Docker Container for Loki Lambda Source: https://github.com/oblador/loki/blob/master/examples/running-renderer-aws-lambda/README.md This command initiates a Docker container from the previously built image. Running this command will start the Loki lambda locally, enabling developers to test and debug its functionality in a simulated environment. ```sh yarn start ``` -------------------------------- ### Loki Visual Regression Testing Workflow Source: https://github.com/oblador/loki/blob/master/packages/loki/README.md These commands outline the typical workflow for using Loki for visual regression testing. It involves starting Storybook, capturing initial reference images, running tests against changes, and approving visual differences. ```bash yarn storybook yarn loki update yarn loki test yarn loki approve ``` -------------------------------- ### Execute Loki tests with AWS Lambda renderer Source: https://github.com/oblador/loki/blob/master/docs/serverless.md This command initiates Loki tests, ensuring that the AWS SDK configuration is properly loaded by setting `AWS_SDK_LOAD_CONFIG=true`. It also specifies the URL of the Storybook static build via `--reactUri`, which must be accessible over HTTPS (e.g., hosted on S3) for the AWS Lambda renderer to access it. ```sh AWS_SDK_LOAD_CONFIG=true yarn loki test --reactUri https://url.to/your/storybook-static/ ``` -------------------------------- ### Docusaurus Blog Post Markdown Template for Editing Source: https://github.com/oblador/loki/blob/master/website/README.md This Markdown template demonstrates the structure of an existing Docusaurus blog post. Similar to documentation pages, it uses front matter for `id` and `title`, and is typically located within the `website/blog` directory for proper rendering. ```markdown --- id: post-needs-edit title: This Blog Post Needs To Be Edited --- Edit me... ``` -------------------------------- ### Configure AWS Lambda handler for Loki renderer Source: https://github.com/oblador/loki/blob/master/docs/serverless.md This JavaScript code defines the entry point for the AWS Lambda function. It exports a handler that utilizes the `createChromeAWSLambdaRenderer` function from the `@loki/renderer-aws-lambda` package to set up the visual regression testing environment within the Lambda execution context. ```js const { createChromeAWSLambdaRenderer } = require('@loki/renderer-aws-lambda'); module.exports = { handler: createChromeAWSLambdaRenderer(), }; ``` -------------------------------- ### Docusaurus Project Directory Structure Specification Source: https://github.com/oblador/loki/blob/master/website/README.md This specification outlines the typical file and directory layout for a Docusaurus project. It details the standard locations for documentation files, blog posts, static assets, and core configuration files, providing a clear overview of the project's organization. ```text my-docusaurus/ docs/ doc-1.md doc-2.md doc-3.md website/ blog/ 2016-3-11-oldest-post.md 2017-10-24-newest-post.md core/ node_modules/ pages/ static/ css/ img/ package.json sidebar.json siteConfig.js ``` -------------------------------- ### New Docusaurus Documentation Page Markdown Template Source: https://github.com/oblador/loki/blob/master/website/README.md This template provides the basic Markdown structure for creating a new Docusaurus documentation page. It specifies the `id` and `title` in the front matter, which are essential for Docusaurus to recognize and link the page within the site's navigation. ```markdown --- id: newly-created-doc title: This Doc Needs To Be Edited --- My new content here.. ``` -------------------------------- ### Docusaurus Documentation Page Markdown Template for Editing Source: https://github.com/oblador/loki/blob/master/website/README.md This Markdown template illustrates the structure of an existing Docusaurus documentation page. It includes front matter with `id` and `title` properties, which are crucial for Docusaurus to identify and display the document correctly within the site's navigation. ```markdown --- id: page-needs-edit title: This Doc Needs To Be Edited --- Edit me... ``` -------------------------------- ### New Docusaurus Blog Post Markdown Template Source: https://github.com/oblador/loki/blob/master/website/README.md This template provides the Markdown structure for creating a new Docusaurus blog post, including author details and title in the front matter. Blog posts are typically named with a `YYYY-MM-DD-Title.md` format and placed in the `website/blog` directory. ```markdown --- author: Frank Li authorURL: https://twitter.com/foobarbaz authorFBID: 503283835 title: New Blog Post --- Lorem Ipsum... ``` -------------------------------- ### Configure Loki to use AWS Lambda target Source: https://github.com/oblador/loki/blob/master/docs/serverless.md This JSON snippet demonstrates how to modify the `package.json` file in your main project to configure Loki. It adds a `configurations` entry under the `loki` section, setting the `target` to `chrome.aws-lambda` and applying a `preset` for specific device emulation, such as 'iPhone 7'. ```json { "loki": { "configurations": { "chrome.iphone7": { "target": "chrome.aws-lambda", "preset": "iPhone 7" } } } } ``` -------------------------------- ### Docusaurus Site Configuration: Header Navigation Links Source: https://github.com/oblador/loki/blob/master/website/README.md This APIDOC entry details the `headerLinks` array within `website/siteConfig.js`, which controls the site's top navigation bar. It explains how to add links to documentation pages, custom React pages, external URLs, and the blog section, specifying the properties for each link type. ```javascript headerLinks: [ // Link to a documentation page by its ID { doc: 'my-examples', label: 'Examples' }, // Link to a custom React page by its filename (without .js extension) { page: 'help', label: 'Help' }, // Link to an external URL { href: 'https://github.com/facebook/Docusaurus', label: 'GitHub' }, // Enable a link to the blog section { blog: true, label: 'Blog' }, // Example for a newly created custom page { page: 'my-new-custom-page', label: 'My New Custom Page' } ] ``` -------------------------------- ### Deploy Loki Lambda function to AWS Source: https://github.com/oblador/loki/blob/master/docs/serverless.md This AWS CLI command creates a new Lambda function named `loki` using the previously created zip file. It specifies crucial configuration parameters such as the Node.js 16.x runtime, the IAM role for permissions, the handler function, memory allocation (2048 MB), and a timeout of 120 seconds for the function's execution. ```sh aws lambda create-function \ --function-name loki \ --runtime nodejs16.x \ --role arn:aws:iam:: \ --handler index.handler \ --memory-size 2048 \ --timeout 120 \ --zip-file fileb://loki-lambda-renderer.zip ``` -------------------------------- ### Update Docusaurus Sidebar Configuration in sidebar.json Source: https://github.com/oblador/loki/blob/master/website/README.md This JavaScript snippet illustrates how to add a newly created documentation page's ID to an existing sidebar configuration within `website/sidebar.json`. This modification ensures the new page appears correctly in the site's navigation menu. ```javascript // Add newly-created-doc to the Getting Started category of docs { "docs": { "Getting Started": [ "quick-start", "newly-created-doc" // new doc here ], ... }, ... } ``` -------------------------------- ### Create IAM role for AWS Lambda function Source: https://github.com/oblador/loki/blob/master/docs/serverless.md This AWS CLI command creates an Identity and Access Management (IAM) role named `lambda-role.loki`. It attaches a trust policy that allows the AWS Lambda service to assume this role, which is necessary for the Lambda function to execute. For simplicity, it initially uses a `AWSDenyAll` policy, which should be replaced with more specific permissions in a production environment. ```sh aws iam create-role \ --role-name lambda-role.loki \ --assume-role-policy-document "arn:aws:iam::aws:policy/AWSDenyAll" ``` -------------------------------- ### Loki CLI: Initialize Command Source: https://github.com/oblador/loki/blob/master/docs/command-line-arguments.md Initializes Loki configuration files, setting up the project for visual regression testing. It can optionally overwrite existing configurations. ```bash yarn run loki init path/to/storybook -- --force ``` ```APIDOC loki init - Description: Initializes Loki configuration. - Flags: --config: Path to storybook folder (Default: .storybook & storybook) --force: Overwrite loki configuration (Default: false) ``` -------------------------------- ### Loki Test Command-Line Flags Reference Source: https://github.com/oblador/loki/blob/master/docs/command-line-arguments.md Comprehensive reference for all command-line flags supported by the `loki test` command. These flags allow for detailed configuration of Storybook host/port, output paths, diffing engine, and integration with AWS Lambda or Docker for screenshot capture. ```APIDOC Command: loki test Description: Captures screenshots and compares them against reference files. Usage: yarn loki test [options] Options: --host Description: Storybook host. Default: localhost --port Description: Storybook port. Default: None --reactUri Description: URI to base of React Storybook. For static build use `file:./storybook-static`. Default: None --reactPort Description: React Storybook port. Default: 6006 --reactNativePort Description: React Native Storybook port. Default: 7007 --reference Description: Path to screenshot reference folder. Default: ./.loki/reference --output Description: Path to screenshot output folder. Default: ./.loki/current --difference Description: Path to image diff folder. Default: ./.loki/difference --diffingEngine (pixelmatch | looks-same | gm) Description: What diffing engine to use. Default: pixelmatch --chromeAwsLambdaBatchSize Description: Number of stories to test per lambda invocation. Default: 1 --chromeAwsLambdaBatchConcurrency Description: Number of stories to test in parallel per lambda invocation. Default: 1 --chromeAwsLambdaFunctionName Description: Name of the use to capture screenshots. Default: loki --chromeAwsLambdaRetries Description: The number of retries for invoking the lambda, in case of failure. Default: 0 --chromeConcurrency Description: How many stories to test in parallel when using chrome. Default: 4 --chromeDockerImage Description: What docker image to use when running chrome. Default: yukinying/chrome-headless-browser-stable:118.0.5993.117 --chromeDockerWithoutSeccomp Description: Run chrome docker without unconfined seccomp settings. Default: false --chromeDockerUseCopy Description: Use docker copy instead of volume mount for local stories. Default: false ``` -------------------------------- ### Run Loki with Storybook in CI Environment Source: https://github.com/oblador/loki/blob/master/docs/continuous-integration.md This command sequence first builds Storybook into static files and then runs Loki. The `--requireReference` flag ensures that tests fail if reference images are missing, which is crucial for CI. The `--reactUri file:./storybook-static` flag points Loki to the locally built Storybook output, avoiding the need for a running Storybook server. ```Shell build-storybook && loki --requireReference --reactUri file:./storybook-static ``` -------------------------------- ### Run Loki Test Command with Custom Port Source: https://github.com/oblador/loki/blob/master/docs/command-line-arguments.md Demonstrates how to execute the `loki test` command, specifying a custom port for Storybook. This command initiates the screenshot capture and comparison process, useful for integrating with specific Storybook instances. ```bash yarn loki test -- --port 9009 ``` -------------------------------- ### Configure Loki in package.json Source: https://github.com/oblador/loki/blob/master/docs/configuration.md Demonstrates how to add and configure the 'loki' section within a 'package.json' file. This includes setting a 'chromeSelector' and defining multiple 'configurations' for different target environments like Chrome (app, Docker, AWS Lambda), iOS simulator, and Android emulator, specifying dimensions or presets. ```json { "name": "my-project", "version": "1.0.0", "loki": { "chromeSelector": "#my-decorator > *", "configurations": { "chrome.laptop": { "target": "chrome.app", "width": 1366, "height": 768 }, "chrome.iphone7": { "target": "chrome.docker", "preset": "iPhone 7" }, "chrome.a4": { "target": "chrome.aws-lambda", "preset": "A4 Paper" }, "ios": { "target": "ios.simulator" }, "android": { "target": "android.emulator" } } } } ``` -------------------------------- ### Loki Core Configuration Parameters Source: https://github.com/oblador/loki/blob/master/docs/configuration.md This section details the available configuration parameters for Loki, used to control various aspects of screenshot testing, including target environments, story filtering, and browser emulation settings. Parameters can be applied globally or per configuration. ```APIDOC target: string Description: Target platform, possible values are `chrome.app`, `chrome.docker`, `chrome.aws-lambda`, `ios.simulator`, `android.emulator`. Targets: All skipStories: string Description: DEPRECATED Same as `loki.skipStories`, but applied to only this configuration. Targets: All storiesFilter: string Description: Same as `loki.storiesFilter`, but applied to only this configuration. Targets: All chromeSelector: string Description: Same as `loki.chromeSelector`, but applied to only this configuration. Targets: chrome.* preset: string Description: Predefined bundled configuration, possible values are `Retina Macbook Pro 15`, `Retina Macbook Pro 15 Dark Mode`, `iPhone 7`, `iPhone 7 Dark Mode`, `iPhone 5`, `iPhone 5 Dark Mode`, `Google Pixel`, `Google Pixel Dark Mode`, `A4 Paper`, and `US Letter Paper`. Targets: chrome.* userAgent: string Description: Custom user agent. Targets: chrome.* width: integer Description: Browser viewport width. Targets: chrome.* height: integer Description: Browser viewport height. Targets: chrome.* disableAutomaticViewportHeight: boolean Description: If the content goes below the viewport do not increase the height so that it fits. Targets: chrome.* deviceScaleFactor: integer Description: Browser pixel density multiple, use `2` for retina, not supported in docker. Targets: chrome.app mobile: boolean Description: Whether to emulate mobile device. This includes viewport meta tag, overlay scrollbars, text autosizing and more. Targets: chrome.* media: string Description: Emulates the given media for CSS media queries. Targets: None features: array Description: Emulates the given features for CSS media queries. See [setEmulatedMedia docs](https://chromedevtools.github.io/devtools-protocol/tot/Emulation/#method-setEmulatedMedia) Targets: chrome.* ``` -------------------------------- ### Loki Command-Line Configuration Options Source: https://github.com/oblador/loki/blob/master/docs/command-line-arguments.md Detailed reference for command-line arguments used to configure Loki's behavior, including Chrome settings, filtering, and output options. These flags control how Loki interacts with the browser, handles diffing, and processes stories. ```APIDOC --chromeEnableAnimations - Description: Enable CSS transitions and animations. - Default: `false` --chromeFlags - Description: Custom chrome flags. - Default: `--headless --disable-gpu --hide-scrollbars` --chromeLoadTimeout - Description: How many milliseconds loki will wait for the page to load before taking as screenshot. - Default: `60000` --chromeRetries - Description: The number of retries for taking the screenshot, in case of failure. - Default: `0` --chromeSelector - Description: CSS selector to the part of the DOM to screenshot. Useful you have decorators that should be excluded. - Default: `#root > *` --chromeTolerance - Description: How many percent tolerated difference compared to reference image. Behaviour of tolerance depends on `diffingEngine`. - Default: `0` --chromeEmulatedMedia - Description: Emulates the given media for CSS media queries. Set to `print` to test print styles. - Default: _None_ --skipStories - Description: **DEPRECATED** Regular expression for stories that should not be tested, it will be tested against a string with the format `${kind} ${story}`. - Default: _None_ --storiesFilter - Description: Opposite of `--skipStories`. - Default: _None_ --configurationFilter - Description: Regular expression for targets that should be tested. - Default: _None_ --targetFilter - Description: Regular expression for targets that should be tested. - Default: _None_ --requireReference - Description: Fail stories without reference image, useful for CI. - Default: _False, true for CI_ --passWithNoStories - Description: If no stories are detected consider this a success. - Default: _False_ --verboseRenderer - Description: Plain text renderer, useful for CI. - Default: _False, true for CI_ --silent - Description: Plain text renderer that will only output errors. - Default: `false` --dockerWithSudo - Description: Run docker commands with sudo. - Default: `false` --dockerNet - Description: Argument to pass to docker --net, e.g. `host` or `bridge`. - Default: _None_ --device - Description: Device/emulator ID to target for screenshots. Useful when running multiple devices on a single machine. - Default: _None_ ``` -------------------------------- ### Build Docker Image for Loki Lambda Source: https://github.com/oblador/loki/blob/master/examples/running-renderer-aws-lambda/README.md This command executes the build process for the Loki lambda, resulting in a Docker image. This image encapsulates the lambda's dependencies and code, making it ready for local execution or deployment. ```sh yarn build ``` -------------------------------- ### Configure Loki with looks-same diffing engine Source: https://github.com/oblador/loki/blob/master/docs/configuration.md Illustrates how to configure the 'looks-same' diffing engine within the Loki configuration in 'package.json'. This allows passing specific options, such as 'ignoreCaret', directly to the underlying image comparison library. ```json { "loki": { "looks-same": { "ignoreCaret": true } } } ``` -------------------------------- ### Storybook Component Property Documentation Schema Source: https://github.com/oblador/loki/blob/master/fixtures/storybook-static/iframe.html This section outlines the standard schema used for documenting component properties within Storybook's argument tables. Each property includes its `Name`, a `Description`, a `Default` value, and the `Control` type used for UI interaction. This structure facilitates clear and consistent property documentation. ```APIDOC Component Property Documentation Format: propertyName: string (required) Description: string Default: string Control: string (e.g., "Set string", "boolean toggle", "number input") Example Entry: propertyName* This is a short description summary defaultValue Set string ``` -------------------------------- ### Configure Global Storybook Settings in JavaScript Source: https://github.com/oblador/loki/blob/master/fixtures/storybook-dynamic/iframe.html This JavaScript code block initializes various global configuration settings for Storybook, accessible via the `window` object. It defines the application type (DEVELOPMENT), logging level, framework options, feature flags (e.g., postcss, emotionAlias), story file paths with import matchers, and the WebSocket URL for the server channel. ```JavaScript window['CONFIG_TYPE'] = "DEVELOPMENT"; window['LOGLEVEL'] = "info"; window['FRAMEWORK_OPTIONS'] = {}; window['FEATURES'] = {"postcss":true,"emotionAlias":true,"warnOnLegacyHierarchySeparator":true}; window['STORIES'] = [{"titlePrefix":"","directory":"./src","files":"**/*.stories.mdx","importPathMatcher":"^\\.[\\\\/](?:src(?:\\/(?!\\.)(?:(?:(?!(?:^|\\/)\\.).)*?)\\/|\\/|$)(?!\\.)(?=.)[^/]*?\\.stories\\.mdx)$"},{"titlePrefix":"","directory":"./src","files":"**/*.stories.@(js|jsx|ts|tsx)","importPathMatcher":"^\\.[\\\\/](?:src(?:\\/(?!\\.)(?:(?:(?!(?:^|\\/)\\.).)*?)\\/|\\/|$)(?!\\.)(?=.)[^/]*?\\.stories\\.(js|jsx|ts|tsx))$"}]; window['SERVER_CHANNEL_URL'] = "ws://localhost:6006/storybook-server-channel"; ``` -------------------------------- ### Storybook Property Definition Schema Source: https://github.com/oblador/loki/blob/master/fixtures/storybook-dynamic/iframe.html This API documentation describes the schema for defining properties within Storybook, likely for its `ArgsTable` or similar argument control mechanisms. It outlines the common fields for each property, including its name, a short description, default value, and the type of control used in the UI. ```APIDOC propertyName*: Description: This is a short description Summary: summary Default: defaultValue Control: Set string ``` -------------------------------- ### Implement Global JavaScript Error Reporting for Development Builds Source: https://github.com/oblador/loki/blob/master/fixtures/storybook-dynamic/iframe.html This JavaScript snippet sets up a global `onerror` handler to capture unhandled runtime errors. In development environments, it sends detailed error information, including message, source, line, column, and stack trace, to a `/runtime-error` endpoint via an XMLHttpRequest. ```JavaScript window.onerror = function onerror(message, source, line, column, err) { if (window.CONFIG_TYPE !== 'DEVELOPMENT') return; var xhr = new window.XMLHttpRequest(); xhr.open('POST', '/runtime-error'); xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); xhr.send( JSON.stringify({ message: message, source: source, line: line, column: column, error: err && { message: err.message, name: err.name, stack: err.stack }, origin: 'preview' }) ); }; ``` -------------------------------- ### Loki Update Command Source: https://github.com/oblador/loki/blob/master/docs/command-line-arguments.md The `loki update` command is used to capture new screenshots and update the existing reference files. This is typically done after making intentional visual changes to components, establishing new baselines for visual regression testing. It accepts the same arguments as `loki test`. ```APIDOC loki update - Description: Capture screenshots and update the reference files. - Usage: Takes same arguments as `loki test`. ``` -------------------------------- ### Loki CLI: Approve Command Source: https://github.com/oblador/loki/blob/master/docs/command-line-arguments.md Prunes old and updates reference files with the images generated in the last run. This command is crucial for managing and updating visual regression test baselines after changes. ```APIDOC loki approve - Description: Prunes old and updates reference files with the images generated in the last run. - Flags: --reference: Path to screenshot reference folder (Default: ./.loki/reference) --output: Path to screenshot output folder (Default: ./.loki/current) --diffOnly: Only approve files that failed `loki test` before (Default: false) ``` -------------------------------- ### Configure Global Storybook Settings Source: https://github.com/oblador/loki/blob/master/fixtures/storybook-static/iframe.html This JavaScript snippet defines various global configuration variables for Storybook, including the `CONFIG_TYPE` (e.g., 'PRODUCTION'), `LOGLEVEL`, `FRAMEWORK_OPTIONS`, and `FEATURES` (like PostCSS and Emotion alias). It also specifies the `STORIES` array, detailing the paths and matchers for story files. ```JavaScript window['CONFIG_TYPE'] = "PRODUCTION"; window['LOGLEVEL'] = "info"; window['FRAMEWORK_OPTIONS'] = {}; window['FEATURES'] = {"postcss":true,"emotionAlias":true,"warnOnLegacyHierarchySeparator":true}; window['STORIES'] = [{"titlePrefix":"","directory":"./src","files":"**/*.stories.mdx","importPathMatcher":"^\\.[\\\\/](?:src(?:\\/(?!\\.)(?:(?:(?!(?:^|\\/)\\.).)*?)\\/|\\/|$)(?!\\.)(?=.)[^/]*?\\.stories\\.mdx)$"},{"titlePrefix":"","directory":"./src","files":"**/*.stories.@(js|jsx|ts|tsx)","importPathMatcher":"^\\.[\\\\/](?:src(?:\\/(?!\\.)(?:(?:(?!(?:^|\\/)\\.).)*?)\\/|\\/|$)(?!\\.)(?=.)[^/]*?\\.stories\\.(js|jsx|ts|tsx))$"}]; ``` -------------------------------- ### Initialize React DevTools Global Hook for Storybook Source: https://github.com/oblador/loki/blob/master/fixtures/storybook-unconfigured/iframe.html This JavaScript snippet ensures that if the current window is an iframe (i.e., `window.parent` is not `window`), it reuses the `__REACT_DEVTOOLS_GLOBAL_HOOK__` from the parent window. This is a common pattern in development environments like Storybook where components might be rendered within an iframe, allowing React DevTools to inspect components across the frame boundary. ```javascript if (window.parent !== window) { window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = window.parent.__REACT_DEVTOOLS_GLOBAL_HOOK__; } ``` -------------------------------- ### Implement Global JavaScript Runtime Error Reporting Source: https://github.com/oblador/loki/blob/master/fixtures/storybook-static/iframe.html This JavaScript code sets up a global `window.onerror` handler to capture unhandled runtime errors. In development mode, it sends detailed error information (message, source, line, column, stack trace) via a POST request to the `/runtime-error` endpoint, aiding in debugging and monitoring. ```JavaScript window.onerror = function onerror(message, source, line, column, err) { if (window.CONFIG_TYPE !== 'DEVELOPMENT') return; // eslint-disable-next-line no-var, vars-on-top var xhr = new window.XMLHttpRequest(); xhr.open('POST', '/runtime-error'); xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); xhr.send( JSON.stringify({ /* eslint-disable object-shorthand */ message: message, source: source, line: line, column: column, error: err && { message: err.message, name: err.name, stack: err.stack }, origin: 'preview' /* eslint-enable object-shorthand */ }) ); }; ``` -------------------------------- ### Handle Asynchronous Storybook Stories in Loki Source: https://github.com/oblador/loki/blob/master/docs/flaky-tests.md Shows how to manage asynchronous Storybook stories in Loki by using `createAsyncCallback`. This ensures Loki waits for network requests or data loading to complete before taking a screenshot, preventing flaky tests caused by unrendered content. ```js import createAsyncCallback from '@loki/create-async-callback'; export const AsyncStory = () => ; ``` -------------------------------- ### Core UI Styling for Storybook Components Source: https://github.com/oblador/loki/blob/master/fixtures/storybook-dynamic/iframe.html This comprehensive CSS block provides styling for various UI elements commonly found in web applications, particularly those using Storybook for component development. It manages the visibility of preparation and error states, defines layout for main content areas (centered, fullscreen, padded), and styles interactive elements like loaders, preview blocks, and argument tables. Includes vendor prefixes for broader browser compatibility and specific workarounds for Internet Explorer 11. ```css :not(.sb-show-preparing-story) > .sb-preparing-story, :not(.sb-show-preparing-docs) > .sb-preparing-docs, :not(.sb-show-nopreview) > .sb-nopreview, :not(.sb-show-errordisplay) > .sb-errordisplay { display: none; } .sb-show-main.sb-main-centered { margin: 0; display: flex; align-items: center; min-height: 100vh; } .sb-show-main.sb-main-centered #root { box-sizing: border-box; margin: auto; padding: 1rem; max-height: 100%; /* Hack for centering correctly in IE11 */ } /* Vertical centering fix for IE11 */ @media screen and (-ms-high-contrast: none), (-ms-high-contrast: active) { .sb-show-main.sb-main-centered:after { content: ''; min-height: inherit; font-size: 0; } } .sb-show-main.sb-main-fullscreen { margin: 0; padding: 0; display: block; } .sb-show-main.sb-main-padded { margin: 0; padding: 1rem; display: block; box-sizing: border-box; } .sb-wrapper { position: fixed; top: 0; bottom: 0; left: 0; right: 0; padding: 20px; font-family: 'Nunito Sans', -apple-system, '.SFNSText-Regular', 'San Francisco', BlinkMacSystemFont, 'Segoe UI', 'Helvetica Neue', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; overflow: auto; } .sb-heading { font-size: 14px; font-weight: 600; letter-spacing: 0.2px; margin: 10px 0; padding-right: 25px; } .sb-nopreview { display: flex; align-content: center; justify-content: center; } .sb-nopreview_main { margin: auto; padding: 30px; border-radius: 10px; background: rgba(0, 0, 0, 0.03); } .sb-nopreview_heading { text-align: center; } .sb-errordisplay { border: 20px solid rgb(187, 49, 49); background: #222; color: #fff; z-index: 999999; } .sb-errordisplay_code { padding: 10px; background: #000; color: #eee; font-family: 'Operator Mono', 'Fira Code Retina', 'Fira Code', 'FiraCode-Retina', 'Andale Mono', 'Lucida Console', Consolas, Monaco, monospace; } .sb-errordisplay pre { white-space: pre-wrap; } @-webkit-keyframes sb-rotate360 { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } @keyframes sb-rotate360 { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } @-webkit-keyframes sb-glow { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } } @keyframes sb-glow { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } } /* We display the preparing loaders *over* the rendering story */ .sb-preparing-story, .sb-preparing-docs { background-color: white; } .sb-loader { -webkit-animation: sb-rotate360 0.7s linear infinite; animation: sb-rotate360 0.7s linear infinite; border-color: rgba(97, 97, 97, 0.29); border-radius: 50%; border-style: solid; border-top-color: #646464; border-width: 2px; display: inline-block; height: 32px; left: 50%; margin-left: -16px; margin-top: -16px; mix-blend-mode: difference; overflow: hidden; position: absolute; top: 50%; transition: all 200ms ease-out; vertical-align: top; width: 32px; z-index: 4; } .sb-previewBlock { background: #fff; border: 1px solid rgba(0, 0, 0, 0.1); border-radius: 4px; box-shadow: rgba(0, 0, 0, 0.1) 0 1px 3px 0; margin: 25px auto 40px; max-width: 600px; } .sb-previewBlock_header { align-items: center; box-shadow: rgba(0, 0, 0, 0.1) 0 -1px 0 0 inset; display: flex; gap: 14px; height: 40px; padding: 0 12px; } .sb-previewBlock_icon { -webkit-animation: sb-glow 1.5s ease-in-out infinite; animation: sb-glow 1.5s ease-in-out infinite; background: #e6e6e6; height: 14px; width: 14px; } .sb-previewBlock_icon:last-child { margin-left: auto; } .sb-previewBlock_body { -webkit-animation: sb-glow 1.5s ease-in-out infinite; animation: sb-glow 1.5s ease-in-out infinite; height: 182px; position: relative; } .sb-argstableBlock { border-collapse: collapse; border-spacing: 0; font-size: 13px; line-height: 20px; margin: 25px auto 40px; max-width: 600px; text-align: left; width: 100%; } .sb-argstableBlock th:first-of-type, .sb-argstableBlock td:first-of-type { padding-left: 20px; } .sb-argstableBlock th:nth-of-type(2), .sb-argstableBlock td:nth-of-type(2) { width: 35%; } .sb-argstableBlock th:nth-of-type(3), .sb-argstableBlock td:nth-of-type(3) { width: 15%; } .sb-argstableBlock th:laste-of-type, .sb-argstableBlock td:laste-of-type { width: 25%; padding-right: 20px; } .sb-argstableBlock th span, .sb-argstableBlock td span { -webkit-animation: sb-glow 1.5s ease-in-out infinite; animation: sb-glow 1.5s ease-in-out infinite; background-color: rgba(0, 0, 0, 0.1); border-radius: 0; box-shadow: none; color: transparent; } .sb-argstableBlock th { padding: 10px 15px; } .sb-argstableBlock-body { border-radius: 4px; box-shadow: rgba(0, 0, 0, 0.1) 0 1px 3px 1px, rgba(0, 0, 0, 0.065) 0 0 0 1px; } .sb-argstableBlock-body tr { background: transparent; overflow: hidden; } .sb-argstableBlock-body tr:not(:first-child) { border-top: 1px solid #e6e6e6; } .sb-argstableBlock-body tr:first-child td:first-child { border-top-left-radius: 4px; } .sb-argstableBlock-body tr:first-child td:last-child { border-top-right-radius: 4px; } .sb-argstableBlock-body tr:last-child td:first-child { border-bottom-left-radius: 4px; } ``` -------------------------------- ### Integrate React and Vue DevTools Global Hooks Source: https://github.com/oblador/loki/blob/master/fixtures/storybook-static/iframe.html This JavaScript snippet attempts to connect React and Vue DevTools global hooks from the top frame to the current window, enabling debugging capabilities across different browser contexts within Storybook. It includes error handling for connection failures. ```JavaScript /* globals window */ /* eslint-disable no-underscore-dangle */ try { if (window.top !== window) { window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = window.top.__REACT_DEVTOOLS_GLOBAL_HOOK__; window.__VUE_DEVTOOLS_GLOBAL_HOOK__ = window.top.__VUE_DEVTOOLS_GLOBAL_HOOK__; window.top.__VUE_DEVTOOLS_CONTEXT__ = window.document; } } catch (e) { // eslint-disable-next-line no-console console.warn('unable to connect to top frame for connecting dev tools'); } ```