### Installation via npm Source: https://github.com/kshutkin/slimlib/blob/main/store/README.md Instructions for installing the Slimlib Store package as a development dependency using npm. ```bash npm install --save-dev @slimlib/store ``` -------------------------------- ### Preact Store Setup and Actions Source: https://context7.com/kshutkin/slimlib/llms.txt Demonstrates the creation of a reactive store using @slimlib/store/preact and defines actions to modify the application state. This includes managing notifications, user profiles, and themes. It relies on Preact and its hooks for component integration. ```typescript import { h } from 'preact'; import { useState } from 'preact/hooks'; import { createStore, useStore } from '@slimlib/store/preact'; // Create store const [appState, appStore] = createStore({ notifications: [], user: { name: '', avatar: '' }, theme: 'light' }); // Actions export function addNotification(message, type = 'info') { appState.notifications.push({ id: Date.now(), message, type, timestamp: new Date().toISOString(), read: false }); } export function markAsRead(id) { const notification = appState.notifications.find(n => n.id === id); if (notification) { notification.read = true; } } export function clearNotifications() { appState.notifications = []; } export function setUser(name, avatar) { appState.user.name = name; appState.user.avatar = avatar; } export function toggleTheme() { appState.theme = appState.theme === 'light' ? 'dark' : 'light'; } ``` -------------------------------- ### Svelte Component Usage Source: https://github.com/kshutkin/slimlib/blob/main/store/README.md Provides an example of how to consume a Svelte store created with Slimlib. It demonstrates importing the store and accessing its state reactively using the `$` prefix. ```svelte // use it in reactive way for reading data $storeName ``` -------------------------------- ### Install Slimlib List with npm Source: https://github.com/kshutkin/slimlib/blob/main/list/README.md Installs the Slimlib List package as a development dependency using npm. This command is typically run in the project's root directory. ```bash npm install --save-dev @slimlib/list ``` -------------------------------- ### Add Notification Button Examples (React) Source: https://context7.com/kshutkin/slimlib/llms.txt These examples demonstrate how to use buttons to trigger the 'addNotification' function with different message types (success, error, info) in a React application. The 'addNotification' function is assumed to be defined elsewhere, likely within the application's state management or notification system. ```javascript import React from 'react'; function App() { // Assume addNotification is defined elsewhere, e.g., from a context or hook const addNotification = (message, type) => { console.log(`Notification - Type: ${type}, Message: ${message}`); // Actual notification logic would go here }; return (
); } export default App; ``` -------------------------------- ### Create Mock and Generate Code with Smart Mock Source: https://github.com/kshutkin/slimlib/blob/main/smart-mock/README.md Demonstrates how to use the Smart Mock factory to create a mock object, perform operations on it, and then generate code for the mock and global variables. It requires the '@slimlib/smart-mock' package. ```javascript import createMockProvider from '@slimlib/smart-mock'; const { createMock, generate, generateGlobals } = createMockProvider(); const mock = createMock({ fly() { return { status: 'flying' }; }, land() {}, name: '' }, 'fly'); mock.name = 'Moth'; const status = mock.fly(); mock.land(); // Example of generating code console.log(generate(mock)); // Output: mock console.log(generate(mock.name)); // Output: 'Moth' console.log(generate(status)); // Output: fly.fly() console.log(generateGlobals()); /* Example Output: fly.name = "Moth" const tmp_0 = fly.land tmp_0() */ ``` -------------------------------- ### Svelte Store Implementation Source: https://github.com/kshutkin/slimlib/blob/main/store/README.md Details the implementation of a Svelte store using `@slimlib/store/svelte`. It shows how to create the store, define actions, and export the store for reactive usage within Svelte components. ```javascript import { createStore } from '@slimlib/store/svelte'; // create store const [state, subscribe] = createStore(); // action export function doSomething() { state.field = value; } export default { subscribe }; ``` -------------------------------- ### React Store Usage Source: https://github.com/kshutkin/slimlib/blob/main/store/README.md Demonstrates how to create and use a store with React components using the `@slimlib/store/react` module. It shows store creation, defining actions, and consuming state within a component via the `useStore` hook. ```javascript import { createStore, useStore } from '@slimlib/store/react'; // create store const [state, store] = createStore(); // action function doSomething() { state.field = value; } //component function Component() { const state = useStore(store); // use state } ``` -------------------------------- ### Preact Store Usage Source: https://github.com/kshutkin/slimlib/blob/main/store/README.md Illustrates the usage of Slimlib Store with Preact applications, mirroring the React implementation. It covers store creation, action definition, and state consumption within a Preact component using `useStore`. ```javascript import { createStore, useStore } from '@slimlib/store/preact'; // create store const [state, store] = createStore(); // action function doSomething() { state.field = value; } //component function Component() { const state = useStore(store); // use state } ``` -------------------------------- ### Svelte Integration - createStore Source: https://github.com/kshutkin/slimlib/blob/main/store/README.md Creates a store for Svelte applications. It returns the state and a subscribe function. ```APIDOC ## `createStore(initialState: T): [T, Store, () => void]` ### Description Store factory created with `notifyAfterCreation` === `true`. ### Method `createStore` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **initialState** (T) - Required - The initial state of the store. ### Request Example ```javascript import { createStore } from '@slimlib/store/svelte'; export const myStore = createStore({ count: 0 }); ``` ### Response #### Success Response (200) - **state** (T) - A proxy object representing the current state. - **subscribe** (Store) - A function to subscribe to store changes. - **notify** (() => void) - A function to manually notify subscribers. #### Response Example ```json [{"count": 0}, { (cb) => { /* subscribe */ }, () => { /* get state */ } }, () => { /* notify */ }] ``` ``` -------------------------------- ### Define and Use Injector with TypeScript Source: https://github.com/kshutkin/slimlib/blob/main/injector/README.md This snippet demonstrates how to create an injector instance using `createInject` and then use it to provide and inject dependencies. It shows how to define a configuration object and then inject it into an asynchronous function to fetch data. ```typescript import createInject from '@slimlib/injector'; const inject = createInject(); inject(($provide: Provider) => { $provide('config', { url: 'http://example.com/json', format: 'json' }); }); inject(async (config: Json) => { const data = await fetch(config.url); const result = config.json ? await data.json() : data; // and so on }); ``` -------------------------------- ### Create and Manage State with RxJS in Slimlib Source: https://context7.com/kshutkin/slimlib/llms.txt Demonstrates how to create a reactive store using Slimlib's RxJS integration. It covers initializing state, converting the store to an observable stream, defining actions for state mutation, and setting up derived observables to react to specific state changes or combinations of states. This allows for efficient handling of asynchronous operations and complex UI updates. ```typescript import { createStore, toObservable } from '@slimlib/store/rxjs'; import { map, filter, distinctUntilChanged, debounceTime, combineLatest } from 'rxjs/operators'; // Create store const [state, store] = createStore({ searchQuery: '', results: [], loading: false, selectedItem: null, filters: { category: 'all', minPrice: 0, maxPrice: 1000 } }); // Convert to observable const state$ = toObservable(store); // Actions export function setSearchQuery(query) { state.searchQuery = query; } export function setResults(results) { state.results = results; state.loading = false; } export function setLoading(loading) { state.loading = loading; } export function selectItem(item) { state.selectedItem = item; } export function setFilter(key, value) { state.filters[key] = value; } // Derived observables const searchQuery$ = state$.pipe( map(s => s.searchQuery), distinctUntilChanged(), debounceTime(300) ); const results$ = state$.pipe( map(s => s.results), distinctUntilChanged() ); const loading$ = state$.pipe( map(s => s.loading), distinctUntilChanged() ); const filters$ = state$.pipe( map(s => s.filters), distinctUntilChanged((a, b) => a.category === b.category && a.minPrice === b.minPrice && a.maxPrice === b.maxPrice ) ); // Filtered results combining multiple streams const filteredResults$ = combineLatest([results$, filters$]).pipe( map(([results, filters]) => { return results.filter(item => { if (filters.category !== 'all' && item.category !== filters.category) { return false; } if (item.price < filters.minPrice || item.price > filters.maxPrice) { return false; } return true; }); }) ); // Search effect searchQuery$.subscribe(async (query) => { if (!query.trim()) { setResults([]); return; } setLoading(true); try { const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`); const results = await response.json(); setResults(results); } catch (error) { console.error('Search failed:', error); setResults([]); setLoading(false); } }); // Logger effect state$.subscribe((state) => { console.log('State updated:', { query: state.searchQuery, resultCount: state.results.length, loading: state.loading, selectedId: state.selectedItem?.id }); }); // Filtered results effect filteredResults$.subscribe((results) => { console.log(`Showing ${results.length} filtered results`); }); // Complex selector combining multiple observables const searchSummary$ = combineLatest([ searchQuery$, results$, loading$, filteredResults$ ]).pipe( map(([query, results, loading, filtered]) => ({ query, totalResults: results.length, filteredResults: filtered.length, loading, hasResults: filtered.length > 0 })) ); searchSummary$.subscribe((summary) => { console.log('Search summary:', summary); }); // React to specific changes state$.pipe( map(s => s.selectedItem), filter(item => item !== null), distinctUntilChanged((a, b) => a?.id === b?.id) ).subscribe((item) => { console.log('Item selected:', item.name); // Could trigger analytics, navigation, etc. }); // Persist filters to localStorage filters$.pipe( debounceTime(500) ).subscribe((filters) => { localStorage.setItem('searchFilters', JSON.stringify(filters)); }); // Usage in application setSearchQuery('laptop'); setTimeout(() => { setFilter('category', 'electronics'); setFilter('maxPrice', 500); }, 1000); ``` -------------------------------- ### Core API - createStore Source: https://github.com/kshutkin/slimlib/blob/main/store/README.md The main store factory function. It accepts an initial state and returns a proxy object for actions, a store for subscriptions, and a notification function. ```APIDOC ## `createStore(initialState: T): [T, Store, () => void]` ### Description Store factory function that takes initial state and returns a proxy object, a store, and a function to notify subscribers. The proxy object is intended for actions, the store is for subscription to changes, and the notification function is for edge cases where the original object might have changed and listeners need to be notified. ### Method `createStore` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **initialState** (T) - Required - The initial state of the store. ### Request Example ```javascript import { createStore } from '@slimlib/store'; const [state, store, notify] = createStore({ count: 0 }); ``` ### Response #### Success Response (200) - **state** (T) - A proxy object representing the current state, intended for modification by actions. - **store** (Store) - An object implementing the publish/subscribe/read pattern for subscribing to store changes. - **notify** (() => void) - A function to manually notify subscribers, used in edge cases. #### Response Example ```json [{"count": 0}, { (cb) => { /* subscribe */ }, () => { /* get state */ } }, () => { /* notify */ }] ``` ``` -------------------------------- ### RxJS Store Integration Source: https://github.com/kshutkin/slimlib/blob/main/store/README.md Demonstrates integrating Slimlib Store with RxJS. It covers creating a store and converting it into an Observable using `toObservable` for reactive stream processing. ```javascript import { createStore, toObservable } from '@slimlib/store/rxjs'; // create store const [state, store] = createStore(); // action export function doSomething() { state.field = value; } // observable export const state$ = toObservable(store); ``` -------------------------------- ### Angular Store Service Source: https://github.com/kshutkin/slimlib/blob/main/store/README.md Shows how to define an Angular store service by extending `SlimlibStore`. This includes setting up initial state, defining selectors for derived state, and creating actions to modify the store's state. ```typescript import { SlimlibStore } from '@slimlib/store/angular'; // create store @Injectable() export class StoreName extends SlimlibStore { constructor() { super(/*Initial state*/{ field: 123 }); } // selectors field = this.select(state => state.field); // actions doSomething() { this.state.field = value; } } ``` -------------------------------- ### React State Management with @slimlib/store/react Source: https://context7.com/kshutkin/slimlib/llms.txt Demonstrates how to create a global store, define actions for state mutation, and utilize hooks to manage and react to state changes within React components. It covers setting up a todo list application with filtering and user authentication. ```typescript import { createStore, useStore } from '@slimlib/store/react'; // Create global store const [appState, appStore] = createStore({ todos: [], filter: 'all', user: { name: '', isAuthenticated: false } }); // Actions outside components export function addTodo(text) { appState.todos.push({ id: Date.now(), text, completed: false, createdAt: new Date().toISOString() }); } export function toggleTodo(id) { const todo = appState.todos.find(t => t.id === id); if (todo) { todo.completed = !todo.completed; } } export function setFilter(filter) { appState.filter = filter; } export function login(name) { appState.user.name = name; appState.user.isAuthenticated = true; } // React component using store function TodoList() { const state = useStore(appStore); const filteredTodos = state.todos.filter(todo => { if (state.filter === 'active') return !todo.completed; if (state.filter === 'completed') return todo.completed; return true; }); return (

