@getnori/rewards 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,6 @@
1
+ Nori SDK
2
+ Copyright 2026 The Nori authors
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+ "Nori" and the Nori logo are trademarks of their owner and are not licensed
6
+ under the Apache License; see section 6 of the License.
package/README.md CHANGED
@@ -1,3 +1,33 @@
1
- # Temporary Holding Version
1
+ # @getnori/rewards
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Show viewers what they earn for watching: a points badge, a "+10 points"
4
+ toast when a view is rewarded, and their earning history.
5
+
6
+ ```sh
7
+ npm install @getnori/core @getnori/rewards
8
+ ```
9
+
10
+ ```tsx
11
+ import { NoriFeed } from "@getnori/feed";
12
+ import { PointsBadge, RewardToasts } from "@getnori/rewards";
13
+
14
+ <View style={{ flex: 1 }}>
15
+ <NoriFeed client={nori} />
16
+ <PointsBadge client={nori} style={{ position: "absolute", top: 56, right: 16 }} />
17
+ <RewardToasts client={nori} />
18
+ </View>
19
+ ```
20
+
21
+ - **Rewards are decided on the server**, from the views `@getnori/feed`
22
+ reports and your reward rules (points per view, minimum watch, daily cap).
23
+ The SDK only displays the decisions.
24
+ - **Points are paid in your loyalty currency.** Nori sends each reward to your
25
+ backend by signed webhook; your loyalty system holds the balance. The badge
26
+ shows what the viewer earned **through Nori** (`client.rewards()`), not
27
+ their loyalty balance.
28
+ - `RewardToasts` also tells the viewer once per session when they reach the
29
+ daily cap (`showDailyCapNotice`).
30
+
31
+ Hooks for your own UI: `useRewards(client)` returns `{ summary, loading, error, refresh }`
32
+ (totals, today's progress, history) and updates the moment a view is rewarded;
33
+ `useRewardDecisions(client, fn)` calls `fn` for every server decision.
package/dist/index.cjs ADDED
@@ -0,0 +1,203 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ PointsBadge: () => PointsBadge,
24
+ RewardToasts: () => RewardToasts,
25
+ useRewardDecisions: () => useRewardDecisions,
26
+ useRewards: () => useRewards
27
+ });
28
+ module.exports = __toCommonJS(index_exports);
29
+
30
+ // src/PointsBadge.tsx
31
+ var import_react_native = require("react-native");
32
+
33
+ // src/useRewards.ts
34
+ var import_react = require("react");
35
+ function useRewardDecisions(client, listener) {
36
+ const ref = (0, import_react.useRef)(listener);
37
+ ref.current = listener;
38
+ (0, import_react.useEffect)(
39
+ () => client.on("reward", (decisions) => {
40
+ for (const d of decisions) ref.current(d);
41
+ }),
42
+ [client]
43
+ );
44
+ }
45
+ function useRewards(client, { historyLimit = 20, refreshDelayMs = 1500 } = {}) {
46
+ const [summary, setSummary] = (0, import_react.useState)(null);
47
+ const [loading, setLoading] = (0, import_react.useState)(true);
48
+ const [error, setError] = (0, import_react.useState)(null);
49
+ const live = (0, import_react.useRef)(true);
50
+ const timer = (0, import_react.useRef)(null);
51
+ const refresh = (0, import_react.useCallback)(async () => {
52
+ try {
53
+ const next = await client.rewards({ limit: historyLimit });
54
+ if (!live.current) return;
55
+ setSummary(next);
56
+ setError(null);
57
+ } catch (e) {
58
+ if (live.current) setError(e);
59
+ } finally {
60
+ if (live.current) setLoading(false);
61
+ }
62
+ }, [client, historyLimit]);
63
+ (0, import_react.useEffect)(() => {
64
+ live.current = true;
65
+ void refresh();
66
+ return () => {
67
+ live.current = false;
68
+ if (timer.current) clearTimeout(timer.current);
69
+ };
70
+ }, [refresh]);
71
+ useRewardDecisions(client, (decision) => {
72
+ if (decision.status !== "rewarded") return;
73
+ setSummary(
74
+ (prev) => prev ? {
75
+ ...prev,
76
+ total_points: prev.total_points + decision.points,
77
+ today: {
78
+ ...prev.today,
79
+ points: prev.today.points + decision.points,
80
+ remaining: Math.max(0, prev.today.remaining - decision.points)
81
+ }
82
+ } : prev
83
+ );
84
+ if (timer.current) clearTimeout(timer.current);
85
+ timer.current = setTimeout(() => void refresh(), refreshDelayMs);
86
+ });
87
+ return { summary, loading, error, refresh };
88
+ }
89
+
90
+ // src/PointsBadge.tsx
91
+ var import_jsx_runtime = require("react/jsx-runtime");
92
+ function PointsBadge({
93
+ client,
94
+ show = "total",
95
+ onPress,
96
+ backgroundColor = "rgba(0,0,0,0.55)",
97
+ textColor = "#ffffff",
98
+ style
99
+ }) {
100
+ const { summary } = useRewards(client);
101
+ if (!summary) return null;
102
+ const points = show === "today" ? summary.today.points : summary.total_points;
103
+ const label = `${points.toLocaleString()} ${summary.currency_name}${show === "today" ? " today" : ""}`;
104
+ const content = /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_react_native.View, { style: [styles.badge, { backgroundColor }, style], testID: "nori-points-badge", children: [
105
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native.Text, { style: [styles.star, { color: textColor }], children: "\u2605" }),
106
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native.Text, { style: [styles.text, { color: textColor }], children: label })
107
+ ] });
108
+ return onPress ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native.Pressable, { onPress, accessibilityRole: "button", accessibilityLabel: label, children: content }) : content;
109
+ }
110
+ var styles = import_react_native.StyleSheet.create({
111
+ badge: { flexDirection: "row", alignItems: "center", alignSelf: "flex-start", borderRadius: 16, paddingHorizontal: 12, paddingVertical: 6 },
112
+ star: { fontSize: 13, marginRight: 6 },
113
+ text: { fontSize: 13, fontWeight: "700" }
114
+ });
115
+
116
+ // src/RewardToasts.tsx
117
+ var import_react2 = require("react");
118
+ var import_react_native2 = require("react-native");
119
+ var import_jsx_runtime2 = require("react/jsx-runtime");
120
+ function RewardToasts({
121
+ client,
122
+ format = (d) => `+${d.points} ${d.currency_name}`,
123
+ showDailyCapNotice = true,
124
+ durationMs = 2500,
125
+ backgroundColor = "rgba(17,17,17,0.9)",
126
+ textColor = "#ffffff",
127
+ style
128
+ }) {
129
+ const [toast, setToast] = (0, import_react2.useState)(null);
130
+ const capShown = (0, import_react2.useRef)(false);
131
+ const counter = (0, import_react2.useRef)(0);
132
+ useRewardDecisions(client, (decision) => {
133
+ if (decision.status === "rewarded" && decision.points > 0) {
134
+ setToast({ key: ++counter.current, text: format(decision) });
135
+ } else if (decision.reason === "daily_cap" && showDailyCapNotice && !capShown.current) {
136
+ capShown.current = true;
137
+ setToast({ key: ++counter.current, text: `You've earned today's maximum ${decision.currency_name}. Come back tomorrow!` });
138
+ }
139
+ });
140
+ if (!toast) return null;
141
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
142
+ ToastView,
143
+ {
144
+ text: toast.text,
145
+ durationMs,
146
+ backgroundColor,
147
+ textColor,
148
+ style,
149
+ onDone: () => setToast((t) => t?.key === toast.key ? null : t)
150
+ },
151
+ toast.key
152
+ );
153
+ }
154
+ function ToastView({
155
+ text,
156
+ durationMs,
157
+ backgroundColor,
158
+ textColor,
159
+ style,
160
+ onDone
161
+ }) {
162
+ const opacity = (0, import_react2.useRef)(new import_react_native2.Animated.Value(0)).current;
163
+ const onDoneRef = (0, import_react2.useRef)(onDone);
164
+ onDoneRef.current = onDone;
165
+ (0, import_react2.useEffect)(() => {
166
+ import_react_native2.Animated.timing(opacity, { toValue: 1, duration: 180, useNativeDriver: true }).start();
167
+ const timer = setTimeout(() => {
168
+ import_react_native2.Animated.timing(opacity, { toValue: 0, duration: 220, useNativeDriver: true }).start(() => onDoneRef.current());
169
+ }, durationMs);
170
+ return () => clearTimeout(timer);
171
+ }, [durationMs, opacity]);
172
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
173
+ import_react_native2.Animated.View,
174
+ {
175
+ pointerEvents: "none",
176
+ style: [styles2.toast, { backgroundColor, opacity }, style],
177
+ accessibilityLiveRegion: "polite",
178
+ accessibilityRole: "alert",
179
+ testID: "nori-reward-toast",
180
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_native2.Text, { style: [styles2.text, { color: textColor }], children: text })
181
+ }
182
+ );
183
+ }
184
+ var styles2 = import_react_native2.StyleSheet.create({
185
+ toast: {
186
+ position: "absolute",
187
+ top: 56,
188
+ alignSelf: "center",
189
+ maxWidth: "86%",
190
+ borderRadius: 20,
191
+ paddingHorizontal: 16,
192
+ paddingVertical: 10
193
+ },
194
+ text: { fontSize: 15, fontWeight: "700", textAlign: "center" }
195
+ });
196
+ // Annotate the CommonJS export names for ESM import in node:
197
+ 0 && (module.exports = {
198
+ PointsBadge,
199
+ RewardToasts,
200
+ useRewardDecisions,
201
+ useRewards
202
+ });
203
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/PointsBadge.tsx","../src/useRewards.ts","../src/RewardToasts.tsx"],"sourcesContent":["export { PointsBadge } from \"./PointsBadge\";\nexport type { PointsBadgeProps } from \"./PointsBadge\";\nexport { RewardToasts } from \"./RewardToasts\";\nexport type { RewardToastsProps } from \"./RewardToasts\";\nexport { useRewards, useRewardDecisions } from \"./useRewards\";\nexport type { RewardsState, UseRewardsOptions } from \"./useRewards\";\n","import React from \"react\";\nimport { Pressable, StyleSheet, Text, View, type StyleProp, type ViewStyle } from \"react-native\";\nimport type { NoriClient } from \"@getnori/core\";\nimport { useRewards } from \"./useRewards\";\n\nexport interface PointsBadgeProps {\n client: NoriClient;\n /** What to show: all-time Nori earnings or today's. Default \"total\". */\n show?: \"total\" | \"today\";\n onPress?: () => void;\n backgroundColor?: string;\n textColor?: string;\n style?: StyleProp<ViewStyle>;\n}\n\n/** A small pill with the viewer's points, e.g. in the feed's corner. Hidden until loaded. */\nexport function PointsBadge({\n client,\n show = \"total\",\n onPress,\n backgroundColor = \"rgba(0,0,0,0.55)\",\n textColor = \"#ffffff\",\n style,\n}: PointsBadgeProps) {\n const { summary } = useRewards(client);\n if (!summary) return null;\n\n const points = show === \"today\" ? summary.today.points : summary.total_points;\n const label = `${points.toLocaleString()} ${summary.currency_name}${show === \"today\" ? \" today\" : \"\"}`;\n const content = (\n <View style={[styles.badge, { backgroundColor }, style]} testID=\"nori-points-badge\">\n <Text style={[styles.star, { color: textColor }]}>★</Text>\n <Text style={[styles.text, { color: textColor }]}>{label}</Text>\n </View>\n );\n return onPress ? (\n <Pressable onPress={onPress} accessibilityRole=\"button\" accessibilityLabel={label}>\n {content}\n </Pressable>\n ) : (\n content\n );\n}\n\nconst styles = StyleSheet.create({\n badge: { flexDirection: \"row\", alignItems: \"center\", alignSelf: \"flex-start\", borderRadius: 16, paddingHorizontal: 12, paddingVertical: 6 },\n star: { fontSize: 13, marginRight: 6 },\n text: { fontSize: 13, fontWeight: \"700\" },\n});\n","import { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { NoriClient, NoriError, RewardDecision, RewardsSummary } from \"@getnori/core\";\n\nexport interface UseRewardsOptions {\n /** History entries to load. Default 20. */\n historyLimit?: number;\n /** Re-read the summary this long after a reward, to pick up credited status. Default 1500 ms. */\n refreshDelayMs?: number;\n}\n\nexport interface RewardsState {\n summary: RewardsSummary | null;\n loading: boolean;\n error: NoriError | Error | null;\n refresh: () => Promise<void>;\n}\n\n/** Calls `listener` with each reward the server grants this viewer. */\nexport function useRewardDecisions(client: Pick<NoriClient, \"on\">, listener: (decision: RewardDecision) => void): void {\n const ref = useRef(listener);\n ref.current = listener;\n useEffect(\n () =>\n client.on(\"reward\", (decisions) => {\n for (const d of decisions) ref.current(d);\n }),\n [client],\n );\n}\n\n/**\n * The viewer's Nori earnings. Updates the moment a view is rewarded, then\n * re-reads the server for the authoritative numbers.\n */\nexport function useRewards(client: NoriClient, { historyLimit = 20, refreshDelayMs = 1500 }: UseRewardsOptions = {}): RewardsState {\n const [summary, setSummary] = useState<RewardsSummary | null>(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState<NoriError | Error | null>(null);\n const live = useRef(true);\n const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const refresh = useCallback(async () => {\n try {\n const next = await client.rewards({ limit: historyLimit });\n if (!live.current) return;\n setSummary(next);\n setError(null);\n } catch (e) {\n if (live.current) setError(e as Error);\n } finally {\n if (live.current) setLoading(false);\n }\n }, [client, historyLimit]);\n\n useEffect(() => {\n live.current = true;\n void refresh();\n return () => {\n live.current = false;\n if (timer.current) clearTimeout(timer.current);\n };\n }, [refresh]);\n\n useRewardDecisions(client, (decision) => {\n if (decision.status !== \"rewarded\") return;\n setSummary((prev) =>\n prev\n ? {\n ...prev,\n total_points: prev.total_points + decision.points,\n today: {\n ...prev.today,\n points: prev.today.points + decision.points,\n remaining: Math.max(0, prev.today.remaining - decision.points),\n },\n }\n : prev,\n );\n if (timer.current) clearTimeout(timer.current);\n timer.current = setTimeout(() => void refresh(), refreshDelayMs);\n });\n\n return { summary, loading, error, refresh };\n}\n","import React, { useEffect, useRef, useState } from \"react\";\nimport { Animated, StyleSheet, Text, type StyleProp, type ViewStyle } from \"react-native\";\nimport type { NoriClient, RewardDecision } from \"@getnori/core\";\nimport { useRewardDecisions } from \"./useRewards\";\n\nexport interface RewardToastsProps {\n client: NoriClient;\n /** Text for a reward. Default \"+10 points\". */\n format?: (decision: RewardDecision) => string;\n /** Tell the viewer once per session when they hit the daily cap. Default true. */\n showDailyCapNotice?: boolean;\n /** How long each toast stays. Default 2500 ms. */\n durationMs?: number;\n backgroundColor?: string;\n textColor?: string;\n style?: StyleProp<ViewStyle>;\n}\n\ninterface Toast {\n key: number;\n text: string;\n}\n\n/**\n * Shows \"+10 points\" when the server rewards a view. Mount it once, above\n * the feed (it positions itself at the top of its parent).\n */\nexport function RewardToasts({\n client,\n format = (d) => `+${d.points} ${d.currency_name}`,\n showDailyCapNotice = true,\n durationMs = 2500,\n backgroundColor = \"rgba(17,17,17,0.9)\",\n textColor = \"#ffffff\",\n style,\n}: RewardToastsProps) {\n const [toast, setToast] = useState<Toast | null>(null);\n const capShown = useRef(false);\n const counter = useRef(0);\n\n useRewardDecisions(client, (decision) => {\n if (decision.status === \"rewarded\" && decision.points > 0) {\n setToast({ key: ++counter.current, text: format(decision) });\n } else if (decision.reason === \"daily_cap\" && showDailyCapNotice && !capShown.current) {\n capShown.current = true;\n setToast({ key: ++counter.current, text: `You've earned today's maximum ${decision.currency_name}. Come back tomorrow!` });\n }\n });\n\n if (!toast) return null;\n return (\n <ToastView\n key={toast.key}\n text={toast.text}\n durationMs={durationMs}\n backgroundColor={backgroundColor}\n textColor={textColor}\n style={style}\n onDone={() => setToast((t) => (t?.key === toast.key ? null : t))}\n />\n );\n}\n\nfunction ToastView({\n text,\n durationMs,\n backgroundColor,\n textColor,\n style,\n onDone,\n}: {\n text: string;\n durationMs: number;\n backgroundColor: string;\n textColor: string;\n style?: StyleProp<ViewStyle>;\n onDone: () => void;\n}) {\n const opacity = useRef(new Animated.Value(0)).current;\n const onDoneRef = useRef(onDone);\n onDoneRef.current = onDone;\n\n useEffect(() => {\n Animated.timing(opacity, { toValue: 1, duration: 180, useNativeDriver: true }).start();\n const timer = setTimeout(() => {\n Animated.timing(opacity, { toValue: 0, duration: 220, useNativeDriver: true }).start(() => onDoneRef.current());\n }, durationMs);\n return () => clearTimeout(timer);\n }, [durationMs, opacity]);\n\n return (\n <Animated.View\n pointerEvents=\"none\"\n style={[styles.toast, { backgroundColor, opacity }, style]}\n accessibilityLiveRegion=\"polite\"\n accessibilityRole=\"alert\"\n testID=\"nori-reward-toast\"\n >\n <Text style={[styles.text, { color: textColor }]}>{text}</Text>\n </Animated.View>\n );\n}\n\nconst styles = StyleSheet.create({\n toast: {\n position: \"absolute\", top: 56, alignSelf: \"center\", maxWidth: \"86%\",\n borderRadius: 20, paddingHorizontal: 16, paddingVertical: 10,\n },\n text: { fontSize: 15, fontWeight: \"700\", textAlign: \"center\" },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,0BAAkF;;;ACDlF,mBAAyD;AAkBlD,SAAS,mBAAmB,QAAgC,UAAoD;AACrH,QAAM,UAAM,qBAAO,QAAQ;AAC3B,MAAI,UAAU;AACd;AAAA,IACE,MACE,OAAO,GAAG,UAAU,CAAC,cAAc;AACjC,iBAAW,KAAK,UAAW,KAAI,QAAQ,CAAC;AAAA,IAC1C,CAAC;AAAA,IACH,CAAC,MAAM;AAAA,EACT;AACF;AAMO,SAAS,WAAW,QAAoB,EAAE,eAAe,IAAI,iBAAiB,KAAK,IAAuB,CAAC,GAAiB;AACjI,QAAM,CAAC,SAAS,UAAU,QAAI,uBAAgC,IAAI;AAClE,QAAM,CAAC,SAAS,UAAU,QAAI,uBAAS,IAAI;AAC3C,QAAM,CAAC,OAAO,QAAQ,QAAI,uBAAmC,IAAI;AACjE,QAAM,WAAO,qBAAO,IAAI;AACxB,QAAM,YAAQ,qBAA6C,IAAI;AAE/D,QAAM,cAAU,0BAAY,YAAY;AACtC,QAAI;AACF,YAAM,OAAO,MAAM,OAAO,QAAQ,EAAE,OAAO,aAAa,CAAC;AACzD,UAAI,CAAC,KAAK,QAAS;AACnB,iBAAW,IAAI;AACf,eAAS,IAA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;AAAA,EAC/B,OAAO;AAAA,IACL,UAAU;AAAA,IAAY,KAAK;AAAA,IAAI,WAAW;AAAA,IAAU,UAAU;AAAA,IAC9D,cAAc;AAAA,IAAI,mBAAmB;AAAA,IAAI,iBAAiB;AAAA,EAC5D;AAAA,EACA,MAAM,EAAE,UAAU,IAAI,YAAY,OAAO,WAAW,SAAS;AAC/D,CAAC;","names":["import_react","import_react_native","import_jsx_runtime","styles"]}
@@ -0,0 +1,55 @@
1
+ import React from 'react';
2
+ import { StyleProp, ViewStyle } from 'react-native';
3
+ import { NoriClient, RewardDecision, RewardsSummary, NoriError } from '@getnori/core';
4
+
5
+ interface PointsBadgeProps {
6
+ client: NoriClient;
7
+ /** What to show: all-time Nori earnings or today's. Default "total". */
8
+ show?: "total" | "today";
9
+ onPress?: () => void;
10
+ backgroundColor?: string;
11
+ textColor?: string;
12
+ style?: StyleProp<ViewStyle>;
13
+ }
14
+ /** A small pill with the viewer's points, e.g. in the feed's corner. Hidden until loaded. */
15
+ declare function PointsBadge({ client, show, onPress, backgroundColor, textColor, style, }: PointsBadgeProps): React.JSX.Element | null;
16
+
17
+ interface RewardToastsProps {
18
+ client: NoriClient;
19
+ /** Text for a reward. Default "+10 points". */
20
+ format?: (decision: RewardDecision) => string;
21
+ /** Tell the viewer once per session when they hit the daily cap. Default true. */
22
+ showDailyCapNotice?: boolean;
23
+ /** How long each toast stays. Default 2500 ms. */
24
+ durationMs?: number;
25
+ backgroundColor?: string;
26
+ textColor?: string;
27
+ style?: StyleProp<ViewStyle>;
28
+ }
29
+ /**
30
+ * Shows "+10 points" when the server rewards a view. Mount it once, above
31
+ * the feed (it positions itself at the top of its parent).
32
+ */
33
+ declare function RewardToasts({ client, format, showDailyCapNotice, durationMs, backgroundColor, textColor, style, }: RewardToastsProps): React.JSX.Element | null;
34
+
35
+ interface UseRewardsOptions {
36
+ /** History entries to load. Default 20. */
37
+ historyLimit?: number;
38
+ /** Re-read the summary this long after a reward, to pick up credited status. Default 1500 ms. */
39
+ refreshDelayMs?: number;
40
+ }
41
+ interface RewardsState {
42
+ summary: RewardsSummary | null;
43
+ loading: boolean;
44
+ error: NoriError | Error | null;
45
+ refresh: () => Promise<void>;
46
+ }
47
+ /** Calls `listener` with each reward the server grants this viewer. */
48
+ declare function useRewardDecisions(client: Pick<NoriClient, "on">, listener: (decision: RewardDecision) => void): void;
49
+ /**
50
+ * The viewer's Nori earnings. Updates the moment a view is rewarded, then
51
+ * re-reads the server for the authoritative numbers.
52
+ */
53
+ declare function useRewards(client: NoriClient, { historyLimit, refreshDelayMs }?: UseRewardsOptions): RewardsState;
54
+
55
+ export { PointsBadge, type PointsBadgeProps, RewardToasts, type RewardToastsProps, type RewardsState, type UseRewardsOptions, useRewardDecisions, useRewards };
@@ -0,0 +1,55 @@
1
+ import React from 'react';
2
+ import { StyleProp, ViewStyle } from 'react-native';
3
+ import { NoriClient, RewardDecision, RewardsSummary, NoriError } from '@getnori/core';
4
+
5
+ interface PointsBadgeProps {
6
+ client: NoriClient;
7
+ /** What to show: all-time Nori earnings or today's. Default "total". */
8
+ show?: "total" | "today";
9
+ onPress?: () => void;
10
+ backgroundColor?: string;
11
+ textColor?: string;
12
+ style?: StyleProp<ViewStyle>;
13
+ }
14
+ /** A small pill with the viewer's points, e.g. in the feed's corner. Hidden until loaded. */
15
+ declare function PointsBadge({ client, show, onPress, backgroundColor, textColor, style, }: PointsBadgeProps): React.JSX.Element | null;
16
+
17
+ interface RewardToastsProps {
18
+ client: NoriClient;
19
+ /** Text for a reward. Default "+10 points". */
20
+ format?: (decision: RewardDecision) => string;
21
+ /** Tell the viewer once per session when they hit the daily cap. Default true. */
22
+ showDailyCapNotice?: boolean;
23
+ /** How long each toast stays. Default 2500 ms. */
24
+ durationMs?: number;
25
+ backgroundColor?: string;
26
+ textColor?: string;
27
+ style?: StyleProp<ViewStyle>;
28
+ }
29
+ /**
30
+ * Shows "+10 points" when the server rewards a view. Mount it once, above
31
+ * the feed (it positions itself at the top of its parent).
32
+ */
33
+ declare function RewardToasts({ client, format, showDailyCapNotice, durationMs, backgroundColor, textColor, style, }: RewardToastsProps): React.JSX.Element | null;
34
+
35
+ interface UseRewardsOptions {
36
+ /** History entries to load. Default 20. */
37
+ historyLimit?: number;
38
+ /** Re-read the summary this long after a reward, to pick up credited status. Default 1500 ms. */
39
+ refreshDelayMs?: number;
40
+ }
41
+ interface RewardsState {
42
+ summary: RewardsSummary | null;
43
+ loading: boolean;
44
+ error: NoriError | Error | null;
45
+ refresh: () => Promise<void>;
46
+ }
47
+ /** Calls `listener` with each reward the server grants this viewer. */
48
+ declare function useRewardDecisions(client: Pick<NoriClient, "on">, listener: (decision: RewardDecision) => void): void;
49
+ /**
50
+ * The viewer's Nori earnings. Updates the moment a view is rewarded, then
51
+ * re-reads the server for the authoritative numbers.
52
+ */
53
+ declare function useRewards(client: NoriClient, { historyLimit, refreshDelayMs }?: UseRewardsOptions): RewardsState;
54
+
55
+ export { PointsBadge, type PointsBadgeProps, RewardToasts, type RewardToastsProps, type RewardsState, type UseRewardsOptions, useRewardDecisions, useRewards };
package/dist/index.js ADDED
@@ -0,0 +1,173 @@
1
+ // src/PointsBadge.tsx
2
+ import { Pressable, StyleSheet, Text, View } from "react-native";
3
+
4
+ // src/useRewards.ts
5
+ import { useCallback, useEffect, useRef, useState } from "react";
6
+ function useRewardDecisions(client, listener) {
7
+ const ref = useRef(listener);
8
+ ref.current = listener;
9
+ useEffect(
10
+ () => client.on("reward", (decisions) => {
11
+ for (const d of decisions) ref.current(d);
12
+ }),
13
+ [client]
14
+ );
15
+ }
16
+ function useRewards(client, { historyLimit = 20, refreshDelayMs = 1500 } = {}) {
17
+ const [summary, setSummary] = useState(null);
18
+ const [loading, setLoading] = useState(true);
19
+ const [error, setError] = useState(null);
20
+ const live = useRef(true);
21
+ const timer = useRef(null);
22
+ const refresh = useCallback(async () => {
23
+ try {
24
+ const next = await client.rewards({ limit: historyLimit });
25
+ if (!live.current) return;
26
+ setSummary(next);
27
+ setError(null);
28
+ } catch (e) {
29
+ if (live.current) setError(e);
30
+ } finally {
31
+ if (live.current) setLoading(false);
32
+ }
33
+ }, [client, historyLimit]);
34
+ useEffect(() => {
35
+ live.current = true;
36
+ void refresh();
37
+ return () => {
38
+ live.current = false;
39
+ if (timer.current) clearTimeout(timer.current);
40
+ };
41
+ }, [refresh]);
42
+ useRewardDecisions(client, (decision) => {
43
+ if (decision.status !== "rewarded") return;
44
+ setSummary(
45
+ (prev) => prev ? {
46
+ ...prev,
47
+ total_points: prev.total_points + decision.points,
48
+ today: {
49
+ ...prev.today,
50
+ points: prev.today.points + decision.points,
51
+ remaining: Math.max(0, prev.today.remaining - decision.points)
52
+ }
53
+ } : prev
54
+ );
55
+ if (timer.current) clearTimeout(timer.current);
56
+ timer.current = setTimeout(() => void refresh(), refreshDelayMs);
57
+ });
58
+ return { summary, loading, error, refresh };
59
+ }
60
+
61
+ // src/PointsBadge.tsx
62
+ import { jsx, jsxs } from "react/jsx-runtime";
63
+ function PointsBadge({
64
+ client,
65
+ show = "total",
66
+ onPress,
67
+ backgroundColor = "rgba(0,0,0,0.55)",
68
+ textColor = "#ffffff",
69
+ style
70
+ }) {
71
+ const { summary } = useRewards(client);
72
+ if (!summary) return null;
73
+ const points = show === "today" ? summary.today.points : summary.total_points;
74
+ const label = `${points.toLocaleString()} ${summary.currency_name}${show === "today" ? " today" : ""}`;
75
+ const content = /* @__PURE__ */ jsxs(View, { style: [styles.badge, { backgroundColor }, style], testID: "nori-points-badge", children: [
76
+ /* @__PURE__ */ jsx(Text, { style: [styles.star, { color: textColor }], children: "\u2605" }),
77
+ /* @__PURE__ */ jsx(Text, { style: [styles.text, { color: textColor }], children: label })
78
+ ] });
79
+ return onPress ? /* @__PURE__ */ jsx(Pressable, { onPress, accessibilityRole: "button", accessibilityLabel: label, children: content }) : content;
80
+ }
81
+ var styles = StyleSheet.create({
82
+ badge: { flexDirection: "row", alignItems: "center", alignSelf: "flex-start", borderRadius: 16, paddingHorizontal: 12, paddingVertical: 6 },
83
+ star: { fontSize: 13, marginRight: 6 },
84
+ text: { fontSize: 13, fontWeight: "700" }
85
+ });
86
+
87
+ // src/RewardToasts.tsx
88
+ import { useEffect as useEffect2, useRef as useRef2, useState as useState2 } from "react";
89
+ import { Animated, StyleSheet as StyleSheet2, Text as Text2 } from "react-native";
90
+ import { jsx as jsx2 } from "react/jsx-runtime";
91
+ function RewardToasts({
92
+ client,
93
+ format = (d) => `+${d.points} ${d.currency_name}`,
94
+ showDailyCapNotice = true,
95
+ durationMs = 2500,
96
+ backgroundColor = "rgba(17,17,17,0.9)",
97
+ textColor = "#ffffff",
98
+ style
99
+ }) {
100
+ const [toast, setToast] = useState2(null);
101
+ const capShown = useRef2(false);
102
+ const counter = useRef2(0);
103
+ useRewardDecisions(client, (decision) => {
104
+ if (decision.status === "rewarded" && decision.points > 0) {
105
+ setToast({ key: ++counter.current, text: format(decision) });
106
+ } else if (decision.reason === "daily_cap" && showDailyCapNotice && !capShown.current) {
107
+ capShown.current = true;
108
+ setToast({ key: ++counter.current, text: `You've earned today's maximum ${decision.currency_name}. Come back tomorrow!` });
109
+ }
110
+ });
111
+ if (!toast) return null;
112
+ return /* @__PURE__ */ jsx2(
113
+ ToastView,
114
+ {
115
+ text: toast.text,
116
+ durationMs,
117
+ backgroundColor,
118
+ textColor,
119
+ style,
120
+ onDone: () => setToast((t) => t?.key === toast.key ? null : t)
121
+ },
122
+ toast.key
123
+ );
124
+ }
125
+ function ToastView({
126
+ text,
127
+ durationMs,
128
+ backgroundColor,
129
+ textColor,
130
+ style,
131
+ onDone
132
+ }) {
133
+ const opacity = useRef2(new Animated.Value(0)).current;
134
+ const onDoneRef = useRef2(onDone);
135
+ onDoneRef.current = onDone;
136
+ useEffect2(() => {
137
+ Animated.timing(opacity, { toValue: 1, duration: 180, useNativeDriver: true }).start();
138
+ const timer = setTimeout(() => {
139
+ Animated.timing(opacity, { toValue: 0, duration: 220, useNativeDriver: true }).start(() => onDoneRef.current());
140
+ }, durationMs);
141
+ return () => clearTimeout(timer);
142
+ }, [durationMs, opacity]);
143
+ return /* @__PURE__ */ jsx2(
144
+ Animated.View,
145
+ {
146
+ pointerEvents: "none",
147
+ style: [styles2.toast, { backgroundColor, opacity }, style],
148
+ accessibilityLiveRegion: "polite",
149
+ accessibilityRole: "alert",
150
+ testID: "nori-reward-toast",
151
+ children: /* @__PURE__ */ jsx2(Text2, { style: [styles2.text, { color: textColor }], children: text })
152
+ }
153
+ );
154
+ }
155
+ var styles2 = StyleSheet2.create({
156
+ toast: {
157
+ position: "absolute",
158
+ top: 56,
159
+ alignSelf: "center",
160
+ maxWidth: "86%",
161
+ borderRadius: 20,
162
+ paddingHorizontal: 16,
163
+ paddingVertical: 10
164
+ },
165
+ text: { fontSize: 15, fontWeight: "700", textAlign: "center" }
166
+ });
167
+ export {
168
+ PointsBadge,
169
+ RewardToasts,
170
+ useRewardDecisions,
171
+ useRewards
172
+ };
173
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/PointsBadge.tsx","../src/useRewards.ts","../src/RewardToasts.tsx"],"sourcesContent":["import React from \"react\";\nimport { Pressable, StyleSheet, Text, View, type StyleProp, type ViewStyle } from \"react-native\";\nimport type { NoriClient } from \"@getnori/core\";\nimport { useRewards } from \"./useRewards\";\n\nexport interface PointsBadgeProps {\n client: NoriClient;\n /** What to show: all-time Nori earnings or today's. Default \"total\". */\n show?: \"total\" | \"today\";\n onPress?: () => void;\n backgroundColor?: string;\n textColor?: string;\n style?: StyleProp<ViewStyle>;\n}\n\n/** A small pill with the viewer's points, e.g. in the feed's corner. Hidden until loaded. */\nexport function PointsBadge({\n client,\n show = \"total\",\n onPress,\n backgroundColor = \"rgba(0,0,0,0.55)\",\n textColor = \"#ffffff\",\n style,\n}: PointsBadgeProps) {\n const { summary } = useRewards(client);\n if (!summary) return null;\n\n const points = show === \"today\" ? summary.today.points : summary.total_points;\n const label = `${points.toLocaleString()} ${summary.currency_name}${show === \"today\" ? \" today\" : \"\"}`;\n const content = (\n <View style={[styles.badge, { backgroundColor }, style]} testID=\"nori-points-badge\">\n <Text style={[styles.star, { color: textColor }]}>★</Text>\n <Text style={[styles.text, { color: textColor }]}>{label}</Text>\n </View>\n );\n return onPress ? (\n <Pressable onPress={onPress} accessibilityRole=\"button\" accessibilityLabel={label}>\n {content}\n </Pressable>\n ) : (\n content\n );\n}\n\nconst styles = StyleSheet.create({\n badge: { flexDirection: \"row\", alignItems: \"center\", alignSelf: \"flex-start\", borderRadius: 16, paddingHorizontal: 12, paddingVertical: 6 },\n star: { fontSize: 13, marginRight: 6 },\n text: { fontSize: 13, fontWeight: \"700\" },\n});\n","import { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { NoriClient, NoriError, RewardDecision, RewardsSummary } from \"@getnori/core\";\n\nexport interface UseRewardsOptions {\n /** History entries to load. Default 20. */\n historyLimit?: number;\n /** Re-read the summary this long after a reward, to pick up credited status. Default 1500 ms. */\n refreshDelayMs?: number;\n}\n\nexport interface RewardsState {\n summary: RewardsSummary | null;\n loading: boolean;\n error: NoriError | Error | null;\n refresh: () => Promise<void>;\n}\n\n/** Calls `listener` with each reward the server grants this viewer. */\nexport function useRewardDecisions(client: Pick<NoriClient, \"on\">, listener: (decision: RewardDecision) => void): void {\n const ref = useRef(listener);\n ref.current = listener;\n useEffect(\n () =>\n client.on(\"reward\", (decisions) => {\n for (const d of decisions) ref.current(d);\n }),\n [client],\n );\n}\n\n/**\n * The viewer's Nori earnings. Updates the moment a view is rewarded, then\n * re-reads the server for the authoritative numbers.\n */\nexport function useRewards(client: NoriClient, { historyLimit = 20, refreshDelayMs = 1500 }: UseRewardsOptions = {}): RewardsState {\n const [summary, setSummary] = useState<RewardsSummary | null>(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState<NoriError | Error | null>(null);\n const live = useRef(true);\n const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const refresh = useCallback(async () => {\n try {\n const next = await client.rewards({ limit: historyLimit });\n if (!live.current) return;\n setSummary(next);\n setError(null);\n } catch (e) {\n if (live.current) setError(e as Error);\n } finally {\n if (live.current) setLoading(false);\n }\n }, [client, historyLimit]);\n\n useEffect(() => {\n live.current = true;\n void refresh();\n return () => {\n live.current = false;\n if (timer.current) clearTimeout(timer.current);\n };\n }, [refresh]);\n\n useRewardDecisions(client, (decision) => {\n if (decision.status !== \"rewarded\") return;\n setSummary((prev) =>\n prev\n ? {\n ...prev,\n total_points: prev.total_points + decision.points,\n today: {\n ...prev.today,\n points: prev.today.points + decision.points,\n remaining: Math.max(0, prev.today.remaining - decision.points),\n },\n }\n : prev,\n );\n if (timer.current) clearTimeout(timer.current);\n timer.current = setTimeout(() => void refresh(), refreshDelayMs);\n });\n\n return { summary, loading, error, refresh };\n}\n","import React, { useEffect, useRef, useState } from \"react\";\nimport { Animated, StyleSheet, Text, type StyleProp, type ViewStyle } from \"react-native\";\nimport type { NoriClient, RewardDecision } from \"@getnori/core\";\nimport { useRewardDecisions } from \"./useRewards\";\n\nexport interface RewardToastsProps {\n client: NoriClient;\n /** Text for a reward. Default \"+10 points\". */\n format?: (decision: RewardDecision) => string;\n /** Tell the viewer once per session when they hit the daily cap. Default true. */\n showDailyCapNotice?: boolean;\n /** How long each toast stays. Default 2500 ms. */\n durationMs?: number;\n backgroundColor?: string;\n textColor?: string;\n style?: StyleProp<ViewStyle>;\n}\n\ninterface Toast {\n key: number;\n text: string;\n}\n\n/**\n * Shows \"+10 points\" when the server rewards a view. Mount it once, above\n * the feed (it positions itself at the top of its parent).\n */\nexport function RewardToasts({\n client,\n format = (d) => `+${d.points} ${d.currency_name}`,\n showDailyCapNotice = true,\n durationMs = 2500,\n backgroundColor = \"rgba(17,17,17,0.9)\",\n textColor = \"#ffffff\",\n style,\n}: RewardToastsProps) {\n const [toast, setToast] = useState<Toast | null>(null);\n const capShown = useRef(false);\n const counter = useRef(0);\n\n useRewardDecisions(client, (decision) => {\n if (decision.status === \"rewarded\" && decision.points > 0) {\n setToast({ key: ++counter.current, text: format(decision) });\n } else if (decision.reason === \"daily_cap\" && showDailyCapNotice && !capShown.current) {\n capShown.current = true;\n setToast({ key: ++counter.current, text: `You've earned today's maximum ${decision.currency_name}. Come back tomorrow!` });\n }\n });\n\n if (!toast) return null;\n return (\n <ToastView\n key={toast.key}\n text={toast.text}\n durationMs={durationMs}\n backgroundColor={backgroundColor}\n textColor={textColor}\n style={style}\n onDone={() => setToast((t) => (t?.key === toast.key ? null : t))}\n />\n );\n}\n\nfunction ToastView({\n text,\n durationMs,\n backgroundColor,\n textColor,\n style,\n onDone,\n}: {\n text: string;\n durationMs: number;\n backgroundColor: string;\n textColor: string;\n style?: StyleProp<ViewStyle>;\n onDone: () => void;\n}) {\n const opacity = useRef(new Animated.Value(0)).current;\n const onDoneRef = useRef(onDone);\n onDoneRef.current = onDone;\n\n useEffect(() => {\n Animated.timing(opacity, { toValue: 1, duration: 180, useNativeDriver: true }).start();\n const timer = setTimeout(() => {\n Animated.timing(opacity, { toValue: 0, duration: 220, useNativeDriver: true }).start(() => onDoneRef.current());\n }, durationMs);\n return () => clearTimeout(timer);\n }, [durationMs, opacity]);\n\n return (\n <Animated.View\n pointerEvents=\"none\"\n style={[styles.toast, { backgroundColor, opacity }, style]}\n accessibilityLiveRegion=\"polite\"\n accessibilityRole=\"alert\"\n testID=\"nori-reward-toast\"\n >\n <Text style={[styles.text, { color: textColor }]}>{text}</Text>\n </Animated.View>\n );\n}\n\nconst styles = StyleSheet.create({\n toast: {\n position: \"absolute\", top: 56, alignSelf: \"center\", maxWidth: \"86%\",\n borderRadius: 20, paddingHorizontal: 16, paddingVertical: 10,\n },\n text: { fontSize: 15, fontWeight: \"700\", textAlign: \"center\" },\n});\n"],"mappings":";AACA,SAAS,WAAW,YAAY,MAAM,YAA4C;;;ACDlF,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AAkBlD,SAAS,mBAAmB,QAAgC,UAAoD;AACrH,QAAM,MAAM,OAAO,QAAQ;AAC3B,MAAI,U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U;AAEpB,EAAAC,WAAU,MAAM;AACd,aAAS,OAAO,SAAS,EAAE,SAAS,GAAG,UAAU,KAAK,iBAAiB,KAAK,CAAC,EAAE,MAAM;AACrF,UAAM,QAAQ,WAAW,MAAM;AAC7B,eAAS,OAAO,SAAS,EAAE,SAAS,GAAG,UAAU,KAAK,iBAAiB,KAAK,CAAC,EAAE,MAAM,MAAM,UAAU,QAAQ,CAAC;AAAA,IAChH,GAAG,UAAU;AACb,WAAO,MAAM,aAAa,KAAK;AAAA,EACjC,GAAG,CAAC,YAAY,OAAO,CAAC;AAExB,SACE,gBAAAH;AAAA,IAAC,SAAS;AAAA,IAAT;AAAA,MACC,eAAc;AAAA,MACd,OAAO,CAACI,QAAO,OAAO,EAAE,iBAAiB,QAAQ,GAAG,KAAK;AAAA,MACzD,yBAAwB;AAAA,MACxB,mBAAkB;AAAA,MAClB,QAAO;AAAA,MAEP,0BAAAJ,KAACK,OAAA,EAAK,OAAO,CAACD,QAAO,MAAM,EAAE,OAAO,UAAU,CAAC,GAAI,gBAAK;AAAA;AAAA,EAC1D;AAEJ;AAEA,IAAMA,UAASE,YAAW,OAAO;AAAA,EAC/B,OAAO;AAAA,IACL,UAAU;AAAA,IAAY,KAAK;AAAA,IAAI,WAAW;AAAA,IAAU,UAAU;AAAA,IAC9D,cAAc;AAAA,IAAI,mBAAmB;AAAA,IAAI,iBAAiB;AAAA,EAC5D;AAAA,EACA,MAAM,EAAE,UAAU,IAAI,YAAY,OAAO,WAAW,SAAS;AAC/D,CAAC;","names":["useEffect","useRef","useState","StyleSheet","Text","jsx","useState","useRef","useEffect","styles","Text","StyleSheet"]}
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@getnori/rewards",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Nori Rewards SDK: points badges, reward toasts and earning history for Nori viewers.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/ad-yuta/nori-sdk.git",
9
+ "directory": "packages/rewards"
10
+ },
11
+ "type": "module",
12
+ "main": "./dist/index.cjs",
13
+ "module": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "react-native": "./dist/index.js",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "react-native": "./dist/index.js",
20
+ "import": "./dist/index.js",
21
+ "require": "./dist/index.cjs"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "README.md",
27
+ "LICENSE",
28
+ "NOTICE"
29
+ ],
30
+ "sideEffects": false,
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "dependencies": {
35
+ "@getnori/core": "^0.1.0"
36
+ },
37
+ "devDependencies": {
38
+ "react": "19.2.3",
39
+ "react-native": "0.86.3"
40
+ },
41
+ "peerDependencies": {
42
+ "react": ">=18",
43
+ "react-native": ">=0.74"
44
+ },
45
+ "scripts": {
46
+ "build": "tsup",
47
+ "typecheck": "tsc --noEmit",
48
+ "test": "vitest run"
49
+ }
6
50
  }