2.2.0-rc-5 • Published 2 years ago

@lsegurado/ls-element v2.2.0-rc-5

Weekly downloads
20
License
MIT
Repository
github
Last release
2 years ago

A Vainilla Library for Web Components

Open in Visual Studio Code npm license npm npm

Why "LS-Element?"

LS-ElementReactStencilJSSvelteJSVanillaJS
Prefer real DOM over virtual DOM
Prefer Javascript templates over compiled plain text
Templates with JSX
Element internals support
Does not require extensions to be identified by the IDE
Differentiation between attributes and properties in jsx / templates
Standard Web Components
Observables / stores support
Esbuild as default bundler
TypeScript support
Reactive
Styling / Constructable Stylesheets support
Automatic component type generation
Without polyfills
Attributes / Native events support
Supports Shadow DOM
Supports Custom Built-in elements
Can be used with different frameworks right out of the box

| ✅ = implemented ⭕ = partially implemented ❌ = not implemented

Getting Started

You can use this template or you can see on Code Sandbox.

Creating components

LS-Element custom elements are plain objects.

New components can be created using the jsx/tsx extension, such as MyCounter.tsx.

import { AdoptedStyle, createCustomElement, EventDispatcher, h } from "@lsegurado/ls-element";
import { counterStyle } from "./counterStyle";

export const MyCounter = createCustomElement('my-counter', {
  reflectedAttributes: {
    count: 0
  },
  methods: {
    decrementCount() { this.count-- },
    incrementCount() { this.count++ },
  },
  events: {
    countChanged: new EventDispatcher<number>()
  },
  observe: {
    count() {
      this.countChanged(this.count)
    }
  },
  render() {
    return (
      <>
        <AdoptedStyle id="style">{counterStyle}</AdoptedStyle>
        <button onpointerup={this.decrementCount}>-</button>
        <span>{this.count}</span>
        <button onpointerup={this.incrementCount}>+</button>
      </>
    )
  }
})

Note: the .tsx extension is required, as this is the standard for TypeScript classes that use JSX.

To use this component, just use it like any other HTML element:

import '../Counter';

<my-counter oncountchanged={(ev) => console.log(`New count value: ${ev.detail}`)} />

Or if you are using jsx

import Counter from '../Counter';

<Counter oncountchanged={(ev) => console.log(`New count value: ${ev.detail}`)} />

Component structure

A component consists of the following properties:

Also, you have to create an Autonomous custom element with a tag or in case you want to create an Customized built-in element you have to declare the tag, the class you want to extend and the tag to extend.

LSStore structure

A store consists of the following properties:

LSStores use proxies to listen for changes in their state, in addition, they are observable. Each component has an LSStore to listen for changes in its state.

CSS

To use css we provide functions to create Constructable Stylesheets.

createStyleSheet

Allows to create a Constructable Stylesheet with a CSSObject

export const counterStyle = createStyleSheet({
  ':host': {
    display: 'flex',
    flexDirection: 'row'
  },
  span: {
    minWidth: '60px',
    textAlign: 'center'
  }
});

css

Allows to create a Constructable Stylesheet with a Template String. Recomended extension for VSCode.

export const counterStyle = css`
  :host {
      display: flex;
      flex-direction: row;
  }

  span {
      min-width: 60px;
      text-align: center;
  }
`

CSS module scripts

We do not provide support for this functionality yet as ESBuild does not support it yet. You can read how it works here

Components

Constructable Stylesheets

If you are not familiar with Constructable Stylesheets please check this link. To use Constructable Stylesheets simply import AdoptedStyle and use it like an style tag (see example). In case your browser doesn't support this feature, it will return a style tag. Remember that you need to use Shadow DOM to be able to use Constructable Stylesheets.

Host

Allows to set attributes and event listeners to the host element itself.

List

Creates a container component without styles with the tag "ls-list"

Fragment

Creates a container component without styles with the tag "ls-fragment"

ElementInternals

(Only available if formAssociated is true)

It allows to:

  • Make the element accessible to the browser
  • Access element internals
  • Validate and assign values to forms

AsyncComponent

Create a component whose content will load after the promise ends. In the meantime you can choose to show a load component or not show anything.

Link

Provides the ability to move around the web page without reloading the page. It uses the same attributes as an anchor tag but also allows the use of URL objects. Uses the goTo method.

Custom element methods

child

Allows to get a child element from the host with the selector

rerender

Forces the element to re-render

idGen

Create unique IDs with a discernible key

Attributes vs Properties in jsx

Usually, if you want to get an html like this:

<div class='test'></div>

In React / Stencil / etc you should write a jsx like this:

() => <div className='test'></div>

And eventually code like this would be executed:

const el = document.createElement('div');
el.className = 'test';

In LS-Element you have the freedom to use both attributes and properties and the result will be the same:

// Using properties
() => <div _className='test'></div>
// Using attributes
() => <div class='test'></div>

And eventually code like this would be executed:

const el = document.createElement('div');
// Using properties
el.className = 'test';
// Using attributes
el.setAttribute('class', 'test')

In this way the jsx syntax of LS-Element is more similar to html.

Special attributes

$staticChildren

Indicates that their children are created but not updated

$doNotTouchChildren

Indicates that their Children are not created or updated. Element creation/update is delegated

$oncreated

Callback that is called when the element is created

$onupdate

Callback that is called when the element is updated

Lists

There are 3 ways to create a list

Using map

It's the usual way to create lists in jsx.

const arrayTest = [0, 1, 2];

