liact
v1.0.2
Published
lit-html + React syntax
Downloads
27
Readme
Liact
English | 日本語
lit-html + Reactのシンタックス = 標準に準拠 & メンテナンス性
Web ComponentをReact風味で宣言的に書くためのライブラリ。
lit-htmlを使用しており、JavaScriptとTypeScriptの両方をサポートしています。
例
lit-htmlを使用してコンポーネントを書きます。 ここでは諸々をインストールする手間を省くため、unpkg.comを活用しています。
// hello-world.js
import { html } from "https://unpkg.com/lit-html?module";
import {
component,
useState,
useEffect
} from "https://unpkg.com/liact";
const languageOf = (code, name) => ({ code, name });
const languages = [
languageOf("En-US", "English"),
languageOf("Ja-JP", "日本語"),
];
const texts = {
"En-US": {
"Hello, world!": "Hello, world!",
"Liact Test": "Liact Test",
},
"Ja-JP": {
"Hello, world!": "こんにちは、世界!",
"Liact Test": "Liact テスト",
},
};
const getText = lang => (id, fallback = "") =>
texts[lang] ? (texts[lang][id] ?? fallback) : fallback;
// コンポーネントを作成し、HTMLカスタム要素として登録します。
customElements.define("hello-world", component((self, props) => {
const [lang, setLang] = setState(self, props.get("lang") ?? "En-US");
const T = getText(lang);
useEffect(self, () => {
document.title = T("Liact Test");
}, [lang]);
return html`
<h1>Liact</h1>
<select @change=${ev => setLang(ev.target.value)}>${
languages.map(({ code, name }) => html`
<option value="${code}" ?selected=${code == lang}>${name}</option>
`)
}</select>
<p>${T("Hello, world!")}</p>
`;
}));そして作成したカスタム要素を読み込み、使用します。
<!-- index.html -->
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<hello-world lang="En-US"></hello-world>
<script type="module" src="./hello-world.js"></script>
</body>
</html>各ファイルをブラウザで見るためにサーバを起動します。
python3 -m http.serverブラウザでhttp://0.0.0.0:8000を開いて見てみましょう。
このように表示されます:
インストール
上記の例で見たように、unpkg.comを使う場合インストールは不要です。
Unpkg.com (推奨)
https://unpkg.com/liactから直接インポートします。
import { component } from "https://unpkg.com/liact";または
<script type="module" src="https://unpkg.com/liact"></script>NPM (またはYarn)
CLIでインストールします:
npm install --save-dev liactまたは、yarnを使う場合:
yarn add liactそして"liact"をインポートします。
import { component } from "liact";TypeScript
TypeScript用の型定義ファイル(liact.d.ts)はnpmパッケージに最初から含まれています。
ドキュメント
https://kurousada.gitlab.io/liact?lang=Ja-JPをご覧ください。
ソースコードはhttps://gitlab.com/kurousada/liactにあります。
API
type Props
Key-value Map of properties given to the element.
export interface Props extends Map<string, string> {
getBoolean(key: string): Boolean | undefined;
getNumber(key: string): Number | undefined;
getString(key: string): String | undefined;
getListOf<T>(f: (value: string) => T, key: string): T[] | undefined;
};Note that Props.prototype.getBoolean will return false for "false", "no" and "off", true if any other value is set.
Example
const myLanguages = component((self, { props }) => {
const languages = props.getListOf(String, "languages") ?? [];
const [language, setLanguage] = useState(self, "English");
return html`
<select @change=${ev => setLanguage(ev.target.value)}>${
languages.map(lang => html`
<option value="lang">${lang}</option>
`)
}</select>
`;
});type Component
Object represents Web Component.
Do not use this object directly and use ViewArgs given as an argument to the view function.
export type Component = unknowntype ViewArgs
Type of a object given to view function as its argument.
export interface ViewArgs {
readonly props : Props;
readonly shadowRoot: ShadowRoot;
readonly slots : HTMLSlotElement[];
render : () => void;
}Members & Methods
| Name | Type | Description | |------------|-------------------|------------------------------| | props | HTMLElement | Props given to the component | | shadowRoot | ShadowRoot | Shadow root of the component | | slots | HTMLSlotElement[] | Slots in the component | | render | () => void | Render function of component |
type View
Type of a function represents view.
export type View = (self: Component, args: ViewArgs) => TemplateResult;Arguments
| Name | Type | Description | |---------|------------------|----------------------------| | self | Component | Used for hooks | | props | Props | Props given to the element |
Returns
| Type | Description |
|----------------|----------------------------------------------|
| TemplateResult | Usually created using html from "lit-html" |
type ComponentOptions
Object represents options for component().
export interface ComponentOptions {
base: Optional<HTMLElement>;
}Members & Methods
| Name | Type | Description | |---------|-----------------------|------------------------------| | base | Optional | Base object of the component |
funtion component()
Create Web Component
export function component<T extends HTMLElement = HTMLElement>(view: View, options: ComponentOptions = {}): T;Arguments
| Name | Type | Description | |---------|------------------|---------------| | view | View | View function | | options | ComponentOptions | Options |
Returns
| Type | Description |
|-----------|-------------------------------------------|
| Component | Usually passed to customElements.define |
Example
import { component } from "liact";
// Create component
const helloMessage = component((self, { props }) => html`
<p>Hello, ${props.get("name") ?? "anonymous"}!</p>
`);
// Register as a HTML Custom Element
customElements.define("hello-message", helloMessage);type SetState
Type of function to set & update state created by useState().
export type SetState<T> = (value: T) => void;Arguments
| Name | Type | Description | |-------|------|------------------------| | value | T | New value of the state |
function useState()
Hook to use state. The associated component will be re-rendered when the state changes.
export function useState<T>(self: Component, initial: T): [T, SetState<T>];Arguments
| Name | Type | Description | |---------|-----------|----------------------------| | self | Component | Used for hooks | | initial | T | Initial value of the state |
Returns
| Type | Description | |------------------|------------------------------------------------| | [T, SetState] | A pair of current state and function to update |
type Ref
Type of object represents a mutable reference to a value.
export interface Ref<T> {
current: T;
}Members & Methods
| Name | Type | Description | |---------|------|----------------------| | current | T | Current value of Ref |
function useRef()
Hook to use Ref. The associated component will not be re-rendered even when the ref changes.
export function useRef<T>(self: Component, initial: T): Ref<T>;Arguments
| Name | Type | Description | |---------|-----------|--------------------------| | self | Component | Used for hooks | | initial | T | Initial value of the ref |
Returns
| Type | Description | |--------|-----------------------------------------------| | Ref | A ref which is a mutable reference to a value |
type Cleanup
Type of function to cleanup an effect. Cleanup functions will be executed on next render of effect.
export type Cleanup = () => void;function useEffect()
Hook to use effect.
Effect will be executed in the end of render phase of the component only when at least one of deps has changed.
Passing [] to deps makes one-time effect while not specifying deps cause executions of effect on every render.
export function useRef<T>(self: Component, f: () => Cleanup, deps?: any[]): void;Arguments
| Name | Type | Description | |------|---------------|---------------------| | self | Component | Used for hooks | | f | () => Cleanup | Function to execute | | deps | any[] | Dependency values |
コントリビューション
プルリクエストはいつでも大歓迎です!
ライセンス
MITライセンス
