@saykit/react 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,32 @@
1
+ # @saykit/react
2
+
3
+ > React integration for [SayKit](https://saykit.js.org).
4
+
5
+ A `<Say>` component for rendering translated content in server and client components, a `<SayProvider>` and `useSay()` for client trees, and a small server runtime (`setSay`, `getSay`, `unstable_createWithSay`).
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pnpm add @saykit/react saykit
11
+ ```
12
+
13
+ You will also need a SayKit build-tool plugin and a `saykit.config.ts`.
14
+
15
+ ## Usage
16
+
17
+ ```tsx
18
+ import { Say, SayProvider } from '@saykit/react/client';
19
+
20
+ function App() {
21
+ return (
22
+ <SayProvider locale="fr" messages={fr}>
23
+ <Say>Hello, {name}!</Say>
24
+ <Say.Plural _={count} one="# item" other="# items" />
25
+ </SayProvider>
26
+ );
27
+ }
28
+ ```
29
+
30
+ ## Documentation
31
+
32
+ [React integration guide](https://saykit.js.org/integrations/react) at [saykit.js.org](https://saykit.js.org).
@@ -0,0 +1,33 @@
1
+ import * as _$react from "react";
2
+ import { PropsWithChildren } from "react";
3
+ import { ReadonlySay, Say } from "saykit";
4
+
5
+ //#region src/runtime/client.d.ts
6
+ type SayRef = {
7
+ current: ReadonlySay | null;
8
+ };
9
+ /**
10
+ * Provide a localised {@link runtime.Say} instance to descendant **client** components via context.
11
+ * Must wrap any component tree using {@link useSay} or {@link Say}.
12
+ *
13
+ * @param props.locale The current locale
14
+ * @param props.messages The current messages for the locale
15
+ */
16
+ declare function SayProvider({
17
+ locale,
18
+ messages,
19
+ children
20
+ }: PropsWithChildren<{
21
+ locale: string;
22
+ messages: Say.Messages;
23
+ }>): _$react.FunctionComponentElement<_$react.ProviderProps<SayRef>>;
24
+ /**
25
+ * Get the current {@link Say} **client** instance.
26
+ * Must be called within a {@link SayProvider}.
27
+ *
28
+ * @returns The current {@link Say} instance
29
+ * @throws If no provider is in the component tree
30
+ */
31
+ declare function useSay(): any;
32
+ //#endregion
33
+ export { SayProvider, useSay };
@@ -0,0 +1,39 @@
1
+ "use client";
2
+ import { createContext, createElement, useContext, useState } from "react";
3
+ import { Say } from "saykit";
4
+ //#region src/runtime/client.ts
5
+ const SayContext = createContext({ current: null });
6
+ SayContext.displayName = "SayContext";
7
+ /**
8
+ * Provide a localised {@link runtime.Say} instance to descendant **client** components via context.
9
+ * Must wrap any component tree using {@link useSay} or {@link Say}.
10
+ *
11
+ * @param props.locale The current locale
12
+ * @param props.messages The current messages for the locale
13
+ */
14
+ function SayProvider({ locale, messages, children }) {
15
+ const [say] = useState(() => {
16
+ const instance = new Say({
17
+ locales: [locale],
18
+ loader: () => messages
19
+ });
20
+ instance.load(locale);
21
+ instance.activate(locale);
22
+ return instance.freeze();
23
+ });
24
+ return createElement(SayContext.Provider, { value: { current: say } }, children);
25
+ }
26
+ /**
27
+ * Get the current {@link Say} **client** instance.
28
+ * Must be called within a {@link SayProvider}.
29
+ *
30
+ * @returns The current {@link Say} instance
31
+ * @throws If no provider is in the component tree
32
+ */
33
+ function useSay() {
34
+ const ref = useContext(SayContext);
35
+ if (!ref.current) throw new Error("'useSay' must be used within a 'SayProvider'");
36
+ return ref.current;
37
+ }
38
+ //#endregion
39
+ export { SayProvider, useSay };
@@ -0,0 +1,88 @@
1
+ "use client"; import { useSay as GET_SAY } from "./client.mjs";import { Fragment, cloneElement, createElement, isValidElement } from "react";
2
+ //#region src/components/renderer.ts
3
+ function Renderer({ html, components }) {
4
+ function getComponent(tag) {
5
+ if (typeof components === "function") return components(tag) ?? tag ?? Fragment;
6
+ return tag && tag in components ? components[tag] : Fragment;
7
+ }
8
+ let nodeKey = 0;
9
+ function parseNode(input) {
10
+ const stack = [];
11
+ let current = [];
12
+ let i = 0;
13
+ while (i < input.length) if (input[i] === "<") {
14
+ const isClosing = input[i + 1] === "/";
15
+ const isSelfClosing = input.slice(i, input.indexOf(">", i) + 1).endsWith("/>");
16
+ const tagStart = i + (isClosing ? 2 : 1);
17
+ const tagEnd = input.indexOf(">", tagStart);
18
+ const tagName = input.slice(tagStart, tagEnd).replace("/", "").trim();
19
+ i = tagEnd + 1;
20
+ if (isSelfClosing) {
21
+ const Component = getComponent(tagName);
22
+ current.push(createElement(Component, { key: nodeKey++ }));
23
+ } else if (isClosing) {
24
+ const last = stack.pop();
25
+ const element = createElement(getComponent(last.tag), { key: nodeKey++ }, ...current);
26
+ current = last.children;
27
+ current.push(element);
28
+ } else {
29
+ stack.push({
30
+ tag: tagName,
31
+ children: current
32
+ });
33
+ current = [];
34
+ }
35
+ } else {
36
+ let textEnd = input.indexOf("<", i);
37
+ if (textEnd === -1) textEnd = input.length;
38
+ const text = input.slice(i, textEnd);
39
+ current.push(text);
40
+ i = textEnd;
41
+ }
42
+ return current;
43
+ }
44
+ return createElement(Fragment, void 0, ...parseNode(html));
45
+ }
46
+ //#endregion
47
+ //#region src/types.ts
48
+ function resolveJsxSafePropKeys(props) {
49
+ const result = {};
50
+ for (const key in props) if (/^_\d+$/.test(key)) result[key.slice(1)] = props[key];
51
+ else result[key] = props[key];
52
+ return result;
53
+ }
54
+ //#endregion
55
+ //#region src/runtime/index.ts
56
+ function Say(props) {
57
+ if (!("id" in props)) throw new Error("'Say' is a macro and must be used with the relevant saykit plugin", { cause: /* @__PURE__ */ new Error("The 'id' property is required for a descriptor") });
58
+ const say = GET_SAY();
59
+ const descriptor = resolveJsxSafePropKeys(props);
60
+ return createElement(Renderer, {
61
+ html: say.call(descriptor),
62
+ components(tag) {
63
+ if (tag && tag in descriptor && isValidElement(descriptor[tag])) {
64
+ const element = descriptor[tag];
65
+ return (props) => cloneElement(element, {
66
+ ...element.props,
67
+ ...props
68
+ });
69
+ } else return tag;
70
+ }
71
+ });
72
+ }
73
+ (function(_Say) {
74
+ function Plural(props) {
75
+ throw new Error("'Say.Plural' is a macro and must be used with the relevant saykit plugin");
76
+ }
77
+ _Say.Plural = Plural;
78
+ function Ordinal(props) {
79
+ throw new Error("'Say.Ordinal' is a macro and must be used with the relevant saykit plugin");
80
+ }
81
+ _Say.Ordinal = Ordinal;
82
+ function Select(props) {
83
+ throw new Error("'Say.Select' is a macro and must be used with the relevant saykit plugin");
84
+ }
85
+ _Say.Select = Select;
86
+ })(Say || (Say = {}));
87
+ //#endregion
88
+ export { Say };
@@ -0,0 +1,84 @@
1
+ import { PropsWithChildren, ReactElement, ReactNode } from "react";
2
+ import { Disallow, NumeralOptions, SelectOptions } from "saykit";
3
+
4
+ //#region src/types.d.ts
5
+ type PropsWithJSXSafeKeys<T> = { [K in keyof T as K extends number | `${number}${string}` ? `_${K}` : K extends `_${number}${string}` ? never : K]: T[K] };
6
+ //#endregion
7
+ //#region src/runtime/index.d.ts
8
+ /**
9
+ * Render the translation for a descriptor.
10
+ *
11
+ * @param descriptor Descriptor to render the translation for
12
+ * @returns The translation node for the descriptor
13
+ * @remark This is a macro and must be used with the relevant saykit plugin
14
+ */
15
+ declare function Say(props: PropsWithChildren<Disallow<{
16
+ context?: string;
17
+ }, 'id'>>): ReactElement;
18
+ declare namespace Say {
19
+ /**
20
+ * Define a pluralised message.
21
+ *
22
+ * @example
23
+ * ```tsx
24
+ * <Say.Plural
25
+ * _={count}
26
+ * one="You have 1 item"
27
+ * other="You have # items"
28
+ * />
29
+ * ```
30
+ *
31
+ * @param props._ Number to determine the plural form of
32
+ * @param props Options pluralisation rules keyed by CLDR categories or specific numbers
33
+ * @returns The plural form of the number, as a React node
34
+ * @remark This is a macro and must be used with the relevant saykit plugin
35
+ */
36
+ function Plural(props: {
37
+ _: number;
38
+ } & PropsWithJSXSafeKeys<Disallow<NumeralOptions, 'id' | 'context'>>): ReactNode;
39
+ /**
40
+ * Define an ordinal message (e.g. "1st", "2nd", "3rd").
41
+ *
42
+ * @example
43
+ * ```tsx
44
+ * <Say.Ordinal
45
+ * _={position}
46
+ * 1="#st"
47
+ * 2="#nd"
48
+ * 3="#rd"
49
+ * other="#th"
50
+ * />
51
+ * ```
52
+ *
53
+ * @param props._ Number to determine the ordinal form of
54
+ * @param props Options ordinal rules keyed by CLDR categories or specific numbers
55
+ * @returns The ordinal form of the number, as a React node
56
+ * @remark This is a macro and must be used with the relevant saykit plugin
57
+ */
58
+ function Ordinal(props: {
59
+ _: number;
60
+ } & PropsWithJSXSafeKeys<Disallow<NumeralOptions, 'id' | 'context'>>): ReactNode;
61
+ /**
62
+ * Define a select message, useful for handling gender, status, or other categories.
63
+ *
64
+ * @example
65
+ * ```tsx
66
+ * <Say.Select
67
+ * _={gender}
68
+ * male="He"
69
+ * female="She"
70
+ * other="They"
71
+ * />
72
+ * ```
73
+ *
74
+ * @param props._ Selector value to determine which option is chosen
75
+ * @param props Options a mapping of possible selector values to message strings
76
+ * @returns The select form of the value, as a React node
77
+ * @remark This is a macro and must be used with the relevant saykit plugin
78
+ */
79
+ function Select(props: {
80
+ _: string;
81
+ } & PropsWithJSXSafeKeys<Disallow<SelectOptions, 'id' | 'context'>>): ReactNode;
82
+ }
83
+ //#endregion
84
+ export { Say };
@@ -0,0 +1,88 @@
1
+ import { getSay as GET_SAY } from "./server.mjs";import { Fragment, cloneElement, createElement, isValidElement } from "react";
2
+ //#region src/components/renderer.ts
3
+ function Renderer({ html, components }) {
4
+ function getComponent(tag) {
5
+ if (typeof components === "function") return components(tag) ?? tag ?? Fragment;
6
+ return tag && tag in components ? components[tag] : Fragment;
7
+ }
8
+ let nodeKey = 0;
9
+ function parseNode(input) {
10
+ const stack = [];
11
+ let current = [];
12
+ let i = 0;
13
+ while (i < input.length) if (input[i] === "<") {
14
+ const isClosing = input[i + 1] === "/";
15
+ const isSelfClosing = input.slice(i, input.indexOf(">", i) + 1).endsWith("/>");
16
+ const tagStart = i + (isClosing ? 2 : 1);
17
+ const tagEnd = input.indexOf(">", tagStart);
18
+ const tagName = input.slice(tagStart, tagEnd).replace("/", "").trim();
19
+ i = tagEnd + 1;
20
+ if (isSelfClosing) {
21
+ const Component = getComponent(tagName);
22
+ current.push(createElement(Component, { key: nodeKey++ }));
23
+ } else if (isClosing) {
24
+ const last = stack.pop();
25
+ const element = createElement(getComponent(last.tag), { key: nodeKey++ }, ...current);
26
+ current = last.children;
27
+ current.push(element);
28
+ } else {
29
+ stack.push({
30
+ tag: tagName,
31
+ children: current
32
+ });
33
+ current = [];
34
+ }
35
+ } else {
36
+ let textEnd = input.indexOf("<", i);
37
+ if (textEnd === -1) textEnd = input.length;
38
+ const text = input.slice(i, textEnd);
39
+ current.push(text);
40
+ i = textEnd;
41
+ }
42
+ return current;
43
+ }
44
+ return createElement(Fragment, void 0, ...parseNode(html));
45
+ }
46
+ //#endregion
47
+ //#region src/types.ts
48
+ function resolveJsxSafePropKeys(props) {
49
+ const result = {};
50
+ for (const key in props) if (/^_\d+$/.test(key)) result[key.slice(1)] = props[key];
51
+ else result[key] = props[key];
52
+ return result;
53
+ }
54
+ //#endregion
55
+ //#region src/runtime/index.ts
56
+ function Say(props) {
57
+ if (!("id" in props)) throw new Error("'Say' is a macro and must be used with the relevant saykit plugin", { cause: /* @__PURE__ */ new Error("The 'id' property is required for a descriptor") });
58
+ const say = GET_SAY();
59
+ const descriptor = resolveJsxSafePropKeys(props);
60
+ return createElement(Renderer, {
61
+ html: say.call(descriptor),
62
+ components(tag) {
63
+ if (tag && tag in descriptor && isValidElement(descriptor[tag])) {
64
+ const element = descriptor[tag];
65
+ return (props) => cloneElement(element, {
66
+ ...element.props,
67
+ ...props
68
+ });
69
+ } else return tag;
70
+ }
71
+ });
72
+ }
73
+ (function(_Say) {
74
+ function Plural(props) {
75
+ throw new Error("'Say.Plural' is a macro and must be used with the relevant saykit plugin");
76
+ }
77
+ _Say.Plural = Plural;
78
+ function Ordinal(props) {
79
+ throw new Error("'Say.Ordinal' is a macro and must be used with the relevant saykit plugin");
80
+ }
81
+ _Say.Ordinal = Ordinal;
82
+ function Select(props) {
83
+ throw new Error("'Say.Select' is a macro and must be used with the relevant saykit plugin");
84
+ }
85
+ _Say.Select = Select;
86
+ })(Say || (Say = {}));
87
+ //#endregion
88
+ export { Say };
@@ -0,0 +1,33 @@
1
+ import * as _$react from "react";
2
+ import { ReactNode } from "react";
3
+ import { ReadonlySay, Say } from "saykit";
4
+ //#region src/runtime/server.d.ts
5
+ /**
6
+ * Set the current {@link Say} **server** instance.
7
+ * Must be called before any {@link getSay} calls.
8
+ *
9
+ * @param say The current {@link Say} instance
10
+ */
11
+ declare function setSay(say: Say | ReadonlySay | (() => Say | ReadonlySay)): void;
12
+ /**
13
+ * Get the current {@link Say} **server** instance.
14
+ * Must only be called after any {@link setSay} calls.
15
+ *
16
+ * @returns The current {@link Say} instance
17
+ * @throws If no {@link Say} instance has been set
18
+ */
19
+ declare function getSay(): ReadonlySay;
20
+ /**
21
+ * Create a {@link withSay} higher-order component factory bound to a specific {@link Say} instance.
22
+ *
23
+ * @param say The {@link Say} instance to bind into the server context
24
+ *
25
+ * @returns A {@link withSay} higher-order component factory
26
+ */
27
+ declare function unstable_createWithSay(say: Say): <P = unknown>(Component: (props: PropsWithSay<P>) => ReactNode, getLocale: (props: P) => string | Promise<string>) => (props: P) => Promise<_$react.FunctionComponentElement<PropsWithSay<P>>>;
28
+ type PropsWithSay<P = unknown> = P & {
29
+ locale: string;
30
+ messages: Say.Messages;
31
+ };
32
+ //#endregion
33
+ export { PropsWithSay, getSay, setSay, unstable_createWithSay };
@@ -0,0 +1,56 @@
1
+ import { cache, createElement } from "react";
2
+ import { Say } from "saykit";
3
+ import "server-only";
4
+ //#region src/runtime/server.ts
5
+ const serverContext = cache(() => ({ current: null }));
6
+ /**
7
+ * Set the current {@link Say} **server** instance.
8
+ * Must be called before any {@link getSay} calls.
9
+ *
10
+ * @param say The current {@link Say} instance
11
+ */
12
+ function setSay(say) {
13
+ const ref = serverContext();
14
+ if (say instanceof Say) ref.current = say.clone().freeze();
15
+ else ref.current = say().clone().freeze();
16
+ }
17
+ /**
18
+ * Get the current {@link Say} **server** instance.
19
+ * Must only be called after any {@link setSay} calls.
20
+ *
21
+ * @returns The current {@link Say} instance
22
+ * @throws If no {@link Say} instance has been set
23
+ */
24
+ function getSay() {
25
+ const ref = serverContext();
26
+ if (!ref.current) throw new Error("Attempt to access the server-only Say instance before initialisation", { cause: /* @__PURE__ */ new Error("'getSay' must be called after 'setSay'") });
27
+ return ref.current;
28
+ }
29
+ /**
30
+ * Create a {@link withSay} higher-order component factory bound to a specific {@link Say} instance.
31
+ *
32
+ * @param say The {@link Say} instance to bind into the server context
33
+ *
34
+ * @returns A {@link withSay} higher-order component factory
35
+ */
36
+ function unstable_createWithSay(say) {
37
+ /**
38
+ * Wrap a server component so that a {@link Say} instance is initialised before render.
39
+ */
40
+ return function withSay(Component, getLocale) {
41
+ return async function WithSay(props) {
42
+ const guess = await getLocale(props);
43
+ const locale = say.match(guess);
44
+ await say.load(locale);
45
+ say.activate(locale);
46
+ setSay(say);
47
+ return createElement(Component, {
48
+ ...props,
49
+ locale: say.locale,
50
+ messages: say.messages
51
+ });
52
+ };
53
+ };
54
+ }
55
+ //#endregion
56
+ export { getSay, setSay, unstable_createWithSay };
package/package.json CHANGED
@@ -1,4 +1,61 @@
1
- {
2
- "name": "@saykit/react",
3
- "version": "0.0.0"
1
+ {
2
+ "name": "@saykit/react",
3
+ "version": "0.1.0",
4
+ "description": "React integration for saykit, i18n hooks and components",
5
+ "keywords": [
6
+ "i18n",
7
+ "internationalization",
8
+ "react",
9
+ "saykit"
10
+ ],
11
+ "homepage": "https://github.com/k0d13/saykit#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/k0d13/saykit/issues"
14
+ },
15
+ "license": "MIT",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/k0d13/saykit.git",
19
+ "directory": "packages/integration-react"
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "!dist/**/*.map"
24
+ ],
25
+ "type": "module",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.mts",
29
+ "react-server": "./dist/index.server.mjs",
30
+ "default": "./dist/index.client.mjs"
31
+ },
32
+ "./client": {
33
+ "types": "./dist/client.d.mts",
34
+ "default": "./dist/client.mjs"
35
+ },
36
+ "./server": {
37
+ "types": "./dist/server.d.mts",
38
+ "default": "./dist/server.mjs"
39
+ }
40
+ },
41
+ "publishConfig": {
42
+ "access": "public",
43
+ "provenance": true
44
+ },
45
+ "dependencies": {
46
+ "server-only": "^0.0.1"
47
+ },
48
+ "devDependencies": {
49
+ "@types/react": "^19.2.14",
50
+ "react": "^19.2.6",
51
+ "saykit": "^0.1.0"
52
+ },
53
+ "peerDependencies": {
54
+ "react": "*",
55
+ "saykit": "*"
56
+ },
57
+ "scripts": {
58
+ "check": "tsc --noEmit",
59
+ "build": "tsdown"
60
+ }
4
61
  }