mirror of
https://github.com/hanzoai/papers.git
synced 2026-10-29 07:34:31 +00:00
91 lines
2.2 KiB
TeX
91 lines
2.2 KiB
TeX
\section{API Design}
|
|
|
|
|
|
\subsection{Store Initialization}
|
|
|
|
\begin{lstlisting}[language=JavaScript,caption=Store creation]
|
|
import { createStore } from "astle";
|
|
|
|
const store = createStore({
|
|
apiKey: "pk_live_xxx",
|
|
endpoint: "https://api.hanzo.ai",
|
|
initialState: {
|
|
cart: loadFromStorage("cart"),
|
|
},
|
|
});
|
|
\end{lstlisting}
|
|
|
|
\subsection{Actions}
|
|
|
|
Actions are factory functions returning events:
|
|
|
|
\begin{lstlisting}[language=JavaScript,caption=Action creators]
|
|
import { actions } from "astle";
|
|
|
|
// Add item to cart
|
|
store.dispatch(actions.cart.addItem({
|
|
productId: "prod_123",
|
|
variantId: "var_456",
|
|
quantity: 2,
|
|
}));
|
|
|
|
// Apply coupon
|
|
store.dispatch(actions.cart.applyCoupon({
|
|
code: "SAVE20",
|
|
}));
|
|
|
|
// Begin checkout
|
|
store.dispatch(actions.checkout.begin());
|
|
\end{lstlisting}
|
|
|
|
\subsection{Selectors}
|
|
|
|
Selectors derive values from state:
|
|
|
|
\begin{lstlisting}[language=JavaScript,caption=Selectors]
|
|
import { selectors } from "astle";
|
|
|
|
const cart = selectors.cart.getCart(store.getState());
|
|
const itemCount = selectors.cart.getItemCount(store.getState());
|
|
const isCheckoutReady = selectors.checkout.isReady(store.getState());
|
|
\end{lstlisting}
|
|
|
|
Selectors are memoized for performance:
|
|
|
|
\begin{lstlisting}[language=JavaScript,caption=Memoized selector]
|
|
const getCartTotal = createSelector(
|
|
[getItems, getDiscounts],
|
|
(items, discounts) => {
|
|
const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
|
|
const discountAmount = discounts.reduce((sum, d) => sum + d.amount, 0);
|
|
return subtotal - discountAmount;
|
|
}
|
|
);
|
|
\end{lstlisting}
|
|
|
|
\subsection{React Bindings}
|
|
|
|
Astle.js provides React hooks for seamless integration:
|
|
|
|
\begin{lstlisting}[language=JavaScript,caption=React integration]
|
|
import { useCart, useCheckout } from "astle/react";
|
|
|
|
function CartPage() {
|
|
const { items, total, addItem, removeItem } = useCart();
|
|
const { begin, status } = useCheckout();
|
|
|
|
return (
|
|
<div>
|
|
{items.map(item => (
|
|
<CartItem key={item.id} item={item} onRemove={() => removeItem(item.id)} />
|
|
))}
|
|
<Total amount={total} />
|
|
<button onClick={begin} disabled={status !== "idle"}>
|
|
Checkout
|
|
</button>
|
|
</div>
|
|
);
|
|
}
|
|
\end{lstlisting}
|
|
|