From 38a908a8fb519e7c43ce4f3baae6fb26b013dbc6 Mon Sep 17 00:00:00 2001 From: Lyudmil Ivanov <55487633+flmel@users.noreply.github.com> Date: Tue, 7 Jan 2025 15:53:59 +0200 Subject: [PATCH 1/3] chore: remove deprecated docs --- .../anatomy/builtin-components.md | 295 ------- .../2.build/3.near-components/anatomy/near.md | 160 ---- .../anatomy/notifications.md | 184 ---- .../3.near-components/anatomy/social.md | 348 -------- .../3.near-components/anatomy/state.md | 114 --- .../3.near-components/anatomy/web-methods.md | 221 ----- docs/2.build/3.near-components/bos-gateway.md | 40 - docs/2.build/3.near-components/environment.md | 42 - docs/2.build/3.near-components/what-is.md | 505 ----------- docs/2.build/4.web3-apps/chain-ui-tutorial.md | 181 ---- docs/2.build/4.web3-apps/chain-ui.md | 83 -- .../4.web3-apps/integrate-components.md | 104 --- .../3.tutorials/near-components/blog-posts.md | 260 ------ .../bos-ethersjs-best-practices.md | 413 --------- .../near-components/bos-ethersjs.md | 149 ---- .../3.tutorials/near-components/bos-loader.md | 68 -- .../near-components/design-system.md | 799 ------------------ .../3.tutorials/near-components/hello-lido.md | 376 --------- .../3.tutorials/near-components/hello-near.md | 143 ---- docs/3.tutorials/near-components/iframes.md | 202 ----- .../near-components/push-notifications.md | 88 -- docs/3.tutorials/welcome.md | 2 - docs/help.md | 22 - docs/welcome.md | 1 - website/docusaurus.config.js | 2 - website/linkinator.config.json | 1 - website/sidebars.js | 44 - website/src/theme/Footer/index.js | 15 - website/src/theme/NotFound/Content/index.js | 1 - 29 files changed, 4863 deletions(-) delete mode 100644 docs/2.build/3.near-components/anatomy/builtin-components.md delete mode 100644 docs/2.build/3.near-components/anatomy/near.md delete mode 100644 docs/2.build/3.near-components/anatomy/notifications.md delete mode 100644 docs/2.build/3.near-components/anatomy/social.md delete mode 100644 docs/2.build/3.near-components/anatomy/state.md delete mode 100644 docs/2.build/3.near-components/anatomy/web-methods.md delete mode 100644 docs/2.build/3.near-components/bos-gateway.md delete mode 100644 docs/2.build/3.near-components/environment.md delete mode 100644 docs/2.build/3.near-components/what-is.md delete mode 100644 docs/2.build/4.web3-apps/chain-ui-tutorial.md delete mode 100644 docs/2.build/4.web3-apps/chain-ui.md delete mode 100644 docs/2.build/4.web3-apps/integrate-components.md delete mode 100644 docs/3.tutorials/near-components/blog-posts.md delete mode 100644 docs/3.tutorials/near-components/bos-ethersjs-best-practices.md delete mode 100644 docs/3.tutorials/near-components/bos-ethersjs.md delete mode 100644 docs/3.tutorials/near-components/bos-loader.md delete mode 100644 docs/3.tutorials/near-components/design-system.md delete mode 100644 docs/3.tutorials/near-components/hello-lido.md delete mode 100644 docs/3.tutorials/near-components/hello-near.md delete mode 100644 docs/3.tutorials/near-components/iframes.md delete mode 100644 docs/3.tutorials/near-components/push-notifications.md diff --git a/docs/2.build/3.near-components/anatomy/builtin-components.md b/docs/2.build/3.near-components/anatomy/builtin-components.md deleted file mode 100644 index fca9965e470..00000000000 --- a/docs/2.build/3.near-components/anatomy/builtin-components.md +++ /dev/null @@ -1,295 +0,0 @@ ---- -id: builtin-components -title: List of Native Components ---- - -import {WidgetEditor} from "@site/src/components/widget-editor" - -A list of all the built-in components to be used on Near Components. - ---- - -## Widget - -The predefined component `Widget` allows you to include an existing component into your code, thus enabling to create complex applications by composing components. - - - -```ts -const props = { name: "Anna", amount: 3 }; - -return ; -``` - - - ---- - -## IpfsImageUpload - -A built-in component that enables users to directly upload an image to the InterPlanetary File System (IPFS). - - - -```js -State.init({image: {}}) - -return <> -

