open-index/open-npm huggingface dataset:
npm package: @silyze/combine-abort-signals
Description: A function that combines multiple abort signals into one
Author: Mihail Mojsoski
Latest version: 1.0.0

# Combine Abort Signals

A function that combines multiple abort signals into one.

## Install

```bash
npm install @silyze/combine-abort-signals
```

## Usage

Import and use it in your project:

```ts
import combineAbortSignals from "@silyze/combine-abort-signals";

const first = new AbortController();
const second = new AbortController();

const signal = combineAbortSignals(first.signal, second.signal);

if (Math.random() < 0.5) {
  first.abort();
} else {
  second.abort();
}

if (signal.aborted) {
  console.log("OK!");
} else {
  throw new Error("This should be unreachable");
}
```

## API

### `combineAbortSignals(...signals: (AbortSignal | undefined)[]): AbortSignal`

Creates a new `AbortSignal` that is aborted when any of the provided signals is aborted.

- Accepts `undefined` entries and ignores them.
- Aborts with the same reason as the first signal to abort.
- Useful for combining cancellation logic from multiple sources.
npm package: @silyze/kb
Description: AI Knowledge Base Interface
Author: Mihail Mojsoski
Latest version: 1.0.3

# @silyze/kb

**AI Knowledge Base Interface** – A modular framework for creating, embedding, and querying document-based knowledge bases with pluggable vector stores and embedding providers.

---

## Features

- Document-agnostic knowledge base structure
- Stream-based processing for scalability
- Customizable vector store and embedding provider interfaces
- Async document scanning and embedding
- Query support with filtering and pagination

---

## Installation

```bash
npm install @silyze/kb
```

---

## Quick Start

```ts
import {
  KnowledgeBase,
  VectorStore,
  EmbeddingProvider,
  DocumentScanner,
} from "@silyze/kb";
```

### Create and Use a Knowledge Base

```ts
const kb = new KnowledgeBase({
  vectorStore: myVectorStore,
  embeddingProvider: myEmbeddingProvider,
});

await kb.createDocument(
  { title: "My Document" },
  myDocumentScanner
  /* source items here */
);

const results = kb.query("What is this about?");
for await (const match of results) {
  console.log(match.text, match.distance);
}
```

---

## API Reference

### `KnowledgeBase`

```ts
new KnowledgeBase({ vectorStore, embeddingProvider });
```

#### `createDocument(info, scanner, ...sources)`

- `info`: Metadata for the document (excluding `id`)
- `scanner`: A `DocumentScanner<T>` to extract text chunks
- `sources`: Input data passed to the scanner

Processes the document and stores its embeddings in the vector store.

#### `query(text, documents?, limit?, offset?)`

Performs a semantic search over indexed documents.

---

### `DocumentScanner<T>`

```ts
abstract class DocumentScanner<T> {
  abstract scan(input: T): AsyncReadStream<string>;
}
```

Implement this to extract text chunks from custom document formats.

---

### `EmbeddingProvider`

```ts
abstract class EmbeddingProvider {
  abstract create(text: string): Promise<Embedding>;
}
```

Produces a vector embedding for a given text.

---

### `VectorStore`

```ts
abstract class VectorStore<TDocumentReference, TDocument> {
  query(
    vector,
    documents?,
    limit?,
    offset?
  ): AsyncReadStream<EmbeddingResult<TDocumentReference>>;
  append(document, embeddings: AsyncReadStream<Embedding>): Promise<void>;
  delete(document): Promise<void>;
  createDocument(document: Omit<TDocument, "id">): Promise<TDocumentReference>;
  getDocuments(): AsyncReadStream<TDocument>;
}
```

Defines the persistence and search behavior for embeddings and documents.

---

## Types

- `Embedding`: `{ text: string; vector: number[] }`
- `EmbeddingResult<T>`: Extends `Embedding` with `{ distance: number; document: T }`
npm package: @silyze/kb-embedding-openai
Description: OpenAI implementation of EmbeddingProvider for @silyze/kb
Author: Mihail Mojsoski
Latest version: 1.0.0

# @silyze/kb-embedding-openai

**OpenAI Embedding Provider for [`@silyze/kb`](https://www.npmjs.com/package/@silyze/kb)**

This package provides an implementation of the `EmbeddingProvider` interface from `@silyze/kb`, using OpenAI's embedding API.

---

## Features

- Plug-and-play embedding provider for `@silyze/kb`
- Supports OpenAI's latest embedding models
- Lightweight and easy to configure

---

## Installation

```bash
npm install @silyze/kb-embedding-openai
```

---

## Usage

```ts
import OpenAiEmbeddingProvider from "@silyze/kb-embedding-openai";

const provider = new OpenAiEmbeddingProvider();

provider
  .create("Hello, world!")
  .then((embedding) => {
    console.log("Embedding created:", embedding);
  })
  .catch((error) => {
    console.error("Error creating embedding:", error);
  });
```

---

## Configuration

You can optionally pass a configuration object when creating the provider:

```ts
new OpenAiEmbeddingProvider({
  apiKey: "your-api-key-here",
  model: "text-embedding-3-large",
});
```

If no API key is provided, the provider will fall back to the `OPENAI_API_KEY` environment variable.

### Available Configuration Options

| Option | Type     | Default                      | Description                         |
| ------ | -------- | ---------------------------- | ----------------------------------- |
| apiKey | `string` | `process.env.OPENAI_API_KEY` | Your OpenAI API key.                |
| model  | `string` | `"text-embedding-3-small"`   | OpenAI model to use for embeddings. |

See [OpenAI's docs](https://platform.openai.com/docs/guides/embeddings) for available embedding models.

---

## API

### `new OpenAiEmbeddingProvider(config?)`

Creates a new instance of the provider.

### `create(text: string): Promise<Embedding>`

Generates an embedding for the given text. Returns a Promise resolving to:

```ts
{
  text: string;
  vector: number[];
}
```

---

## Example Output

```json
{
  "text": "Hello, world!",
  "vector": [0.0123, 0.9876, ..., 0.4567]
}
```
npm package: @silyze/kb-scanner-csv
Description: CSV implementation of DocumentScanner<T> for @silyze/kb
Author: Mihail Mojsoski
Latest version: 1.0.0

# @silyze/kb-scanner-csv

**CSV implementation of `DocumentScanner<T>` for `@silyze/kb`**, built on top of `csv-parser` and `@silyze/kb-scanner-text`.

## Features

- Parses CSV strings into structured rows.
- Converts rows into readable text format.
- Uses token-based chunking via `TextScanner` for embedding compatibility.
- Fully async via `AsyncReadStream` and `AsyncTransform`.

## Installation

```bash
npm install @silyze/kb-scanner-csv
```

## Usage

```ts
import CsvScanner from "@silyze/kb-scanner-csv";

const scanner = new CsvScanner();

const csv = `name,age
Mihail,24
Simeon,24`;

async function run() {
  const chunks = await scanner.scan(csv).transform().toArray();

  console.log(chunks);
}

run().then();
```

## Configuration

`CsvScanner` supports the same configuration options as `TextScanner`, plus any options from [`csv-parser`](https://www.npmjs.com/package/csv-parser):

```ts
type CsvScannerConfig = TextScannerConfig & csv.Options;
```

Examples:

- `tokensPerPage`: Number of tokens per chunk (default: 512).
- `overlap`: Chunk overlap (e.g., `0.5` for 50%).
- `model`: OpenAI model passed to `tiktoken`.
- `separator`: CSV column separator (e.g., `;` or `,`).

## How it works

1. Accepts a CSV string as input.
2. Parses rows using `csv-parser`.
3. Converts each row to a key=value string.
4. Joins all rows into a single text block.
5. Scans and chunks it using `TextScanner`.

This allows structured tabular data to be processed and embedded similarly to raw text, enabling it to work seamlessly in the `@silyze/kb` pipeline.

## Example Output

For the input:

```csv
name,age
Mihail,24
Simeon,24
```

Output after scan and transform may be:

```ts
['name="Mihail",age="24"\nname="Simeon",age="24"'];
```

The text will be chunked based on your configured token size and overlap.
npm package: @silyze/kb-scanner-html
Description: HTML implementation of DocumentScanner<T> for @silyze/kb
Author: Mihail Mojsoski
Latest version: 1.0.0

# @silyze/kb-scanner-html

**HTML implementation of `DocumentScanner<T>` for `@silyze/kb`**, using [`jsdom`](https://www.npmjs.com/package/jsdom) to extract visible text content and [`TextScanner`](https://www.npmjs.com/package/@silyze/kb-scanner-text) for token-based chunking.

## Features

- Parses HTML strings and extracts visible text via `innerText`.
- Automatically includes nested element content in reading order.
- Uses `TextScanner` to split extracted text into token-based chunks compatible with OpenAI’s `tiktoken`.
- Fully async via `AsyncReadStream`.

## Installation

```bash
npm install @silyze/kb-scanner-html
```

## Usage

```ts
import HtmlScanner from "@silyze/kb-scanner-html";

const scanner = new HtmlScanner();

const html = `<h1>Hello World!<div>2</div></h1>`;

async function run() {
  const chunks = await scanner.scan(html).transform().toArray();
  console.log(chunks);
}

run().then();
```

Output:

```ts
["Hello World!2"];
```

## Configuration

`HtmlScanner` accepts all [`TextScanner`](https://www.npmjs.com/package/@silyze/kb-scanner-text) configuration options:

```ts
type HtmlScannerConfig = TextScannerConfig;
```

Examples:

- `tokensPerPage` – tokens per chunk (default: `512`)
- `overlap` – overlap ratio or count (default: `0.5`)
- `model` – tokenizer model name (default: `"text-embedding-3-small"`)
- `encoding` – text encoding (default: `"utf-8"`)

## How It Works

1. Parses the HTML string using `jsdom`.
2. Reads `innerText` from each document child to capture visible text in reading order, including nested elements.
3. Joins all extracted text with newlines.
4. Passes the combined text into `TextScanner` for token-based chunking.

## Example

For:

```html
<h1>
  Hello World!
  <div>2</div>
</h1>
<p>This is an HTML example.</p>
```

You might get:

```ts
["Hello World!2\nThis is an HTML example."];
```

Longer HTML documents will be chunked according to your configured token size and overlap.
npm package: @silyze/kb-scanner-md
Description: Markdown implementation of DocumentScanner<T> for @silyze/kb
Author: Mihail Mojsoski
Latest version: 1.0.0

# @silyze/kb-scanner-md

**Markdown implementation of `DocumentScanner<T>` for `@silyze/kb`**, using [`marked`](https://www.npmjs.com/package/marked) to convert Markdown to HTML, then [`HtmlScanner`](https://www.npmjs.com/package/@silyze/kb-scanner-html) to extract visible text and chunk it for AI embedding.

## Features

- Converts Markdown to HTML using `marked`.
- Extracts visible text from the HTML using `HtmlScanner` (`jsdom` + `innerText`).
- Splits text into token-based chunks via `TextScanner`, compatible with OpenAI’s `tiktoken`.
- Fully async via `AsyncReadStream`.

## Installation

```bash
npm install @silyze/kb-scanner-md
```

## Usage

```ts
import MarkdownScanner from "@silyze/kb-scanner-md";

const scanner = new MarkdownScanner();

const md = `
# Hello World
This is a **Markdown** document.
`;

async function run() {
  const chunks = await scanner.scan(md).transform().toArray();
  console.log(chunks);
}

run().then();
```

Output:

```ts
["Hello World\nThis is a Markdown document."];
```

## Configuration

`MarkdownScanner` accepts the same configuration options as [`TextScanner`](https://www.npmjs.com/package/@silyze/kb-scanner-text):

```ts
type MarkdownScannerConfig = TextScannerConfig;
```

Examples:

- `tokensPerPage` – tokens per chunk (default: `512`)
- `overlap` – overlap ratio or count (default: `0.5`)
- `model` – tokenizer model name (default: `"text-embedding-3-small"`)
- `encoding` – text encoding (default: `"utf-8"`)

## How It Works

1. Parses Markdown into HTML via `marked`.
2. Feeds the HTML into `HtmlScanner`.
3. Extracts visible text with `innerText`.
4. Passes text into `TextScanner` for token-based chunking.
5. Returns an `AsyncReadStream<string>` of chunks.

## Example

For:

```md
# Hello

**Bold** and _italic_ text.
```

Output might be:

```ts
["Hello\nBold and italic text."];
```

Longer documents are automatically chunked according to your token configuration.
npm package: @silyze/kb-scanner-text
Description: Text implementation for DocumentScanner<T> for @silyze/kb
Author: Mihail Mojsoski
Latest version: 1.0.2

# @silyze/kb-scanner-text

**Text implementation of `DocumentScanner<T>` for `@silyze/kb`**, using token-based chunking compatible with OpenAI's `tiktoken`.

## Features

- Splits raw text or `Uint8Array` input into token-based chunks.
- Configurable token stride and overlap.
- Supports multiple OpenAI models via `tiktoken`.
- Fully async via `AsyncReadStream` and `AsyncTransform` utilities.

## Installation

```bash
npm install @silyze/kb-scanner-text
```

## Usage

```ts
import TextScanner from "@silyze/kb-scanner-text";

const scanner = new TextScanner({
  model: "text-embedding-3-small", // optional
  tokensPerPage: 512, // optional
  overlap: 0.5, // optional: 50% overlap
});

async function run() {
  const input = "The quick brown fox jumps over the lazy dog.";
  const chunks = await scanner.scan(input).transform().toArray();

  console.log(chunks);
}

run().then();
```

## Configuration

`TextScanner` accepts the following optional configuration:

```ts
type TextScannerConfig = {
  encoding?: string; // default: "utf-8"
  tokensPerPage?: number; // default: 512
  model?: TiktokenModel; // default: "text-embedding-3-small"
  overlap?: number; // default: 0.5 (50%)
};
```

- `encoding`: Text encoding for `Uint8Array` input.
- `tokensPerPage`: Number of tokens per chunk.
- `overlap`: Overlap between chunks — can be a float (ratio) or integer (absolute).
- `model`: Model name passed to `tiktoken.encoding_for_model()`.

## How it works

1. Accepts a string or `Uint8Array` input.
2. Cleans up and tokenizes the text using `tiktoken`.
3. Chunks the token list using sliding windows, with optional overlap.
4. Decodes each chunk and yields it as a string via an `AsyncReadStream`.

This is designed to work as a plugin for the `@silyze/kb` knowledge base system, where documents need to be scanned and embedded for vector search.

## Example Output

Given a basic string:

```ts
await scanner.scan("Hello world! This is a test.").transform().toArray();
```

You might get:

```ts
["Hello world! This is a test."];
```

Longer input will be chunked according to `tokensPerPage` and `overlap`.
npm package: @silyze/pg-utils
Description: Utility functions for PostgreSQL
Author: Simeon Markoski, Mihail Mojsoski
Latest version: 1.1.0

# pg-utils

**pg-utils** is a Node.js library designed to simplify interactions with PostgreSQL databases by providing convenient functions for common tasks such as inserting, updating, querying, and error handling. This package utilizes the popular `pg` library for database connections.

## Installation

You can install **pg-utils** via npm:

```bash
npm install pg-utils
```

## Usage

### Importing

```javascript
import { Pool } from 'pg';
import { insert, update, has, getValue } from 'pg-utils';
```

### Connecting to PostgreSQL

Before using any functions, make sure you have established a connection to your PostgreSQL database using `pg.Pool`.

```javascript
const pool = new Pool({
  // Your PostgreSQL connection configuration
});
```

### Inserting Data

```javascript
const tempData = { /* Data to be inserted */ };
const tableName = 'your_table_name';

// Insert data into the specified table
const result = await insert(pool, tempData, tableName);

// Optionally, specify columns to return after insertion
const columnsToReturn = ['id', 'name'];
const resultWithReturn = await insert(pool, tempData, tableName, columnsToReturn);
```

### Updating Data

```javascript
const updateData = { /* Updated data */ };
const tableName = 'your_table_name';
const whereClause = [['id', 123]]; // Example WHERE clause

await update(pool, updateData, tableName, whereClause);
```

### Querying Data

```javascript
const query = 'SELECT * FROM your_table WHERE condition = true';

// Check if any data exists based on the query
const exists = await has(pool, query);

// Get data based on the query
const data = await getValue(pool, query);
```

### Error Handling

The package provides custom error handling with `ThrowError` class, which extends `Error`.

```javascript
try {
  // Your code using pg-utils functions
} catch (error) {
  if (error instanceof ThrowError) {
    console.error('Query execution failed:', error.query);
  } else {
    console.error('An unexpected error occurred:', error);
  }
}
```

## Contributing

Contributions are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request.

## License

This project is licensed under the [MIT License](LICENSE).
npm package: @silyze/resolver
Description: Promise.withResolvers() wrapper and polyfill
Author: Mihail Mojsoski
Latest version: 1.0.0

# @silyze/resolver

A minimal wrapper around `Promise.withResolvers()` with a built-in polyfill for environments that do not yet support the native API.

This utility allows you to obtain a `promise`, `resolve`, and `reject` object in a clean and consistent way.

## Features

- Uses native `Promise.withResolvers()` when available (Node 22+, modern browsers)
- Falls back to a spec-compliant polyfill when not available
- Type-safe with full TypeScript support
- Lightweight and dependency-free
- Supports both CommonJS and ES Modules

## Installation

```bash
npm install @silyze/resolver
```

## Usage

```ts
import createResolver from "@silyze/resolver";

const { promise, resolve, reject } = createResolver<number>();

setTimeout(() => resolve(42), 1000);

const result = await promise; // 42
```

## API

### `createResolver<T>(): ResolverWithPromise<T>`

Returns an object with the following properties:

| Property  | Type                     | Description                                |                      |
| --------- | ------------------------ | ------------------------------------------ | -------------------- |
| `promise` | `Promise<T>`             | The promise that can be awaited or chained |                      |
| `resolve` | \`(value: T              | PromiseLike<T>) => void\`                  | Resolves the promise |
| `reject`  | `(error: Error) => void` | Rejects the promise                        |                      |

### Example

```ts
const { promise, resolve, reject } = createResolver<string>();

someStream.on("data", resolve);
someStream.on("error", reject);

try {
  const data = await promise;
  console.log("Received:", data);
} catch (err) {
  console.error("Stream failed:", err);
}
```

## Polyfill Behavior

If `Promise.withResolvers()` is not available, this package will fall back to an internal implementation using `new Promise()`.

### Compatibility

| Environment     | Native Support | Works with @silyze/resolver |
| --------------- | -------------- | --------------------------- |
| Node.js 22+     | Yes            | Yes (uses native)           |
| Node.js 14–21   | No             | Yes (uses polyfill)         |
| Modern Browsers | Yes            | Yes                         |
| Older Browsers  | No             | Yes                         |

## Type Definitions

```ts
export type Resolver<T> = {
  resolve: (value: T | PromiseLike<T>) => void;
  reject: (error: Error) => void;
};

export type ResolverWithPromise<T> = Resolver<T> & {
  promise: Promise<T>;
};
```
npm package: @silyze/soft-removable-repository
Description: Soft removable extensions for @mojsoski/ormm
Author: Mihail Mojsoski
Latest version: 1.0.0

# Soft Removable Repository

Soft-delete (soft-remove) extensions for `@mojsoski/ormm`, built on top of `@silyze/batch-repository`. Automatically filters out records marked as removed and provides batch soft-delete support.

## Installation

```bash
npm install @silyze/soft-removable-repository
```

## Usage

Extend `SoftRemovableRepository` for your model to inherit soft-delete behavior:

```ts
import SoftRemovableRepository, {
  SoftRemovable,
} from "@silyze/soft-removable-repository";

interface UserModel extends SoftRemovable {
  name: string;
  email: string;
}

class UserRepository extends SoftRemovableRepository<"users", UserModel> {}

const repo = new UserRepository();
```

All standard repository methods (`getById`, `list`, `count`, `update`, `remove`) will now automatically exclude records where `removed === true`.

## API Reference

### Model Interface

```ts
export interface SoftRemovable<T extends object = object>
  extends IBaseModel<T> {
  removed?: boolean;
}
```

- **removed**: Optional flag indicating soft deletion.

### `class SoftRemovableRepository<Table extends string, T extends SoftRemovable>`

Extends `BatchRepository<Table, T>` and overrides core methods to respect the `removed` flag.

#### `getById(id: string): Promise<T | null>`

Fetch a record by `id`. Returns `null` if the record is marked as removed or does not exist.

#### `list(where: WhereFilter<T>, pagination?: PaginationFilter, order?: OrderFilter<T>): Promise<T[]>`

List records matching the `where` filter, automatically adding `removed: false` to the criteria.

- **where**: Conditions to filter records (excluding removed ones).
- **pagination**: Optional pagination (`limit`, `offset`).
- **order**: Optional ordering.

#### `count(where: WhereFilter<T>): Promise<number>`

Count records matching the `where` filter, excluding removed ones.

#### `update(update: UpdateFilter<T>, where: WhereFilter<T>): Promise<string[]>`

Update records matching `where`, excluding those marked as removed. Returns updated IDs.

#### `remove(where: WhereFilter<T>): Promise<string[]>`

Soft-delete matching records by setting `removed = true`. Returns the affected record IDs.

#### `removeBatch(ids: string[]): Promise<string[]>`

Batch soft-delete by IDs, issuing a single `UPDATE ... WHERE id IN (...)`. Returns the list of IDs that were flagged removed.

#### `createBatch`, `updateBatch`

Inherited from `BatchRepository`, unaffected by the `removed` flag.

## Examples

```ts
// Soft-delete a single record
const deletedIds = await repo.remove({ id: "123" });
console.log(deletedIds); // ["123"]

// Attempt to fetch a removed record
const user = await repo.getById("123");
console.log(user); // null

// List active users only
const users = await repo.list({});

// Restore or update non-removed records
await repo.update({ email: "new@example.com" }, { id: "456" });

// Batch soft-delete
const batchDeleted = await repo.removeBatch(["123", "456", "789"]);
console.log(batchDeleted); // ["123", "456", "789"]
```
npm package: @silyze/typed-event-target
Description: A typed EventTarget implementation
Author: Mihail Mojsoski
Latest version: 1.0.0

# Typed Event Target

A strongly-typed `EventTarget` implementation for TypeScript, enabling type-safe event listening and dispatching.

## Installation

```bash
npm install @silyze/typed-event-target
```

## Usage

```ts
import createEventTarget from "@silyze/typed-event-target";

// Define a custom event
class MyEvent extends Event {
  constructor(public detail: { message: string }) {
    super("my-event");
  }
}

// Create a typed event target for MyEvent and event type "my-event"
const target = createEventTarget<MyEvent, "my-event">();

target.addEventListener("my-event", (event) => {
  console.log(event.detail.message);
});

target.dispatchEvent(new MyEvent({ message: "Hello, world!" }));
```

## API Reference

### `createEventTarget<TEvent extends Event, TEventType extends string>(): TypedEventTarget<TEvent, TEventType>`

Creates a new typed event target instance.

- **Returns**: `TypedEventTarget<TEvent, TEventType>`

### `TypedEventTarget<TEvent, TEventType>`

Extends the standard `EventTarget` API with TypeScript type safety.

#### `addEventListener(type: TEventType, listener: TypedEventListenerOrEventListenerObject<TEvent> | null): void`

Registers an event listener for the specified event type.

- **type**: The event type string.
- **listener**: A callback function or object with a `handleEvent` method.

#### `removeEventListener(type: TEventType, listener: TypedEventListenerOrEventListenerObject<TEvent> | null): void`

Removes a previously registered event listener.

- **type**: The event type string.
- **listener**: The same listener passed to `addEventListener`.

#### `dispatchEvent(event: TEvent): boolean`

Dispatches an event to all listeners of its type.

- **event**: An instance of `TEvent` whose `type` matches `TEventType`.
- **Returns**: `false` if `event.defaultPrevented` is `true` or if there are no listeners; otherwise `true`.

## Types

- `TypedEventListener<T>`: `(evt: T) => void`
- `TypedEventListenerObject<T>`: `{ handleEvent(object: T): void }`
- `TypedEventListenerOrEventListenerObject<T>`: `TypedEventListener<T> | TypedEventListenerObject<T>`
- `TypedEventTarget<TEvent, TEventType>`: The main interface extending `EventTarget` with typed methods.

## Example with Class Listener

```ts
import createEventTarget from "@silyze/typed-event-target";

class DataEvent extends Event {
  constructor(public data: number[]) {
    super("data");
  }
}

class DataHandler {
  handleEvent(event: DataEvent) {
    console.log("Received data:", event.data);
  }
}

const dataTarget = createEventTarget<DataEvent, "data">();
const handler = new DataHandler();
dataTarget.addEventListener("data", handler);

dataTarget.dispatchEvent(new DataEvent([1, 2, 3]));

dataTarget.removeEventListener("data", handler);
```
npm package: @sim-design/form
Description: ## 快速开始
Author: yanxiangang1986
Latest version: 1.1.2

# 表单通用组件

## 快速开始

```
npm install @sim-design/form --save
```

## 参数

| 参数           | 说明                          | 类型      |
| -------------- | ----------------------------- | --------- |
| formId         | 表单 id                       | string    |
| onOk           | 表单回调，返回 key:value 对象 | Function  |
| FormCheckType  | 考核规则。对象字符串          | string    |
| FormKeys       | 正确答案                      | string    |
| FormScores     | 得分规则。对象字符串          | string    |
| FormDataSource | 映射数据源。对象字符串        | string    |
| showCorrect    | 显示对错图标                  | Boolean   |
| dragProps      | 拖拽区相关配置项              | dragProps |
| dropProps      | 放置区相关配置项              | dragProps |

## dragProps

| 参数           | 说明                   | 类型          |
| -------------- | ---------------------- | ------------- |
| titleStyle     | 面板标题样式           | CSSProperties |
| panelStyle     | 面板样式               | CSSProperties |
| contentStyle   | 面板拖拽源父类容器样式 | CSSProperties |
| itemWrapStyle  | 单个拖拽源容器默认样式 | CSSProperties |
| itemStyle      | 选项默认样式           | CSSProperties |
| itemHoverStyle | 选项默认选中样式       | CSSProperties |
| itemDelStyle   | 选项被删除时样式       | CSSProperties |

## dropProps

| 参数 | 说明 | 类型 |
| itemWrapStyle | 单个列表容器默认样式 | CSSProperties |
| itemStyle | 单个列表默认样式 | CSSProperties |
| itemHoverStyle | 单个列表选中样式 | CSSProperties |
| itemDelSrc | 单项删除图片 | string |

```
panelTitleStyle示例：
{
    fontSize:1rem;
    color:red;
}

panelStyle示例：
{
    background: #fff;
    padding: 10px;
    margin: 20px;
}
```

## Ref 方法实例

你可以通过 ref 获取数据域

| 参数           | 说明                | 类型   |
| -------------- | ------------------- | ------ |
| getFieldsValue | 获取提交数据        | Object |
| getFormScore   | 获取表单得分信息 id | Object |

## 用法示例

```
import {useState,useRef} from 'react'
import SimForm from "@sim-design/form";

const Demo = (props) => {

    const [showCorrect, setShowCorrect] = useState(false)

    const formRef = useRef()

    // 获取得分和提交记录
    //const values = formRef?.current.getFieldsValue()
    //const values = formRef?.current.getFormScore()

    return <SimForm ref={formRef} formId="123123123" showCorrect={showCorrect} />
}
```