Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(mount): pass attributes directly to component #48

Closed
wants to merge 16 commits into from
Closed
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
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ on:
pull_request:
branches:
- main
- next

jobs:
build:
Expand Down
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,24 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- Add ability to pass attributes to a component on mount

## [0.0.33-1] - 2024-06-02

### Fixed

- `Component<S>` now requires `state` if `S` is defined ([#43](https://github.com/tentjs/tent/issues/43))

## [0.0.33-0] - 2024-05-27

### Added

- Add `mounted` to `tags` to run code after the tag has been mounted

## [0.0.32] - 2024-05-20

### Fixed
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@tentjs/tent",
"version": "0.0.32",
"version": "0.0.33-1",
"description": "A jsx-free, super-lightweight and zero-dependency library to add interactivity to the web - without all the nonsense.",
"source": "src/main.ts",
"main": "dist/main.js",
Expand Down
23 changes: 22 additions & 1 deletion src/__tests__/attributes.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { addAttribute } from '../attributes';
import { addAttribute, addAttributes } from '../attributes';
import { tags } from '../tags';

describe('attributes.ts', () => {
test('adds a simple attribute', () => {
Expand Down Expand Up @@ -34,4 +35,24 @@ describe('attributes.ts', () => {

expect(el.value).toBe('test');
});

test("doesn't add `mounted` as an attribute", () => {
const el = document.createElement('div');

addAttribute(el, 'mounted', 'test');

expect(el.hasAttribute('mounted')).toBe(false);
});

test('addAttributes adds all attributes', () => {
const el = tags.div([]);

addAttributes(el, {
id: 'test',
foo: 'bar',
});

expect(el.getAttribute('id')).toBe('test');
expect(el.getAttribute('foo')).toBe('bar');
});
});
29 changes: 29 additions & 0 deletions src/__tests__/component.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import { getByText, getByTestId, fireEvent } from '@testing-library/dom';

const { div, p, button } = tags;

beforeEach(() => {
document.body.innerHTML = '';
});

const Counter: Component<{ count: number }> = {
state: { count: 0 },
view: ({ state }) =>
Expand Down Expand Up @@ -47,4 +51,29 @@ describe('components', () => {

expect(mounted).toHaveBeenCalledTimes(1);
});

test('with state', () => {
const WithState: Component<{ count: number }> = {
state: { count: 0 },
view: ({ state }) => div(p(`Count: ${state.count}`)),
};

mount(document.body, WithState);

const el = getByText(document.body, /Count: 0/);

expect(el).toBeDefined();
});

test('without state', () => {
const WithoutState: Component = {
view: () => div(p(`No state`)),
};

mount(document.body, WithoutState);

const el = getByText(document.body, /No state/);

expect(el).toBeDefined();
});
});
68 changes: 67 additions & 1 deletion src/__tests__/main.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { Component, mount, tags } from '../main';
import { fireEvent, getByRole, getByTestId } from '@testing-library/dom';
import { mount, tags, type Component } from '../main';

beforeEach(() => {
document.body.innerHTML = '';
});

describe('main', () => {
test('`null` element', () => {
Expand Down Expand Up @@ -34,4 +39,65 @@ describe('main', () => {
}),
).not.toThrow();
});

test('that attributes are set when using `mount` with attrs set', () => {
const target = document.createElement('div');
target.setAttribute('data-testid', 'test');
document.body.append(target);

const TestComponent: Component = {
view: () => tags.div('Hey, this is me!'),
};

mount(target, TestComponent, {
id: 'foo',
foo: 'bar',
});

const el = getByTestId(document.body, 'test');

expect(el.getAttribute('id')).toBe('foo');
expect(el.getAttribute('foo')).toBe('bar');
});

test('that attributes are set when using `mount` and dynamic mounting', () => {
const target = document.createElement('div');
target.setAttribute('data-testid', 'test');
document.body.append(target);

const modalTarget = document.createElement('div');
modalTarget.setAttribute('data-testid', 'modal');
document.body.append(modalTarget);

const Parent: Component = {
view: () =>
tags.button('Click me', {
onclick() {
mount(modalTarget, Modal, { modalId: 'foo' });
},
}),
};

const Modal: Component = {
view: () => tags.p('I am a modal'),
};

mount(target, Parent, {
id: 'foo',
foo: 'bar',
});

const el = getByTestId(document.body, 'test');

expect(el.getAttribute('id')).toBe('foo');
expect(el.getAttribute('foo')).toBe('bar');

const btn = getByRole(document.body, 'button');

fireEvent.click(btn);

const modal = getByTestId(document.body, 'modal');

expect(modal.getAttribute('modalId')).toBe('foo');
});
});
8 changes: 8 additions & 0 deletions src/__tests__/tags.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,12 @@ describe('tags.ts', () => {
expect(el.$tent.attributes['data-bar']).toBe('baz');
expect(el.$tent.attributes['onclick']).toBe(fn);
});

test('mounted', () => {
const fn = jest.fn();
const el = createTag(['div', 'test', { mounted: fn }]);

expect(fn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenCalledWith({ el });
});
});
45 changes: 17 additions & 28 deletions src/attributes.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,24 @@
import { type TentNode, type Attrs } from './types';
import { type TentNode, type Attrs, type TagAttrsValues } from './types';

function addAttributes<A extends Attrs>(el: TentNode<A>, attributes: A) {
for (const key in attributes) {
const value = attributes[key as string];

addAttribute(el, key, value);
}
}

function addAttribute<A extends Attrs>(
el: TentNode<A> | HTMLElement,
key: string,
value: string | boolean | number,
value: TagAttrsValues,
) {
if (key === 'mounted') return;

if ('$tent' in el) {
el.$tent.attributes[key] = value;
}

if (typeof value === 'boolean') {
if (value) {
el.setAttribute(key, '');
Expand All @@ -24,29 +38,4 @@ function addAttribute<A extends Attrs>(
}
}

/**
* @deprecated
* Use `el.dataset` instead, will be removed in the next major version.
*/
function getAttribute<A>(el: HTMLElement | Element) {
return <K extends keyof A>(name: K): A[K] | undefined => {
const attr = el.attributes.getNamedItem(name as string);

if (!attr) {
return;
}

const value = attr.value;

if (value === '') {
// TODO: This might not be the desired behavior.
// I should find a better way to handle this,
// what I want to avoid is returning `T | undefined | 'true'`
return 'true' as A[K];
}

return value as A[K];
};
}

export { addAttribute, getAttribute };
export { addAttributes, addAttribute };
39 changes: 15 additions & 24 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,22 @@
import { getAttribute } from './attributes';
import {
type Children,
type Context,
type Component,
type TentNode,
type Attrs,
} from './types';
import type { Children, Context, Component, TentNode, Attrs } from './types';
import { createTag, tags } from './tags';
import { walker } from './walker';
import { addAttributes } from './attributes';

function mount<S extends {} = {}, A extends Attrs = {}>(
element: HTMLElement | Element | TentNode<A> | null,
component: Component<S, A>,
attributes?: A,
) {
if (element == null) {
return;
}
if (element == null) return;

let node: TentNode<A>;
const { state = {} as S, view, mounted } = component;
const { view, mounted } = component;
const state = 'state' in component ? component.state : ({} as S);
const el = element as TentNode<A>;

el.$tent = {
attributes: {},
};
el.$tent = { attributes: {} };
addAttributes(el, attributes);

const handler = {
get(obj: S, key: string) {
Expand All @@ -43,30 +36,28 @@ function mount<S extends {} = {}, A extends Attrs = {}>(

const s = Reflect.set(obj, prop, value);

walker(node, view({ state: proxy, el, attr: getAttribute<A>(el) }));
walker(node, view({ state: proxy, el }));

return s;
},
};

const proxy = new Proxy<S>({ ...state }, handler);

node = view({ state: proxy, el, attr: getAttribute<A>(el) });
node.$tent = {
attributes: {},
};
node = view({ state: proxy, el });
node.$tent = { attributes: {} };

el.append(node);

mounted?.({ state: proxy, el, attr: getAttribute<A>(el) });
mounted?.({ state: proxy, el });
}

export {
mount,
tags,
mount,
createTag,
type Component,
type Children,
type Context,
type TentNode,
type Children,
type Component,
};
Loading