Releases: atomicojs/atomico
Fix ssr
The dispatchEvent function is added as a test utility
The dispatchEvent function is intended to facilitate component testing, allowing you to dispatch events from an event and customize its target, example:
import { fixture, asyncEventListener, dispatchEvent } from "atomico/test-dom";
test("check target", async () => {
const myComponent = fixture(<MyComponent />);
const eventName = "myEvent";
queueMicrotask(() => {
const target = { value: 1000 };
const event = new Event(eventName);
dispatchEvent(myComponent, event, target);
});
const event = await asyncEventListener(myComponent, eventName);
expect(event.target).toEqual({ value: 1000 });
});
🚀 New version of [email protected] with improvements in the development experience 💻 🎉
new features at [email protected]
List of new features
- Custom Type Support
- Adding the use of the new operator to create an instance of an uncovered attribute.
- Eliminating the atomico/core module at the types level.
- Add support for AbortController to the useAsync, useSuspense, and usePromise hooks.
- Default value assignment whenever values equal to
null | undefined
Custom Type Support
With Atomico, you can now create your own types, enabling you to, for example:
- Receive multiple input types and reduce them to a single value. Example:
const TypeImport = createType((value: string | Promise<any>) =>
typeof value === 'string' ? import(value) : value
);
The above TypeImport type will always give you a value derived from dynamic imports.
- Serialize non-serializable values for Atomico
interface User {
id: number;
nickname: string;
role: 'admin' | 'client';
}
const TypeUser = createType(
(value: User | string): User =>
typeof value === 'string' ? JSON.parse(value) : value,
(value) => value.role
);
The TypeUser type above allows receiving inputs as either an object or a string and always returns a User object. When reflected as an attribute, it will reflect the role property of the user object.
Adding the use of the new operator to create an instance of an uncovered attribute.
When Atomico receives an attribute, it parses its value according to the type. However, this analysis only covers types like String, Boolean, Number, Object, and Array. Now, Atomico allows transforming a string value into the associated type using the 'new' operator. Example:
component.props = {
startDate: Date,
};
The above declaration used to result in an error since a string is not of type Date. Now, Atomico internally instantiates the Date type, using the input value as an argument.
New way of working with value.
Previously, the 'value' defined only the initial value of the component's prop, but now it sets the default value. Example:
function myComponent({ theme }: Props<typeof myComponent>) {
return <host shadowDom>{theme}</host>;
}
myComponent.props = {
theme: {
type: String,
value: (): 'primary' | 'secondary' => 'primary',
},
};
const MyComponent = c(myComponent);
Now, if we set <MyComponent theme={null}/>
, it will be changed to primary
.
This also implies that when inferring props, they come as both existing and optional at the function level. Example:
Before
function myComponent(props: Props<typeof myComponent>) {
const double = props?.value ? props?.value * 2 : 0;
return <host>{double}</host>;
}
myComponent.props = {
value: { type: Number, value: 0 },
};
Now at [email protected]
function myComponent(props: Props<typeof myComponent>) {
const double = props.value * 2;
return <host>{double}</host>;
}
myComponent.props = {
value: { type: Number, value: 0 },
};
AbortController Support for useAsync, useSuspense, and usePromise hooks.
Atomico now introduces a new hook called useAbortController, which allows aborting the execution of asynchronous calls, example:
import { useAsync, useAbortController } from 'atomico';
async function getUser(id: number, signal: AbortSignal) {
return fetch(`/id/${id}`, { signal });
}
function myComponent({ userId }: Props<typeof myComponent>) {
const { signal } = useAbortController([userId]);
const user = useAsync(getUser, [userId, signal]);
return <host>{user.name}</host>;
}
myComponent.props = { userId: { type: Number, value: 0 } };
The significant advantage of using useAbortController is the automatic cancellation of asynchronous processes that depend on it when modifying the arguments provided to useAbortController (similar to useEffect).
Eliminating the atomico/core module at the types level.
At times, when using auto-import, VS Code might infer atomico/core
as a valid path. This has been removed to enhance code editor auto-completion.
Internal Changes
Preventing loss of options by avoiding module references and using a symbol-based global.
Type improvements and type fixes
Type improvements
AtomicoElement
Allows you to identify constructors created with Atomico at the typescript level, example:
type IsAtomicoElement = typeof MyElement extends AtomicoElement ? 1 : 0;
Props
Now the props type can be used with the satifields operator, example:
const props = {
range: Number,
next: {
type: String,
event: {
type: "demo",
},
},
} satisfies Props;
Fixed
- Using the Component type fixes the generation of the types for the strict props object.
- Fixed types returned by useRef when using an Atomico constructor.
fix dispatchEvent when using ssr
Sometimes when generating an update from SSR the event system of the props is dispatched, this version omits the dispatch of events in SSR
Fix jsx-runtime and export createElement
1.71.0 Fix jsx-runtime and export createElement
Dynamic name for the classes that returns c is added
This change is intended to give consistency between the name of the function and the name of the class returned by the c
function, example:
function myComponent(){}
c( myComponent ).name; // MyComponent
When defining the custom Element as a class, the name will be taken from the functional webcomponent and it will be used as a class name in camel case format.
Improvement for error log and jsx-runtime
Error log
For errors due to transformation of serializable values, Atomico now adds a wrapper to improve the inspection of the origin of the error, example:
With this you can easily identify which is the target (webcomponent) that generates the error due to a wrong attribute setting.
jsx-runtime
Added path jsx-dev-runtime
as an alias for path jsx-runtime
.
New hooks useInsertionEffect, useId, useAsync and useSuspense 🎉
This PR refactors part of the Atomico code, to introduce new features and maintenance improvements.
new features.
- The hooks api has been refactored to now allow hooks to be tagged, thanks to this tag in the future it will be possible to filter the execution of hooks and improve their inspection, currently this functionality is being used by the new
useInsertionEffect
hook. - in the previous version it introduced use Promise as an advance to asynchronous handling within the core, this hook has allowed us to add in this version 2 new hooks
useAsync
anduseSuspense
. - se agrega
useId
, con soporte tanto al usar SSR o Browser.
useInsertionEffect
copy of React's useInsertionEffect, similar to useEffect, but this hook is executed before rendering the DOM, this hook is useful for 3rd party apis looking to manipulate the DOM before rendering the component's DOM.
useId
copy of React's useId, creates a unique ID for the Atomico context, the generated ID will depend on the origin, whether it is SSR or Client.
SSR ID Example: s0-1
.
CLIENT ID Example: c0-1
.
useAsync y useSuspense
useAsync: this hook is a step before the adoption of React's use
hook, it allows to suspend the rendering execution of the webcomponent and to communicate to useSuspense
the execution suspension.
const getUser = (id: number): Promise<{ name: string }> =>
fetch(`user/${id}`).then((res) => res.json());
function component({ id }) {
const user = useAsync(getUser, [id]);
return <host>{user.name}</host>;
}
Nota 1: This hook conditions the execution of the promise according to a list of optional arguments, which allows the promise to be regenerated every time the list changes.
Nota 2: useAsync
suspends rendering execution and resumes it only if the promise has been resolved or rejected.
useSuspense: captures all nested executions that have been paused, it returns an object that defines the state of the executions.
function component() {
const status = useSuspense();
return (
<host shadowDom>
{status.pending ? "Loading..." : status.fulfilled ? "Done!" : "Error!"}~
<slot />
</host>
);
}
Maintenance improvements
- migration of the use of let by const, to improve the maintenance syntax within core.
- deleveraging of the context api internally.
- migration of types from JSDOC to JSDOC with TS.
Warnings
This new change has generated modifications to the core at the level of hooks, currently the changes have passed all the tests without complications, we will be attentive to any bug or unexpected behavior.
For creators of third party APIs based on createHooks, cleanEffects now has 3 execution steps:
- The first run clears the effects of
useInsertionEffects
. - The second run clears the effects of
useLayoutEffects
. - The third and last run clears the effects of
useEffect
.
You should update your tests by adding the third run to clean up the useEffect, example:
hooks.cleanEffects()()();
the usePromise hook is added
usePromise
This hook allows us to observe the resolution of a promise, with this hook we seek to provide a utility at the core level to work with asynchronous tasks
Syntax
import { usePromise } from "atomico";
const callback = (id: number)=>Promise.resolve(id);
const args:Parameters<typeof callback> = [1];
const autorun = true;
const promise = usePromise( callback, args, autorun );
where:
callback
: asynchronous function.args
: arguments that callback requires.autorun
: by default true, it automatically executes the promise, if it is false the execution of the promise is suspended.promise
: return object, at the type level it defines the following properties:pending
: boolean, defines if the promise is executed but pending resolution.fulfilled
: boolean , defines if the promise has been fulfilledresult
: result of the promise.rejected
: boolean, defines if the promise has been rejected.
Example
import { usePromise } from "atomico";
const getUsers = (id: number) => Promise.resolve({ id, name: "Atomico" });
function component() {
const promise = usePromise(getUsers, [1]);
return (
<host>
{promise.fulfilled ? (
<h1>Done!</h1>
) : promise.pending ? (
<h1>Loading...</h1>
) : (
<h1>Error!</h1>
)}
</host>
);
}
Note: At the type level, autocompletion is conditional on the state you are looking to observe.