Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/app/content/articles/core-build.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
---
title: Core build
description: Use the core engine (~10 kB) and compose only the actions you need
description: Use the core engine kB) and compose only the actions you need
category: advanced
position: 3
---

The full Attractive.js build includes all built-in actions at ~20 kB (6.6 kB gzipped). The core build strips out all actions, only the engine at ~10 kB (~3.5 kB gzipped).
The full Attractive.js build includes all built-in actions, you can also just use the core and compose actions as you need.
```js
import Attractive from "attractivejs/core";
```
Expand Down
127 changes: 127 additions & 0 deletions docs/app/content/articles/element.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
---
title: Attractive Element
description: A base class for custom elements that scopes Attractive to the component. Actions, targets and lifecycle without the boilerplate.
category: extensions
position: 5
---

`AttractiveElement` is a base class for custom elements. It scopes Attractive to the component, so `@click`, `@target`, gates and triggers work inside the component without a `connectedCallback`, `querySelector` or manual teardown.

```js
import { AttractiveElement } from "attractivejs/element";
```


## A simple example: tabs

Actions in HTML call component methods directly. The component manages its own state and resolves targets within its own subtree.

```html
<ui-tabs>
<nav>
<button @click="select" data-panel="details">Details</button>
<button @click="select" data-panel="settings">Settings</button>
</nav>

<div id="details" class="panel">…</div>
<div id="settings" class="panel" hidden>…</div>
</ui-tabs>
```

```js
class Tabs extends AttractiveElement {
connect() {
this.#show("details");
}

select(element, { dataset }) {
this.#show(dataset.panel);
}

// private

#show(name) {
this.targets(".panel").forEach((panel) => (panel.hidden = true));

this.target(name).hidden = false;
}
}

customElements.define("ui-tabs", Tabs);
```

The action name in the attribute resolves to a method on the class, called with the element and its context (so `select` receives the clicked button's `dataset`). Private methods stay out of HTML.

What the class handles for you:

| Boilerplate | Replaced by |
| ----------------------------- | ------------------------ |
| `connectedCallback` | `connect()` |
| `disconnectedCallback` | `disconnect()` |
| `new Attractive()` + `activate({ on: this })` | automatic |
| `deactivate()` | automatic |
| `this.querySelector("#menu")` | `this.target("menu")` |
| `document.querySelector(…)` | `this.element(…)` |


## Lifecycle

`connect()` runs once the component's scope is active; `disconnect()` runs before it is torn down.

```js
class Counter extends AttractiveElement {
connect() {
this.count = 0;
}

increment() {
this.target("count").textContent = ++this.count;
}
}
```


## Scoped targets

`this.target(id)` and `this.targets(selector)` query within the component. `target()` takes a bare id, the same convention as `@target`.

```html
<ui-counter>
<button @click="increment">+</button>

<output id="count">0</output>
</ui-counter>
```

Each component resolves its own `#count`, even when the same id appears on the page twice.


## Any element on the page

`this.element(selector)` and `this.elements(selector)` reach the rest of the document. This is useful for calling methods on other components.

```js
class Form extends AttractiveElement {
submit() {
this.element("ui-button").activate();
}
}
```


## Reactive targets

A method named `{id}TargetConnected()` runs when an element with that id enters the component, and `{id}TargetDisconnected()` when it leaves. This catches targets added after the component connects.

```js
class Panel extends AttractiveElement {
detailsTargetConnected(element) {
element.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 200 });
}
}
```


## Alongside a document-wide activation

Components work when a global `Attractive.activate()` is also running. The component manages its own subtree and the page-wide activation leaves it alone, so actions never fire twice.
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@
"./core": {
"import": "./dist/attractive.core.js"
},
"./element": {
"import": "./dist/element.js"
},
"./actions": {
"import": "./dist/actions/index.js"
},
Expand Down
83 changes: 83 additions & 0 deletions playground/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,36 @@
/>
<script type="module">
import Attractive from "../dist/attractive.min.js";
import { AttractiveElement } from "../dist/element.min.js";

class Tabs extends AttractiveElement {
connect() {
this.#show("details");
}

select(element, { dataset }) {
this.#show(dataset.panel);
}

#show(name) {
this.targets(".panel").forEach((panel) => (panel.hidden = true));
this.target(name).hidden = false;
}
}

customElements.define("ui-tabs", Tabs);

class Counter extends AttractiveElement {
connect() {
this.count = 0;
}

increment() {
this.target("count").textContent = ++this.count;
}
}

