usegamigameapi 1.0.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.
@@ -0,0 +1,23 @@
1
+ declare function useGameAPI({ onAnswerCorrect, onAnswerIncorrect }: any): {
2
+ quiz: any;
3
+ currentResult: any;
4
+ answers: (boolean | null)[];
5
+ correctCount: number;
6
+ currentQuestionIndex: number;
7
+ selectedAnswer: {
8
+ id: number;
9
+ content: string;
10
+ } | null;
11
+ isSubmitting: boolean;
12
+ hasSubmitted: boolean;
13
+ isCompleted: boolean;
14
+ handleAnswerSelect: (answer: {
15
+ id: number;
16
+ content: string;
17
+ }) => void;
18
+ updateAnswer: () => Promise<void>;
19
+ handleContinue: () => void;
20
+ finish: () => void;
21
+ };
22
+
23
+ export { useGameAPI };
@@ -0,0 +1,23 @@
1
+ declare function useGameAPI({ onAnswerCorrect, onAnswerIncorrect }: any): {
2
+ quiz: any;
3
+ currentResult: any;
4
+ answers: (boolean | null)[];
5
+ correctCount: number;
6
+ currentQuestionIndex: number;
7
+ selectedAnswer: {
8
+ id: number;
9
+ content: string;
10
+ } | null;
11
+ isSubmitting: boolean;
12
+ hasSubmitted: boolean;
13
+ isCompleted: boolean;
14
+ handleAnswerSelect: (answer: {
15
+ id: number;
16
+ content: string;
17
+ }) => void;
18
+ updateAnswer: () => Promise<void>;
19
+ handleContinue: () => void;
20
+ finish: () => void;
21
+ };
22
+
23
+ export { useGameAPI };
package/dist/index.js ADDED
@@ -0,0 +1,177 @@
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
+ useGameAPI: () => useGameAPI
24
+ });
25
+ module.exports = __toCommonJS(index_exports);
26
+
27
+ // src/useGameAPI.ts
28
+ var import_react = require("react");
29
+
30
+ // src/bridge.ts
31
+ var ACTIONS = {
32
+ SHOW_LO5: "SHOW_LO5",
33
+ // Sub -> Main: Web con đã sẵn sàng, yêu cầu web cha gửi câu hỏi
34
+ RETURN_LO5: "RETURN_LO5",
35
+ // Main -> Sub: Web cha gửi nội dung câu hỏi
36
+ UPDATE_ANSWER: "UPDATE_ANSWER",
37
+ // Sub -> Main: Gửi đáp án user chọn cho web cha
38
+ RETURN_UPDATE_ANSWER: "RETURN_UPDATE_ANSWER",
39
+ // Main -> Sub: Web cha gửi lại kết quả đúng/sai cho web con
40
+ FINISH: "FINISH"
41
+ // Sub -> Main: Yêu cầu resize iframe
42
+ };
43
+ var QuestionBridge = class {
44
+ constructor() {
45
+ this.handlers = {};
46
+ window.addEventListener("message", this.handleMessage.bind(this));
47
+ }
48
+ // Hàm nhận message
49
+ handleMessage(event) {
50
+ const { type, payload } = event.data;
51
+ if (this.handlers[type]) {
52
+ this.handlers[type](payload);
53
+ }
54
+ }
55
+ // Đăng ký hàm xử lý cho từng loại sự kiện (để UI gọi)
56
+ // stw -> lovable
57
+ on(type, callback) {
58
+ this.handlers[type] = callback;
59
+ }
60
+ // lovable -> stw
61
+ // Gửi message lên Main Web
62
+ send(type, payload = {}) {
63
+ if (window.parent) {
64
+ window.parent.postMessage({ type, payload }, "*");
65
+ }
66
+ }
67
+ };
68
+ var bridge = new QuestionBridge();
69
+
70
+ // src/useGameAPI.ts
71
+ function useGameAPI({ onAnswerCorrect, onAnswerIncorrect }) {
72
+ const [currentQuestionIndex, setCurrentQuestionIndex] = (0, import_react.useState)(0);
73
+ const currentQuestionIndexRef = (0, import_react.useRef)(0);
74
+ const [selectedAnswer, setSelectedAnswer] = (0, import_react.useState)(null);
75
+ const [answers, setAnswers] = (0, import_react.useState)([]);
76
+ const [quiz, setQuiz] = (0, import_react.useState)(null);
77
+ const [currentResult, setCurrentResult] = (0, import_react.useState)(null);
78
+ const [correctCount, setCorrectCount] = (0, import_react.useState)(0);
79
+ const [isSubmitting, setIsSubmitting] = (0, import_react.useState)(false);
80
+ const [hasSubmitted, setHasSubmitted] = (0, import_react.useState)(false);
81
+ const [isCompleted, setIsCompleted] = (0, import_react.useState)(false);
82
+ const isLastQuestionRef = (0, import_react.useRef)(false);
83
+ const finish = (0, import_react.useCallback)(() => {
84
+ bridge.send(ACTIONS.FINISH);
85
+ }, []);
86
+ const updateAnswer = (0, import_react.useCallback)(async () => {
87
+ if (!selectedAnswer || isSubmitting) {
88
+ return;
89
+ }
90
+ bridge.send(ACTIONS.UPDATE_ANSWER, selectedAnswer.id);
91
+ setIsSubmitting(true);
92
+ setHasSubmitted(true);
93
+ return Promise.resolve();
94
+ }, [selectedAnswer, isSubmitting]);
95
+ const handleContinue = (0, import_react.useCallback)(() => {
96
+ if (!hasSubmitted) return;
97
+ if (isLastQuestionRef.current) {
98
+ setIsCompleted(true);
99
+ } else {
100
+ bridge.send(ACTIONS.SHOW_LO5);
101
+ const nextIndex = currentQuestionIndexRef.current + 1;
102
+ currentQuestionIndexRef.current = nextIndex;
103
+ setCurrentQuestionIndex(nextIndex);
104
+ setSelectedAnswer(null);
105
+ setIsSubmitting(false);
106
+ setHasSubmitted(false);
107
+ setCurrentResult(null);
108
+ }
109
+ }, [hasSubmitted]);
110
+ const handleAnswerSelect = (0, import_react.useCallback)(
111
+ (answer) => {
112
+ if (!isSubmitting && !hasSubmitted) {
113
+ setSelectedAnswer(answer);
114
+ }
115
+ },
116
+ [isSubmitting, hasSubmitted]
117
+ );
118
+ (0, import_react.useEffect)(() => {
119
+ bridge.send(ACTIONS.SHOW_LO5);
120
+ bridge.on(ACTIONS.RETURN_LO5, (_data) => {
121
+ setQuiz(_data);
122
+ });
123
+ bridge.on(ACTIONS.RETURN_UPDATE_ANSWER, (_data) => {
124
+ const isCorrect = (_data == null ? void 0 : _data.isCorrect) === true;
125
+ const isLast = (_data == null ? void 0 : _data.isLastQuestion) === true;
126
+ isLastQuestionRef.current = isLast;
127
+ setAnswers((prevAnswers) => {
128
+ const next = [...prevAnswers];
129
+ next[currentQuestionIndexRef.current] = isCorrect;
130
+ return next;
131
+ });
132
+ if (isCorrect) {
133
+ setCorrectCount((prev) => prev + 1);
134
+ console.log({ currentQuestionIndex: currentQuestionIndexRef.current });
135
+ onAnswerCorrect == null ? void 0 : onAnswerCorrect({ currentQuestionIndex: currentQuestionIndexRef.current });
136
+ } else {
137
+ onAnswerIncorrect == null ? void 0 : onAnswerIncorrect();
138
+ }
139
+ setIsSubmitting(false);
140
+ setCurrentResult(_data);
141
+ });
142
+ }, []);
143
+ return {
144
+ // State Data
145
+ quiz,
146
+ // Dữ liệu câu hỏi hiện tại (để render UI)
147
+ currentResult,
148
+ // Kết quả vừa trả lời (để hiện giải thích đúng/sai)
149
+ answers,
150
+ // Mảng lịch sử kết quả (để vẽ progress bar)
151
+ correctCount,
152
+ // Số câu đúng
153
+ currentQuestionIndex,
154
+ // Index hiện tại (để UI biết đang ở câu mấy)
155
+ // State Status
156
+ selectedAnswer,
157
+ // Đáp án đang được chọn
158
+ isSubmitting,
159
+ // Trạng thái đang submmit
160
+ hasSubmitted,
161
+ isCompleted,
162
+ // Trạng thái khi hoàn thành câu hỏi cuối
163
+ // Methods
164
+ handleAnswerSelect,
165
+ // Hàm gán đáp án user đã chọn
166
+ updateAnswer,
167
+ // Hàm gửi đáp án user chọn lên web cha
168
+ handleContinue,
169
+ // Hàm chuyển qua câu hỏi tiếp theo hoặc kết thúc
170
+ finish
171
+ // Hàm kết thúc
172
+ };
173
+ }
174
+ // Annotate the CommonJS export names for ESM import in node:
175
+ 0 && (module.exports = {
176
+ useGameAPI
177
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,150 @@
1
+ // src/useGameAPI.ts
2
+ import { useState, useCallback, useRef, useEffect } from "react";
3
+
4
+ // src/bridge.ts
5
+ var ACTIONS = {
6
+ SHOW_LO5: "SHOW_LO5",
7
+ // Sub -> Main: Web con đã sẵn sàng, yêu cầu web cha gửi câu hỏi
8
+ RETURN_LO5: "RETURN_LO5",
9
+ // Main -> Sub: Web cha gửi nội dung câu hỏi
10
+ UPDATE_ANSWER: "UPDATE_ANSWER",
11
+ // Sub -> Main: Gửi đáp án user chọn cho web cha
12
+ RETURN_UPDATE_ANSWER: "RETURN_UPDATE_ANSWER",
13
+ // Main -> Sub: Web cha gửi lại kết quả đúng/sai cho web con
14
+ FINISH: "FINISH"
15
+ // Sub -> Main: Yêu cầu resize iframe
16
+ };
17
+ var QuestionBridge = class {
18
+ constructor() {
19
+ this.handlers = {};
20
+ window.addEventListener("message", this.handleMessage.bind(this));
21
+ }
22
+ // Hàm nhận message
23
+ handleMessage(event) {
24
+ const { type, payload } = event.data;
25
+ if (this.handlers[type]) {
26
+ this.handlers[type](payload);
27
+ }
28
+ }
29
+ // Đăng ký hàm xử lý cho từng loại sự kiện (để UI gọi)
30
+ // stw -> lovable
31
+ on(type, callback) {
32
+ this.handlers[type] = callback;
33
+ }
34
+ // lovable -> stw
35
+ // Gửi message lên Main Web
36
+ send(type, payload = {}) {
37
+ if (window.parent) {
38
+ window.parent.postMessage({ type, payload }, "*");
39
+ }
40
+ }
41
+ };
42
+ var bridge = new QuestionBridge();
43
+
44
+ // src/useGameAPI.ts
45
+ function useGameAPI({ onAnswerCorrect, onAnswerIncorrect }) {
46
+ const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
47
+ const currentQuestionIndexRef = useRef(0);
48
+ const [selectedAnswer, setSelectedAnswer] = useState(null);
49
+ const [answers, setAnswers] = useState([]);
50
+ const [quiz, setQuiz] = useState(null);
51
+ const [currentResult, setCurrentResult] = useState(null);
52
+ const [correctCount, setCorrectCount] = useState(0);
53
+ const [isSubmitting, setIsSubmitting] = useState(false);
54
+ const [hasSubmitted, setHasSubmitted] = useState(false);
55
+ const [isCompleted, setIsCompleted] = useState(false);
56
+ const isLastQuestionRef = useRef(false);
57
+ const finish = useCallback(() => {
58
+ bridge.send(ACTIONS.FINISH);
59
+ }, []);
60
+ const updateAnswer = useCallback(async () => {
61
+ if (!selectedAnswer || isSubmitting) {
62
+ return;
63
+ }
64
+ bridge.send(ACTIONS.UPDATE_ANSWER, selectedAnswer.id);
65
+ setIsSubmitting(true);
66
+ setHasSubmitted(true);
67
+ return Promise.resolve();
68
+ }, [selectedAnswer, isSubmitting]);
69
+ const handleContinue = useCallback(() => {
70
+ if (!hasSubmitted) return;
71
+ if (isLastQuestionRef.current) {
72
+ setIsCompleted(true);
73
+ } else {
74
+ bridge.send(ACTIONS.SHOW_LO5);
75
+ const nextIndex = currentQuestionIndexRef.current + 1;
76
+ currentQuestionIndexRef.current = nextIndex;
77
+ setCurrentQuestionIndex(nextIndex);
78
+ setSelectedAnswer(null);
79
+ setIsSubmitting(false);
80
+ setHasSubmitted(false);
81
+ setCurrentResult(null);
82
+ }
83
+ }, [hasSubmitted]);
84
+ const handleAnswerSelect = useCallback(
85
+ (answer) => {
86
+ if (!isSubmitting && !hasSubmitted) {
87
+ setSelectedAnswer(answer);
88
+ }
89
+ },
90
+ [isSubmitting, hasSubmitted]
91
+ );
92
+ useEffect(() => {
93
+ bridge.send(ACTIONS.SHOW_LO5);
94
+ bridge.on(ACTIONS.RETURN_LO5, (_data) => {
95
+ setQuiz(_data);
96
+ });
97
+ bridge.on(ACTIONS.RETURN_UPDATE_ANSWER, (_data) => {
98
+ const isCorrect = (_data == null ? void 0 : _data.isCorrect) === true;
99
+ const isLast = (_data == null ? void 0 : _data.isLastQuestion) === true;
100
+ isLastQuestionRef.current = isLast;
101
+ setAnswers((prevAnswers) => {
102
+ const next = [...prevAnswers];
103
+ next[currentQuestionIndexRef.current] = isCorrect;
104
+ return next;
105
+ });
106
+ if (isCorrect) {
107
+ setCorrectCount((prev) => prev + 1);
108
+ console.log({ currentQuestionIndex: currentQuestionIndexRef.current });
109
+ onAnswerCorrect == null ? void 0 : onAnswerCorrect({ currentQuestionIndex: currentQuestionIndexRef.current });
110
+ } else {
111
+ onAnswerIncorrect == null ? void 0 : onAnswerIncorrect();
112
+ }
113
+ setIsSubmitting(false);
114
+ setCurrentResult(_data);
115
+ });
116
+ }, []);
117
+ return {
118
+ // State Data
119
+ quiz,
120
+ // Dữ liệu câu hỏi hiện tại (để render UI)
121
+ currentResult,
122
+ // Kết quả vừa trả lời (để hiện giải thích đúng/sai)
123
+ answers,
124
+ // Mảng lịch sử kết quả (để vẽ progress bar)
125
+ correctCount,
126
+ // Số câu đúng
127
+ currentQuestionIndex,
128
+ // Index hiện tại (để UI biết đang ở câu mấy)
129
+ // State Status
130
+ selectedAnswer,
131
+ // Đáp án đang được chọn
132
+ isSubmitting,
133
+ // Trạng thái đang submmit
134
+ hasSubmitted,
135
+ isCompleted,
136
+ // Trạng thái khi hoàn thành câu hỏi cuối
137
+ // Methods
138
+ handleAnswerSelect,
139
+ // Hàm gán đáp án user đã chọn
140
+ updateAnswer,
141
+ // Hàm gửi đáp án user chọn lên web cha
142
+ handleContinue,
143
+ // Hàm chuyển qua câu hỏi tiếp theo hoặc kết thúc
144
+ finish
145
+ // Hàm kết thúc
146
+ };
147
+ }
148
+ export {
149
+ useGameAPI
150
+ };
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "usegamigameapi",
3
+ "version": "1.0.0",
4
+ "description": "",
5
+ "main": "dist/index.cjs",
6
+ "module": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "files": ["dist"],
9
+ "peerDependencies": {
10
+ "react": ">=16.8"
11
+ },
12
+ "scripts": {
13
+ "test": "echo \"Error: no test specified\" && exit 1",
14
+ "build": "tsup"
15
+ },
16
+ "keywords": [],
17
+ "author": "",
18
+ "license": "ISC",
19
+ "type": "commonjs",
20
+ "dependencies": {
21
+ "react": "^19.2.3"
22
+ },
23
+ "devDependencies": {
24
+ "@types/react": "^19.2.8",
25
+ "tsup": "^8.5.1",
26
+ "typescript": "^5.9.3"
27
+ }
28
+ }