Raw State: {JSON.stringify(state.image)}

- - -``` - -
- ---- - -## Files - -A built-in component that enables to input files with drag and drop support. Read more about the `Files` component [here](https://www.npmjs.com/package/react-files). - - - -```js -const [img, setImg] = useState(null); -const [msg, setMsg] = useState('Upload an Image') - -const uploadFile = (files) => { - setMsg('Uploading...') - - const file = fetch( - "https://ipfs.near.social/add", - { - method: "POST", - headers: { Accept: "application/json" }, - body: files[0] - } - ) - - setImg(file.body.cid) - setMsg('Upload an Image') -} - -return <> - - {msg} - - {img ?
: ''} -; -``` - -
- ---- - -## Markdown - -A component that enables to render Markdown. - - - -```jsx -const markdown = (` -## A title - -This is some example **markdown** content, with _styled_ text -`) - -return ; -``` - - - -:::tip Markdown Editor - -Checkout this [Markdown Editor](https://near.social/#/mob.near/widget/MarkdownEditorIframeExample), and [its source code](https://near.social/mob.near/widget/WidgetSource?src=mob.near/widget/MarkdownEditorIframeExample). -::: - ---- - -## OverlayTrigger - -Used to display a message or icon when the mouse is over a DOM element. - - - -```javascript -const [show, setShow] = useState(false); - -const overlay = ( -
- This is the overlay Message -
-); - -return ( - - - -); -``` - -
- -
- - Component props - -The OverlayTrigger component has several props that allow you to customize its behavior: - -| Prop | Description | -|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `show` | A boolean value that determines whether the overlay is currently visible or not. | -| `trigger` | An array of events that trigger the display of the overlay. In this example, the `trigger` prop is set to `["hover", "focus"]`, which means that the overlay will be displayed when the user hovers over or focuses on the element. | -| `delay` | An object that specifies the delay before the overlay is displayed or hidden. In this example, the `delay` prop is set to `{ show: 250, hide: 300 }`, which means that the overlay will be displayed after a 250-millisecond delay and hidden after a 300-millisecond delay. | -| `placement` | A string that specifies the position of the overlay relative to the trigger element. In this example, the `placement` prop is set to `"auto"`, which means that the position will be automatically determined based on available space. | -| `overlay` | The content that will be displayed in the overlay. In this example, the `overlay` prop is set to a `
` element containing the message "This is the overlay message. | -
- ---- - -## InfiniteScroll - -Infinitely load a grid or list of items. This component allows you to create a simple, lightweight infinite scrolling page or element by supporting both window and scrollable elements. - -Read more about the [react-infinite-scroller](https://www.npmjs.com/package/react-infinite-scroller) package. - - - -```js -const allNumbers = Array.from(Array(100).keys()) -const [lastNumber, setLastNumber] = useState(0); -const [display, setDisplay] = useState([]); - -const loadNumbers = (page) => { - const toDisplay = allNumbers - .slice(0, lastNumber + page*10) - .map(n =>

{n}

) - - console.log(lastNumber + page*10) - setDisplay(toDisplay); - setLastNumber(lastNumber + page*10); -}; - -return ( - - {display} - -); -``` - -
- ---- - -## TypeAhead - -Provides a type-ahead input field for selecting an option from a list of choices. More information about the component can be found [here](https://github.com/ericgio/react-bootstrap-typeahead). - - - -```jsx -const [selected, setSelected] = useState([]); -const options = ["Apple", "Banana", "Cherry", "Durian", "Elderberry"]; - -return <> - setSelected(v)} - placeholder='Choose a fruit...' - /> -
-

Selected: {selected.join(', ')}