customElements.define("ui-counter", Counter);

Attractive.activate({ debug: true });
</script>
Expand All @@ -21,6 +51,34 @@ <h2>Copy</h2>
<button @action="copy" @target="source">Copy</button>
<input id="source" value="copied text" readonly />

<h2>Tabs</h2>
<p>
A <code>&lt;ui-tabs&gt;</code> component: HTML actions call the class
methods, <code>target()</code>/<code>targets()</code> stay scoped.
</p>

<ui-tabs>
<nav>
<button @click="select" data-panel="details">Details</button>
<button @click="select" data-panel="settings">Settings</button>
</nav>

<div id="details" class="panel">Details content</div>
<div id="settings" class="panel" hidden>Settings content</div>
</ui-tabs>

<h2>Counter</h2>
<p>
A <code>&lt;ui-counter&gt;</code> component: state in
<code>connect()</code>, HTML actions call methods, and
<code>target("count")</code> stays scoped.
</p>

<ui-counter>
<button @click="increment">+</button>
<output id="count">0</output>
</ui-counter>

<style>
.active {
color: red;
Expand All @@ -30,6 +88,31 @@ <h2>Copy</h2>
[data-copy-success="true"] {
border-color: aqua;
}

ui-tabs nav {
display: flex;
gap: 0.25rem;
border-bottom: 1px solid #ccc;
margin-bottom: 0.75rem;

button {
margin-block-end: -1px;
padding: 0.4rem 0.75rem;
background: none;
border: 0;
border-bottom: 2px solid transparent;
cursor: pointer;

&:hover {
background: #eef;
}
}
}

ui-counter output {
margin-inline-start: 0.75rem;
font-weight: 600;
}
</style>
</body>
</html>
17 changes: 17 additions & 0 deletions rolldown.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,5 +172,22 @@ export default [
}
}),

defineConfig({
input: "src/element.js",
output: {
file: "dist/element.js",
format: "es"
}
}),

defineConfig({
input: "src/element.js",
output: {
file: "dist/element.min.js",
format: "es",
minify: true
}
}),

...actionConfigs
];
7 changes: 5 additions & 2 deletions src/actions/base.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Debug from "./../debug";
import { scopeOf } from "../core/scopes";

export default class ActionBase {
static actionFor(method) {
Expand All @@ -19,12 +20,14 @@ export default class ActionBase {
}

get targets() {
const scope = scopeOf(this.element);

if (this.targetsSelector) {
return Array.from(document.querySelectorAll(this.targetsSelector));
return Array.from(scope.querySelectorAll(this.targetsSelector));
}

if (this.target) {
const target = document.getElementById(this.target);
const target = scope.querySelector(`[id="${this.target}"]`);

if (!target) {
Debug.warn(`Target "#${this.target}" not found`);
Expand Down
13 changes: 13 additions & 0 deletions src/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,19 @@ class Attractive {
return this;
}

onTargetConnected(id, callback) {
this.#elementLifecycle.onTargetAdded(id, callback);
this.#activation.notifyExistingTargets(id);

return this;
}

onTargetDisconnected(id, callback) {
this.#elementLifecycle.onTargetRemoved(id, callback);

return this;
}

addEventListener(type, callback) {
this.#subscriptions.add(type, callback);

Expand Down
13 changes: 10 additions & 3 deletions src/core/actions.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import debounce from "./helpers/debounce";
import { actionAttributes, getActionAttributes } from "./attributes";
import { insideNestedScope } from "./scopes";

const debounceTimers = new WeakMap();

Expand Down Expand Up @@ -53,6 +54,8 @@ class Actions {

if (!this.#scope.contains(element)) return;

if (insideNestedScope(element, this.#scope)) return;

this.#debounced(
() => this.#execute({ event, with: context, on: element }),

Expand All @@ -79,13 +82,15 @@ class Actions {
}

if (Actions.#nonBubblingEvents.has(eventType)) {
element.addEventListener(eventType, (event) =>
element.addEventListener(eventType, (event) => {
if (insideNestedScope(element, this.#scope)) return;

this.#events.process(event, {
on: element,
using: this.#defaultEventType({ for: element }),
with: value
})
);
});
});
}
}
}
Expand Down Expand Up @@ -181,6 +186,8 @@ class Actions {
#execute({ event, with: context, on: element }) {
if (!this.#scope.contains(element)) return;

if (insideNestedScope(element, this.#scope)) return;

const defaultEventType = context
? context.eventType
: this.#defaultEventType({ for: element });
Expand Down
Loading
Loading