jkunz 550ec92197 feat(domtools): adopt global styles as constructed sheets, so a page works under style-src 'self'
setGlobalStyles() appended a <style> element, which a Content-Security-Policy without 'unsafe-inline' blocks. It now adopts a constructed stylesheet into document.adoptedStyleSheets, and dispose() removes only the sheets its instance adopted. elementBasic.setup() adopts the scrollbar hiding as its own sheet, which setScrollbarsHidden() switches; it stays on by default. elementBasic.styles is deprecated in favour of staticStyles. A Node test serves a page under a strict policy to Chromium and finds no violation.
2026-10-22 15:03:02 +00:00
2020-05-23 14:44:42 +00:00
2026-10-11 00:44:51 +00:00

@design.estate/dees-domtools

Browser-side TypeScript utilities for bootstrapping DOM work, responsive styling, theme handling, scrolling, metadata setup, and Lit-based web components.

It gives you a singleton-style DomTools runtime plus a few focused exports for CSS breakpoints, base element styling, and low-level integrations with the underlying design.estate and push.rocks packages.

Issue Reporting and Security

For reporting bugs, issues, or security vulnerabilities, please visit community.foss.global/. This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a code.foss.global/ account to submit Pull Requests directly.

Installation

pnpm add @design.estate/dees-domtools

What It Includes

  • DomTools for one-time app bootstrap and shared browser services
  • ThemeManager (the class behind domtools.themeManager) and its TThemePreference type, for a bright/dark theme that follows the system until the reader picks one
  • breakpoints helpers for viewport and container-query driven Lit CSS
  • css.cssGridColumns() for simple grid-template generation
  • elementBasic helpers for Lit base styles and one-time global CSS setup
  • TypedRequest re-exported from @api.global/typedrequest 9
  • plugins for direct access to the package ecosystem used internally

The plugins export keeps the commonly used downstream namespaces available, including plugins.smartstate, plugins.smartpromise (deferreds and delayFor/Timeout), plugins.smartrouter, plugins.smartrx, plugins.smarturl, and plugins.typedrequest. plugins.typedrequest and convenience.typedrequest are @api.global/typedrequest 9; code that connects its own typedrequest router or target to deesComms must use typedrequest 9 as well.

Quick Start

import { DomTools } from '@design.estate/dees-domtools';

const domtools = await DomTools.setupDomTools();
await domtools.domReady.promise;

console.log(domtools.elements.headElement);
console.log(domtools.elements.bodyElement);

setupDomTools() is safe to call repeatedly. By default it returns a shared global instance and avoids duplicate initialization work.

If you need an isolated instance for testing or short-lived usage, pass ignoreGlobal: true. Isolated instances follow the same domToolsReady and domReady lifecycle as the shared singleton.

DomTools Lifecycle

import { DomTools } from '@design.estate/dees-domtools';

const domtools = await DomTools.setupDomTools({
  ignoreGlobal: false,
});

await domtools.domToolsReady.promise;
await domtools.domReady.promise;

setupDomTools() resolves once the instance is initialized and its readiness listeners are installed. domReady resolves later, once document.head and document.body are available.

Main instance properties:

  • elements.headElement and elements.bodyElement
  • router from @push.rocks/smartrouter
  • websetup from @push.rocks/websetup
  • smartstate and domToolsStatePart
  • themeManager
  • scroller
  • keyboard after domReady
  • deesComms, a @design.estate/dees-comms 2 instance
  • convenience.typedrequest, convenience.smartjson, convenience.smartpromise, convenience.smarturl

If you need the already-created global instance synchronously, use DomTools.getGlobalDomToolsSync() after startup has completed.

Cleanup

import { DomTools } from '@design.estate/dees-domtools';

const domtools = await DomTools.setupDomTools({
  ignoreGlobal: true,
});

// ...use the instance

domtools.dispose();

dispose() removes the listeners, DOM resources and adopted stylesheets owned by that DomTools instance, and leaves the stylesheets other code adopted in place and in order. For shared global usage you usually keep the singleton alive for the lifetime of the page, but disposal is useful for tests and intentionally short-lived isolated instances.

DOM, CSS, and External Resources

import { DomTools } from '@design.estate/dees-domtools';

const domtools = await DomTools.setupDomTools();

await domtools.setGlobalStyles(`
  body {
    margin: 0;
    font-family: Inter, sans-serif;
  }
`);

await domtools.setExternalCss(
  'https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap'
);

await domtools.setExternalScript('https://cdn.example.com/some-script.js');

setGlobalStyles() adopts the CSS into document.adoptedStyleSheets as a constructed stylesheet instead of adding a <style> element, so it applies under a Content-Security-Policy whose style-src has no 'unsafe-inline', such as style-src 'self'. An adopted sheet comes after every <style> and <link> sheet of the document, so its rules beat document rules of equal specificity, and a constructed sheet drops @import rules. setExternalCss() adds a <link rel="stylesheet">, which the policy allows when it allows the stylesheet's origin.

