Module: twind/observe

DocumentationGithubModule SizeTypescript

Allows to copy-paste tailwind examples. This feature can be used together with your favorite framework without any additional setup.

The twind/observe modules allows to use the class attribute for tailwind rules. If such a rule is detected the corresponding CSS rule is created and injected into the stylesheet. No need for tw but it can be used on the same elements as well.

This is meant for advanced use cases. Most of the time you may want to use twind/shim.

Usage

import { observe } from 'twind/observe'

observe(document.body)

document.body.innerHTML = `
  <main class="h-screen bg-purple-400 flex items-center justify-center">
    <h1 class="font-bold text(center 5xl white sm:gray-800 md:pink-700)">
      This is Twind!
    </h1>
  </main>
`

🚀 live and interactive shim demo

All Twind syntax features like grouping are supported within class attributes

If you want to simplify the instantiation and automatically observe take look at twind/shim.

Customization

twind/observe uses the default/global tw instance if not configured otherwise. You can provide a custom instance in several ways:

import { create } from 'twind'
import { observe, createObserver } from 'twind/observe'

// Create a custom instance
const instance = create(/* ... */)

// 1. As second parameter
observe(document.body, instance)

// 2. As this context
observe.call(instance, document.body)
observe.bind(instance)(document.body)

// 3. Use the factory
createObserver(instance).observe(document.body)

API

import { createObserver, observe } from 'twind/observe'

const observer = createObserver(/* custom instance */)

// Or to start observing an element right away
// const observer = observe(node, /* custom instance */)

// Start observing a node; can be called several times with different nodes
observer.observe(node)

// Stop observing all nodes
observer.disconnect()

Example

This example shows how a custom observer instance can be used to shim a web component.

❗ This example is using Constructable Stylesheet Objects and DocumentOrShadowRoot.adoptedStyleSheets which have limited browser support at the moment (December 2020).

import { LitElement, html } from 'lit-element'
import { create, cssomSheet } from 'twind'
import { createObserver } from 'twind/observe'

// 1. Create separate CSSStyleSheet
const sheet = cssomSheet({ target: new CSSStyleSheet() })

// 2. Use that to create an own twind instance
const instance = create({ sheet })

class TwindElement extends LitElement {
  // 3. Apply the same style to each instance of this component
  static styles = [sheet.target]

  // 4. Start observing class attributes changes
  connectedCallback() {
    super.connectedCallback()
    this._observer = createObserver(instance).observe(this.renderRoot)
  }

  // 5. Stop observing class attributes changes
  disconnectedCallback() {
    super.disconnectedCallback()
    this._observer.disconnect()
  }

  render() {
    // 5. Use tailwind rules in class attributes
    return html`
      <main class="h-screen bg-purple-400 flex items-center justify-center">
        <h1 class="font-bold text(center 5xl white sm:gray-800 md:pink-700)">This is Twind!</h1>
      </main>
    `
  }
}

customElements.define('twind-element', TwindElement)

document.body.innerHTML = '<twind-element></twind-element>'

🚀 live and interactive demo

Implementation Details

This uses a MutationObserver to detect changed class attributes or added DOM nodes. On detection the class attribute is parsed and translated by twind to inject the required classes into the stylesheet and the class attribute is updated to reflect the added CSS class names that may have been hashed.

Table of contents

Interfaces

References

Apply

Re-exports: Apply


BlendMode

Re-exports: BlendMode


BorderStyle

Re-exports: BorderStyle


CSSAtKeyframes

Re-exports: CSSAtKeyframes


CSSAtMedia

Re-exports: CSSAtMedia


CSSAtSupports

Re-exports: CSSAtSupports


CSSCustomProperties

Re-exports: CSSCustomProperties


CSSProperties

Re-exports: CSSProperties


CSSPseudos

Re-exports: CSSPseudos


CSSRuleValue

Re-exports: CSSRuleValue


CSSRules

Re-exports: CSSRules


CSSRulesThunk

Re-exports: CSSRulesThunk


CSSSimplePseudos

Re-exports: CSSSimplePseudos


CompletionTokens

Re-exports: CompletionTokens


Configuration

Re-exports: Configuration


Context

Re-exports: Context


CoreCompletionTokens

Re-exports: CoreCompletionTokens


CorePlugins

Re-exports: CorePlugins


CoreVariants

Re-exports: CoreVariants