Todos ({filteredTodos.length})

{filteredTodos.map(todo => (
toggleTodo(todo.id)} /> {todo.text}
))}
); } function TodoInput() { const [input, setInput] = React.useState(''); const handleSubmit = (e) => { e.preventDefault(); if (input.trim()) { addTodo(input); setInput(''); } }; return (
setInput(e.target.value)} placeholder="Add todo..." />
); } function FilterButtons() { const state = useStore(appStore); return (
{['all', 'active', 'completed'].map(filter => ( ))}
); } function UserInfo() { const state = useStore(appStore); if (!state.user.isAuthenticated) { return ; } return
Welcome, {state.user.name}!
; } // App composition function App() { return (
); } export default App; ``` -------------------------------- ### $provide Function Usage Source: https://github.com/kshutkin/slimlib/blob/main/injector/README.md Describes the `$provide` function used for defining injectable services. ```APIDOC ## $provide(key, value) ### Description A predefined injectable function used to register services or values within the injector's scope. ### Method N/A (Method of the injected Provider) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (string) - Required - The name of the service or value to be provided. - **value** (unknown) - Required - The actual service or value to register. ### Request Example ```typescript import createInject from '@slimlib/injector'; const inject = createInject(); // Assuming 'service' is an imported object or class instance // import service from './myService'; inject(($provide: Provider) => { $provide('service', service); $provide('config', { apiUrl: '/api' }); }); ``` ### Response #### Success Response (N/A) This function does not return a value directly but registers the provided key-value pair within the injector's scope. #### Response Example ```javascript // After calling $provide, the registered 'service' can be injected elsewhere inject((service) => { // Use the injected service service.doSomething(); }); ``` ``` -------------------------------- ### Core State Management with Slimlib Store Source: https://context7.com/kshutkin/slimlib/llms.txt Demonstrates creating, initializing, and interacting with a Slimlib store. It covers direct state mutation, subscribing to changes, updating nested objects, manual notifications, and unwrapping the proxy to access the original state. State changes trigger automatic notifications, and updates to nested properties are handled efficiently. ```typescript import { createStoreFactory, unwrapValue } from '@slimlib/store/core'; // Create store factory (notifyAfterCreation = true for immediate notifications) const createStore = createStoreFactory(true); // Initialize store with state const [state, store, notify] = createStore({ user: { name: 'Guest', loggedIn: false }, cart: { items: [], total: 0 }, theme: 'light' }); // Subscribe to changes const unsubscribe = store((updatedState) => { console.log('State changed:', updatedState); console.log('Cart total:', updatedState.cart.total); }); // Mutate state directly - triggers notification state.user.name = 'Alice'; state.user.loggedIn = true; // Add cart items state.cart.items.push({ id: 1, name: 'Book', price: 29.99 }); state.cart.items.push({ id: 2, name: 'Pen', price: 5.99 }); // Update total (notification batched via microtask) state.cart.total = state.cart.items.reduce((sum, item) => sum + item.price, 0); // Toggle theme state.theme = state.theme === 'light' ? 'dark' : 'light'; // Read current state without subscribing const currentState = store(); console.log('Current user:', currentState.user.name); console.log('Items in cart:', currentState.cart.items.length); // Unwrap proxy to get original object const originalState = unwrapValue(state); console.log('Original state object:', originalState); // Nested object updates trigger notifications state.cart.items[0].price = 24.99; state.cart.total = state.cart.items.reduce((sum, item) => sum + item.price, 0); // Manual notification (rarely needed) notify(); // Cleanup unsubscribe(); // Multiple stores for different domains const [authState, authStore] = createStore({ token: null, expiresAt: null }); const [uiState, uiStore] = createStore({ sidebarOpen: false, modalVisible: false, notifications: [] }); // Independent subscriptions authStore((state) => { if (state.token) { console.log('User authenticated'); } }); uiStore((state) => { console.log(`Notifications: ${state.notifications.length}`); }); // Update independent states authState.token = 'jwt-token-xyz'; authState.expiresAt = Date.now() + 3600000; uiState.sidebarOpen = true; uiState.notifications.push({ id: 1, message: 'Welcome!', type: 'info' }); ``` -------------------------------- ### Injector Creation API Source: https://github.com/kshutkin/slimlib/blob/main/injector/README.md Provides the `createInject` function to generate a new injector instance. ```APIDOC ## createInject() ### Description Returns a new instance of an injector function to work with. ### Method N/A (Factory Function) ### Endpoint N/A ### Parameters None ### Request Example ```javascript import createInject from '@slimlib/injector'; const inject = createInject(); ``` ### Response #### Success Response (N/A) Returns an injector function. #### Response Example ```javascript // Returns a function that can be used for injection const injectorFunction = createInject(); ``` ``` -------------------------------- ### Smart Mock API Source: https://github.com/kshutkin/slimlib/blob/main/smart-mock/README.md This section details the functions exported by the default Smart Mock provider. ```APIDOC ## Default Export ### Description The default export is a factory function that returns three other functions (`createMock`, `generate`, `generateGlobals`) which share a common internal state. ### Usage ```javascript import createMockProvider from '@slimlib/smart-mock'; const { createMock, generate, generateGlobals } = createMockProvider(); ``` ``` ```APIDOC ## `createMock(object: T, name: string): T` ### Description This function creates a mock wrapper around a given JavaScript object. It records all operations performed on this object. The `name` parameter defines a global name for this object, which is used later during code generation. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **object** (`T extends object`) - Required - The object to mock. This can be a real object or a pure mock object with the desired behavior. - **name** (`string`) - Required - The global name to associate with this mock object. ### Request Example ```javascript const mockObject = { fly() { return { status: 'flying' }; }, land() {}, name: '' }; const mock = createMock(mockObject, 'fly'); ``` ### Response - **T** (`T`) - The mocked object, which records operations. ``` ```APIDOC ## `generate(object: unknown): string` ### Description Generates code for a specific export point (exit point) of the mocked object. This function attempts to automatically inline operations where possible. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **object** (`unknown`) - Required - The object or value for which to generate code. ### Request Example ```javascript // Assuming 'mock' is the object created by createMock const generatedCode = generate(mock); const generatedName = generate(mock.name); ``` ### Response - **string** - The generated code string for the provided object. ``` ```APIDOC ## `generateGlobals(): string` ### Description Generates the global code that could not be inlined into specific export points. This function ensures that only code not previously generated is emitted, updating internal counters and flags. ### Parameters None ### Request Example ```javascript const globalCode = generateGlobals(); ``` ### Response - **string** - The generated global code string. ``` -------------------------------- ### createStore Factory Function Source: https://github.com/kshutkin/slimlib/blob/main/store/README.md Explains the core `createStore` function which initializes and returns a reactive state object, a store for subscriptions, and a notification function. This is the fundamental building block for state management in slimlib. ```typescript type StoreCallback = (value: T) => void; type UnsubscribeCallback = () => void; interface Store { (cb: StoreCallback): UnsubscribeCallback; (): T; } createStore(initialState: T): [T, Store, () => void] ``` -------------------------------- ### Svelte Store Creation and Actions with Slimlib Source: https://context7.com/kshutkin/slimlib/llms.txt This TypeScript code defines a state store using @slimlib/store/svelte, including initial state, actions to modify the state, and export for Svelte's auto-subscription. It handles state mutations and logs history. ```typescript // store.ts import { createStore } from '@slimlib/store/svelte'; // Create store (notifyAfterCreation = true for Svelte) const [state, subscribe] = createStore({ count: 0, name: 'Counter App', history: [], settings: { step: 1, max: 100 } }); // Actions export function increment() { if (state.count < state.settings.max) { state.count += state.settings.step; state.history.push({ action: 'increment', value: state.count, time: Date.now() }); } } export function decrement() { if (state.count > 0) { state.count -= state.settings.step; state.history.push({ action: 'decrement', value: state.count, time: Date.now() }); } } export function reset() { state.count = 0; state.history.push({ action: 'reset', value: 0, time: Date.now() }); } export function setStep(step) { state.settings.step = step; } export function setMax(max) { state.settings.max = max; } export function setName(name) { state.name = name; } // Export as default for Svelte auto-subscription export default { subscribe }; ``` -------------------------------- ### Angular Integration - SlimlibStore Source: https://github.com/kshutkin/slimlib/blob/main/store/README.md Base class for creating store services in Angular. Provides state management and selector capabilities. ```APIDOC ## `SlimlibStore` ### Description Base class for store services in Angular. It facilitates state management and offers methods for creating selectors. ### Constructor - **`constructor(initialState: T)`**: Initializes the store with the provided initial state. ### Properties - **`state: T`**: A proxy object representing the current state of the store. ### Methods - **`select(...signals: Signal[], projector: (state: T, ...signalValue: SignalValue) => R): Signal`**: Creates a signal that projects a derived value from the store's state and other signals. ### Request Example ```typescript import { Injectable } from '@angular/core'; import { SlimlibStore } from '@slimlib/store/angular'; interface AppState { field: number; } @Injectable() export class AppStore extends SlimlibStore { constructor() { super({ field: 123 }); } field = this.select(state => state.field); doSomething() { this.state.field = 456; } } ``` ### Response #### Success Response (200) Provides a base class and methods for Angular store services. #### Response Example N/A ``` -------------------------------- ### Core API - createStoreFactory Source: https://github.com/kshutkin/slimlib/blob/main/store/README.md Returns a createStore factory. If `notifyAfterCreation` is truthy, the factory will notify subscribers immediately after a store is created. ```APIDOC ## `createStoreFactory(notifyAfterCreation: boolean)` ### Description Returns a createStore factory which notifies immediately after creating store if `notifyAfterCreation` is truthy. ### Method `createStoreFactory` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const createStoreWithImmediateNotification = createStoreFactory(true); const [state, store, notify] = createStoreWithImmediateNotification(initialState); ``` ### Response #### Success Response (200) Returns a factory function that creates stores. #### Response Example None ``` -------------------------------- ### Injector Function Usage Source: https://github.com/kshutkin/slimlib/blob/main/injector/README.md Explains how to use the injector function to inject dependencies into another function. ```APIDOC ## injector(function, scope) ### Description Injects arguments into a function and invokes it. ### Method N/A (Function Invocation) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **function** (function) - Required - The function to inject parameters and call. - **scope** (object) - Optional - The `this` context for the function. Defaults to `{}`. ### Request Example ```javascript import createInject from '@slimlib/injector'; const inject = createInject(); inject(($provide: Provider) => { $provide('service', service); }); inject(async (config: Json) => { const data = await fetch(config.url); // ... rest of the logic }); ``` ### Response #### Success Response (N/A) Returns the result of the invoked function. #### Response Example ```javascript // Assuming the injected function returns a value const result = inject(() => 'some value'); console.log(result); // Output: 'some value' ``` ``` -------------------------------- ### Create and Use Refiner Function (TypeScript) Source: https://github.com/kshutkin/slimlib/blob/main/refine-partition/README.md Demonstrates how to create a refiner function using the slimlib library and then use it to refine a partition by providing new candidate sets. The output is an iterable of iterables representing the refined partition. ```typescript import refiner from '../src'; const refineNext = refiner(); refineNext(['a', 'b', 'c']); refineNext(['b', 'c', 'e']); console.log(refineNext()); // Iterable of Iterables: ((a), (b, c), (e)) ``` -------------------------------- ### Svelte Component for Counter with Slimlib Store Source: https://context7.com/kshutkin/slimlib/llms.txt This Svelte component demonstrates integrating with the Slimlib store for state management. It uses the '$store' syntax for auto-subscription and includes UI elements for displaying and manipulating the counter state. ```svelte

