# 存储

保留一个值到下次访问，跟踪变化，并在服务器上读取 cookie。

用存储辅助函数保存一个值，稍后再读回来。它们支持 localStorage、sessionStorage 和 cookie，还能让你监听变化。

对于用户偏好，比如主题或侧边栏状态，把一个存储传给 [`createPreference`](https://ui-sdk.cn/docs/core/behaviors/preferences#remember-the-choice)。

## 选择存储
按值的保留时长和服务器是否需要读取它来选择：

| 存储                   | 保留时长                     | 共享对象           | 服务器可读取 |
| ---------------------- | ---------------------------- | ------------------ | ------------ |
| `createLocalStorage`   | 直到被移除                   | 站点上的其他标签页 | 否           |
| `createSessionStorage` | 标签页打开期间               | 当前标签页         | 否           |
| `createCookieStorage`  | 一年，或 `maxAge` 指定的秒数 | 请求和其他标签页   | 是           |

想留到下次访问的笔记可以用 localStorage。临时的草稿可以用 sessionStorage。会影响服务端渲染内容的偏好可以用 cookie。

## 保存一个值
这些辅助函数按名称存储字符串，这个名称会成为 localStorage 或 sessionStorage 的键，或者 cookie 的名字：

```ts
import { createLocalStorage } from "@ui-sdk/core"

const note = createLocalStorage("note")

note.set("Buy milk")
note.get()
note.remove()
note.get()
```

第一次 `get()` 返回 `"Buy milk"`。调用 `remove()` 之后，它返回 `null`。

输入一条笔记并重新加载页面。切换存储类型，或者打开另一个标签页，看看哪些值会保留下来。

## 存储不可用时
浏览器可能禁止存储，或者存储空间会用完。如果读取失败，`get()` 返回 `null`。对 localStorage 和 sessionStorage 来说，写入成功时 `set` 和 `remove` 返回 `true`，失败时返回 `false`。

用 `available()` 做初始检查。之后的写入仍可能失败，所以也要检查它的返回值：

```ts
if (!note.available()) {
  console.log("Saving is unavailable here.")
}

if (!note.set("Buy milk")) {
  console.log("The note wasn't saved.")
}
```

存储已满时，你仍然可以读取或移除已有的值。

对 cookie 来说，`true` 表示没有报告错误，并不能确认 cookie 已经保存或移除。

在服务器上，localStorage 和 sessionStorage 不可用。要在那里读取保存的值，[请使用 cookie](https://ui-sdk.cn/docs/core/storage#read-a-cookie-on-the-server)。

## 跟踪变化
先用 `get` 读取初始值，再订阅变化。`subscribe` 不会用初始值调用你的监听器：

```ts
function logNote(value: string | null) {
  console.log(value ?? "")
}

logNote(note.get())
const stop = note.subscribe(logNote)
```

通过种类和 ID 相同的存储写入时，页面上的监听器会收到通知，包括通过 `note` 本身的写入。localStorage 还会跟踪其他标签页的变化。在支持 `cookieStore` 的浏览器里，cookie 也会跟踪其他标签页。

不再需要订阅时调用返回的函数，比如组件卸载时：

```ts
stop()
```

## 在服务器上读取 cookie
在服务端渲染期间，传入请求的 `Cookie` 头来读取保存的值：

```ts
import { createCookieStorage } from "@ui-sdk/core"

function readDensity(request: Request) {
  const density = createCookieStorage("density", {
    cookie: request.headers.get("cookie"),
  })

  return density.get()
}
```

像上面那样在请求处理函数里创建存储，让每个访客的 cookie 保持独立。在浏览器里，它读取 `document.cookie`。

在服务器上，提供 `Cookie` 头时 `available()` 返回 `true`，但 `set` 和 `remove` 返回 `false`。这个辅助函数读取请求的 cookie，不设置响应头。它的 `readsOnServer` 标记让 `createPreference` 这类辅助函数能在初始状态里使用保存的值。

默认情况下，cookie 保留一年，使用路径 `/` 和 `SameSite=Lax`，在 HTTPS 页面上使用 `Secure`。你可以用 `maxAge`、`path`、`domain`、`sameSite` 和 `secure` 修改这些设置。

## 在水合前显示值
服务器无法读取 localStorage 或 sessionStorage。对于依赖保存值的样式，`script` 会生成一段 JavaScript，在水合之前把值放到 `data-*` 属性上：

```ts
import { createLocalStorage } from "@ui-sdk/core"

const densityStorage = createLocalStorage("density")
const script = densityStorage.script({
  attribute: "data-density",
  values: ["comfortable", "compact"],
})
```

渲染元素时带上它的默认属性，比如 `data-density="comfortable"`。紧跟在这个元素之后，把 `script` 渲染成内联 JavaScript。它会在页面加载时读取保存的值，并更新前一个元素的属性。

只有列在 `values` 里的值才会被写入。保存的值缺失或无效时，属性保持服务器渲染的样子。属性名必须以 `data-` 开头。

脚本只更新属性。组件挂载时读取存储，并订阅变化，让它的状态保持最新。当你[在自己的框架里渲染这段脚本](https://ui-sdk.cn/docs/server-rendering#render-the-storage-script-yourself)时，要考虑到属性会在水合之前发生变化。

种类和 ID 相同的脚本共享一次初始读取。cookie 存储的 `script` 返回 `undefined`，因为服务器自己就能渲染 cookie 的值。

对于用户偏好，[用 `Preferences` 应用它们](https://ui-sdk.cn/docs/core/behaviors/preferences#apply-preferences)，这样只需渲染一段脚本，就能让它们的属性保持最新。

## API 参考
- `id` (`string`): The ID the value is kept under: the localStorage or sessionStorage key, or the cookie's name. Example: [Keep a Value](https://ui-sdk.cn/docs/core/storage#keep-a-value).
- `kind` (`Kind`): Where the value is kept: `"local"`, `"session"` or `"cookie"`. Example: [Choose a Storage](https://ui-sdk.cn/docs/core/storage#choose-a-storage).
- `readsOnServer` (`boolean`): Whether the server reads the value too, so it renders right from the first render. True for cookies. Example: [Read a Cookie on the Server](https://ui-sdk.cn/docs/core/storage#read-a-cookie-on-the-server).
- `script` (`(options: StorageScriptOptions) => string`): The inline script a component renders right after its root, which puts the saved value on the root before hydration, so CSS shows it on the first paint. Undefined for a cookie, since the server renders its value. Example: [Show a Value Before Hydration](https://ui-sdk.cn/docs/core/storage#show-a-value-before-hydration).
- `available` (`() => boolean`): Whether storage appears available. A later write can still fail. On the server, a cookie with a request header is available for reading only. Example: [When Storage Is Unavailable](https://ui-sdk.cn/docs/core/storage#when-storage-is-unavailable).
- `get` (`() => string | null`): The value kept under the ID, or null when nothing is, or the storage is unavailable. Example: [Keep a Value](https://ui-sdk.cn/docs/core/storage#keep-a-value).
- `set` (`(value: string) => boolean`): Saves a value under the ID. Returns false when writing is unavailable or the browser reports a write failure. For cookies, true means the assignment didn't throw; it doesn't confirm the cookie was saved. Example: [Keep a Value](https://ui-sdk.cn/docs/core/storage#keep-a-value).
- `remove` (`() => boolean`): Removes the value. Returns false when writing is unavailable or the browser reports a write failure. For cookies, true means the assignment didn't throw; it doesn't confirm the cookie was removed. Example: [Keep a Value](https://ui-sdk.cn/docs/core/storage#keep-a-value).
- `subscribe` (`(listener: (value: string | null) => void) => () => void`): Hears the value change, through another storage with the same ID on the page or in another tab. Returns the function that stops it. Example: [Follow Changes](https://ui-sdk.cn/docs/core/storage#follow-changes).

- `cookie?` (`string | null`): The request's `Cookie` header, so the server reads the same value the browser will. Example: [Read a Cookie on the Server](https://ui-sdk.cn/docs/core/storage#read-a-cookie-on-the-server).
- `maxAge?` (`number`): How long the cookie lasts, in seconds. Example: [Read a Cookie on the Server](https://ui-sdk.cn/docs/core/storage#read-a-cookie-on-the-server).
- `path?` (`string`): The paths that send the cookie. Example: [Read a Cookie on the Server](https://ui-sdk.cn/docs/core/storage#read-a-cookie-on-the-server).
- `domain?` (`string`): The domain that sends the cookie. Defaults to the page's host. Example: [Read a Cookie on the Server](https://ui-sdk.cn/docs/core/storage#read-a-cookie-on-the-server).
- `sameSite?` (`"lax" | "none" | "strict"`): Whether other sites' requests send the cookie. Example: [Read a Cookie on the Server](https://ui-sdk.cn/docs/core/storage#read-a-cookie-on-the-server).
- `secure?` (`boolean`): Whether only HTTPS requests send the cookie. Defaults to true on HTTPS pages. Example: [Read a Cookie on the Server](https://ui-sdk.cn/docs/core/storage#read-a-cookie-on-the-server).

- `attribute` (``data-${string}``): The attribute that shows the value, which has to start with `data-`, like `"data-color-scheme"`. Example: [Show a Value Before Hydration](https://ui-sdk.cn/docs/core/storage#show-a-value-before-hydration).
- `values` (`readonly string[]`): The values it may show. Anything else saved under the ID leaves the root as the server rendered it. Example: [Show a Value Before Hydration](https://ui-sdk.cn/docs/core/storage#show-a-value-before-hydration).