-; -``` - -
- ---- - -## Styled Components - -[Styled Components](https://styled-components.com/) is a popular library for styling React components using CSS-in-JS. - - - -```jsx -const Button = styled.button` - /* Adapt the colors based on primary prop */ - background: ${(props) => (props.primary ? "palevioletred" : "white")}; - color: ${(props) => (props.primary ? "white" : "palevioletred")}; - - font-size: 1em; - margin: 1em; - padding: 0.25em 1em; - border: 2px solid palevioletred; - border-radius: 10px; -`; - -return ( -
- - -
-); -``` - -
- ---- - -## Tooltip - -Displays a message once the mouse hovers over a particular item. This component was imported from [`React-Bootstrap`](https://react-bootstrap-v3.netlify.app/components/tooltips/). - - - -```js -const tooltip = ( - - Holy guacamole! Check this info. - -); - -return <> - - - - - - - - - - - - - - - - -``` - - \ No newline at end of file diff --git a/docs/2.build/3.near-components/anatomy/near.md b/docs/2.build/3.near-components/anatomy/near.md deleted file mode 100644 index c906ee8c9bb..00000000000 --- a/docs/2.build/3.near-components/anatomy/near.md +++ /dev/null @@ -1,160 +0,0 @@ ---- -id: near -title: Interacting with Near ---- - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; -import {WidgetEditor} from "@site/src/components/widget-editor" - -The components can use the `Near` object to interact with smart contracts in the NEAR blockchain. There are three methods: - -- [`Near.view`](#nearview) -- [`Near.block`](#nearblock) -- [`Near.call`](#nearcall) - ---- - -## Near.view -Queries a read-only method from a NEAR smart contract, returning: -- **`null`**: If the query is still being processed -- **`undefined`**: If the query is complete and no value was returned by the contract -- A **value**: If the query is complete and a value was returned by the contract - - - -```js -const greeting = Near.view("hello.near-examples.testnet", "get_greeting", {}); - -if (greeting === null) return "Loading..."; - -return `The contract says: ${greeting}`; -``` - - - -
- Parameters - -| param | required | type | description | -|--------------------|--------------|-----------------|--------------------------------------------------------------------------------------------------------------------------------| -| `contractName` | **required** | string | Name of the smart contract | -| `methodName` | **required** | string | Name of the method to call | -| `args` | _optional_ | object instance | Arguments to pass to the method | -| `blockId/finality` | _optional_ | string | Block ID or finality of the transaction | -| `subscribe` | _optional_ | boolean | This feature allows users to subscribe to a query, which automatically refreshes the data for all subscribers every 5 seconds. | - -
- -:::tip -Notice that the optional parameter `subscribe` allows users to subscribe to a query, which automatically refreshes the data every 5 seconds. -::: - -
- -#### Avoiding a Common Pitfall - -If you want to initialize the state with the result of a `Near.view` call, be sure to check first that the value was obtained, to avoid initializing the state with `null`. - - - -```js -const contractGreet = Near.view("hello.near-examples.testnet", "get_greeting", {}); - -// you need to first check that the value was obtained -if (contractGreet === null) return "Loading..."; - -const [greeting, setGreeting] = useState(contractGreet); - -return `The contract says: ${greeting}`; -``` - - - -If you don't want to delay the render of your component, you can also use the `useEffect` hook to control the value returned by `Near.view` - - - -```js -const contractGreet = Near.view('hello.near-examples.testnet', 'get_greeting'); - -const [greeting, setGreeting] = useState('Loading ...'); - -useEffect(() => { - if (contractGreet !== null) setGreeting(contractGreet); -}, [contractGreet]); - -return `The contract says: ${greeting}`; -``` - - - ---- - -## Near.call - -Calls a smart contract method from the blockchain. Since a transaction needs to be signed, the user must be logged in in order to make the call. - - - -```js -if (!context.accountId) return "Please login..."; - -const onClick = () => { - Near.call( - "hello.near-examples.testnet", - "set_greeting", - { greeting: "Hello!" } - ); -}; - -return <> -
Hello {context.accountId}
- -; -``` -
- -
- Parameters - -| param | required | type | description | -|----------------|--------------|-----------------|-----------------------------------------------------------------------------| -| `contractName` | **required** | string | Name of the smart contract to call | -| `methodName` | **required** | string | Name of the method to call on the smart contract | -| `args` | _optional_ | object instance | Arguments to pass to the smart contract method as an object instance | -| `gas` | _optional_ | string / number | Maximum amount of gas to be used for the transaction (default 300Tg) | -| `deposit` | _optional_ | string / number | Amount of NEAR tokens to attach to the call as deposit (in yoctoNEAR units) | - -
- -:::tip -Remember that you can login using the `Login` button at the navigation bar. -::: - ---- - -## Near.block - -Queries a block from the blockchain. - - - -```js -return Near.block("optimistic"); -``` - - - -
- Parameters - -| param | required | type | description | -|-------------------------|------------|------|---------------------------------------------------------------------------------------------------------------------------------------------------| -| `blockHeightOrFinality` | _optional_ | any | The block height or finality level to use for the blockchain query (desired block height, or one of the following strings: `optimistic`, `final`) | - -- desired block height: The height of the specific block to query, expressed as a positive integer -- `optimistic`: Uses the latest block recorded on the node that responded to your query (< 1 second delay) -- `final`: a block that has been validated on at least 66% of the nodes in the network (approx. 2s) - -
\ No newline at end of file diff --git a/docs/2.build/3.near-components/anatomy/notifications.md b/docs/2.build/3.near-components/anatomy/notifications.md deleted file mode 100644 index b58d50fcca0..00000000000 --- a/docs/2.build/3.near-components/anatomy/notifications.md +++ /dev/null @@ -1,184 +0,0 @@ ---- -id: notifications -title: Social Notifications ---- -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; -import {WidgetEditor} from "@site/src/components/widget-editor" - -Applications such as [NEAR Social](https://near.social) and the [NEAR Dev Portal](https://dev.near.org/) allow components to send notifications to their users. - -Notifications are great to inform users in real time that something has happened, and can be [easily incorporated into any web app](../../../3.tutorials/near-components/push-notifications.md). - ---- - -## Sending Notifications - -Notifications are implemented as a particular case of [indexed actions](./social.md#socialindex). - -This means that to send a notification we just need to `index` the `notify` action for the indexer, with a `key` and a `value`. - -- The `key` tells **which account** to notify. -- The `value` includes the [notification type](#notification-types) and the item being notified of. - - - -```js -const notifyMe = () => { - Social.set({ - index: { - notify: JSON.stringify({ - key: context.accountId, - value: "docs notification" - }) - } - }); -} - -return <> - {context.accountId? - - : -

Please login to be notified

- } - -``` - -
- - -In this example, the account executing the code is notifying `mob.near` that they liked their social post created at the block height `102169725`. - ---- - -## Notification Types - -Since notifications are indexed actions, anyone can create their own kind of notification. - -While there is no standard for notifications, we recommend using the following types: - - - - -```js - Social.set({ - index: JSON.stringify({ - notify: { - key: "mob.near", - value: { - type: "custom", - message: "A message in the notification", - widget: "The widget to open when clicking on the notification", - params: { parameters: "to pass to the widget", ... }, - }, - } - }) - }); -``` - -**Note**: currently, only dev.near.org implements custom notifications - - - - - -```js - Social.set({ - index: JSON.stringify({ - notify: { - key: "mob.near", - value: { - type: "like", - item: { - type: "social", - path: "mob.near/post/main", - blockHeight: 102169725 - } - } - } - }) - }) -``` - -**Reference**: [LikeButton](https://near.org/near/widget/ComponentDetailsPage?src=near/widget/LikeButton&tab=source) - - - - - -```js - Social.set({ - index: JSON.stringify({ - notify: { - key: "nearhacks.near", - value: { - type: "comment", - item: { - type: "social", - path: "nearhacks.near/post/main", - blockHeight: 102224773 - } - } - } - }) - }) -``` - -**Reference**: [CommentButton](https://near.org/near/widget/ComponentDetailsPage?src=near/widget/Comments.Compose&tab=source) - - - - - -```js - Social.set({ - index: JSON.stringify({ - notify: { - key: "mob.near", - value: { - type: "follow", - } - } - }) - }) -``` - -**Reference**: [FollowButton](https://near.org/near/widget/ComponentDetailsPage?src=near/widget/FollowButton&tab=source) - - - - - -:::caution -There is no standard for notifications, but you can contribute to create one [in this public discussion](https://github.com/NearSocial/standards/pull/19/files). -::: - ---- - -## Parsing Notifications - -In order to get all notifications for an user, we make a call to the Social indexer. - - - -```js -// login to see your notifications -const accountId = context.accountId || 'influencer.testnet' - -const index = Social.index("notify", accountId, {limit: 2, order: "desc", subscribe: true}); - -return <> -