{$store.name}

{$store.count}

History ({$store.history.length} actions)

    {#each $store.history.slice(-5).reverse() as entry}
  • {entry.action}: {entry.value} {new Date(entry.time).toLocaleTimeString()}
  • {/each}
``` -------------------------------- ### Preact User Profile Component Source: https://context7.com/kshutkin/slimlib/llms.txt A Preact component for managing user profile information, including name and avatar, using Slimlib store and local component state for editing. It allows creating, editing, and displaying user details. Dependencies include Preact, Preact hooks, and @slimlib/store/preact. ```typescript // User profile component function UserProfile() { const state = useStore(appStore); const [editing, setEditing] = useState(false); const [name, setName] = useState(''); const handleSave = () => { if (name.trim()) { setUser(name, `https://api.dicebear.com/7.x/avataaars/svg?seed=${name}`); setEditing(false); } }; if (!state.user.name) { return ( ); } return ( ); } ``` -------------------------------- ### RxJS Integration - toObservable Source: https://github.com/kshutkin/slimlib/blob/main/store/README.md Converts a Slimlib store into an RxJS Observable, allowing for reactive programming patterns. ```APIDOC ## `toObservable(store: Store): Observable` ### Description Converts a store into an RxJS Observable. ### Method `toObservable` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **store** (Store) - Required - The store object to convert. ### Request Example ```javascript import { createStore, toObservable } from '@slimlib/store/rxjs'; const [state, store] = createStore({ count: 0 }); const state$ = toObservable(store); state$.subscribe(newState => console.log(newState)); ``` ### Response #### Success Response (200) - **Observable** - An RxJS Observable that emits the store's state changes. #### Response Example ```javascript // Observable emitting state updates ``` ``` -------------------------------- ### Preact Integration - useStore Source: https://github.com/kshutkin/slimlib/blob/main/store/README.md Hook to subscribe to a store within a Preact component. It returns the current state of the store. ```APIDOC ## `useStore(store: Store): Readonly` ### Description Function to subscribe to a store inside a component. Returns the current state. ### Method `useStore` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **store** (Store) - Required - The store object to subscribe to. ### Request Example ```javascript import { useStore } from '@slimlib/store/preact'; function MyComponent() { const state = useStore(myStore); // use state } ``` ### Response #### Success Response (200) - **Readonly** - The current state of the store, returned as read-only. #### Response Example ```json { "field": "value" } ``` ``` -------------------------------- ### Angular Store Service with Signals and Actions - @slimlib/store/angular Source: https://context7.com/kshutkin/slimlib/llms.txt This snippet demonstrates creating a state management service in Angular using SlimlibStore. It defines a CartState interface, initializes the store, creates computed selectors for derived state (subtotal, discountAmount, taxAmount, total, itemCount) using signals, and implements various actions (addItem, removeItem, updateQuantity, applyDiscount, clear) to modify the state. Dependencies include '@angular/core' and '@slimlib/store/angular'. ```typescript import { Injectable, Component, Signal } from '@angular/core'; import { SlimlibStore } from '@slimlib/store/angular'; // Define state interface interface CartState { items: Array<{ id: number; name: string; price: number; quantity: number }>; discount: number; taxRate: number; } // Create store service @Injectable({ providedIn: 'root' }) export class CartStore extends SlimlibStore { constructor() { super({ items: [], discount: 0, taxRate: 0.08 }); } // Computed selectors combining signals subtotal = this.select( this.signal, (state) => state.items.reduce((sum, item) => sum + (item.price * item.quantity), 0) ); discountAmount = this.select( this.subtotal, this.signal, (subtotal, state) => subtotal * state.discount ); taxAmount = this.select( this.subtotal, this.discountAmount, this.signal, (subtotal, discount, state) => (subtotal - discount) * state.taxRate ); total = this.select( this.subtotal, this.discountAmount, this.taxAmount, (subtotal, discount, tax) => subtotal - discount + tax ); itemCount = this.select( this.signal, (state) => state.items.reduce((sum, item) => sum + item.quantity, 0) ); // Actions addItem(item: { id: number; name: string; price: number }) { const existing = this.state.items.find(i => i.id === item.id); if (existing) { existing.quantity++; } else { this.state.items.push({ ...item, quantity: 1 }); } } removeItem(id: number) { const index = this.state.items.findIndex(i => i.id === id); if (index !== -1) { this.state.items.splice(index, 1); } } updateQuantity(id: number, quantity: number) { const item = this.state.items.find(i => i.id === id); if (item) { item.quantity = Math.max(0, quantity); if (item.quantity === 0) { this.removeItem(id); } } } applyDiscount(percent: number) { this.state.discount = Math.min(Math.max(percent, 0), 1); } clear() { this.state.items = []; this.state.discount = 0; } } ``` -------------------------------- ### Dependency Injection with @slimlib/injector Source: https://context7.com/kshutkin/slimlib/llms.txt Parameter-name-based dependency injector for Node.js. It extracts function parameter names at runtime and resolves them from a registry. Supports async functions and 'this' context scoping. ```typescript import createInject from '@slimlib/injector'; // Create injector instance const inject = createInject(); // Register dependencies using $provide inject(($provide) => { $provide('database', { connection: 'mongodb://localhost:27017', name: 'myapp' }); $provide('logger', { log: (msg) => console.log(`[LOG] ${msg}`), error: (msg) => console.error(`[ERROR] ${msg}`) }); $provide('apiKey', 'sk-abc123xyz'); }); // Inject dependencies by parameter name inject((database, logger, apiKey) => { logger.log(`Connecting to ${database.connection}`); logger.log(`API Key: ${apiKey}`); // Use dependencies... }); // Works with async functions inject(async (database, logger) => { try { const result = await fetchData(database.connection); logger.log('Data fetched successfully'); return result; } catch (error) { logger.error(error.message); throw error; } }); // Scope support for 'this' context const scope = { multiplier: 2 }; inject(function(logger) { logger.log(`Multiplier: ${this.multiplier}`); }, scope); ``` -------------------------------- ### Initialize Slimlib List Source: https://github.com/kshutkin/slimlib/blob/main/list/README.md Demonstrates how to create a new, empty list object using the List constructor. Supports generic type definition for list nodes in TypeScript. ```javascript const list = new List; ``` ```typescript const list = new List(); ``` -------------------------------- ### Preact Main App Structure Source: https://context7.com/kshutkin/slimlib/llms.txt The main App component in Preact, orchestrating the layout and rendering of other components like UserProfile and ThemeToggle, as well as the main content area including the NotificationList. It sets up the basic structure for the application. This code assumes Preact is available. ```typescript // Main app function App() { return (

My App

``` -------------------------------- ### Partition Refinement Algorithm with TypeScript Source: https://context7.com/kshutkin/slimlib/llms.txt Implements the partition refinement algorithm for iteratively splitting sets into equivalence classes. It takes an initial set and subsequent refinement sets to progressively narrow down the equivalence classes. Useful for graph isomorphism and automata minimization. ```typescript import refiner from '@slimlib/refine-partition'; // Create refiner for string elements const refineNext = refiner(); // Initialize partition with first set refineNext(['a', 'b', 'c', 'd', 'e']); // Refine with second set - splits into intersecting/non-intersecting refineNext(['b', 'c', 'd', 'f']); // Result: Partition has {a, e}, {b, c, d}, {f} // Further refinement refineNext(['c', 'd', 'e', 'g']); // Result: {a}, {b}, {c, d}, {e}, {f}, {g} // Get current partition const partition = refineNext(); // Convert to array for inspection const result = [...partition].map(set => [...set]); console.log(result); // [['a'], ['b'], ['c', 'd'], ['e'], ['f'], ['g']] // Practical example: Graph isomorphism const graphRefiner = refiner(); // Initialize with all vertices graphRefiner([1, 2, 3, 4, 5, 6]); // Refine by vertices with degree 2 graphRefiner([1, 3, 5]); // Refine by vertices connected to vertex 1 graphRefiner([2, 3]); // Refine by vertices in triangle graphRefiner([1, 2, 3]); const equivalenceClasses = [...graphRefiner()].map(cls => [...cls]); console.log('Equivalence classes:', equivalenceClasses); // Each class contains vertices that are equivalent under the refinement criteria // Empty refinement returns current state const currentState = refineNext(); for (const subset of currentState) { console.log('Subset:', [...subset]); } ```