Corners

Re-exports: Corners


CounterStyle

Re-exports: CounterStyle


DarkMode

Re-exports: DarkMode


Directive

Re-exports: Directive


DirectiveHandler

Re-exports: DirectiveHandler


Edges

Re-exports: Edges


Empty

Re-exports: Empty


Falsy

Re-exports: Falsy


FontFace

Re-exports: FontFace


FromTheme

Re-exports: FromTheme


GlobalValue

Re-exports: GlobalValue


Hasher

Re-exports: Hasher


InlineDirective

Re-exports: InlineDirective


Instance

Re-exports: Instance


Interpolate

Re-exports: Interpolate


InterpolateKind

Re-exports: InterpolateKind


Join

Re-exports: Join


JoinFromObject

Re-exports: JoinFromObject


MaybeArray

Re-exports: MaybeArray


MaybeObjInterpolationGeneric

Re-exports: MaybeObjInterpolationGeneric


MaybeThunk

Re-exports: MaybeThunk


MaybeTokenInterpolation

Re-exports: MaybeTokenInterpolation


Mode

Re-exports: Mode


Negatable

Re-exports: Negatable


NonEmptyString

Re-exports: NonEmptyString


Plugin

Re-exports: Plugin


Plugins

Re-exports: Plugins


Prefixer

Re-exports: Prefixer


Preflight

Re-exports: Preflight


Range

Re-exports: Range


ReportInfo

Re-exports: ReportInfo


Rule

Re-exports: Rule


Sheet

Re-exports: Sheet


SheetConfig

Re-exports: SheetConfig


SheetInit

Re-exports: SheetInit


SheetInitCallback

Re-exports: SheetInitCallback


SimplePseudoClasses

Re-exports: SimplePseudoClasses


SimplePseudoElements

Re-exports: SimplePseudoElements


TW

Re-exports: TW


TWCallable

Re-exports: TWCallable


Theme

Re-exports: Theme


ThemeColor

Re-exports: ThemeColor


ThemeColorObject

Re-exports: ThemeColorObject


ThemeConfiguration

Re-exports: ThemeConfiguration


ThemeContainer

Re-exports: ThemeContainer


ThemeFontSize

Re-exports: ThemeFontSize


ThemeHelper

Re-exports: ThemeHelper


ThemeOutline

Re-exports: ThemeOutline


ThemeResolver

Re-exports: ThemeResolver


ThemeScreen

Re-exports: ThemeScreen


ThemeScreenValue

Re-exports: ThemeScreenValue


ThemeSection

Re-exports: ThemeSection


ThemeSectionRecord

Re-exports: ThemeSectionRecord


ThemeSectionResolver

Re-exports: ThemeSectionResolver


ThemeSectionResolverContext

Re-exports: ThemeSectionResolverContext


ThemeSectionType

Re-exports: ThemeSectionType


ToString

Re-exports: ToString


Token

Re-exports: Token


TokenGrouping

Re-exports: TokenGrouping


TypescriptCompat

Re-exports: TypescriptCompat


Unwrap

Re-exports: Unwrap


UserCompletionTokens

Re-exports: UserCompletionTokens


Variants

Re-exports: Variants


apply

Re-exports: apply


autoprefix

Re-exports: autoprefix


create

Re-exports: create


cssomSheet

Re-exports: cssomSheet


directive

Re-exports: directive


expandGroups

Re-exports: expandGroups


hash

Re-exports: hash


mode

Re-exports: mode


noprefix

Re-exports: noprefix


setup

Re-exports: setup


silent

Re-exports: silent


strict

Re-exports: strict


theme

Re-exports: theme


tw

Re-exports: tw


voidSheet

Re-exports: voidSheet


warn

Re-exports: warn

Functions

createObserver

ConstcreateObserver(options?: ShimConfiguration): TwindObserver

Creates a new TwindObserver.

Parameters:

NameTypeDefault valueDescription
optionsShimConfiguration{}to use

Returns: TwindObserver

Defined in: src/observe/index.ts:57


observe

observe(target: Node, config: ShimConfiguration | undefined | void): TwindObserver

Creates a new TwindObserver and start observing the passed target element.

Parameters:

NameTypeDescription
targetNodeto shim
configShimConfiguration | undefined | voidto use

Returns: TwindObserver

Defined in: src/observe/index.ts:147