For page metadata and favicons:

import { DomTools } from '@design.estate/dees-domtools';

const domtools = await DomTools.setupDomTools();

await domtools.setWebsiteInfo({
  metaObject: {
    title: 'Example App',
    description: 'A browser app bootstrapped with DomTools',
  },
  faviconUrl: '/favicon.ico',
});

Theme Management

import { DomTools } from '@design.estate/dees-domtools';

const domtools = await DomTools.setupDomTools();
const { themeManager } = domtools;

themeManager.themeObservable.subscribe((isBright) => {
  console.log('bright mode?', isBright);
});

themeManager.goDark();
themeManager.goBright();
themeManager.toggleDarkBright();

await themeManager.enableAutomaticGlobalThemeChange();

The theme manager starts from prefers-color-scheme and publishes updates through an RxJS ReplaySubject<boolean>.

Theme preference

A theme toggle sets the reader's preference rather than the theme of the moment:

themeManager.preference; // 'system' | 'bright' | 'dark' (TThemePreference)
themeManager.setPreference(themeManager.goBrightBoolean ? 'dark' : 'bright'); // true when kept
themeManager.setPreference('system'); // follow prefers-color-scheme again

'system' follows prefers-color-scheme; 'bright' and 'dark' hold that theme while the system's scheme changes. A picked preference is kept in localStorage under ThemeManager.preferenceStorageKey (dees-domtools:theme-preference, per browser and origin; 'system' removes the key) and is read before the theme manager's first emission, so a reload starts in it without showing the system theme first. Another tab's pick reaches every open page of the origin through the storage event. setPreference() returns false when the browser refuses the page its storage: the pick then holds for this page only, and it throws on a value that is no TThemePreference. An unknown stored value counts as no pick. goBright(), goDark() and toggleDarkBright() set the theme for now and leave the preference alone.

A toggle that shows the preference, not only the theme, subscribes to stateObservable, a ReplaySubject<IThemeState> that replays the current state and emits on every change of the preference, the system's colour scheme or the theme, also when the theme stays (a pick of the theme the system already shows, the system changing while a pick holds, another tab's pick):

themeManager.stateObservable.subscribe(({ preference, systemBright, goBright }) => {
  // e.g. offer "follow the system" while a pick holds the theme the system shows
});
themeManager.systemBright; // the system's colour scheme is light, as prefers-color-scheme last reported it

The page's DomTools is one instance on globalThis shared by every copy of this package, so it is the copy that creates it whose ThemeManager serves the page: every copy in a bundle must be a version with setPreference() for a toggle to rely on it.

enableAutomaticGlobalThemeChange() waits for domReady, so it is safe to call before document.body exists.

Keyboard Shortcuts

The keyboard helper is created after document.body exists, so wait for domReady before using it.

import { DomTools } from '@design.estate/dees-domtools';

const domtools = await DomTools.setupDomTools();
await domtools.domReady.promise;

const keyboard = domtools.keyboard!;
const { keyEnum } = keyboard;

keyboard.on([keyEnum.Ctrl, keyEnum.S]).subscribe(() => {
  console.log('save triggered');
});

keyboard.triggerKeyPress([keyEnum.Ctrl, keyEnum.S]);

Scrolling

import { DomTools } from '@design.estate/dees-domtools';

const domtools = await DomTools.setupDomTools();
const { scroller } = domtools;

scroller.onScroll(() => {
  console.log('scroll event');
});

await scroller.enableLenisScroll({
  disableOnNativeSmoothScroll: true,
});

const section = document.querySelector('#details') as HTMLElement;
await scroller.toElement(section, { duration: 600 });

The scroller uses native scroll listeners by default and switches to Lenis when enabled.

Responsive CSS Helpers

breakpoints is designed for Lit CSS and ships both preset breakpoints and lower-level helpers.

import { breakpoints } from '@design.estate/dees-domtools';
import { css } from 'lit';

const styles = css`
  :host {
    display: block;
    padding: 24px;
  }

  ${breakpoints.cssForTablet(css`
    :host {
      padding: 16px;
    }
  `)}

  ${breakpoints.cssForPhone(css`
    :host {
      padding: 10px;
    }
  `)}
`;

Available values:

  • breakpoints.desktop => 1600
  • breakpoints.notebook => 1240
  • breakpoints.tablet => 1024
  • breakpoints.phablet => 600
  • breakpoints.phone => 400

Available helpers:

  • cssForDesktop()
  • cssForNotebook()
  • cssForTablet()
  • cssForPhablet()
  • cssForPhone()
  • cssForViewport()
  • cssForContainer()
  • cssForConstraint()
  • cssForConstraintContainer()
  • containerContextStyles()