arrayTest.map(item => <div key={item}>{item}</div>)

This will generate an element like:

<ls-list>
  <div>0</div>
  <div>1</div>
  <div>2</div>
</ls-list>

Why create the ls-list element? This is the way to avoid using Virtual DOM. Because the algorithm is dumb, it needs a way to remember that element is a list.

Using List component

It's similar to using maps. But it allows to use different container than ls-list.

const arrayTest = [0, 1, 2];

<List 
  as="span"
  data={arrayTest}
  renderItem={item => <div key={item}>{item}</div>}
/>

This will generate an element like:

<span>
  <div>0</div>
  <div>1</div>
  <div>2</div>
</span>

Using ElementList

Is a proxy that allows you to avoid using dom diff algorithms to render lists. This allows it to have a performance close to vanilla js. An operation on the data implies an operation on the associated elements.

const arrayTest = new ElementList(0, 1, 2);

<arrayTest.List 
  as="span"
  renderItem={item => <div>{item}</div>}
/>

This will generate an element like:

<span>
  <div>0</div>
  <div>1</div>
  <div>2</div>
</span>

Comparison

Routing

The intention of using a custom routing tool is to avoid the use of strings to represent the urls and to use modern apis that allow the use of the URL object itself. It also allows to separate the components of the routes which allows a cleaner code.

Note: This is still a work in progress and may change in the future.

const Redirect = () => {
  goTo(urls.syncRoute())
  // Will generate and go to this url: /sync-route
  return <></>
}

//Parent routes
export const { urls, Router, components } = registerRoutes({
  syncRoute: createRoute({
    /**The component to display */
    component: <div>Hello World</div>,
    title: 'Sync title'
  }),
  //Redirect route
  '/': createRoute({
    component: <Redirect />
  }),
});

//Child routes
export const { urls: urlsChild, Router: RouterChild } = registerRoutes({
  // Async route
  asyncChildRoute: createAsyncRoute<{ searchParam1: string, searchParam2: number }, '#hash1' | '#hash2'>()({
    /** The promise to wait */
    promise: () => import('./AsyncChildExample'),
    /** The component key (by default is default)*/
    key: 'AsyncChildExample',
    /**The title of the page */
    title: 'Async Page title'
    /**The component to display while the promise is loading */
    loadingComponent: <span>Loading...</span>
  }),
  //The parent route
}, urls.syncRoute);

urlsChild.childRoute({ searchParams: { searchParam1: 'param 1', searchParam2: 2}, hash: '#hash1' })
// Will generate this url: /sync-route/async-child-route?searchParam1=param+1&searchParam2=2#hash1

Router and RouterChild are components that represent the mount points of each registered route.

The "components" function is a utility to create asynchronous components that includes the search params and component hashes with the types that were defined when the route was registered

export const AsyncChildExample = components.childRoute(({ searchParams, hash }) => {
  return (
    <>
      {/* Will show the value of searchParam1 */}
      <div>{searchParams.searchParam1}</div>
      {/* Will show true if the hash is #hash1 */}
      <div>{hash['#hash1']}</div>
    </>
  );
});

Limitations

Observable objects

Because some objects are not proxy compatible we limit the observable objects to:

  • Arrays
  • Dates
  • Maps
  • Sets
  • Any object whose prototype is Object

Polyfills

If you REALLY need polyfills i recommend you to read this topics:

Browser Support

Customized built-in elements

Autonomous custom elements

Compatibility with frameworks

Element internals

Supporting LS Element

Sponsors

Support us with a donation and help us continue our activities here.

Contributors

License

2.2.0-rc

2 years ago

2.2.0-rc-1

2 years ago

2.2.0-rc-2

2 years ago

2.2.0-rc-5

2 years ago

2.2.0-rc-3

2 years ago

2.2.0-rc-4

2 years ago

2.1.14

2 years ago

2.1.12

2 years ago

2.1.13

2 years ago

2.1.10

2 years ago

2.1.11

2 years ago

2.1.9

2 years ago

2.1.0-rc2

2 years ago

2.1.0-rc1

2 years ago

2.1.0-rc3

2 years ago

2.1.2

2 years ago

2.1.1

2 years ago

2.1.4

2 years ago

2.1.3

2 years ago

2.1.6

2 years ago

2.1.5

2 years ago

2.1.8

2 years ago

2.1.7

2 years ago

2.1.0

2 years ago

2.0.3

3 years ago

2.0.2

3 years ago

2.0.5

3 years ago

2.0.4

3 years ago

2.0.7

3 years ago

2.0.6

3 years ago

2.0.9

3 years ago

2.0.8

3 years ago

2.0.1

3 years ago

2.0.0

3 years ago

1.2.6

3 years ago

1.2.5

3 years ago

1.2.4

3 years ago

1.2.0

3 years ago

1.2.3

3 years ago

1.2.2

3 years ago

1.2.1

3 years ago

1.1.7

4 years ago

1.1.6

4 years ago

1.1.5

4 years ago

1.1.4

4 years ago

1.1.3

4 years ago

1.1.2

4 years ago

1.1.1

4 years ago

1.1.0

4 years ago

1.0.19

4 years ago

1.0.20

4 years ago

1.0.18

4 years ago

1.0.17

4 years ago

1.0.16

4 years ago

1.0.15

4 years ago

1.0.14

4 years ago

1.0.13

4 years ago

1.0.12

4 years ago

1.0.11

4 years ago

1.0.10

4 years ago

1.0.9

4 years ago

1.0.8

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago