> ## Documentation Index
> Fetch the complete documentation index at: https://docs.supernote.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Element Operations

> Read, create, insert, modify, and replace Elements in NOTE/DOC files.

`Element` is the unified data structure for “all visible elements” in NOTE/DOC: strokes, titles, links, TextBox elements, geometries, five-star elements, pictures, etc. are all represented as `Element`, and distinguished by `type`.

* Element types and fields: [`Element`](https://docs.supernote.com/en/api-reference/supernote-plugin/types/trail)
* Type constants: [`ElementType`](https://docs.supernote.com/en/api-reference/supernote-plugin/types/trail#elementtype)

This chapter provides a reusable workflow around the following capabilities:

* Get page elements: [`PluginFileAPI.getElements`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-file-api/get-page-trails)
* Create a new element object: [`PluginCommAPI.createElement`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-comm-api/create-trail)
* Insert element：[`PluginFileAPI.insertElements`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-file-api/insert-trails)
* Modify element：[`PluginFileAPI.modifyElements`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-file-api/modify-trails)
* Replace all elements on a page: [`PluginFileAPI.replaceElements`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-file-api/replace-trails)

## Key Concepts

### 1) Why call createElement first?

Some fields in `Element` can be very large (e.g., stroke sample points, pressure points, angle points, contour points). To avoid JS-side memory issues, the SDK uses an "accessor" design:

* On the RN side you receive an [`ElementDataAccessor`](https://docs.supernote.com/en/api-reference/supernote-plugin/types/trail-data-accessor) (a reference/handle)
* Raw point data caching and read/write happen on the native side

Therefore, when creating a new element, it is recommended to call `PluginCommAPI.createElement(...)` first so the native side can create and initialize the required caches and accessor references, and then fill in the content you want to write on the JS side.

### 2) Conventions: page and layer

* `page`: documentation uses zero-based page numbers (aligned with UI page numbering).
* `layer`: in notes, common layers are `0..3`. **Links/titles must be on the main layer (`layer=0`)**, otherwise validation fails.
  Document files only have a single layer: the main layer.

### 3) Document limitations

Document files do not allow inserting **TextBox elements / titles / links**. Forcing insertion will be rejected by validation.

### 4) Element Caching and Release

Some fields in `Element` (stroke sample points, pressure points, angle points, contour points, etc.) can hold a large amount of data. Transferring all of it to the RN side at once not only creates memory pressure, but transfer/conversion time also grows noticeably as the data size grows. Because of this, the native side caches each `Element` by `uuid`, and the RN side only holds a reference (`uuid` + accessors), fetching data on demand.

Around this cache there is a full create → read → write → release flow:

| Operation | Method | Description |
| - | - | - |
| Create | [`createElement`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-comm-api/create-trail) | Creates a cache entry and returns an `Element` with a `uuid` |
| Read | [`getElements`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-file-api/get-page-trails) / [`getElement`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-file-api/get-element) / [`getLastElement`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-file-api/get-last-element) / [`getLassoElements`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-comm-api/get-lasso-data) / [`getCacheElement(uuid)`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-comm-api/get-cache-element) | The first four fetch a whole page / a single element / the last element / lasso-selected elements, and all create or refresh the cache; `getCacheElement` fetches already-cached data by `uuid` without producing a new read |
| Write / process | [`insertElements`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-file-api/insert-trails) / [`modifyElements`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-file-api/modify-trails) / [`replaceElements`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-file-api/replace-trails) / [`recognizeElements`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-comm-api/recognize-elements) / [`convertElement2Sticker`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-comm-api/convert-trail2-sticker) / [`modifyPageElements`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-comm-api/modify-page-elements) / [`insertPageElements`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-comm-api/insert-page-elements) / [`batchUpdatePageElements`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-comm-api/batch-update-page-elements) | Require that the element's `uuid` is still present in the cache; `uuid` does not change before/after the call; elements no longer in the cache are silently skipped instead of causing a separate error |
| Release one | [`recycleElement(uuid)`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-comm-api/recycle-trail) / `element.recycle()` | Releases only this one element; either form works the same way |
| Release all | [`clearElementCache()`](https://docs.supernote.com/en/api-reference/supernote-plugin/plugin-comm-api/clear-trail-cache) | Clears **all** `Element` caches at once; every previous `uuid`/`Element` object becomes invalid, so use with caution |

A few things worth noting:

* **Write APIs depend on the cache still existing**: `insertElements`/`modifyElements`/`replaceElements`/`recognizeElements`/`convertElement2Sticker`/`modifyPageElements`/`insertPageElements`/`batchUpdatePageElements` all require that the passed-in element's `uuid` is currently present in the native cache. This is a different check from "the element already exists on the page" (for example, `modifyElements` requires the target to already exist on that page) — a `uuid` that can't be found in the cache is skipped at an earlier stage, before the "does it already exist on the page" check even happens.
* **The cache is not guaranteed to live forever**: `clearElementCache()` only runs when a plugin calls it; the SDK never triggers it automatically on the plugin's behalf. Conversely, the host environment may also automatically reclaim part or all of the cache under memory pressure, so you shouldn't assume a `uuid` stays valid indefinitely — release elements as soon as you're done with them.
* **This is a different, coarser-grained cache than `ElementDataAccessor`**: large point fields such as `angles`/`contoursSrc` add another on-demand paging accessor layer on top of the cached `Element`. The accessor itself also keeps a smaller cache on the RN side — read methods such as `get`/`getRange` cache the values they fetch, while write methods such as `add`/`set`/`setRange` automatically clear that cache on success; `preload`/`isCached`/`getCacheStats`/`clearCache` are also available for manual warm-up, inspection, and clearing. Releasing the whole `Element` also clears its accessor caches. See [`ElementDataAccessor`](https://docs.supernote.com/en/api-reference/supernote-plugin/types/trail-data-accessor) for details.

> [!TIP]
>
> The small cache that `ElementDataAccessor` keeps on the RN side is different from the native-side Element cache described here; see [`ElementDataAccessor`](https://docs.supernote.com/en/api-reference/supernote-plugin/types/trail-data-accessor) for the distinction.

## Get Page Elements

When you need to read all elements on a page (for display, filtering, editing, copying, etc.), use `getElements`:

```ts wrap theme={null}
import { PluginFileAPI } from 'sn-plugin-lib';

/**
 * Get all elements on a given page in a given file.
 */
export async function loadPageElements(notePath: string, page: number) {
  const res = await PluginFileAPI.getElements(page, notePath);
  if (!res?.success) {
    throw new Error(res?.error?.message ?? 'Failed to get page elements');
  }
  return res.result ?? [];
}
```

> [!TIP]
>
> After `getElements` succeeds, the SDK automatically normalizes element structures and fills in accessors. You can directly read typed fields such as `stroke/title/link/textBox/geometry/picture` based on `type`.

## Create a New Element

To create a new element that will be inserted into a page, use `createElement(type)`:

```ts wrap theme={null}
import { PluginCommAPI, ElementType } from 'sn-plugin-lib';

/**
 * Create a new stroke element (Element).
 */
export async function createStrokeElement() {
  const res = await PluginCommAPI.createElement(ElementType.TYPE_STROKE);
  if (!res?.success) {
    throw new Error(res?.error?.message ?? 'createElement failed');
  }
  return res.result;
}
```

> [!NOTE]
>
> The `Element` returned by `createElement` includes `uuid`, and fills required `ElementDataAccessor` fields based on the element type (e.g., `angles/contoursSrc`, and `stroke.*` for stroke elements).

## Insert Elements into a Page

After preparing the element array to insert (usually from `createElement` or copied from existing elements), use `insertElements` to insert into a target page:

```ts wrap theme={null}
import { PluginFileAPI, PluginCommAPI, ElementType } from 'sn-plugin-lib';

/**
 * Insert a newly-created stroke element into a page.
 */
export async function insertOneStroke(notePath: string, page: number) {
  const created = await PluginCommAPI.createElement(ElementType.TYPE_STROKE);
  if (!created?.success || !created.result) {
    throw new Error(created?.error?.message ?? 'createElement failed');
  }

  const element = created.result;
  element.pageNum = page;
  element.layerNum = 0;

  const res = await PluginFileAPI.insertElements(notePath, page, [element]);
  if (!res?.success) {
    throw new Error(res?.error?.message ?? 'Failed to insert elements');
  }
  return true;
}
```

> [!WARNING]
>
> TextBox elements/links/titles can only be operated on the main layer (`layer=0`). Before insertion, ensure `element.layerNum = 0`, otherwise validation fails.

## Modify Existing Elements

The key constraint is: **you can only modify elements that already exist on the page**. The SDK checks existence using identifiers (e.g., `numInPage`). Non-existent elements will not be modified successfully.

The safest workflow:

1. Call `getElements` to fetch the original element list
2. Find the target element (e.g., by `numInPage` or `uuid`)
3. Modify fields and pass that element (or a set of elements) to `modifyElements`

```ts wrap theme={null}
import { PluginFileAPI } from 'sn-plugin-lib';

/**
 * Modify an element on a page (workflow example; fields depend on element type).
 */
export async function modifyOneElement(notePath: string, page: number, numInPage: number) {
  const listRes = await PluginFileAPI.getElements(page, notePath);
  if (!listRes?.success || !listRes.result) {
    throw new Error(listRes?.error?.message ?? 'Failed to get page elements');
  }

  const elements = listRes.result;
  const target = elements.find((e: any) => e.numInPage === numInPage);
  if (!target) {
    throw new Error(`Element not found: numInPage=${numInPage}`);
  }

  target.thickness = (target.thickness ?? 0) + 1;

  const modRes = await PluginFileAPI.modifyElements(notePath, page, [target]);
  if (!modRes?.success) {
    throw new Error(modRes?.error?.message ?? 'Failed to modify elements');
  }
  return modRes.result;
}
```

> [!TIP]
>
> If you need to modify "point data" (e.g., stroke sample points), you usually write via `ElementDataAccessor.set/setRange` on the native side instead of replacing JS arrays directly.

## Replace All Elements on a Page

Use `replaceElements` when you want to "clear all existing elements and replace the page with a new set". Common scenarios: full-page re-layout, batch import, or writing edited results in one shot.

```ts wrap theme={null}
import { PluginFileAPI } from 'sn-plugin-lib';

/**
 * Replace all elements on a page with a new set (clears existing elements).
 */
export async function replacePageElements(notePath: string, page: number, elements: any[]) {
  const res = await PluginFileAPI.replaceElements(notePath, page, elements);
  if (!res?.success) {
    throw new Error(res?.error?.message ?? 'Failed to replace page elements');
  }
  return true;
}
```

> [!WARNING]
>
> `replaceElements` clears existing elements first and then writes the new set. If you expose this in your UI, consider adding a confirmation step or an undo strategy.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.