Viewport helpers emit both @media and @container wccToolsViewport rules. Container helpers target a named CSS container only.

CSS Utility

import { css } from '@design.estate/dees-domtools';

const columns = css.cssGridColumns(3, 24);

console.log(columns);

This returns a ready-to-insert grid-template-columns string.

Lit Element Setup

import { elementBasic } from '@design.estate/dees-domtools';
import { LitElement, html } from 'lit';

class DemoElement extends LitElement {
  static styles = [elementBasic.staticStyles];

  async connectedCallback() {
    super.connectedCallback();
    await elementBasic.setup(this);
  }

  render() {
    return html`<p>Hello DOM tools</p>`;
  }
}

elementBasic.staticStyles is the base stylesheet for a component, and elementBasic.styles renders the same element defaults as a <style> element inside a template. Every element of the component's shadow tree gets box-sizing: border-box, and every built-in element (HTML, SVG, MathML) fades background and color over 0.1s. The fade never reaches the host of a custom element nested in the component: that host keeps the transition its own styles declare, so a nested component can still animate its host, such as a sidebar collapsing its width. The defaults carry zero specificity, so any rule of the component overrides them.

elementBasic.styles is deprecated: an inline <style> element is blocked by a Content-Security-Policy whose style-src has no 'unsafe-inline'. Use elementBasic.staticStyles, which lit adopts as a constructed stylesheet.

elementBasic.setup() performs the shared DomTools setup and adopts the package's global sheets once: the base body rules (margin: 0, the system font stack, box-sizing: border-box), then a sheet that hides the document's scrollbars (setGlobalStyles(css, { hidesScrollbars: true })). The global sheets come after every sheet of the document, so an equal-specificity body rule for margin, font-family, box-sizing or scrollbar-width, or a ::-webkit-scrollbar rule, in a <style> or <link> placed in the body or added later, or in a sheet adopted before elementBasic.setup(), loses to them; give such a rule a higher specificity, such as html body.

The scrollbars are hidden by default. On a long document the scrollbar is the reader's only position indicator, so such a page shows them:

import { DomTools, elementBasic } from '@design.estate/dees-domtools';

const domtools = await DomTools.setupDomTools();
domtools.setScrollbarsHidden(false);
await elementBasic.setup();

The choice holds for the DomTools instance, also when it is made before elementBasic.setup(), so the scrollbars are never hidden first; setScrollbarsHidden(true) hides them again and domtools.scrollbarsHidden reads the choice. Scrollbars inside a component's shadow tree stay hidden through elementBasic.staticStyles.

The page's DomTools is one instance on globalThis shared by every copy of this package, so setScrollbarsHidden() exists only when the copy that created it is 5.3 or later, and it switches anything only when a 5.3 or later elementBasic.setup() ran first. An older copy's setup() keeps the hiding inside the base sheet, where nothing turns it off, or, on an older instance, inserts <style> elements that the policy blocks: resolve the bundle to one copy (pnpm why @design.estate/dees-domtools).

The returned promise resolves after the shared base styles have been injected, and domtools.globalStylesReady resolves at the same point.

State and One-Time Work

domToolsStatePart starts with this shape:

{
  virtualViewport: 'native',
  jwt: '',
}

You can also guard expensive async work with runOnce():

import { DomTools } from '@design.estate/dees-domtools';

const domtools = await DomTools.setupDomTools();

const result = await domtools.runOnce('load-config', async () => {
  return { ok: true };
});

Repeated callers receive the first result, and repeated failures re-throw the stored error.

Extra Exports

import { TypedRequest, ThemeManager, type IThemeState, type TThemePreference, plugins } from '@design.estate/dees-domtools';
  • ThemeManager is the class of domtools.themeManager, exported for ThemeManager.preferenceStorageKey and for typing; use the page's instance rather than constructing one, TThemePreference ('system' | 'bright' | 'dark') for a preference, and IThemeState for what stateObservable emits (see Theme preference)
  • TypedRequest is re-exported from @api.global/typedrequest 9 for typed request flows
  • plugins exposes the underlying modules used by the package, including smartrouter, smartstate, smartrx, smartpromise, and typedrequest

Runtime Notes

  • This package is browser-oriented and touches window, document, navigator, and matchMedia
  • keyboard is null until domReady resolves
  • The published package targets the latest Chrome via browserslist
  • Global styles are adopted stylesheets (document.adoptedStyleSheets), supported since Chrome 73, Firefox 101 and Safari 16.4

This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the license file.

Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.

Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.

Company Information

Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany

For any legal inquiries or further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

S
Description
tools that simplify dom interactions.
Readme
3.5 MiB
Languages
TypeScript 100%