Notifications for {accountId}

- {index.map(e => <> {JSON.stringify(e, null, 2)}
) } - -``` - -
- -:::caution -Please notice that anyone can create a notification for the user, and thus some form of filtering might be needed. -::: - -:::tip -You can also check how the [Notifications Page](https://near.org/near/widget/ComponentDetailsPage?src=near/widget/NotificationsPage&tab=source) is implemented. -::: diff --git a/docs/2.build/3.near-components/anatomy/social.md b/docs/2.build/3.near-components/anatomy/social.md deleted file mode 100644 index 9d62c34c7f2..00000000000 --- a/docs/2.build/3.near-components/anatomy/social.md +++ /dev/null @@ -1,348 +0,0 @@ ---- -id: social -title: Social Interactions ---- - -import {WidgetEditor} from "@site/src/components/widget-editor" - -NEAR components can natively communicate with the [SocialDB smart contract](https://github.com/NearSocial/social-db) (currently deployed at [social.near](https://nearblocks.io/address/social.near)). - -The `SocialDB` is a contract that stores `key-value` pairs, and is used mostly to store social-related data, such as `posts`, `likes`, or `profiles`. - -:::tip -Besides user data, the `SocialDB` contract stores **all existing NEAR components**. -::: - ---- - -## Social.get - -`Social.get` queries a key from the SocialDB contract and returns the data. The key being queried can contain wildcards. - -For example: - - - `alice.near/profile/**` will match the entire profile data of account alice.near. - - `alice.near/profile/*` will match all the fields of the profile, but not the nested objects. - - `alice.near/profile/name` will match only the name field of the profile. - - `*/widget/*` will match all the widgets of all the accounts. - -
- - - -```js -// Ask for the `profile` key of the influencer.testnet account -const profile = Social.get("influencer.testnet/profile/*"); - -// Ask a component from the influencer.testnet account -const widget = Social.get("influencer.testnet/widget/Greeter"); - -if(profile === null || widget === null) return "Loading ..." - -return ( -
-

Profile: {JSON.stringify(profile)}

-

Widgets: {JSON.stringify(widget)}

-
-); -``` - -
- - -
- Parameters - -| param | required | type | description | -|------------|--------------|--------------------|------------------------------| -| `patterns` | **required** | string / string[] | the path pattern(s) | -| `finality` | _optional_ | `"final"` / number | the block height or finality | -| `options` | _optional_ | object | the `options` object. | - -:::info options object - -- `subscribe` _(optional)_: if true, the data will be refreshed every 5 seconds. -- `return_deleted` _(optional)_: whether to return deleted values (as `null`). Default is `false`. - -::: - -The block height or finality can be used to get the data at a specific block height or finality. -If the block height or finality is not specified, the data will be fetched at the `optimistic` finality (the latest block height). - -For block height and finality `final`, instead of calling the NEAR RPC directly, the VM uses the Social API Server to fetch the data. - -Social API server indexes the data for SocialDB and allows to fetch the data at any block height with additional options. - -It also allows returning more data than an RPC call because it's not restricted by the gas limit. -In general, the API server also serves data faster than the NEAR RPC, because it doesn't execute the contract code in a virtual machine. - -
- -:::tip -While the data is fetching, `Social.get` returns `null`. -::: - - ---- - -## Social.getr -`Social.getr` is just a wrapper helper for `Social.get`, it appends `**` to each of the path pattern. - - - -```js -const profile = Social.getr("influencer.testnet/profile"); - -return ( -
-

Profile: {JSON.stringify(profile)}

-
-); -``` - -
- -
- Parameters - -| param | required | type | description | -|------------|--------------|--------------------|------------------------------| -| `patterns` | **required** | string / string[] | the path pattern(s) | -| `finality` | _optional_ | `"final"` / number | the block height or finality | -| `options` | _optional_ | object | the `options` object. | - -:::info options object - -- `subscribe` _(optional)_: if true, the data will be refreshed every 5 seconds. -- `return_deleted` _(optional)_: whether to return deleted values (as `null`). Default is `false`. - -::: - -
- ---- - -## Social.keys - -The `keys` method allows to get the list of keys that match a pattern. It's useful for querying the data without reading values. - -It also has an additional `options` field that can be used to specify the return type and whether to return deleted keys. - - - -```js -const data = Social.keys(`influencer.testnet/profile/*`, "final"); - -return JSON.stringify(data) -``` - - - -
- Parameters - -`Social.keys` takes up to 3 arguments: - -| param | required | type | description | -|------------|--------------|--------------------|------------------------------| -| `patterns` | **required** | string / string[] | the path pattern(s) | -| `finality` | _optional_ | `"final"` / number | the block height or finality | -| `options` | _optional_ | object | the `options` object. | - -:::info options object - -- `subscribe` _(optional)_: if true, the data will be refreshed every 5 seconds. -- `return_type` _(optional)_: either `"History"`, `"True"`, or `"BlockHeight"`. If not specified, it will return the `"True"`. -- `return_deleted` _(optional)_: whether to return deleted values (as `null`). Default is `false`. -- `values_only` _(optional)_: whether to return only values (don't include objects). Default is `false`. - -::: - -
- -:::tip -The Social API server supports custom options `return_type: "History"`. For each matching key, it will return an array containing all the block heights when the value was changed in ascending order. -It can be used for building a feed, where the values are overwritten. -::: - ---- - -## Social.set - -Takes a `data` object and commits it to SocialDB. The data object can contain multiple keys, and each key can contain multiple values. - -Importantly, a user can only commit to **their own** space in `SocialDB` (e.g. `alice.near` can only write in `alice.near/**`), except if [**given explicit permission**](https://github.com/NearSocial/social-db#permissions) by the owner of another space. - -Each time a user wants to commit data, they will be prompted to confirm the action. On confirming, the user can choose to not be asked again in the future. - - - -```js -const onClick = () => { - Social.set({ - post: { - main: JSON.stringify({ - type: "md", - text: "I've read the docs!" - }) - } - }) -} - -if(!context.accountId) return "Please login..."; - -return <> -

Save a message showing some love to the NEAR Docs

- - -``` - -
- -
- Parameters - -`Social.set` arguments: - - | param | required | type | description | - |-----------|--------------|--------|----------------------------------------------------------------------------------------------------| - | `data` | **required** | object | the data object to be committed. Similar to `CommitButton`, it shouldn't start with an account ID. | - | `options` | _optional_ | object | optional object. | - -:::info options object - -- `force` _(optional)_: whether to overwrite the data. -- `onCommit` _(optional)_: function to trigger on successful commit. Will pass the -data that was written (including `accountID`). -- `onCancel` _(optional)_: function to trigger if the user cancels the commit. - -::: - -
- -:::tip -By default `Social.set` will omit saving data that is already saved (e.g. if the user already liked a post, it won't save the like again). To force saving the data, pass the `force` option. -::: - ---- - -## Social.index -NEAR Social readily provides an indexer - a service that listen to actions in SocialDB, and caches them so they can be retrieved without needing to interact with the contract. - -The indexer is very useful, for example, to rapidly store and retrieve information on all comments for a post. Without the indexer, we would need to check all entries in the contract to see who answered, surely running out of GAS before completion. - -
- -### Indexing an Action -To index an action we need to add the `index` key to the data being saved, within the `index` key we will save the `action` being indexed, alongside a `key` and a `value` that identifies this specific instance. - - - -```js -// General form of an indexed action -// { -// index: { -// actionName: JSON.stringify({ key, value }) -// } -// } - -const onClick = () => { - Social.set({ - index: { - readDocs: JSON.stringify({key: "docs", value: "like"}) - } , - }) -} - -return <> - {context.accountId ? - <> -

Index an action showing some love to the NEAR Docs

- - : -

Login to index an action

} - -``` - -
- -In the example above we index a `docs` action. In this case the `action` is `docs`, and the `key` that identifies it is `"read"`. - -
- - Standards - -#### Indexing a Post -To index a post, the standard is to save the action `post`, with `{key: "main", value: {type: "md"}`. - -```js -{ - index: { - post: JSON.stringify({ - key: "main", - value: {type: "md"} - }) - } -} -``` - -#### Indexing a Like -To index a like, the standard is to save the action `like`, with `{key: object-representing-the-post, value: {type: "like" }}` - -```js -{ - index: { - like: JSON.stringify({ - key: {type: 'social', path: 'influencer.testnet/post/main', blockHeight: 152959480 }, - value: {type: "like"}}) - } -} -``` - -
- -
- -### Retrieving Indexed Actions - -To retrieve indexed actions we use the `Social.index` method. It takes the `action` and the `key` as arguments, and returns an array of all the indexed values alongside the `blockHeight` in which they were indexed, and which user made the action. - - - - -```js -const readDocs = Social.index("readDocs", "docs") - -return <> -

Number of indexed "readDocs" actions with key "docs": {readDocs.length}

- - Indexed actions - {JSON.stringify(readDocs)} - -``` - -
- - -
- Parameters - -`Social.index` arguments: - - | param | required | type | description | - |-----------|--------------|--------|--------------------------------------------------------------------------------------------| - | `action` | **required** | string | is the `index_type` from the standard, e.g. in the path `index/like` the action is `like`. | - | `key` | **required** | string | is the inner indexed value from the standard. | - | `options` | _optional_ | object | the `options` object. | - -:::info options object - -- `subscribe` _(optional)_: if true, the data will be refreshed every 5 seconds. -- `accountId` _(optional)_: If given, it should either be a string or an array of account IDs to filter values by them. Otherwise, not filters by account Id. -- `order` _(optional)_: Either `asc` or `desc`. Defaults to `asc`. -- `limit` _(optional)_: Defaults to `100`. The number of values to return. Index may return more than index values, if the last elements have the same block height. -- `from` _(optional)_: Defaults to `0` or `Max` depending on order. - -::: - -
\ No newline at end of file diff --git a/docs/2.build/3.near-components/anatomy/state.md b/docs/2.build/3.near-components/anatomy/state.md deleted file mode 100644 index 7a25b75741c..00000000000 --- a/docs/2.build/3.near-components/anatomy/state.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -id: state -title: Basics ---- -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; -import {WidgetEditor} from "@site/src/components/widget-editor" - -Borrowing from React, Near Components use hooks such as [**`useState`**](#state) and [**`useEffect`**](#useeffect-hook) to handle the state's logic, and [**props**](#props) to receive parameters. - -Near Components are stored in the blockchain, for which you will use the `NEAR VM` to [retrieve and execute them in the browser](../../4.web3-apps/integrate-components.md). - -Using a VM enforces components to be sandboxed, making them very secure since they cannot access your `LocalStorage` or other elements in the page they are incorporated to. However, because of this, components cannot import external libraries. However, they can [**import functions**](#import) from other components. - ---- - -## State -To handle the component's state you can use `useState` hook. The `useState` hook returns a tuple of two values: the current state and a function that updates it. - - - -```jsx -const [count, setCount] = useState(0); - -return ( -
-

You clicked {count} times

- -
-); - -``` - -
- -Each time a state variable is updated, the component will be **re-rendered**. This means that the **whole code will run again**. - ---- - -## Props -Each component has access to a local variable named `props` which holds the properties received as input when the component is composed. - - - -```jsx -return <> -

This component props: {JSON.stringify(props)}

- - -``` - -
- ---- - -## useEffect Hook - -The [`useEffect` hook](https://react.dev/learn/synchronizing-with-effects) is used to handle side effects. It will execute each time one of the dependencies changes. - - - -```jsx -const [count, setCount] = useState(0); -const [visible, setVisible] = useState(false); - -useEffect(() => { - if(count > 5) setVisible(true); -}, [count]); - -return ( -
-

You clicked {count} times

- - -
-); -``` -
- ---- - -## Import - -Components can import functions from other components. This is useful to reuse code and to create libraries of components. - - - -```jsx -const {add, multiply} = VM.require('influencer.testnet/widget/Math'); - -return <> -

2 + 3 = {add(2, 3)}

-

2 * 3 = {multiply(2, 3)}

- -``` - -
- -Where the code of the `Math` component is: - -```js -function add(a, b) { - return a + b; -} - -function multiply(a, b) { - return a * b; -} - -return { add, multiply }; -``` \ No newline at end of file diff --git a/docs/2.build/3.near-components/anatomy/web-methods.md b/docs/2.build/3.near-components/anatomy/web-methods.md deleted file mode 100644 index ec9e46f1418..00000000000 --- a/docs/2.build/3.near-components/anatomy/web-methods.md +++ /dev/null @@ -1,221 +0,0 @@ ---- -id: web-methods -title: Web Browser Methods ---- - -import {WidgetEditor} from "@site/src/components/widget-editor" - -NEAR Components have access to classic web methods that enable them to: -- [Fetch](#fetch) data from external sources. -- [Cache](#cache) values to avoid redundant computations. -- Use [LocalStorage](#localstorage) to store data in the web browser. -- Access to the [Clipboard](#clipboard). - ---- - -## Fetch - -`fetch` allows to fetch data from the URL. It acts like a hook. It's a wrapper around the `fetch` function from the browser behind the caching layer. - -The possible returned values are: -- If the data is not cached, it returns `null` and fetches the data in the background. -- If the data is cached, it returns the cached value and then revalidates it. - - - -```js -const res = fetch("https://rpc.mainnet.near.org/status"); - -return res.body; -``` - - - -
- -#### Async Version - -`asyncFetch` is the `async` version of [`fetch`](#fetch), meaning that it returns a promise instead of a value. - - - -```js -const [uptime, setUptime] = useState(null); - -function reportUptime() { - const promise = asyncFetch("https://rpc.mainnet.near.org/status") - - promise.then( - res => { setUptime(res.body.uptime_sec) } - ); -} - -return <> -

{uptime? `Uptime: ${uptime}s` : `Fetch a value` }

- - -``` - -
- -:::tip -In contrast with `fetch`, `asyncFetch` does **not** cache the resulting value, so it should only be used within a function to avoid frequent requests on every render. -::: - ---- - -## Cache - -The `useCache` hook takes a promise through a generator function, fetches the data and caches it. It can be used to easily use and cache data from async data sources. - -The cache is global for the VM, but each cached element is identified by a unique `dataKey` within each component. - -The possible values returned are: -- `null` if the cache is cold and data is fetching -- the `cached value` while the data is being fetched -- A new `value` if new data is fetched. - - - -```js -const status = useCache( - () => - asyncFetch("https://rpc.mainnet.near.org/status").then((res) => res.body), - "mainnetRpcStatus", - { subscribe: true } -); - -return status; -``` - - - -
- Parameters - -| param | required | type | description | -|--------------------|--------------|--------|----------------------------------------------------------------------| -| `promiseGenerator` | **required** | object | a function that returns a promise, which generates data. | -| `dataKey` | **required** | object | the unique name (within the current component) to identify the data. | -| `options` | _optional_ | object | optional argument. | - -:::info options object - -- `subscribe` _(optional)_: if `true`, the data refreshes periodically by invalidating cache. - -::: - -:::note -- `promiseGenerator`: you don't return the promise directly, because it should only be fired once. -::: - -
- -:::tip -The [fetch](#fetch) method is built on top of the `useCache` hook. -::: - -:::note -The data is being cached and compared as JSON serialized objects. -::: - ---- - -## LocalStorage - -NEAR Components have access to a simulated `localStorage` through the `Storage` object: - -- [`Storage.get`](#storageget) -- [`Storage.set`](#storageset) -- [`Storage.privateGet`](#storageprivateget) -- [`Storage.privateSet`](#storageprivateset) - - - -```jsx -const [time, setTime] = useState(stored || Date.now()) - -const storeValue = () => { - const date = Date.now(); - Storage.set('time_now', date) -} - -return <> -

Time Now: {Date.now()}

-

Time Stored: {Storage.get('time_now')}

- - -``` - -
- -
- Parameters - -#### Storage.get - -`Storage.get(key, widgetSrc?)` - returns the public value for a given key under the given widgetSrc or the current component if `widgetSrc` is omitted. Can only read public values. - - | param | required | type | description | - |-------------|--------------|--------|--------------------------| - | `key` | **required** | object | a user-defined key | - | `widgetSrc` | _optional_ | object | a user-defined component | - ---- - -#### Storage.set - -`Storage.set(key, value)` - sets the public value for a given key under the current widget. The value will be public, so other widgets can read it. - - | param | required | type | description | - |---------|--------------|--------|----------------------| - | `key` | **required** | object | a user-defined key | - | `value` | **required** | object | a user-defined value | - ---- - -#### Storage.privateGet - -`Storage.privateGet(key)` - returns the private value for a given key under the current component. - - | param | required | type | description | - |-------|--------------|--------|------------------------------------------------| - | `key` | **required** | object | a user-defined key under the current component | - ---- - -#### Storage.privateSet - -`Storage.privateSet(key, value)` - sets the private value for a given key under the current component. The value is private, only the current component can read it. - -:::note -Private and public values can share the same key and don't conflict. -::: - - | param | required | type | description | - |---------|--------------|--------|------------------------------------------------| - | `key` | **required** | object | a user-defined key under the current component | - | `value` | **required** | object | a user-defined value | - -
- ---- - -## Clipboard - -NEAR Components can **write** data to the system's clipboard through the `clipboard.writeText` method. - -Writing to the clipboard is **only** allowed in **trusted actions**, for example, when the user clicks a button. - - - -```js -const copyToClipboard = (test) => { clipboard.writeText("Hello World!") } - -return <> - -