atomico

Atomico a micro-library for creating webcomponents using only functions, hooks and virtual-dom.

MIT License

Downloads
22.9K
Stars
1.1K
Committers
7

Bot releases are hidden (Show)

atomico - Fix ssr

Published by UpperCod about 1 year ago

  1. Fix the use of the serialize function from the atomico/utils module when used from SSR.
  2. Fix the use of the template function in the SSR (Server-Side Rendering) of the atomico module.
atomico - The dispatchEvent function is added as a test utility

Published by UpperCod about 1 year ago

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 features at [email protected]

List of new features

  1. Custom Type Support
  2. Adding the use of the new operator to create an instance of an uncovered attribute.
  3. Eliminating the atomico/core module at the types level.
  4. Add support for AbortController to the useAsync, useSuspense, and usePromise hooks.
  5. 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:

  1. 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.

  1. 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.

atomico - Type improvements and type fixes

Published by UpperCod over 1 year ago

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

  1. Using the Component type fixes the generation of the types for the strict props object.
  2. Fixed types returned by useRef when using an Atomico constructor.
atomico - fix dispatchEvent when using ssr

Published by UpperCod over 1 year ago

Sometimes when generating an update from SSR the event system of the props is dispatched, this version omits the dispatch of events in SSR

atomico - Fix jsx-runtime and export createElement

Published by UpperCod over 1 year ago

atomico - Dynamic name for the classes that returns c is added

Published by UpperCod over 1 year ago

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.

atomico - Improvement for error log and jsx-runtime

Published by UpperCod almost 2 years ago

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:

image

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.

atomico - New hooks useInsertionEffect, useId, useAsync and useSuspense 🎉

Published by UpperCod almost 2 years ago

This PR refactors part of the Atomico code, to introduce new features and maintenance improvements.

new features.

  1. 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.
  2. 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 and useSuspense.
  3. 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

  1. migration of the use of let by const, to improve the maintenance syntax within core.
  2. deleveraging of the context api internally.
  3. 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:

  1. The first run clears the effects of useInsertionEffects.
  2. The second run clears the effects of useLayoutEffects.
  3. 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()()();
atomico - the usePromise hook is added

Published by UpperCod almost 2 years ago

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 fulfilled
    • result: 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.

atomico - Fix Any export

Published by UpperCod almost 2 years ago

Exposes at the Any type level, this is an alias for null but at the Atomico level

atomico - Fix the any declaration when using the Component type

Published by UpperCod almost 2 years ago

atomico - Fix types for TS when using Component type

Published by UpperCod almost 2 years ago

atomico - Fix Component types for Typescript

Published by UpperCod almost 2 years ago

Atomico through TS declarations extracted all the global constructors available in Window, sometimes these constructors were modified by third-party libraries, which could cause the props to not be inferred correctly.

This version limits the declared types ( If you are a user of any global type not considered, attach it to an issue to add it to the allowed types )

atomico - new JSX type is added (feature for TSX only)

Published by UpperCod about 2 years ago

JSX type

this new type creates a wrapper to instantiate an element retrieved from the DOM in JSX, example:

import { JSX } from "atomico";

const [ Template ] = useSlot< JSX<{value: number} >>(ref);
 
<Template value={10}/>

This enhances the technique of referencing slots as templates

atomico - Fix props.children for lite components

Published by UpperCod about 2 years ago

Now lite components correctly receive props.children

atomico - Add support for function components

Published by UpperCod about 2 years ago

Thanks to @efoken, [email protected] now allows stateless function instances in JSX🎉, for example:

// Just a plain function, no Custom Element...
const CloseIcon = (props) => (
  <svg viewBox="0 0 16 16" width="16" height="16" {...props}>...</svg>
);

// ... can be re-used in JSX like this:
function button() {
  return (
    <host shadowDom>
      <button>
        <CloseIcon aria-hidden="true" />
      </button>
    </host>
  );
}
atomico - Fix recycling when keys are used

Published by UpperCod about 2 years ago

atomico - Add recycling support

Published by UpperCod about 2 years ago

This feature allows you to recycle the node and its props, but the hooks will be restarted.

atomico - Fix the export for TS of the tag Fragment

Published by UpperCod about 2 years ago