### Install Project Dependencies
Source: https://github.com/xcloudtech/rt-state/blob/master/CONTRIBUTING.md
Commands to install the necessary project dependencies using either npm or yarn. This step is crucial before running any project scripts or tests.
```bash
npm install
# or
yarn install
```
--------------------------------
### Clone and Setup Upstream Repository
Source: https://github.com/xcloudtech/rt-state/blob/master/CONTRIBUTING.md
Instructions for cloning the rt-state repository and configuring the upstream remote for collaborative development. This ensures you can pull changes from the main project.
```bash
git clone https://github.com/xcloudtech/rt-state.git
cd rt-state
git remote add upstream https://github.com/xcloudtech/rt-state.git
```
--------------------------------
### Running Tests with npm
Source: https://github.com/xcloudtech/rt-state/blob/master/CONTRIBUTING.md
Demonstrates how to execute tests using npm commands. Includes options for running all tests, enabling watch mode for continuous testing, and generating code coverage reports. Assumes a Node.js environment with npm installed.
```bash
# Run all tests
npm test
# Run tests in watch mode
npm test -- --watch
# Run tests with coverage
npm test -- --coverage
```
--------------------------------
### Install rt-state
Source: https://github.com/xcloudtech/rt-state/blob/master/README.md
Installs the rt-state library using package managers like npm, yarn, or pnpm. This is the first step to integrate rt-state into your project.
```bash
npm install rt-state
# or
yarn add rt-state
# or
pnpm add rt-state
```
--------------------------------
### Conventional Commits Examples
Source: https://github.com/xcloudtech/rt-state/blob/master/CONTRIBUTING.md
Examples of commit messages following the Conventional Commits specification. This standard helps in automating changelog generation and understanding commit history.
```bash
git commit -m "feat: add new state management feature"
git commit -m "fix: resolve memory leak in component cleanup"
git commit -m "docs: update API documentation"
```
--------------------------------
### Basic Counter Example with create
Source: https://github.com/xcloudtech/rt-state/blob/master/README.md
Demonstrates creating a component with state and functions using the `create` function. State and functions are defined once and persist across re-renders, avoiding the need for useCallback and managing dependencies manually.
```tsx
import { create, state } from 'rt-state';
const Counter = create<{ title: string }>((ctx) => {
// State is created once, persists across re-renders
const data = state({ count: 0 });
// Functions are created once, no need for useCallback
const increment = () => data.count++;
const decrement = () => data.count--;
// Return the render function
return (props) => (
{props.title}
Count: {data.count}
);
});
// Usage
//
```
--------------------------------
### Component Creation with create()
Source: https://github.com/xcloudtech/rt-state/blob/master/README.md
The main function for creating components. It accepts a setup function that runs once, allowing for state initialization, lifecycle hook registration (like `onDispose`), and watching state changes.
```tsx
import { create, state, watch } from 'rt-state';
const MyComponent = create((ctx) => {
// Setup phase - runs once
const localState = state({ data: 'initial' });
// Lifecycle hooks
ctx.onDispose(() => {
console.log('Component unmounting');
});
// Watch state changes
watch(
() => console.log('State changed:', localState.data),
() => [localState.data]
);
// Return render function
return (props) => (
{props.title}
{localState.data}
);
});
```
--------------------------------
### Simplified Component Creation with createS()
Source: https://github.com/xcloudtech/rt-state/blob/master/README.md
A simplified creator for components that do not require complex setup logic. It directly accepts a render function and can utilize React Hooks or rt-state hooks within it.
```tsx
import { createS, useRState } from 'rt-state';
const SimpleComponent = createS((props) => {
// Use React hooks normally or rt-state hooks
const localState = useRState({ count: 0 });
return (
Count: {localState.count}
);
});
```
--------------------------------
### Project Build and Script Commands
Source: https://github.com/xcloudtech/rt-state/blob/master/CONTRIBUTING.md
Common npm scripts available for managing the rt-state project. These include building the library, running tests, and linting the code.
```bash
npm run build
# Build the library for production
npm run test
# Run the test suite
npm run lint
# Run ESLint
```
--------------------------------
### Running Tests
Source: https://github.com/xcloudtech/rt-state/blob/master/CONTRIBUTING.md
Provides commands to execute the project's test suite. Includes options for running all tests, enabling watch mode for continuous testing, and generating test coverage reports.
```bash
# Run all tests
npm test
# Run tests in watch mode
npm test -- --watch
# Run tests with coverage
npm test -- --coverage
```
--------------------------------
### rt-state API Reference
Source: https://github.com/xcloudtech/rt-state/blob/master/README.md
A comprehensive reference for the rt-state library's APIs, categorized by functionality. Includes state creation, component rendering, reactivity utilities, provider patterns, and helper hooks.
```APIDOC
State APIs:
state(initialValue: T): State
- Creates a reactive object state.
stateS(initialValue: T): StateS
- Creates a reactive single value state (for primitives).
stateArray(initialValue: T[]): StateArray
- Creates an optimized reactive array state.
extract(state): T
- Extracts the plain, non-reactive value from a state object.
setState(state, newValue)
- Batches state updates for performance.
Component APIs:
create(setup: (ctx: Context) => RenderFunction): React.FC
- Creates a component with context, enabling reactive setup logic.
createS(render: (props: T) => JSX.Element, config?): React.FC
- Creates a component directly from a render function, suitable for simpler components.
view(render: () => JSX.Element): JSX.Element
- Wraps a render function to enable fine-grained reactivity, re-rendering only when dependencies change.
Reactivity APIs:
watch(callback, deps, options?)
- Watches state changes and executes a callback. `deps` is a function returning an array of dependencies. `options` can include `compare: true` or `global: true`.
link(getter, setter?, options?)
- Creates computed values or links state properties. Useful for derived state and two-way binding.
hooks(callback)
- Integrates standard React hooks (e.g., useState, useEffect) into rt-state components.
Provider APIs:
createProvider(): Provider
- Creates a context provider for sharing state between components.
provider.use(): T
- Hook to access the context data provided by the nearest Provider.
Utility APIs:
useRState(initial)
- React hook version of `state`.
useRStateS(initial)
- React hook version of `stateS`.
useRStateArray(initial)
- React hook version of `stateArray`.
useOnce(callback)
- Runs a callback function exactly once, similar to `useEffect` with an empty dependency array.
```
--------------------------------
### Run Project Tests
Source: https://github.com/xcloudtech/rt-state/blob/master/CONTRIBUTING.md
Command to execute the project's test suite. It's recommended to run tests locally to ensure your changes do not break existing functionality.
```bash
npm test
```
--------------------------------
### Storybook UI Styling
Source: https://github.com/xcloudtech/rt-state/blob/master/docs/iframe.html
Provides CSS rules for styling various Storybook UI components and layouts, including preparation states, preview blocks, loaders, and error displays. It defines styles for centering, padding, and visual feedback.
```css
/* While we aren't showing the main block yet, but still preparing, we want everything the user has rendered, which may or may not be in #storybook-root, to be display none */
.sb-show-preparing-story:not(.sb-show-main) > :not(.sb-preparing-story) { display: none; }
.sb-show-preparing-docs:not(.sb-show-main) > :not(.sb-preparing-docs) { display: none; }
/* Hide our own blocks when we aren't supposed to be showing them */
:not(.sb-show-preparing-story) > .sb-preparing-story,
:not(.sb-show-preparing-docs) > .sb-preparing-docs,
:not(.sb-show-nopreview) > .sb-nopreview,
:not(.sb-show-errordisplay) > .sb-errordisplay {
display: none;
}
.sb-show-main.sb-main-centered {
margin: 0;
display: flex;
align-items: center;
min-height: 100vh;
}
.sb-show-main.sb-main-centered #storybook-root {
box-sizing: border-box;
margin: auto;
padding: 1rem;
max-height: 100%;
/* Hack for centering correctly in IE11 */
}
/* Vertical centering fix for IE11 */
@media screen and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.sb-show-main.sb-main-centered:after {
content: '';
min-height: inherit;
font-size: 0;
}
}
.sb-show-main.sb-main-fullscreen {
margin: 0;
padding: 0;
display: block;
}
.sb-show-main.sb-main-padded {
margin: 0;
padding: 1rem;
display: block;
box-sizing: border-box;
}
.sb-wrapper {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
padding: 20px;
font-family: 'Nunito Sans', -apple-system, '.SFNSText-Regular', 'San Francisco', BlinkMacSystemFont, 'Segoe UI', 'Helvetica Neue', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
overflow: auto;
}
.sb-heading {
font-size: 14px;
font-weight: 600;
letter-spacing: 0.2px;
margin: 10px 0;
padding-right: 25px;
}
.sb-nopreview {
display: flex;
align-content: center;
justify-content: center;
}
.sb-nopreview_main {
margin: auto;
padding: 30px;
border-radius: 10px;
background: rgba(0, 0, 0, 0.03);
}
.sb-nopreview_heading {
text-align: center;
}
.sb-errordisplay {
border: 20px solid rgb(187, 49, 49);
background: #222;
color: #fff;
z-index: 999999;
}
.sb-errordisplay_code {
padding: 10px;
background: #000;
color: #eee;
font-family: 'Operator Mono', 'Fira Code Retina', 'Fira Code', 'FiraCode-Retina', 'Andale Mono', 'Lucida Console', Consolas, Monaco, monospace;
}
.sb-errordisplay pre {
white-space: pre-wrap;
}
@-webkit-keyframes sb-rotate360 {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
@keyframes sb-rotate360 {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
@-webkit-keyframes sb-glow {
0%, 100% { opacity: 1; }
50% { opacity: 0.4; }
}
@keyframes sb-glow {
0%, 100% { opacity: 1; }
50% { opacity: 0.4; }
}
/* We display the preparing loaders *over* the rendering story */
.sb-preparing-story,
.sb-preparing-docs {
background-color: white;
/* Maximum possible z-index. It would be better to use stacking contexts to ensure it's always on top, but this isn't possible as it would require making CSS changes that could affect user code */
z-index: 2147483647;
}
.sb-loader {
-webkit-animation: sb-rotate360 0.7s linear infinite;
animation: sb-rotate360 0.7s linear infinite;
border-color: rgba(97, 97, 97, 0.29);
border-radius: 50%;
border-style: solid;
border-top-color: #646464;
border-width: 2px;
display: inline-block;
height: 32px;
left: 50%;
margin-left: -16px;
margin-top: -16px;
mix-blend-mode: difference;
overflow: hidden;
position: absolute;
top: 50%;
transition: all 200ms ease-out;
vertical-align: top;
width: 32px;
z-index: 4;
}
.sb-previewBlock {
background: #fff;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 4px;
box-shadow: rgba(0, 0, 0, 0.1) 0 1px 3px 0;
margin: 25px auto 40px;
max-width: 600px;
}
.sb-previewBlock_header {
align-items: center;
box-shadow: rgba(0, 0, 0, 0.1) 0 -1px 0 0 inset;
display: flex;
gap: 14px;
height: 40px;
padding: 0 12px;
}
.sb-previewBlock_icon {
-webkit-animation: sb-glow 1.5s ease-in-out infinite;
animation: sb-glow 1.5s ease-in-out infinite;
background: #e6e6e6;
height: 14px;
width: 14px;
}
.sb-previewBlock_icon:last-child {
margin-left: auto;
}
.sb-previewBlock_body {
-webkit-animation: sb-glow 1.5s ease-in-out infinite;
animation: sb-glow 1.5s ease-in-out infinite;
height: 182px;
position: absolute;
width: calc(100% - 24px);
}
```
--------------------------------
### Linting and Code Formatting
Source: https://github.com/xcloudtech/rt-state/blob/master/CONTRIBUTING.md
Commands to check code style and automatically fix linting issues using ESLint and Prettier. Maintaining code quality is essential for project health.
```bash
# Check linting
npm run lint
# Auto-fix linting issues
npm run lint -- --fix
```
--------------------------------
### Component Property Definitions
Source: https://github.com/xcloudtech/rt-state/blob/master/docs/iframe.html
Defines the structure and expected values for component properties. Each property includes its name, a short description, and a default value.
```APIDOC
propertyName*
Description: This is a short description
Default: summary
Control: defaultValue
Type: Set string
propertyName*
Description: This is a short description
Default: summary
Control: defaultValue
Type: Set string
propertyName*
Description: This is a short description
Default: summary
Control: defaultValue
Type: Set string
```
--------------------------------
### Storybook Runtime Configuration
Source: https://github.com/xcloudtech/rt-state/blob/master/docs/index.html
Sets up global Storybook runtime features, including feature flags, reference data, logging level, and documentation options. It also imports essential Storybook manager bundles for various add-ons.
```javascript
window['FEATURES'] = { "warnOnLegacyHierarchySeparator": true, "buildStoriesJson": false, "storyStoreV7": true, "argTypeTargetsV7": true, "legacyDecoratorFileOrder": false, "disallowImplicitActionsInRenderV8": false }; window['REFS'] = {}; window['LOGLEVEL'] = "info"; window['DOCS_OPTIONS'] = { "defaultName": "Docs", "autodocs": "tag" }; window['CONFIG_TYPE'] = "PRODUCTION"; import './sb-manager/runtime.js'; import './sb-addons/links-0/manager-bundle.js'; import './sb-addons/essentials-controls-1/manager-bundle.js'; import './sb-addons/essentials-actions-2/manager-bundle.js'; import './sb-addons/essentials-backgrounds-3/manager-bundle.js'; import './sb-addons/essentials-viewport-4/manager-bundle.js'; import './sb-addons/essentials-toolbars-5/manager-bundle.js'; import './sb-addons/essentials-measure-6/manager-bundle.js'; import './sb-addons/essentials-outline-7/manager-bundle.js'; import './sb-addons/onboarding-8/manager-bundle.js'; import './sb-addons/interactions-9/manager-bundle.js';
```
--------------------------------
### Configure Storybook Global Variables
Source: https://github.com/xcloudtech/rt-state/blob/master/docs/iframe.html
Sets global configuration variables for Storybook, including environment type, log level, framework options, feature flags, and story definitions. It also includes a fallback for module.hot and global window assignment.
```javascript
window.CONFIG_TYPE = 'PRODUCTION';
window.LOGLEVEL = 'info';
window.FRAMEWORK_OPTIONS = {};
window.CHANNEL_OPTIONS = {};
window.FEATURES = {
"warnOnLegacyHierarchySeparator": true,
"buildStoriesJson": false,
"storyStoreV7": true,
"argTypeTargetsV7": true,
"legacyDecoratorFileOrder": false,
"disallowImplicitActionsInRenderV8": false
};
window.STORIES = [
{
"titlePrefix": "",
"directory": "./src/stories",
"files": "*.stories.tsx",
"importPathMatcher": "^\\.[\\\\/](?:src\\/stories\\/(?!\\.)(?=.)[^/]*?\\.stories\\.tsx)$"
}
];
window.DOCS_OPTIONS = {
"defaultName": "Docs",
"autodocs": "tag"
};
// We do this so that "module && module.hot" etc. in Storybook source code
// doesn't fail (it will simply be disabled)
window.module = undefined;
window.global = window;
```
--------------------------------
### Migration from `useContext` to rt-state Provider
Source: https://github.com/xcloudtech/rt-state/blob/master/README.md
Illustrates how to migrate from React's `useContext` API to rt-state's `createProvider` pattern for managing and accessing shared state across components.
```tsx
// Before (useContext)
const ThemeContext = createContext();
const theme = useContext(ThemeContext);
// After (rt-state)
const ThemeProvider = createProvider<{ theme: string }>();
const theme = ThemeProvider.use();
```
--------------------------------
### Watching State Changes with `watch`
Source: https://github.com/xcloudtech/rt-state/blob/master/README.md
Demonstrates how to watch for state changes in rt-state. It shows how to watch specific dependencies within components and how to set up global watchers. The `compare: true` option allows comparing old and new values.
```tsx
const data = state({ count: 0, name: 'test' });
// Watch specific dependencies
const watcher = watch(
() => console.log('Count changed:', data.count),
() => [data.count], // Only triggers when count changes
{ compare: true } // Compare old vs new values
);
// Global watchers (outside components)
watch(
() => console.log('Global state changed'),
() => [globalState.value],
{ global: true }
);
```
--------------------------------
### Create Feature or Fix Branch
Source: https://github.com/xcloudtech/rt-state/blob/master/CONTRIBUTING.md
Commands to create a new Git branch for your work. It's standard practice to name branches descriptively, indicating whether it's a feature, fix, or documentation change.
```bash
git checkout -b feature/your-feature-name
# or
git checkout -b fix/issue-number-description
```
--------------------------------
### TypeScript Coding Standards
Source: https://github.com/xcloudtech/rt-state/blob/master/CONTRIBUTING.md
Guidelines for writing TypeScript code within the rt-state project. Emphasizes type safety, avoiding 'any', and exporting necessary types.
```typescript
// Use TypeScript for all new code
// Provide proper type annotations
// Avoid 'any' types unless absolutely necessary
// Export types and interfaces that might be useful to consumers
```
--------------------------------
### Development Tool Integration
Source: https://github.com/xcloudtech/rt-state/blob/master/docs/iframe.html
A JavaScript snippet designed to connect development tools (like React DevTools or Vue DevTools) across different frames, ensuring they can inspect components in the top frame.
```javascript
try {
if (window.top !== window) {
window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = window.top.__REACT_DEVTOOLS_GLOBAL_HOOK__;
window.__VUE_DEVTOOLS_GLOBAL_HOOK__ = window.top.__VUE_DEVTOOLS_GLOBAL_HOOK__;
window.top.__VUE_DEVTOOLS_CONTEXT__ = window.document;
}
} catch (e) {
// eslint-disable-next-line no-console
console.warn('unable to connect to top frame for connecting dev tools');
}
```
--------------------------------
### Rebase Branch on Upstream Main
Source: https://github.com/xcloudtech/rt-state/blob/master/CONTRIBUTING.md
Instructions for updating your local feature branch with the latest changes from the upstream main branch. This helps prevent merge conflicts.
```bash
git fetch upstream
git rebase upstream/main
```
--------------------------------
### Provider Pattern for Context
Source: https://github.com/xcloudtech/rt-state/blob/master/README.md
Illustrates the provider pattern in rt-state for sharing state across components. It covers creating a provider, providing values from a parent component, and consuming those values in child components using `DataProvider.use()`.
```tsx
// Create a provider
const DataProvider = createProvider<{ user: User }>();
// Use in parent component
const ParentComponent = create((ctx) => {
const userData = state({ user: currentUser });
return (props) => (
);
});
// Access in child components
const ChildComponent = create((ctx) => {
const parentData = DataProvider.use(); // Accesses parent's userData
return () =>
User: {parentData.user.name}
;
});
```
--------------------------------
### Migration from `useEffect` to rt-state `watch`
Source: https://github.com/xcloudtech/rt-state/blob/master/README.md
Demonstrates the conversion of `useEffect` hooks that depend on state changes to rt-state's `watch` function, providing a more declarative way to handle side effects based on reactive data.
```tsx
// Before (useEffect)
useEffect(() => {
console.log('Count changed:', count);
}, [count]);
// After (rt-state)
watch(
() => console.log('Count changed:', count.value),
() => [count.value]
);
```
--------------------------------
### Migration from `useState` to rt-state
Source: https://github.com/xcloudtech/rt-state/blob/master/README.md
Shows the transformation of code from using React's built-in `useState` hook to rt-state's reactive state primitives. It highlights the simplified syntax for state updates.
```tsx
// Before (useState)
const [count, setCount] = useState(0);
const increment = useCallback(() => setCount(c => c + 1), []);
// After (rt-state)
const count = stateS(0);
const increment = () => count.value++;
```
--------------------------------
### Fine-Grained Reactivity with `view`
Source: https://github.com/xcloudtech/rt-state/blob/master/README.md
Demonstrates how to achieve ultra-fine control over re-renders using the `view()` function. It ensures that only the specific parts of the JSX that depend on reactive state actually re-render when that state changes.
```tsx
const data = state({ x: 1, y: 2, z: 3 });
const Component = createS(() => (
{/* Only re-renders when data.x changes */}
{view(() => X: {data.x})}
{/* Only re-renders when data.y changes */}
{view(() => Y: {data.y})}
{/* This div never re-renders unless props change */}
Static content
));
```
--------------------------------
### Integrating React Hooks with `hooks`
Source: https://github.com/xcloudtech/rt-state/blob/master/README.md
Explains how to integrate existing React hooks (like `useState` and `useEffect`) within rt-state components using the `hooks()` function. This allows seamless use of React's lifecycle and state management within the rt-state framework.
```tsx
const MyComponent = create((ctx) => {
// Wrap React hooks in the hooks() function
const [reactState, setReactState] = hooks(() =>
React.useState('initial')
);
const effectRef = hooks(() => {
React.useEffect(() => {
console.log('Effect ran');
}, []);
});
return () =>
{reactState}
;
});
```
--------------------------------
### Object State Management with state()
Source: https://github.com/xcloudtech/rt-state/blob/master/README.md
Manages object state, tracking field-level changes for fine-grained reactivity. When updating nested objects, it's recommended to change the reference to ensure reactivity.
```tsx
const data = state({ name: 'John', age: 25, city: 'NYC' });
// Only components using `name` will re-render
data.name = 'Jane';
// For nested objects, change the reference
data.address = { ...data.address, street: 'New Street' };
```
--------------------------------
### Storybook UI Hiding Rule
Source: https://github.com/xcloudtech/rt-state/blob/master/docs/index.html
A CSS rule designed to hide the main Storybook root element. This is often used to prevent the Storybook UI from rendering in specific contexts or for testing purposes.
```css
#storybook-root[hidden] { display: none !important; }
```
--------------------------------
### Single Value State Management with stateS()
Source: https://github.com/xcloudtech/rt-state/blob/master/README.md
Manages primitive values or entire state objects, allowing direct value updates or forced updates. This is suitable for simple state variables where tracking individual fields is not necessary.
```tsx
const count = stateS(0);
const message = stateS('Hello');
const items = stateS([1, 2, 3]);
// Update the value
count.value = 10;
message.value = 'World';
items.value = [...items.value, 4];
// Force update without changing value
count.forceUpdate();
```
--------------------------------
### Array State Management with stateArray()
Source: https://github.com/xcloudtech/rt-state/blob/master/README.md
Optimized for large arrays, providing item-level reactivity. This allows components rendering specific array items to re-render only when their particular item changes, improving performance.
```tsx
const longList = stateArray([
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
// ... many items
]);
// Only the specific item component re-renders
longList.getItem(0).name = 'Updated Item 1';
```
--------------------------------
### Computed Values with link()
Source: https://github.com/xcloudtech/rt-state/blob/master/README.md
Creates a computed state property that derives its value from other states using a getter function. It also supports a setter function to update the source states, enabling two-way binding for derived values.
```tsx
import { stateS, link } from 'rt-state';
const firstName = stateS('John');
const lastName = stateS('Doe');
const fullName = link(
() => `${firstName.value} ${lastName.value}`, // getter
(value: string) => { // setter
const [first, last] = value.split(' ');
firstName.value = first;
lastName.value = last;
}
);
// Use like a regular state
console.log(fullName.value); // "John Doe"
fullName.value = "Jane Smith"; // Updates both firstName and lastName
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.