Styling and Shadow DOM
Relevant source files
The following files were used as context for generating this wiki page:- src/utils/react-shadow-host/create-shadow-host.tsx
- src/utils/shadow-root.ts
- src/assets/styles/theme.css
- src/utils/styles.ts
- src/entrypoints/host.content/index.tsx
- src/entrypoints/side.content/index.tsx
- src/utils/react-shadow-host/shadow-host-builder.ts
- src/entrypoints/options/pages/translation/custom-translation-style/css-editor.tsx
- src/entrypoints/options/pages/translation/custom-translation-style/style-preview.tsx
- src/components/markdown-renderer.tsx
As a browser extension, Read Frog injects its UI components directly into web pages. To prevent CSS conflicts with the host page's styles and to ensure a consistent user experience, the extension encapsulates all its UI within the Shadow DOM. This strategy provides robust style isolation.
This document outlines the architecture and mechanisms used for creating, styling, and managing Shadow DOM instances across the extension's content scripts, including the main host UI, the side panel, and the selection pop-up. It covers style injection, dynamic style mirroring, theming, and custom user styling.
Shadow DOM Initialization
The extension's UI is mounted into the host page using the WXT framework's createShadowRootUi utility. This function creates a host element and attaches a shadow root to it, providing an isolated DOM tree for the React application to render into. This process is consistent across different content scripts, such as host.content, side.content, and selection.content.
Sources: src/entrypoints/host.content/index.tsx:29-47, src/entrypoints/side.content/index.tsx:28-79, src/entrypoints/selection.content/index.tsx:18-40
UI Mounting Process
The onMount callback provided to createShadowRootUi is the core of the setup process. It orchestrates the creation of the React root, style injection, and other necessary configurations.
The following diagram illustrates the general flow for mounting a UI component into the Shadow DOM.
This diagram shows the sequence of function calls during the initialization of a content script's UI, from defining the script to mounting the final React component inside an isolated Shadow DOM.
Sources: src/entrypoints/host.content/index.tsx:29-47, src/entrypoints/side.content/index.tsx:28-79
Key Components in Initialization
| Component/Function | Description | File |
|---|---|---|
createShadowRootUi | A WXT utility that creates the shadow host and manages its lifecycle. | host.content/index.tsx, side.content/index.tsx |
insertShadowRootUIWrapperInto | Creates a <div> wrapper inside the shadow root to serve as the React root container. This avoids issues with rendering directly onto the <body> or the shadow host itself. | src/utils/shadow-root.ts |
addStyleToShadow | Copies specific <style> tags from the main document's <head> into the shadow root. | src/utils/styles.ts:1-17 |
mirrorDynamicStyles | Sets up a MutationObserver to watch for and replicate dynamic style changes from the main document to the shadow root. | src/utils/styles.ts:41-147 |
protectInternalStyles | Prevents essential internal style elements from being removed from the document head by other scripts. | src/utils/styles.ts:153-195 |
protectSelectAllShadowRoot | A utility to prevent document.querySelectorAll('*') from traversing into the shadow root from the main page. | src/entrypoints/host.content/index.tsx:36 |
Style Management
A multi-layered strategy is used to manage styles within the Shadow DOM, ensuring both isolation from the host page and consistency with the extension's design system.
Theming and Base Styles
Theming is handled through CSS custom properties (variables) defined in theme.css. These variables cover colors for both light and dark modes. The ThemeProvider component, along with the isDarkMode utility, applies the appropriate theme by adding a dark class to the UI wrapper.
/* src/assets/styles/theme.css:2-25 */
:root {
--background: 0 0% 100%;
--foreground: 240 10% 3.9%;
/* ... other light theme variables */
}
.dark {
--background: 240 10% 3.9%;
--foreground: 0 0% 98%;
/* ... other dark theme variables */
}
These variables are used by components throughout the application, including shadcn/ui components and custom components like MarkdownRenderer.
Sources: src/assets/styles/theme.css, src/utils/react-shadow-host/shadow-host-builder.ts:50-54, src/components/markdown-renderer.tsx
ShadowHostBuilder
The ShadowHostBuilder class is a low-level utility responsible for preparing the initial styles within a newly created shadow root.
This diagram shows the structure of the ShadowHostBuilder class and its relationship with the ShadowHostOptions interface.
Its build method performs several key actions:
- Applies a CSS Reset: If
inheritStylesis false, it injects a CSS reset to isolate the component from inherited styles. The reset starts withall: initial;. - Processes CSS Content: It takes an array of CSS strings, replacing
:rootselectors with:hostto make them compatible with the Shadow DOM. - Splits CSS: It uses
splitShadowRootCssto separate rules that must be in the main document (like@font-faceand@property) from those that can be inside the shadow root. - Injects Styles: It injects the document-level CSS into the main document and the shadow-level CSS into a
<style>tag within the shadow root. - Creates a Wrapper: It creates and returns a
<div>wrapper for the React content, applying dark mode classes if necessary.
Sources: src/utils/react-shadow-host/shadow-host-builder.ts
Dynamic Style Mirroring
Some libraries inject <style> tags into the document's <head> dynamically. To ensure these styles are also applied within the isolated Shadow DOM, the mirrorDynamicStyles function is used.
This function:
- Identifies a source style element in the main document using a CSS selector.
- Creates a "mirror" style element inside the shadow root. It prefers using
adoptedStyleSheetsfor performance but falls back to a<style>element if not supported. - Uses a
MutationObserverto watch the source style element for changes to itstextContent. - Uses another
MutationObserverondocument.headto detect if the source style element is added to the DOM later. - When changes are detected, it updates the mirror style sheet inside the shadow root.
This is used in side.content to mirror styles from the goober CSS-in-JS library.
This sequence diagram details how mirrorDynamicStyles sets up observers to keep styles synchronized between the main document and the Shadow DOM.
Sources: src/utils/styles.ts:41-147, src/entrypoints/side.content/index.tsx:40
Side Panel Styling Interaction
The side panel (side.content) has a unique interaction with the host page's styling. When it is open, it injects a <style> tag into the main document's <head> to shrink the <html> element's width. This prevents the side panel from overlapping the page's content and avoids horizontal scrollbars.
The width is dynamically calculated based on the user-resizable width of the side panel, which is stored in the extension's configuration.
// src/entrypoints/side.content/components/side-content/index.tsx:81-92
styleTag.textContent = `
html {
width: calc(100% - ${sideContent.width}px) !important;
position: relative !important;
min-height: 100vh !important;
}
`;
This mechanism ensures seamless integration of the side panel with the host page's layout.
Sources: src/entrypoints/side.content/components/side-content/index.tsx:75-101
Custom Translation Styling
The extension allows users to provide their own custom CSS to style the translated text nodes. This feature is implemented in the options page and applied during the translation process.
CSS Editor and Preview
- CSS Editor: A CodeMirror-based editor allows users to write custom CSS. The input is debounced and validated in real-time using
lintCSS, which leverages thecss-treelibrary. - Style Preview: A live preview area shows how the custom styles will look. It uses a sample text and applies the styles via the
decorateTranslationNodefunction.
The following diagram shows the flow of creating and applying custom CSS.
This diagram illustrates the user flow for defining custom CSS in the options and how that configuration is then used during the live page translation.
Sources: src/entrypoints/options/pages/translation/custom-translation-style/css-editor.tsx, src/entrypoints/options/pages/translation/custom-translation-style/style-preview.tsx, src/utils/host/translate/decorate-translation.ts (inferred from usage in style-preview.tsx)
Conclusion
The Read Frog extension employs a sophisticated system for styling and UI isolation, centered around the Shadow DOM. By combining the WXT framework's utilities, custom style management functions like mirrorDynamicStyles, and a robust theming system, it successfully avoids conflicts with host websites. This architecture ensures that the extension's components are rendered consistently and correctly across the web, providing a reliable and seamless language-learning experience. The addition of features like custom user styling further enhances the flexibility and user-centric design of the application.