Compare commits
875 Commits
v2.1.1
...
ios-haptics
| Author | SHA1 | Date | |
|---|---|---|---|
| 1a106545f7 | |||
| ffa1094f93 | |||
| e890e913f5 | |||
| 12a4966b84 | |||
| cc702027b0 | |||
| 328c858e4e | |||
| dcf77aac2a | |||
| cdf3391aad | |||
| 787446b4ee | |||
| 5febdb2d7d | |||
| 005f40b536 | |||
| 01a6012a0a | |||
| c009eb4d5c | |||
| 9bdfa1a485 | |||
| 6742792e90 | |||
| 8f6d52a9f9 | |||
| 51a25919c7 | |||
| 1405b5e2c2 | |||
| 8b3b412b16 | |||
| bbcefbb79e | |||
| 83f2f1de7e | |||
| 3dd77c2fcc | |||
| b51b11063f | |||
| 4ffa3119a7 | |||
| dbf7ed9bb2 | |||
| 8f5f33560e | |||
| 41392d9299 | |||
| 4623438652 | |||
| 6948938768 | |||
| db9cdd04c5 | |||
| 528cf905fb | |||
| 2c08bcd94a | |||
| 9de3fa7112 | |||
| 28027cd7b2 | |||
| e54fad61ae | |||
| 31189801f8 | |||
| d579e91bbd | |||
| 27133d69f2 | |||
| 5e895e59ae | |||
| c5f9f8be6c | |||
| 1a58875418 | |||
| 8ee6388ab8 | |||
| 5878b8ad5f | |||
| ec4359f1aa | |||
| f217394012 | |||
| 32908f7b4f | |||
| bd333b9584 | |||
| 3ac1dc6b0a | |||
| 025ecd8645 | |||
| 0fca39a1bd | |||
| 3152f7f0ec | |||
| 7cba044b9d | |||
| 4245b2aede | |||
| 3cdec3ceb6 | |||
| aa8f7539ae | |||
| c6b3cb8758 | |||
| 59f68efdc7 | |||
| dc81585f9a | |||
| 54e6c964db | |||
| dceda199c3 | |||
| 8967012035 | |||
| 0b73d4aac5 | |||
| 6f53f7ad99 | |||
| 399df4da4d | |||
| c06a66ade4 | |||
| 1fca26ae2e | |||
| ccd8f213f6 | |||
| 1c25702453 | |||
| 357ba7d8c8 | |||
| 207ca6893a | |||
| 6dc7fb7ade | |||
| 37df5d0bd1 | |||
| 19906cf918 | |||
| 874010c4fe | |||
| d256acdef3 | |||
| 98e0273bdb | |||
| e26407d740 | |||
| b42f12ce77 | |||
| 7a10e4a406 | |||
| eda18d8b93 | |||
| 126dce1dfc | |||
| 70809a8c7c | |||
| 5b15300f23 | |||
| 105da53e2e | |||
| 8585dd4833 | |||
| 7bc4a632b0 | |||
| 12bda76526 | |||
| 0222248d76 | |||
| a542dd3b36 | |||
| fc292a8654 | |||
| 9214bd823b | |||
| 8f5b8264c9 | |||
| 94f821d064 | |||
| 6d73e6d06b | |||
| bd724de1e8 | |||
| 9d899cfe87 | |||
| 173f789242 | |||
| 07a9b956cb | |||
| 0e7f847de0 | |||
| 4998ea8f5d | |||
| 0cc81cd35f | |||
| ed09c8947d | |||
| 2e79d93806 | |||
| f05097087b | |||
| 72268dfde6 | |||
| 7b63f6112c | |||
| ce61d8d1a6 | |||
| c4a10b1303 | |||
| 76c6846e91 | |||
| ac1e82b52d | |||
| 437b8de652 | |||
| adadb6ed53 | |||
| f7c90a4a23 | |||
| 82632bb76c | |||
| 3a70d34e6d | |||
| 221d3f4aff | |||
| 6a1a462ab0 | |||
| 5ee8bc1cc0 | |||
| 76d53859cf | |||
| e482afbd3f | |||
| 11ff27efe2 | |||
| 8f6f678132 | |||
| f25139103c | |||
| 0028b506e7 | |||
| 926c27d51c | |||
| c4454ee2a1 | |||
| e56737f776 | |||
| feb6c1a9f6 | |||
| 6f8d225597 | |||
| 9ecd99a6a1 | |||
| 287097627d | |||
| 3ee491a63b | |||
| 7944f73da3 | |||
| 17c1936817 | |||
| c570f4689d | |||
| 064ab1e101 | |||
| 9c0d49b904 | |||
| 69634e7c05 | |||
| db48ce7c40 | |||
| 36c6e537a7 | |||
| cbc3df0bef | |||
| 2ecd557430 | |||
| 61c84ed137 | |||
| a24b755e08 | |||
| 46a970b900 | |||
| 594e7ea8fa | |||
| 0a5e72efd0 | |||
| 0f1021e0d3 | |||
| be65c659b2 | |||
| b64aa4b24a | |||
| f63d8943d8 | |||
| e6efdc3539 | |||
| 517a72cce7 | |||
| ebe0cfdf03 | |||
| a501337fd3 | |||
| e3916b3bc1 | |||
| de22e921d4 | |||
| 3a512f04e2 | |||
| 6fc68766c9 | |||
| bfd1daf7ba | |||
| ae81c13cc1 | |||
| 41358d27ce | |||
| ac8bffba23 | |||
| 748365de40 | |||
| 361f8b9506 | |||
| f4363dcbff | |||
| c1ec7a25ed | |||
| 272586d033 | |||
| c77c098843 | |||
| ea7afa94f7 | |||
| 0c29506402 | |||
| b0609e7877 | |||
| 946be28b81 | |||
| 89250c7472 | |||
| cfc7a0d31c | |||
| 21003e3aed | |||
| 93e8a6290f | |||
| 47831ffa64 | |||
| 1533420320 | |||
| e3ef542875 | |||
| 3bf55990c0 | |||
| 283b31813c | |||
| 6e1197a067 | |||
| b7d1fbf860 | |||
| 8fde660075 | |||
| 50c7d67928 | |||
| e355c43925 | |||
| 696204870d | |||
| 0a7e01d17c | |||
| dd87bc96ec | |||
| a12d5db560 | |||
| 614634789c | |||
| 29696fa3d3 | |||
| ffc31e8e8f | |||
| 720a7e91fe | |||
| 05096e2cd9 | |||
| 05667460eb | |||
| b10dae7655 | |||
| c799b9efd6 | |||
| fe4834e157 | |||
| 5d972249a4 | |||
| f607a01577 | |||
| 1e232e6a9e | |||
| 431c388129 | |||
| 72b63dac21 | |||
| be82cb9626 | |||
| c2c6f711b5 | |||
| 3fba81a7d2 | |||
| 6f2b51197f | |||
| 00c801e9dc | |||
| 47e7d05cb9 | |||
| 4ef6d1b149 | |||
| badd19d27c | |||
| e67f90582b | |||
| 7fa6e574f8 | |||
| 9b36bf3325 | |||
| bc1c4cb7cf | |||
| 119f684fb3 | |||
| 45134ef9cc | |||
| db502b462c | |||
| ed083bfdad | |||
| 47811f9190 | |||
| ba99cdc51c | |||
| 7092f7306f | |||
| 357dd56de0 | |||
| fadec0574a | |||
| 469806886a | |||
| f7ab980ecd | |||
| c6b5ab2284 | |||
| 2231673ee6 | |||
| f8907475f9 | |||
| 4252841125 | |||
| ee8220c1f0 | |||
| 11e29646a7 | |||
| a9bab7f8e8 | |||
| 0b69ab51f4 | |||
| 2a32e79b13 | |||
| 39fc7549ac | |||
| 414f42e339 | |||
| 8e3f778f5b | |||
| bc83d08961 | |||
| 7d83273410 | |||
| fabcb4170d | |||
| 8b824f8cc9 | |||
| 3e429fe0b0 | |||
| a261934ab0 | |||
| 822ff13ac3 | |||
| afa475ecef | |||
| 853b5ead9c | |||
| a5746ee915 | |||
| fa3376ac4f | |||
| 6f0c10fe9b | |||
| 2f1bf0bca5 | |||
| 9be98d9a8d | |||
| c4dd8e7c3d | |||
| 42832b72e3 | |||
| e77436d02a | |||
| 302d7732ef | |||
| b09b4938d2 | |||
| 0a0d6de111 | |||
| 4e9b893822 | |||
| c60e87ad65 | |||
| 8e07ad515a | |||
| b4c4b8eb21 | |||
| 23ee6f1196 | |||
| 4b97baa428 | |||
| c8e844a19a | |||
| 205a252cac | |||
| ad604eae68 | |||
| 57064b4f40 | |||
| bb7b8da581 | |||
| 5683f6ea1e | |||
| 61c606822a | |||
| bc12331cd4 | |||
| 2478bf1c66 | |||
| ade9eb4999 | |||
| 213bbb21c1 | |||
| dd3ae4da4e | |||
| 681d2ab90b | |||
| 24a645277e | |||
| fa34922cce | |||
| 89c71ed073 | |||
| 0f02563d3a | |||
| f49909dedf | |||
| ab43225f0c | |||
| 2bb1b07dd6 | |||
| f93c759bf2 | |||
| 38630be23d | |||
| ef4ac2e3f4 | |||
| 32b36b2f54 | |||
| dee5c82fa8 | |||
| 22d66a28d7 | |||
| 984a56c412 | |||
| 207e7a13a2 | |||
| cc7feebbb0 | |||
| 9b8cff63da | |||
| 925619b13c | |||
| ceb7bbc718 | |||
| 53a607fa53 | |||
| e13473809d | |||
| e9eeebc4b1 | |||
| b42d241882 | |||
| 68da609a9e | |||
| 1afa78ae39 | |||
| 00a9ad20de | |||
| e0ff462f12 | |||
| f4e38123e4 | |||
| eb1c873b9a | |||
| 22f13c1505 | |||
| cbfc8f149f | |||
| 2e41859747 | |||
| 3b176a3e8f | |||
| a1e1e1d57f | |||
| eb973cc20b | |||
| f66ab92e51 | |||
| 4d573ffaa8 | |||
| 081189886a | |||
| 1efc8de880 | |||
| 8bf9db382e | |||
| 103b9c71bf | |||
| e27057788b | |||
| 4983b3c1ef | |||
| 197ab6c28a | |||
| fd0d47160d | |||
| 4697d269bc | |||
| 73bf03cfab | |||
| c3d4d5f06e | |||
| 4c201cc2d3 | |||
| d28364531b | |||
| c30a6a7bcd | |||
| c4354774ad | |||
| 8a44f77fb1 | |||
| f3eb4adba5 | |||
| 9ebd9a304f | |||
| 0487586af9 | |||
| 2c737ca322 | |||
| c9823055fd | |||
| d2cd5f22bf | |||
| b223a9c1f2 | |||
| 2d1a3ff6f5 | |||
| 90bd10d87a | |||
| 280bcbd5ab | |||
| 65ecfca05e | |||
| 91f5afc110 | |||
| 1c980fb039 | |||
| e93c665123 | |||
| 6be49ec14a | |||
| 793b408e3f | |||
| 213e8abf28 | |||
| bac2f3a5c7 | |||
| 1e38d9d2a2 | |||
| 419c1ceb48 | |||
| f6bde5871a | |||
| 9c56a7f987 | |||
| 2e8efab2aa | |||
| 0f45ce743f | |||
| 7794cd5dbd | |||
| c0cb6454ac | |||
| 2f45a9bbf5 | |||
| 11a61322e8 | |||
| cb1bc1a865 | |||
| 622cb14813 | |||
| 4afea98e77 | |||
| 79f3cc85dd | |||
| 4052f865c9 | |||
| 5887f790c6 | |||
| 6fc5d3ed97 | |||
| 0eaf30cd8b | |||
| f1d5e8d4ca | |||
| 7763aa2e0a | |||
| 500f06b538 | |||
| 85227c2175 | |||
| a570b318d7 | |||
| 99e32d9491 | |||
| 74022e8181 | |||
| d0b5164e6d | |||
| defc39c0f3 | |||
| a9844b3a4f | |||
| 77b8498850 | |||
| 4c34aba66d | |||
| 2bf4ed2af8 | |||
| 5afeac3c14 | |||
| 39e3c0b30f | |||
| d749718584 | |||
| 922a66835a | |||
| 0d4a96e785 | |||
| a3e10bc12b | |||
| 49c482f2ba | |||
| 0ad7a7892b | |||
| 989b423714 | |||
| 13f703a3ec | |||
| aa7c8e038b | |||
| 0469b6cec9 | |||
| ef88ca4235 | |||
| 1adbe1c98a | |||
| b97299ce0a | |||
| 93eeffb1ad | |||
| 081ad9240f | |||
| 7d3b92048b | |||
| 3c425a4e68 | |||
| 4ae90080e8 | |||
| 2cdcd543a4 | |||
| 71f8ee0e16 | |||
| 92634705b3 | |||
| 7aee4fe712 | |||
| 0e4ce974f0 | |||
| 4ddcee95d9 | |||
| 4e1f7b6007 | |||
| 00f3deb5b2 | |||
| b8037c48e9 | |||
| a3dfe25d13 | |||
| 50a834c4fc | |||
| f00332fca5 | |||
| 384936f106 | |||
| 81966dac0d | |||
| 7c8e4f1735 | |||
| b9b9363468 | |||
| 11ecfb1bcf | |||
| 605f4e52fe | |||
| a45e649374 | |||
| 3f32c95b35 | |||
| 2919bdf691 | |||
| 6192dfc568 | |||
| de57399301 | |||
| c6e6326b50 | |||
| cf59b6d0da | |||
| d836b1f068 | |||
| 6071a28dd9 | |||
| 03fa16ded2 | |||
| b8eb0a8549 | |||
| 5dac0214ea | |||
| 3ddb7c8ceb | |||
| 03d4b6c4f2 | |||
| 55b551f214 | |||
| 6fe17c1cfd | |||
| 93ccb572e5 | |||
| 03aa1e6dbc | |||
| 059fb67d26 | |||
| eec7f1d5b5 | |||
| 5ab16fbbf3 | |||
| a74f7037ff | |||
| 18cf251c7e | |||
| 5de5488b24 | |||
| 83887b0516 | |||
| ec24c4cfae | |||
| 002461e7cb | |||
| d12e75ae5c | |||
| a480379fa5 | |||
| c37d0d15a6 | |||
| 79ccfd661a | |||
| 67e8c23020 | |||
| 94f0c8308d | |||
| c77b68eed2 | |||
| 80820ae9c4 | |||
| 5288b7a718 | |||
| 4643830512 | |||
| ef04de67c0 | |||
| 5847cceba6 | |||
| f62b86027c | |||
| 8e5018d3b2 | |||
| 8df17f5ae7 | |||
| dd31ce681f | |||
| fd9a963b27 | |||
| 672d252492 | |||
| bc4e00520e | |||
| d777d1bc98 | |||
| 4cd97124da | |||
| 74345fdb2f | |||
| 7e7abdee3d | |||
| 9ed2127494 | |||
| 30608ae8ed | |||
| ae43014cf2 | |||
| ea8d3dd0f3 | |||
| 02231ea1f9 | |||
| effc704613 | |||
| 51fb1fd1cb | |||
| 1988e1b849 | |||
| 1b782f65d1 | |||
| 6c4eddece7 | |||
| cf0524a211 | |||
| a796f279a5 | |||
| efc491bad4 | |||
| 8d04bbbdbe | |||
| f6c08f8afa | |||
| 3197c53fcc | |||
| 7b793149b3 | |||
| 24c938728a | |||
| 1c358a3c79 | |||
| 3bbed8875c | |||
| a3e6ff34db | |||
| 0f7fc673eb | |||
| 646c95a86f | |||
| 87a8974c8c | |||
| 9b5df28b93 | |||
| e876e290da | |||
| f26f033b14 | |||
| 565f323179 | |||
| 82b2aeb294 | |||
| 6b59658f00 | |||
| 2e1e4416b3 | |||
| e92a2c571c | |||
| d3a418b5ee | |||
| c9945107e9 | |||
| 4c70133ca9 | |||
| 0df942cb9d | |||
| 37a63f068b | |||
| cc8638e8b2 | |||
| fd20081ce8 | |||
| cf9d409166 | |||
| 7d8ac49fe2 | |||
| dc3be6564b | |||
| 337e27f2b5 | |||
| c400437662 | |||
| e8941e8ef6 | |||
| 169823980f | |||
| aa7376b357 | |||
| 6a0e88cbf1 | |||
| 01b7e1cea2 | |||
| 910f43e0a5 | |||
| 6bf630bb40 | |||
| 5e71b3f44a | |||
| 5ffab157d7 | |||
| c6e791d18f | |||
| a80b306248 | |||
| c8c294a8ad | |||
| 5a30376f2c | |||
| 373219ecfa | |||
| 1ef1400699 | |||
| 7966d07158 | |||
| 9ffab3d2dd | |||
| dbcbd8928b | |||
| a659611897 | |||
| 78b4716a2a | |||
| 08e26e28d0 | |||
| b1c61a7888 | |||
| e951a3b00a | |||
| 62b5aab753 | |||
| 7b307ffe22 | |||
| edee9f7030 | |||
| 71949890da | |||
| 5ae233ff62 | |||
| 19400a78e5 | |||
| 497d6979d0 | |||
| 59eab8afea | |||
| 74b84eb5ac | |||
| bfc864cc7c | |||
| 6c067a3ae6 | |||
| 503fed5fdb | |||
| 32cb3eeba3 | |||
| 7e49e85495 | |||
| c3d7984d7a | |||
| b024518f5e | |||
| 83c1e9aa6c | |||
| 8a6cb02dc0 | |||
| 91237c252c | |||
| f7821451c7 | |||
| 9056b43696 | |||
| cdf54e9eff | |||
| 7a49e9646c | |||
| 2189f5e7c4 | |||
| 2822b4c159 | |||
| 3dd2591709 | |||
| ab2145ffe9 | |||
| 3ee880d1dd | |||
| 586e103161 | |||
| 5776bf2a51 | |||
| ceb442ebf1 | |||
| e6a2bdc65f | |||
| c9205adbab | |||
| 29d56daab3 | |||
| 4d7ac5e619 | |||
| fb3686fef4 | |||
| ed14ef0cd9 | |||
| fd90f90cbb | |||
| b6cee104b9 | |||
| 5c6df95734 | |||
| 8941aca968 | |||
| e1348f782e | |||
| b652976784 | |||
| 530c0681d0 | |||
| e38f57f823 | |||
| f3b9eb9f73 | |||
| bd7be9590a | |||
| e1fa43c9f0 | |||
| ccb0d9ec71 | |||
| eca4a5ba77 | |||
| 6dd29c571f | |||
| 28f1e2b517 | |||
| 21374b2cb4 | |||
| ada87468cc | |||
| 0a4b488d69 | |||
| aa257b34ec | |||
| c48e6c7123 | |||
| 827bc4b836 | |||
| c7d115f873 | |||
| 45c585a27d | |||
| dc3fe02767 | |||
| a1ef06510e | |||
| 56002c68ca | |||
| 30bd73f8f9 | |||
| 9d8a30f678 | |||
| 2b0b99d598 | |||
| 8551852c9d | |||
| 7ade0eaeb1 | |||
| debdbf770b | |||
| 01976685e8 | |||
| bac5d71480 | |||
| 0ad655d1cf | |||
| a526e301da | |||
| 9c16c6df40 | |||
| 3220e9482b | |||
| 9a033d7f91 | |||
| 2329458a84 | |||
| c613a7aedd | |||
| d4d502f418 | |||
| 7f37f16c7b | |||
| a67d007435 | |||
| a5c6645d2d | |||
| cbe50a0232 | |||
| a48ac48202 | |||
| 0a7aaca6e5 | |||
| 6e41ea3b42 | |||
| 75ada621d9 | |||
| 12d578ff57 | |||
| 3486b7f503 | |||
| 0aed5e0f31 | |||
| 34c40980e3 | |||
| b13eb6012c | |||
| ecc3284a94 | |||
| b10c8ff182 | |||
| d96e222a15 | |||
| ec63533108 | |||
| 6f74366dd9 | |||
| 4b5825790a | |||
| c257e61fa7 | |||
| f7391c0e0b | |||
| dce3d5b411 | |||
| a2490da3b4 | |||
| 1aacc0073f | |||
| 6f2d80b99e | |||
| a8e7901eac | |||
| d4ae9d9611 | |||
| d82a3cffe8 | |||
| 05e189b938 | |||
| d32d0b17d0 | |||
| 1d87315426 | |||
| 4db0e8870d | |||
| deb59b314b | |||
| 4c75d4f559 | |||
| 8bd2bca879 | |||
| 97748dfd34 | |||
| 0d8b320f31 | |||
| 6ab05471b2 | |||
| 1291a0e932 | |||
| a2d40c5cbf | |||
| 2e5e6c9ad3 | |||
| c1e9143483 | |||
| 774f7d2dbe | |||
| de9eab1e4e | |||
| 9b1925d6de | |||
| a6ad1bdcdb | |||
| f9c8bbc4cc | |||
| 3634440c8b | |||
| c963673a19 | |||
| 0602c1b59d | |||
| d8a81879b1 | |||
| c054bc7bc7 | |||
| daf35f6e41 | |||
| d947a951ad | |||
| 273cf1094d | |||
| c907779b3c | |||
| 2d9ff34ded | |||
| d1a85659ba | |||
| d832e6e364 | |||
| 66cfe9ee45 | |||
| e530e38721 | |||
| d98ae9cdbf | |||
| 5100b76ad3 | |||
| 8328af802f | |||
| 87914291c6 | |||
| 0c7daef65e | |||
| 09da778d3b | |||
| 2ad64bbca7 | |||
| 247b94f3b3 | |||
| 8078ad5609 | |||
| 7fd70ac0d9 | |||
| dbdaff2ada | |||
| 3e53e368a4 | |||
| 6a7c037ea8 | |||
| 2414441efa | |||
| 14deb86a7a | |||
| 572c3b082e | |||
| d2b466df93 | |||
| 3f11465a7e | |||
| ece9a37af4 | |||
| 7f4cf8bdcd | |||
| d6538aac50 | |||
| 3a47fccf16 | |||
| c659eaeead | |||
| 37c7a37bdf | |||
| d3f23544cc | |||
| 9d5ea22806 | |||
| 1388d0e514 | |||
| e3412fac46 | |||
| e43c0b1e2e | |||
| b13a5ae1ae | |||
| 8c52848212 | |||
| 053007e7ea | |||
| 9889cb07d4 | |||
| 142b144318 | |||
| a47e53ff2d | |||
| 25bfe4f0fa | |||
| 8b88cd3cf6 | |||
| 748bf43847 | |||
| 586c536c46 | |||
| 4a84a782db | |||
| e2dbc0e1cf | |||
| 2b434de40b | |||
| a51c174021 | |||
| c1373174ca | |||
| c3f0ecf7d5 | |||
| 2f2fdb1809 | |||
| 95a123532b | |||
| 2cc7c7bcaf | |||
| b314b98dd6 | |||
| 5ec79e9612 | |||
| 9e89972008 | |||
| 05864d001a | |||
| f9fc81ce71 | |||
| 66a23cc99b | |||
| aa2d724a13 | |||
| 67f840c0ec | |||
| f2e545ff09 | |||
| 11142bc96a | |||
| e3d01bc6aa | |||
| d3fc1c602a | |||
| 926ad380f3 | |||
| b55a9bae43 | |||
| f8c46d7a11 | |||
| 75ca14c900 | |||
| 163712471c | |||
| 974cdcccc9 | |||
| bbe53a4c69 | |||
| 88d9e783b8 | |||
| 854f9aca23 | |||
| 69dde41d9c | |||
| e159e5bb6d | |||
| fce3c81029 | |||
| b14717eddb | |||
| 5891014ff6 | |||
| b51535bfa0 | |||
| 8476edd18f | |||
| e528cdb36d | |||
| 8696c698ed | |||
| c236caefad | |||
| f9de5282c9 | |||
| a4c2895c68 | |||
| e33ee800bc | |||
| 24aa80840c | |||
| d9aa6258cd | |||
| 941e6ee4e6 | |||
| ffab9d3aaa | |||
| 4d16e1ab83 | |||
| 6781685252 | |||
| 88bdf87e95 | |||
| 6b3d98bd66 | |||
| ec7ceb2352 | |||
| c62c38b136 | |||
| 33bf59f353 | |||
| b4d3c4833c | |||
| 44b54f6c32 | |||
| 57f7af3141 | |||
| 23dbd9112a | |||
| 44c8103600 | |||
| d2441b345b | |||
| 2c828c8778 | |||
| 8097f0e5fb | |||
| 14644d0cb3 | |||
| 4c89a20bbe | |||
| 6a2285ef72 | |||
| 37a791f113 | |||
| 06f820d355 | |||
| 3a2571ccc6 | |||
| dd614e6a6a | |||
| f5595b3477 | |||
| e9c34df51e | |||
| 82b9964a61 | |||
| a0cb5cc307 | |||
| 0b26ef51a2 | |||
| da3cc5f997 | |||
| 96356eb804 | |||
| 80067a212c | |||
| d962d7952b | |||
| ae4847ce50 | |||
| a07a2de786 | |||
| 96ce34c7f1 | |||
| c6fa1acf66 | |||
| a7c29c4a85 | |||
| 91364385c3 | |||
| d958722e63 | |||
| d3a19ebfaa | |||
| c17883bdb8 | |||
| 0b90b0206b | |||
| 8f958ef6c7 | |||
| 2118fa483b | |||
| 2bb9c7738a | |||
| 7ed55b00a6 | |||
| 4feb051177 | |||
| 27bce0d334 | |||
| ddf50724f0 | |||
| d07bd75d07 | |||
| d59ba03cc6 | |||
| 04112110f7 | |||
| d835cb5e6a | |||
| 6e5a6b5d91 | |||
| 270cb51acc | |||
| 579c78b2ad | |||
| 470cdd1c76 | |||
| 2abbae38d9 | |||
| 46dc8d9e12 | |||
| 59cbb9d740 | |||
| c50c9bec7e | |||
| 14ebcb1165 | |||
| 3728ad02e6 | |||
| ba9e1f5375 | |||
| 598c5f90ea | |||
| 6e1a195615 | |||
| 452848f14f | |||
| 4ccc123209 | |||
| a987449789 | |||
| ba9ff0964b | |||
| 3cd64fb0af | |||
| 6e8e6fe243 | |||
| 476f1bade2 | |||
| cf1d9ad53f | |||
| 680ff86202 | |||
| 9797fcd95a | |||
| 5d3841d6a7 | |||
| 9e5de53ad4 | |||
| 13cdbc565c | |||
| 5ea4b0f73d | |||
| f3e262bd3a | |||
| 96b8288c5b | |||
| a85590f5fb | |||
| 5a93bdd0a6 | |||
| be582f4db7 | |||
| 01a174f9e3 | |||
| ecc306079b | |||
| 251ea43e33 | |||
| 37b8fc6752 | |||
| 17b986c21d | |||
| d6b3dbc9f9 | |||
| 1f41478d53 | |||
| bd71520cb5 | |||
| 6276d135e4 | |||
| 3abdbc2d88 | |||
| 241f234a82 | |||
| 28ee5b6881 | |||
| d92790f0af | |||
| e18d0592d6 | |||
| 11802fc38a | |||
| b2ae35d597 | |||
| ec37a8befe | |||
| 804dd550a2 | |||
| 736d76f457 | |||
| 84734d7304 | |||
| e19b99a2bc | |||
| 577334cbaa | |||
| 35b615dc9f | |||
| ef8e9a3ccf | |||
| 27d5544f8b | |||
| e98111bf00 | |||
| c8c68f1898 | |||
| f47ccbec51 | |||
| ba53bc05a4 |
@@ -0,0 +1,112 @@
|
||||
---
|
||||
name: lockdown-mode
|
||||
description: Apple Lockdown Mode restrictions and their impact on web APIs inside WKWebView/Safari/WebView. Reference when debugging or building features for lockdown-enabled devices.
|
||||
---
|
||||
|
||||
# Apple Lockdown Mode
|
||||
|
||||
Apple's Lockdown Mode is an opt-in security hardening profile that disables or restricts many web platform APIs inside Safari and WKWebView. Since this app ships inside a Capacitor WKWebView shell, **every restriction that applies to Safari also applies to our app**.
|
||||
|
||||
## Platform Availability
|
||||
|
||||
Lockdown Mode is available on:
|
||||
|
||||
- **iOS 16** or later (iPhone)
|
||||
- **iPadOS 16** or later (iPad)
|
||||
- **watchOS 10** or later (Apple Watch)
|
||||
- **macOS Ventura** or later (Mac)
|
||||
|
||||
Additional protections are available starting in iOS 17, iPadOS 17, watchOS 10, and macOS Sonoma.
|
||||
|
||||
For full details, see [About Lockdown Mode](https://support.apple.com/en-us/105120) on Apple Support.
|
||||
|
||||
## Testing Baseline
|
||||
|
||||
This document is based on testing against **iOS 18.7 / Safari 26.4** on an iPhone with Lockdown Mode enabled (April 2026). The web API restrictions documented below apply to Safari and WKWebView across all supported platforms (iOS, iPadOS, and macOS).
|
||||
|
||||
## Blocked APIs
|
||||
|
||||
These APIs are **completely unavailable** (return `undefined`, `null`, or throw) when Lockdown Mode is active.
|
||||
|
||||
| API | Impact | Notes |
|
||||
|-----|--------|-------|
|
||||
| **IndexedDB** | Critical | `indexedDB` global is missing entirely. Any library that relies on IndexedDB for storage will fail (Dexie, idb, localForage with IndexedDB driver, etc.). |
|
||||
| **Service Workers** | High | `navigator.serviceWorker` is absent. No offline caching, no background sync, no push notifications via SW. |
|
||||
| **Cache API** | High | `caches` global is absent. Often used alongside Service Workers for offline strategies. |
|
||||
| **WebAssembly** | High | `WebAssembly` global is `undefined`. Libraries compiled to WASM (e.g. libsodium-wrappers, secp256k1-wasm, SQLite WASM) will not load. |
|
||||
| **Web Locks** | High | `navigator.locks` is absent. Cross-tab coordination patterns that depend on this will break silently. |
|
||||
| **WebRTC** | High | `RTCPeerConnection` is absent. No peer-to-peer audio/video/data channels. |
|
||||
| **WebGL / WebGL2** | Medium | All canvas `getContext('webgl'*)` calls return `null`. GPU-accelerated rendering, maps (Mapbox GL, deck.gl), and 3D are broken. |
|
||||
| **FileReader** | Medium | `FileReader` constructor is absent. Cannot read `Blob`/`File` objects client-side (e.g. image preview before upload). Use the `File` constructor + `URL.createObjectURL()` as a workaround for previews. |
|
||||
| **SharedArrayBuffer** | Medium | `SharedArrayBuffer` is `undefined`. May also require COOP/COEP headers on non-lockdown browsers, so this is often already unavailable. |
|
||||
| **Speech Synthesis** | Low | `window.speechSynthesis` is absent. Text-to-speech features won't work. |
|
||||
| **Notifications API** | Low | `Notification` is absent. Web push permission prompts won't appear. (Capacitor local notifications via the native plugin are unaffected.) |
|
||||
| **WebCodecs** | Low | `VideoDecoder` / `VideoEncoder` are absent (`AudioDecoder` remains). Low-level media processing is unavailable. |
|
||||
| **Gamepad API** | Low | `navigator.getGamepads` is absent. |
|
||||
| **OPFS** | Medium | `navigator.storage.getDirectory` method does not exist. The `navigator.storage` object is present but the Origin Private File System API is stripped. SQLite-over-OPFS and any other OPFS-based storage will fail. |
|
||||
| **Web Share API** | Low | `navigator.share` is absent. Use Capacitor's `@capacitor/share` plugin instead -- the native share sheet still works. |
|
||||
|
||||
## Available APIs
|
||||
|
||||
These APIs **still work** under Lockdown Mode and can be relied on.
|
||||
|
||||
| API | Notes |
|
||||
|-----|-------|
|
||||
| **File constructor** | `new File(...)` works. You can create File/Blob objects. |
|
||||
| **FontFace API** | Dynamic font loading via `new FontFace()` succeeds. Remote font fetches may fail with a network error (data URIs rejected). |
|
||||
| **JIT compilation** | JavaScript JIT appears active (~110ms for 1M iterations). Performance is not interpreter-level degraded. |
|
||||
| **PDF viewer** | `navigator.pdfViewerEnabled` is `true`. Inline `<embed type="application/pdf">` works. |
|
||||
| **Cookies** | `navigator.cookieEnabled` is `true`. |
|
||||
| **Credential Management** | `navigator.credentials` is available. |
|
||||
| **localStorage / sessionStorage** | Standard Web Storage APIs remain functional. |
|
||||
|
||||
## Implications for This App
|
||||
|
||||
### Storage
|
||||
|
||||
- **localStorage works** -- our primary client-side storage (app config, relay lists, etc.) is unaffected.
|
||||
- **IndexedDB is gone** -- if any dependency silently uses IndexedDB (e.g. some Nostr caching layers, TanStack Query persisters), it will fail. Ensure all storage paths fall back to localStorage or in-memory.
|
||||
- **OPFS is gone** -- `navigator.storage.getDirectory` is stripped (the method doesn't exist, though the `navigator.storage` object itself remains). SQLite-over-OPFS (e.g. wa-sqlite, sql.js with OPFS backend) and any other OPFS-based persistence will not work.
|
||||
|
||||
### Cryptography
|
||||
|
||||
- **WebAssembly is blocked** -- any WASM-based crypto libraries (secp256k1 compiled to WASM, libsodium WASM builds) will not load. Use pure-JS implementations (e.g. `@noble/secp256k1`, `@noble/hashes`) which are already what nostr-tools uses.
|
||||
- **WebCrypto (`crypto.subtle`)** -- not listed as blocked in testing. The SubtleCrypto API should still be available for NIP-44 encryption via the standard Web Crypto path.
|
||||
|
||||
### Media & Rendering
|
||||
|
||||
- **WebGL is gone** -- map libraries that require WebGL (Mapbox GL JS, Google Maps WebGL renderer) will show blank canvases. Use raster tile alternatives or static map images.
|
||||
- **FileReader is gone** -- image/file preview workflows that use `FileReader.readAsDataURL()` need a workaround. Use `URL.createObjectURL(file)` directly for `<img src>` previews instead.
|
||||
|
||||
### Communication
|
||||
|
||||
- **WebRTC is gone** -- any peer-to-peer features (voice/video calls, WebRTC data channels) are completely unavailable.
|
||||
- **Fetch / XMLHttpRequest** -- standard network requests appear unaffected. Relay WebSocket connections should work normally.
|
||||
|
||||
### Native Plugin Workarounds
|
||||
|
||||
Several blocked web APIs have Capacitor plugin equivalents that bypass WKWebView restrictions entirely:
|
||||
|
||||
| Blocked Web API | Capacitor Alternative |
|
||||
|---|---|
|
||||
| Web Share | `@capacitor/share` (already installed) |
|
||||
| Notifications | `@capacitor/local-notifications` (already installed) |
|
||||
| File downloads | `@capacitor/filesystem` + share (already implemented in `downloadFile.ts`) |
|
||||
|
||||
### Detection
|
||||
|
||||
The report used a scoring heuristic (8/12 key APIs blocked = 70%) to detect Lockdown Mode. There is no official API to query Lockdown Mode status. Detection relies on probing for the absence of multiple APIs that are specifically disabled by Lockdown Mode but normally present in Safari.
|
||||
|
||||
## Raw Diagnostic Report
|
||||
|
||||
For exact error messages, navigator properties, weight scores, and per-API diagnostic output, see [ios-report.txt](ios-report.txt).
|
||||
|
||||
## Guidance for Feature Decisions
|
||||
|
||||
When building new features, consider:
|
||||
|
||||
1. **Always provide pure-JS fallbacks** for any crypto or data-processing library that might ship a WASM build.
|
||||
2. **Never depend on IndexedDB or OPFS** as the sole storage mechanism. Both are completely stripped. Always fall back to localStorage or in-memory stores.
|
||||
3. **Avoid WebGL-dependent UI** for core functionality. Use it as a progressive enhancement with a CSS/Canvas 2D fallback.
|
||||
4. **Use Capacitor plugins** for sharing, notifications, and file operations rather than web APIs -- they work on all native platforms regardless of Lockdown Mode.
|
||||
5. **Test on a Lockdown Mode device** when shipping features that touch storage, crypto, or media APIs.
|
||||
@@ -0,0 +1,229 @@
|
||||
============================================================
|
||||
LOCKDOWN MODE DETECTOR REPORT
|
||||
2026-04-06T23:40:58.170Z
|
||||
============================================================
|
||||
|
||||
VERDICT: Lockdown Mode Likely Active
|
||||
8 of 12 key APIs are blocked, consistent with iOS/macOS Lockdown Mode.
|
||||
Score: 70% (8/12 key APIs blocked)
|
||||
|
||||
============================================================
|
||||
API TEST RESULTS (detailed)
|
||||
============================================================
|
||||
|
||||
------------------------------------------------------------
|
||||
[BLOCKED] IndexedDB (weight: 3)
|
||||
Client-side structured storage
|
||||
Result: Can't find variable: indexedDB
|
||||
Diagnostics:
|
||||
uncaught: Can't find variable: indexedDB
|
||||
|
||||
------------------------------------------------------------
|
||||
[BLOCKED] WebAssembly (weight: 2)
|
||||
Binary instruction execution
|
||||
Result: WebAssembly is undefined
|
||||
Diagnostics:
|
||||
typeof WebAssembly: undefined
|
||||
WebAssembly global does not exist
|
||||
|
||||
------------------------------------------------------------
|
||||
[BLOCKED] Web Locks API (weight: 3)
|
||||
Cross-tab resource coordination
|
||||
Result: navigator.locks is undefined
|
||||
Diagnostics:
|
||||
typeof navigator.locks: undefined
|
||||
'locks' in navigator: false
|
||||
navigator.locks is falsy
|
||||
|
||||
------------------------------------------------------------
|
||||
[BLOCKED] Speech Synthesis (weight: 3)
|
||||
Web Speech API (text-to-speech)
|
||||
Result: window.speechSynthesis is undefined
|
||||
Diagnostics:
|
||||
typeof window.speechSynthesis: undefined
|
||||
'speechSynthesis' in window: false
|
||||
typeof SpeechSynthesisUtterance: undefined
|
||||
speechSynthesis is falsy
|
||||
|
||||
------------------------------------------------------------
|
||||
[BLOCKED] FileReader API (weight: 2)
|
||||
Local file reading interface
|
||||
Result: FileReader is undefined
|
||||
Diagnostics:
|
||||
typeof FileReader: undefined
|
||||
FileReader constructor does not exist
|
||||
|
||||
------------------------------------------------------------
|
||||
[AVAILABLE] File Constructor (weight: 2)
|
||||
File object creation
|
||||
Result: File created: name=test.txt size=4
|
||||
Diagnostics:
|
||||
typeof File: function
|
||||
calling new File(['test'], 'test.txt', {type:'text/plain'})...
|
||||
succeeded
|
||||
f.name: test.txt
|
||||
f.size: 4
|
||||
f.type: text/plain
|
||||
f instanceof Blob: true
|
||||
|
||||
------------------------------------------------------------
|
||||
[BLOCKED] WebGL (weight: 2)
|
||||
GPU-accelerated graphics
|
||||
Result: all WebGL contexts returned null
|
||||
Diagnostics:
|
||||
getContext('webgl2'): null
|
||||
getContext('webgl'): null
|
||||
getContext('experimental-webgl'): null
|
||||
|
||||
------------------------------------------------------------
|
||||
[BLOCKED] WebGL2 (weight: 1)
|
||||
Advanced GPU graphics context
|
||||
Result: getContext('webgl2') returned null
|
||||
Diagnostics:
|
||||
getContext('webgl2'): null
|
||||
|
||||
------------------------------------------------------------
|
||||
[BLOCKED] Service Worker (weight: 1)
|
||||
Background script registration
|
||||
Result: navigator.serviceWorker not present
|
||||
Diagnostics:
|
||||
'serviceWorker' in navigator: false
|
||||
typeof navigator.serviceWorker: undefined
|
||||
|
||||
------------------------------------------------------------
|
||||
[BLOCKED] Web Share API (weight: 0)
|
||||
Native sharing interface
|
||||
Result: navigator.share is undefined
|
||||
Diagnostics:
|
||||
typeof navigator.share: undefined
|
||||
typeof navigator.canShare: undefined
|
||||
|
||||
------------------------------------------------------------
|
||||
[BLOCKED] Gamepad API (weight: 1)
|
||||
Game controller input
|
||||
Result: navigator.getGamepads not present
|
||||
Diagnostics:
|
||||
'getGamepads' in navigator: false
|
||||
|
||||
------------------------------------------------------------
|
||||
[BLOCKED] WebRTC (weight: 2)
|
||||
Real-time peer communication
|
||||
Result: RTCPeerConnection is undefined
|
||||
Diagnostics:
|
||||
typeof RTCPeerConnection: undefined
|
||||
typeof webkitRTCPeerConnection: undefined
|
||||
|
||||
------------------------------------------------------------
|
||||
[AVAILABLE] FontFace API (weight: 1)
|
||||
Dynamic font loading
|
||||
Result: status: loaded
|
||||
Diagnostics:
|
||||
typeof FontFace: function
|
||||
new FontFace() succeeded
|
||||
ff.status: unloaded
|
||||
ff.family: test
|
||||
ff.status after load: loaded
|
||||
|
||||
------------------------------------------------------------
|
||||
[AVAILABLE] Remote Fonts (weight: 2)
|
||||
Loading fonts from network via data URI
|
||||
Result: API works, load rejected: A network error occurred.
|
||||
Diagnostics:
|
||||
FontFace created with data URI
|
||||
ff.status before load: unloaded
|
||||
caught: DOMException: A network error occurred.
|
||||
|
||||
------------------------------------------------------------
|
||||
[AVAILABLE] JIT Compilation (weight: 2)
|
||||
JavaScript JIT optimization heuristic
|
||||
Result: 99.0ms for 1M iterations (JIT likely)
|
||||
Diagnostics:
|
||||
running 1,000,000 iterations of Math.sqrt*Math.sin...
|
||||
elapsed: 99.00ms
|
||||
sum (to prevent dead-code elimination): -681.7597
|
||||
threshold: <150ms suggests JIT active
|
||||
verdict: likely JIT
|
||||
|
||||
------------------------------------------------------------
|
||||
[BLOCKED] Notifications API (weight: 1)
|
||||
Push notification permission
|
||||
Result: Notification not in window
|
||||
Diagnostics:
|
||||
'Notification' in window: false
|
||||
typeof Notification: undefined
|
||||
|
||||
------------------------------------------------------------
|
||||
[BLOCKED] WebCodecs (weight: 1)
|
||||
Low-level VideoDecoder API
|
||||
Result: VideoDecoder is undefined
|
||||
Diagnostics:
|
||||
typeof VideoDecoder: undefined
|
||||
typeof VideoEncoder: undefined
|
||||
typeof AudioDecoder: function
|
||||
|
||||
------------------------------------------------------------
|
||||
[AVAILABLE] PDF Embed (weight: 2)
|
||||
Inline PDF rendering via embed/pdfViewerEnabled
|
||||
Result: pdfViewerEnabled is true
|
||||
Diagnostics:
|
||||
navigator.pdfViewerEnabled: true
|
||||
typeof navigator.pdfViewerEnabled: boolean
|
||||
created and appended <embed type=application/pdf>
|
||||
navigator.mimeTypes['application/pdf']: [object MimeType]
|
||||
|
||||
------------------------------------------------------------
|
||||
[BLOCKED] SharedArrayBuffer (weight: 1)
|
||||
Shared memory between workers
|
||||
Result: SharedArrayBuffer is undefined
|
||||
Diagnostics:
|
||||
typeof SharedArrayBuffer: undefined
|
||||
requires COOP/COEP headers to be present; may not indicate Lockdown Mode specifically
|
||||
|
||||
------------------------------------------------------------
|
||||
[BLOCKED] Cache API (weight: 1)
|
||||
Programmatic HTTP cache (CacheStorage)
|
||||
Result: caches not in window
|
||||
Diagnostics:
|
||||
'caches' in window: false
|
||||
typeof caches: undefined
|
||||
|
||||
------------------------------------------------------------
|
||||
[BLOCKED] OPFS (weight: 2)
|
||||
Origin Private File System (navigator.storage.getDirectory)
|
||||
Result: navigator.storage.getDirectory is not a function
|
||||
Diagnostics:
|
||||
typeof navigator.storage: object
|
||||
typeof navigator.storage.getDirectory: undefined
|
||||
getDirectory method does not exist
|
||||
|
||||
============================================================
|
||||
NAVIGATOR INFO
|
||||
============================================================
|
||||
|
||||
userAgent: Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1
|
||||
platform: iPhone
|
||||
vendor: Apple Computer, Inc.
|
||||
language: en-US
|
||||
languages: en-US
|
||||
cookieEnabled: true
|
||||
doNotTrack: null
|
||||
maxTouchPoints: 5
|
||||
hardwareConcurrency: 4
|
||||
deviceMemory: N/A
|
||||
pdfViewerEnabled: true
|
||||
webdriver: false
|
||||
connection: unavailable
|
||||
mediaDevices: unavailable
|
||||
storage: available
|
||||
serviceWorker: unavailable
|
||||
credentials: available
|
||||
bluetooth: unavailable
|
||||
gpu (WebGPU): unavailable
|
||||
screenWidth: 393
|
||||
screenHeight: 852
|
||||
devicePixelRatio: 3
|
||||
colorDepth: 24
|
||||
|
||||
============================================================
|
||||
END OF REPORT
|
||||
============================================================
|
||||
@@ -108,6 +108,7 @@ Prepend a new section to `CHANGELOG.md` directly below the `# Changelog` heading
|
||||
- Use present tense ("Add dark mode toggle", not "Added dark mode toggle")
|
||||
- Focus on what the user sees/experiences, not internal implementation details
|
||||
- Use the current date in YYYY-MM-DD format
|
||||
- **Never use Nostr protocol jargon.** NIP numbers (e.g., "NIP-89", "NIP-17"), kind numbers (e.g., "kind 30078"), and other protocol-level references must not appear in the changelog. Describe the feature in plain language from the user's perspective. For example, write "App cards for Nostr apps" instead of "App cards for Nostr apps (NIP-89)". The changelog audience is end users, not protocol developers.
|
||||
- **Collapse related work into one entry.** If a feature was added and then fixed/tweaked across multiple commits in the same release, present the finished result as a single "Added" entry. Never list something as "Added" and then also list fixes for that same thing -- the user sees the end product, not the development history.
|
||||
- **Omit purely internal changes.** CI fixes, build pipeline tweaks, developer tooling, and infrastructure changes should be omitted from the changelog entirely unless they have a direct, visible impact on the user experience. The changelog is for users, not developers.
|
||||
- **Compare the actual code between versions** to understand what really changed, rather than just reading commit messages. Commit messages may over- or under-represent the significance of changes.
|
||||
|
||||
@@ -2,4 +2,6 @@ VITE_SENTRY_DSN="https://********************************@*****************.exam
|
||||
VITE_PLAUSIBLE_DOMAIN="example.tld"
|
||||
VITE_PLAUSIBLE_ENDPOINT="https://plausible.example.tld/api/event"
|
||||
# Hex pubkey of the nostr-push server (found in nostr-push startup logs as "worker_pubkey")
|
||||
VITE_NOSTR_PUSH_PUBKEY=""
|
||||
VITE_NOSTR_PUSH_PUBKEY=""
|
||||
# Set to "*" to allow any host in the Vite dev server (eg. when proxying through a custom domain)
|
||||
# ALLOWED_HOSTS="*"
|
||||
@@ -26,19 +26,52 @@ test:
|
||||
script:
|
||||
- npm run test
|
||||
|
||||
pages:
|
||||
deploy-nsite:
|
||||
stage: deploy
|
||||
timeout: 5 minutes
|
||||
timeout: 10 minutes
|
||||
rules:
|
||||
- if: $CI_COMMIT_TAG
|
||||
when: never
|
||||
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
|
||||
variables:
|
||||
NSYTE_VERSION: "v0.24.1"
|
||||
script:
|
||||
# Build the web app
|
||||
- npm ci
|
||||
- npm run build
|
||||
- rm -rf public
|
||||
- mv dist public
|
||||
- cp dist/index.html dist/404.html
|
||||
|
||||
# Download nsyte binary
|
||||
- curl -fsSL "https://github.com/sandwichfarm/nsyte/releases/download/${NSYTE_VERSION}/nsyte-linux" -o /usr/local/bin/nsyte
|
||||
- chmod +x /usr/local/bin/nsyte
|
||||
|
||||
# Deploy to nsite via nsyte using the nbunksec credential
|
||||
- >-
|
||||
nsyte deploy ./dist
|
||||
-i
|
||||
--sec "$NSITE_NBUNKSEC"
|
||||
--name ditto
|
||||
--relays "wss://relay.ditto.pub,wss://relay.nsite.lol,wss://relay.dreamith.to,wss://relay.primal.net"
|
||||
--servers "https://blossom.primal.net,https://blossom.ditto.pub,https://blossom.dreamith.to"
|
||||
--fallback "/index.html"
|
||||
--use-fallback-relays
|
||||
--use-fallback-servers
|
||||
|
||||
build-web:
|
||||
stage: build
|
||||
timeout: 10 minutes
|
||||
needs: []
|
||||
rules:
|
||||
- if: $CI_COMMIT_TAG
|
||||
when: never
|
||||
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
|
||||
script:
|
||||
- npm ci
|
||||
- npm run build
|
||||
- cp dist/index.html dist/404.html
|
||||
artifacts:
|
||||
paths:
|
||||
- public
|
||||
only:
|
||||
variables:
|
||||
- $CI_DEFAULT_BRANCH == $CI_COMMIT_REF_NAME
|
||||
- dist/
|
||||
|
||||
build-apk:
|
||||
stage: build
|
||||
@@ -112,8 +145,9 @@ build-apk:
|
||||
- npx vite build -l error
|
||||
- cp dist/index.html dist/404.html
|
||||
|
||||
# Sync web assets to Capacitor Android project
|
||||
# Sync web assets to Capacitor Android project and register local plugins
|
||||
- npx cap sync android
|
||||
- node scripts/patch-cap-config.mjs
|
||||
|
||||
# Build signed release APK
|
||||
- cd android && chmod +x gradlew && ./gradlew assembleRelease bundleRelease && cd ..
|
||||
@@ -185,6 +219,8 @@ publish-zapstore:
|
||||
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
|
||||
variables:
|
||||
SIGN_WITH: $ZAPSTORE_BUNKER_URL
|
||||
RELAY_URLS: "wss://relay.zapstore.dev,wss://relay.ditto.pub,wss://relay.dreamith.to,wss://relay.primal.net"
|
||||
BLOSSOM_URL: "https://blossom.ditto.pub"
|
||||
script:
|
||||
- go install github.com/zapstore/zsp@latest
|
||||
|
||||
@@ -198,4 +234,33 @@ publish-zapstore:
|
||||
- VERSION="${CI_COMMIT_TAG#v}"
|
||||
- sed -i "2i release_source:\ ./${APK_PATH}" zapstore.yaml
|
||||
- sed -i "2i version:\ ${VERSION}" zapstore.yaml
|
||||
- zsp publish -y --skip-metadata --skip-preview zapstore.yaml
|
||||
- zsp publish --quiet --skip-metadata --skip-preview zapstore.yaml
|
||||
|
||||
publish-google-play:
|
||||
stage: publish
|
||||
image: ruby:3.3
|
||||
needs:
|
||||
- build-apk
|
||||
rules:
|
||||
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
|
||||
script:
|
||||
- gem install fastlane --no-document
|
||||
|
||||
# Decode base64-encoded service account JSON to a temp file
|
||||
- echo "$GOOGLE_PLAY_SERVICE_ACCOUNT_JSON" | base64 -d > /tmp/play-service-account.json
|
||||
|
||||
# Upload the AAB to Google Play production track
|
||||
- >-
|
||||
fastlane supply
|
||||
--aab artifacts/Ditto.aab
|
||||
--package_name pub.ditto.app
|
||||
--track production
|
||||
--json_key /tmp/play-service-account.json
|
||||
--skip_upload_metadata
|
||||
--skip_upload_changelogs
|
||||
--skip_upload_images
|
||||
--skip_upload_screenshots
|
||||
--skip_upload_apk
|
||||
|
||||
# Clean up
|
||||
- rm -f /tmp/play-service-account.json
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
Thanks for contributing to Ditto! Please read [CONTRIBUTING.md](CONTRIBUTING.md) in full before submitting -- it covers everything you need to get your MR accepted.
|
||||
|
||||
## Related Issue
|
||||
|
||||
<!-- Link the GitLab issue. MRs without a linked issue will not be reviewed. -->
|
||||
|
||||
Closes #
|
||||
|
||||
## What Changed
|
||||
|
||||
<!-- 1-3 sentences: what you changed and why. -->
|
||||
|
||||
## Live Preview
|
||||
|
||||
<!-- REQUIRED for UI changes. Deploy your branch and paste the URL. -->
|
||||
<!-- Example: npx surge dist your-branch.surge.sh -->
|
||||
<!-- Write "N/A -- no UI changes" only if this MR has zero visual impact. -->
|
||||
|
||||
## Screenshots
|
||||
|
||||
<!-- REQUIRED for UI changes. Show before and after. -->
|
||||
<!-- Write "N/A -- no UI changes" only if this MR has zero visual impact. -->
|
||||
|
||||
**Before:**
|
||||
|
||||
|
||||
**After:**
|
||||
|
||||
## Philosophy Alignment
|
||||
|
||||
<!-- Answer this question for your change: -->
|
||||
<!-- "Does this make Ditto more magnetic, more threatening to the status quo, -->
|
||||
<!-- and more peaceful to inhabit?" -->
|
||||
<!-- See: https://about.ditto.pub/philosophy -->
|
||||
<!-- For bug fixes: "Bug fix -- restores intended behavior" is acceptable. -->
|
||||
|
||||
## How to Test
|
||||
|
||||
<!-- Steps a reviewer can follow to verify this works. -->
|
||||
|
||||
1.
|
||||
2.
|
||||
3.
|
||||
|
||||
## Self-Review Checklist
|
||||
|
||||
<!-- Complete ALL items. MRs with unchecked boxes will not be reviewed. -->
|
||||
<!-- Check a box: replace [ ] with [x] -->
|
||||
|
||||
### Process
|
||||
|
||||
- [ ] I read `AGENTS.md` before starting
|
||||
- [ ] I read the [Ditto Philosophy](https://about.ditto.pub/philosophy)
|
||||
- [ ] I used plan/research mode before writing code
|
||||
- [ ] I used Claude Opus 4.6 (or equivalent frontier model)
|
||||
|
||||
### Self-review
|
||||
|
||||
Copy-paste this into your AI tool and fix any findings before submitting:
|
||||
|
||||
> Review this diff against the self-review checklist in CONTRIBUTING.md step 8. Read that file first, then check every item. For each finding, state the file, line, and issue.
|
||||
|
||||
- [ ] I ran the self-review prompt above and addressed all findings
|
||||
|
||||
### Testing
|
||||
|
||||
- [ ] I ran `npm run test` locally and it passes
|
||||
- [ ] I tested the change manually in the browser
|
||||
@@ -294,14 +294,16 @@ When adding support for a new Nostr event kind to the application, the kind must
|
||||
- `WELL_KNOWN_KIND_LABELS` in `src/components/ExternalContentHeader.tsx` -- used in addressable event preview headers
|
||||
- The icon fallback in `AddressableEventPreview` in the same file
|
||||
|
||||
6. **Inline embeds / quote posts** -- events can be quoted inline via `nostr:nevent1...` or `nostr:naddr1...` URIs in note content. Both `EmbeddedNote` and `EmbeddedNaddr` render a compact card (author + title/content preview) for all kinds automatically — no per-kind registration needed. The same components are reused by CommentContext hover cards and the reply composer.
|
||||
6. **Embedded note cards** (`src/components/EmbeddedNote.tsx`, `src/components/EmbeddedNaddr.tsx`) -- these are the small preview cards shown inside quote posts, reply context indicators, and CommentContext hover cards. They are **separate components** from `NoteCard` and render a minimal card (author + title/content preview + attachment indicators). Basic rendering works for all kinds automatically, but kinds whose media lives in tags rather than in the `content` field (e.g. kind 20 photos via `imeta` tags) may need attachment indicator logic added to `EmbeddedNoteCard`.
|
||||
|
||||
> **Note**: Do not confuse these with the `compact` prop on `NoteCard`. The `compact` prop simply hides action buttons on a full `NoteCard`; `EmbeddedNote`/`EmbeddedNaddr` are entirely different components with their own rendering logic.
|
||||
|
||||
7. **Reply composer** (`src/components/ReplyComposeModal.tsx`):
|
||||
- The `EmbeddedPost` component delegates to the shared `EmbeddedNote`/`EmbeddedNaddr` components — no per-kind registration needed
|
||||
|
||||
#### Why so many places?
|
||||
|
||||
These are genuinely different UI contexts (feed cards, detail pages, inline embeds, reply previews, comment context labels) with different rendering requirements. However, several of them maintain independent kind-to-label maps that could theoretically be unified. When in doubt, search the codebase for an existing kind number like `30617` to find all the registration points.
|
||||
These are genuinely different UI contexts (feed cards, detail pages, embedded note cards, reply previews, comment context labels) with different rendering requirements. However, several of them maintain independent kind-to-label maps that could theoretically be unified. When in doubt, search the codebase for an existing kind number like `30617` to find all the registration points.
|
||||
|
||||
### NIP.md
|
||||
|
||||
@@ -407,6 +409,74 @@ Without filtering approvals by the moderator list, anyone could publish kind 455
|
||||
|
||||
Author filtering is not needed for public user-generated content where anyone should be able to post (kind 1 notes, reactions, discovery queries, public feeds, etc.).
|
||||
|
||||
#### Sanitizing URLs from Event Data
|
||||
|
||||
**CRITICAL**: Any URL extracted from Nostr event tags, content, or metadata fields is **untrusted user input**. Malicious URLs can cause harm in many ways beyond `javascript:` XSS — `data:` URIs for resource exhaustion, `http://` URLs leaking user IPs without TLS, relative paths triggering unintended requests to the app's own origin, and more. Reasoning about which rendering context is "safe enough" to skip sanitization is fragile and error-prone.
|
||||
|
||||
**Rule: sanitize every event-sourced URL unconditionally**, regardless of where it will be used (`href`, `img src`, `style`, etc.). Use `sanitizeUrl()` from `@/lib/sanitizeUrl`:
|
||||
|
||||
```typescript
|
||||
import { sanitizeUrl } from '@/lib/sanitizeUrl';
|
||||
|
||||
// Single URL — returns the normalised href, or undefined if not valid https
|
||||
const url = sanitizeUrl(getTag(event.tags, 'url'));
|
||||
if (url) {
|
||||
// safe to use in any context
|
||||
}
|
||||
|
||||
// Array of URLs — filter out invalid entries
|
||||
const links = getAllTags(event.tags, 'r')
|
||||
.map(([, v]) => sanitizeUrl(v))
|
||||
.filter((v): v is string => !!v);
|
||||
```
|
||||
|
||||
`sanitizeUrl` accepts `string | undefined | null` and returns the normalised `href` string only when the URL parses successfully **and** uses the `https:` protocol. All other inputs (malformed URLs, `javascript:`, `data:`, `http:`, relative paths, etc.) return `undefined`.
|
||||
|
||||
**Best practice — sanitize at the parse layer.** When writing a parser function that extracts URLs from event tags (e.g. `parseThemeDefinition`, `parseBadgeDefinition`), apply `sanitizeUrl()` before returning the parsed data. This way every downstream consumer is automatically protected without needing to remember to sanitize at each usage site.
|
||||
|
||||
**When sanitization is NOT required:**
|
||||
- URLs extracted by regex that already constrains the protocol (e.g. `NoteContent` tokeniser matches only `https?://`)
|
||||
- Hardcoded or application-generated URLs (relay configs, internal routes, etc.)
|
||||
- URLs displayed as plain text without being placed into any HTML attribute or CSS value
|
||||
|
||||
#### Preventing CSS Injection from Event Data
|
||||
|
||||
**CRITICAL**: Any value from a Nostr event that is interpolated into a CSS string (inside a `<style>` element or inline `style` attribute) is a CSS injection vector. A malicious value containing `"`, `)`, `}`, or `;` can break out of the CSS context and inject arbitrary rules — for example, overlaying phishing content or hiding UI elements.
|
||||
|
||||
**Common CSS injection surfaces:**
|
||||
- `background-image: url("${url}")` — a URL with `"); body { display:none }` breaks out
|
||||
- `font-family: "${family}"` — a family name with `"; } body { visibility:hidden } .x {` breaks out
|
||||
- `@font-face { src: url("${url}") }` — same risk as background URLs
|
||||
|
||||
**Mitigation strategy — sanitize at the parse layer:**
|
||||
|
||||
1. **URLs in CSS `url()` values**: Pass through `sanitizeUrl()` at parse time. The `URL` constructor normalises the string, percent-encoding characters like `"`, `)`, and `\` that could escape the CSS context. Invalid or non-`https:` URLs are rejected entirely. This is already done for theme event background and font URLs in `src/lib/themeEvent.ts`.
|
||||
|
||||
2. **Strings in CSS declarations** (e.g. font family names): Use `sanitizeCssString()` from `src/lib/fontLoader.ts`, which uses an allowlist approach — only Unicode letters, numbers, spaces, hyphens, underscores, apostrophes, and periods are permitted. Everything else is stripped.
|
||||
|
||||
```typescript
|
||||
// ❌ UNSAFE — raw event data interpolated into CSS
|
||||
const bgUrl = getTagValue(event.tags, 'bg');
|
||||
style.textContent = `body { background-image: url("${bgUrl}"); }`;
|
||||
|
||||
const family = getTagValue(event.tags, 'f');
|
||||
style.textContent = `html { font-family: "${family}"; }`;
|
||||
|
||||
// ✅ SAFE — URLs validated, strings sanitised
|
||||
import { sanitizeUrl } from '@/lib/sanitizeUrl';
|
||||
|
||||
const bgUrl = sanitizeUrl(getTagValue(event.tags, 'bg'));
|
||||
if (bgUrl) {
|
||||
style.textContent = `body { background-image: url("${bgUrl}"); }`;
|
||||
}
|
||||
|
||||
// For non-URL strings, allowlist safe characters only
|
||||
const safeFamily = family.replace(/[^\p{L}\p{N} _\-'.]/gu, '');
|
||||
style.textContent = `html { font-family: "${safeFamily}"; }`;
|
||||
```
|
||||
|
||||
**Rule of thumb**: Never interpolate untrusted strings into CSS without sanitisation. If it's a URL, use `sanitizeUrl()`. If it's any other string, strip characters that can break out of the CSS string context.
|
||||
|
||||
### The `useNostr` Hook
|
||||
|
||||
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
|
||||
@@ -693,6 +763,88 @@ export function MyComponent() {
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Mutating Replaceable Events (CRITICAL)
|
||||
|
||||
Replaceable (kind 10000-19999) and addressable (kind 30000-39999) events require a read-modify-write cycle: fetch the current event, modify its tags, then publish a new version. **Never read from TanStack Query cache before mutating** -- the cache can be stale from another device or a rapid prior operation, and republishing stale data silently drops the user's data.
|
||||
|
||||
Use `fetchFreshEvent()` from `src/lib/fetchFreshEvent.ts` inside every mutation, and **always pass the fetched event as `prev`** so `useNostrPublish` can preserve `published_at`:
|
||||
|
||||
```typescript
|
||||
import { fetchFreshEvent } from '@/lib/fetchFreshEvent';
|
||||
|
||||
// Inside a mutation function:
|
||||
const prev = await fetchFreshEvent(nostr, {
|
||||
kinds: [10003],
|
||||
authors: [user.pubkey],
|
||||
});
|
||||
const currentTags = prev?.tags ?? [];
|
||||
// ...modify tags...
|
||||
await publishEvent({
|
||||
kind: 10003,
|
||||
content: prev?.content ?? '',
|
||||
tags: newTags,
|
||||
prev: prev ?? undefined,
|
||||
});
|
||||
```
|
||||
|
||||
This applies to all list-type hooks (bookmarks, pins, interests, follow sets, badges, etc.). See `useFollowActions` and `useMuteList` for complete examples.
|
||||
|
||||
#### The `prev` Property on Event Templates
|
||||
|
||||
`useNostrPublish` accepts an optional `prev` property on the event template. This is the **previous version** of the event being replaced. The hook uses it to automatically manage the `published_at` tag (NIP-24) for replaceable and addressable events:
|
||||
|
||||
- **First publish (no `prev`)**: `published_at` is set equal to `created_at`
|
||||
- **Update (`prev` provided)**: `published_at` is preserved from the old event
|
||||
- **Old event lacks `published_at`**: nothing is fabricated
|
||||
- **Caller already set `published_at` in tags**: left alone
|
||||
|
||||
**Convention**: Name the local variable `prev` at the call site (not `freshEvent` or `latestEvent`) so it reads naturally when passed to `publishEvent`:
|
||||
|
||||
```typescript
|
||||
const prev = await fetchFreshEvent(nostr, { kinds: [3], authors: [user.pubkey] });
|
||||
// ...
|
||||
await publishEvent({ kind: 3, content: prev?.content ?? '', tags: newTags, prev: prev ?? undefined });
|
||||
```
|
||||
|
||||
`prev` is stripped from the template before signing — it never appears in the published Nostr event.
|
||||
|
||||
### D-Tag Collision Prevention for Addressable Events
|
||||
|
||||
Addressable events (kind 30000-39999) are identified by `pubkey + kind + d-tag`. Publishing an event with the same d-tag as an existing one **silently replaces** it. This is by design for intentional updates (edit flows), but dangerous when creating *new* content with user-derived d-tags (slugs from titles, user-entered identifiers, etc.).
|
||||
|
||||
#### When to Check for Collisions
|
||||
|
||||
**Must check before publishing** when the d-tag is derived from user input (slugified titles, user-entered identifiers, etc.). **No check needed** when the d-tag is a `crypto.randomUUID()`, a canonical format with embedded pubkey prefix, or intentionally the same as an existing event (edit/update flows).
|
||||
|
||||
#### Implementation Pattern
|
||||
|
||||
Before publishing a **new** addressable event with a user-derived d-tag, query for an existing event with that d-tag. If one exists, block the publish and tell the user to change the identifier.
|
||||
|
||||
```typescript
|
||||
// Before publishing a new addressable event:
|
||||
const slug = slugify(title, { lower: true, strict: true });
|
||||
|
||||
const existing = await nostr.query([
|
||||
{ kinds: [30023], authors: [user.pubkey], '#d': [slug], limit: 1 },
|
||||
]);
|
||||
|
||||
if (existing.length > 0) {
|
||||
toast({
|
||||
title: 'Slug already in use',
|
||||
description: 'Change the slug or edit the existing item.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Safe to publish
|
||||
publishEvent({ kind: 30023, content, tags: [['d', slug], ...otherTags] });
|
||||
```
|
||||
|
||||
**Skip the check in edit mode** -- when the user explicitly loaded an existing event to update, overwriting is the intended behavior.
|
||||
|
||||
Prefer UUID or canonical formats when the d-tag doesn't need to be human-readable. Only use slugified input when the d-tag will appear in URLs or needs to be meaningful to users, and always add a collision check.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
@@ -954,6 +1106,16 @@ const defaultConfig: AppConfig = {
|
||||
|
||||
The app uses NIP-65 compatible relay management with automatic sync when users log in. Local storage persists user preferences and relay configurations.
|
||||
|
||||
### Adding a New AppConfig Value
|
||||
|
||||
Adding a new configuration field requires updates in **three places**. Missing any of them will cause build failures or runtime issues.
|
||||
|
||||
1. **TypeScript interface** (`src/contexts/AppContext.ts`): Add the field to the `AppConfig` interface with a JSDoc comment.
|
||||
|
||||
2. **Zod schema** (`src/lib/schemas.ts`): Add the same field to `AppConfigSchema`. The `DittoConfigSchema` (used to validate the build-time `ditto.json` file) is derived from `AppConfigSchema` with `.strict()` mode, so any field present in `ditto.json` but missing from the Zod schema will cause a build error.
|
||||
|
||||
3. **Default value** (`src/contexts/AppContext.ts`): If the field is required (not optional), add a default value in `defaultConfig`. Optional fields (`?` in the interface, `.optional()` in Zod) can be omitted from the default.
|
||||
|
||||
### Relay Management
|
||||
|
||||
The project includes a complete NIP-65 relay management system:
|
||||
@@ -1241,6 +1403,10 @@ Run available tools in this priority order:
|
||||
|
||||
The validation ensures code quality and catches errors before deployment, regardless of the development environment.
|
||||
|
||||
### Contributing Guide
|
||||
|
||||
When preparing changes for a merge request, also follow the guidelines in `CONTRIBUTING.md`. It includes a self-review checklist (step 8) that should be run against your diff before committing.
|
||||
|
||||
### Using Git
|
||||
|
||||
If git is available in your environment (through a `shell` tool, or other git-specific tools), you should utilize `git log` to understand project history. Use `git status` and `git diff` to check the status of your changes, and if you make a mistake use `git checkout` to restore files.
|
||||
@@ -1315,10 +1481,10 @@ After adding or removing plugins, run `npx cap sync` to update the native projec
|
||||
The project uses GitLab CI (`.gitlab-ci.yml`) with the following stages:
|
||||
|
||||
1. **test** - Runs `npm run test` on every commit (skipped for tags)
|
||||
2. **deploy** - Builds and deploys to GitLab Pages (default branch only)
|
||||
2. **deploy** - Builds and deploys to nsite via nsyte (`deploy-nsite` job, default branch only)
|
||||
3. **build** - Builds a signed release APK (`build-apk` job, tags only)
|
||||
4. **release** - Creates a GitLab Release with the APK artifact (tags only)
|
||||
5. **publish** - Publishes the APK to Zapstore (`publish-zapstore` job, tags only)
|
||||
5. **publish** - Publishes the APK to Zapstore (`publish-zapstore` job, tags only) and AAB to Google Play (`publish-google-play` job, tags only)
|
||||
|
||||
### Creating a Release
|
||||
|
||||
@@ -1328,7 +1494,7 @@ Releases are triggered by pushing a version tag. Use the npm script:
|
||||
npm run release
|
||||
```
|
||||
|
||||
This creates a tag in the format `v2026.03.14+abc1234` (date + short commit hash) and pushes it to GitLab, which triggers the `build-apk`, `release`, and `publish-zapstore` stages.
|
||||
This creates a tag in the format `v2026.03.14+abc1234` (date + short commit hash) and pushes it to GitLab, which triggers the `build-apk`, `release`, `publish-zapstore`, and `publish-google-play` stages.
|
||||
|
||||
### Zapstore Publishing
|
||||
|
||||
@@ -1355,19 +1521,94 @@ NIP-46 bunker signing requires two keys: the **user's key** (held by Amber) and
|
||||
The `publish-zapstore` job restores the client key from `ZAPSTORE_CLIENT_KEY` into `~/.config/zsp/bunker-keys/<bunker-pubkey>.key` before running `zsp`, so the bunker recognizes the CI runner as an already-authorized client.
|
||||
|
||||
**Initial setup (one-time):**
|
||||
1. Generate a client key: `nak key generate` (save the hex output)
|
||||
2. Store it as `ZAPSTORE_CLIENT_KEY` in GitLab CI/CD variables
|
||||
3. Get a bunker URL from Amber (with `secret` param for first connection)
|
||||
4. Authorize the client key locally using `nak`:
|
||||
```bash
|
||||
export NOSTR_CLIENT_KEY="<the hex client key>"
|
||||
nak event --sec "bunker://<pubkey>?relay=...&secret=<secret>" -c "test"
|
||||
```
|
||||
5. Approve the connection on Amber when prompted
|
||||
6. Store the bunker URL **without the `secret` param** as `ZAPSTORE_BUNKER_URL` in GitLab CI/CD variables (the secret is single-use and no longer needed after authorization)
|
||||
|
||||
Run the NIP-46 client-initiated auth script:
|
||||
|
||||
```bash
|
||||
node scripts/nip46-auth.mjs
|
||||
```
|
||||
|
||||
This generates a `nostrconnect://` URI. Import/paste it into Amber and approve the connection. The script will then output the `bunker://` URI and client key hex, and write the client key to `~/.config/zsp/bunker-keys/`. Update the GitLab CI/CD variables with the printed values.
|
||||
|
||||
The script accepts options:
|
||||
- `--relay <url>` -- relay for NIP-46 communication (default: `wss://relay.ditto.pub`)
|
||||
- `--name <name>` -- app name shown to the signer (default: `Ditto`)
|
||||
- `--timeout <sec>` -- how long to wait for approval (default: 300)
|
||||
|
||||
**Key points:**
|
||||
- The `secret` in bunker URLs is **single-use** -- it is consumed on first connection and cannot be reused
|
||||
- The `ZAPSTORE_CLIENT_KEY` must be authorized locally first by connecting to the bunker with a fresh secret and approving on Amber
|
||||
- After authorization, the bunker recognizes the client key and no secret or manual approval is needed for CI runs
|
||||
- If the client key is rotated, the authorization step must be repeated with a new bunker URL secret
|
||||
- If the client key is rotated, run the script again and update the GitLab CI/CD variables
|
||||
|
||||
### nsite Publishing
|
||||
|
||||
The project automatically deploys the web app to [nsite](https://nsite.run) on every push to the default branch using [nsyte](https://github.com/sandwichfarm/nsyte). The `deploy-nsite` CI job builds the Vite app and uploads the `dist/` directory to Blossom servers, publishing site manifest events to Nostr relays.
|
||||
|
||||
nsyte uses a NIP-46 bunker credential called `nbunksec` -- a bech32-encoded string that bundles the bunker pubkey, client secret key, and relay info into a single self-contained token. This is passed to nsyte via `--sec`.
|
||||
|
||||
**GitLab CI/CD Variables** (Settings > CI/CD > Variables):
|
||||
|
||||
| Variable | Description | Protected | Masked | Raw |
|
||||
|---|---|---|---|---|
|
||||
| `NSITE_NBUNKSEC` | nbunksec credential from `nsyte ci`. Must start with `nbunksec1`. | Yes | Yes | Yes |
|
||||
|
||||
#### Initial Setup (one-time)
|
||||
|
||||
1. Install nsyte locally:
|
||||
```bash
|
||||
curl -fsSL https://nsyte.run/get/install.sh | bash
|
||||
```
|
||||
|
||||
2. Generate the CI credential:
|
||||
```bash
|
||||
nsyte ci
|
||||
```
|
||||
This will guide you through connecting a NIP-46 bunker (e.g. Amber) and output an `nbunksec1...` string. The credential is shown only once.
|
||||
|
||||
3. Add the `nbunksec1...` value as the `NSITE_NBUNKSEC` variable in GitLab CI/CD settings (Settings > CI/CD > Variables). Mark it as **Protected** and **Masked**.
|
||||
|
||||
#### Configured Relays and Servers
|
||||
|
||||
The deploy job publishes to these relays:
|
||||
- `wss://relay.ditto.pub`
|
||||
- `wss://relay.nsite.lol`
|
||||
- `wss://relay.dreamith.to`
|
||||
- `wss://relay.primal.net`
|
||||
|
||||
And uploads blobs to these Blossom servers:
|
||||
- `https://blossom.primal.net`
|
||||
- `https://blossom.ditto.pub`
|
||||
- `https://blossom.dreamith.to`
|
||||
|
||||
The `--use-fallback-relays` and `--use-fallback-servers` flags also include nsyte's built-in defaults for broader coverage. The `--fallback "/index.html"` flag enables SPA client-side routing.
|
||||
|
||||
#### Credential Rotation
|
||||
|
||||
To rotate the nsite credential:
|
||||
1. Revoke the old bunker connection in your signer app
|
||||
2. Run `nsyte ci` again to generate a new `nbunksec1...` string
|
||||
3. Update the `NSITE_NBUNKSEC` variable in GitLab CI/CD settings
|
||||
|
||||
### Google Play Publishing
|
||||
|
||||
The project automatically publishes Android AABs (App Bundles) to [Google Play](https://play.google.com/store/apps/details?id=pub.ditto.app) using [fastlane supply](https://docs.fastlane.tools/actions/supply/). The `publish-google-play` CI job runs after a successful AAB build and uploads directly to the production track.
|
||||
|
||||
**GitLab CI/CD Variables** (Settings > CI/CD > Variables):
|
||||
|
||||
| Variable | Description | Protected | Masked | Raw |
|
||||
|---|---|---|---|---|
|
||||
| `GOOGLE_PLAY_SERVICE_ACCOUNT_JSON` | Full JSON contents of the Google Play API service account key file | Yes | Yes | No |
|
||||
|
||||
#### Initial Setup (one-time)
|
||||
|
||||
1. Create or reuse a project in the [Google Cloud Console](https://console.cloud.google.com/projectcreate)
|
||||
2. Enable the [Google Play Developer API](https://console.developers.google.com/apis/api/androidpublisher.googleapis.com/) for that project
|
||||
3. In Google Cloud Console, go to [Service Accounts](https://console.cloud.google.com/iam-admin/serviceaccounts), create a service account, and download a JSON key file for it
|
||||
4. In Google Play Console, go to [Users & Permissions](https://play.google.com/console/users-and-permissions), click **Invite new users**, enter the service account email, and grant it permission to manage releases for `pub.ditto.app`
|
||||
5. Add the full JSON contents of the key file as the `GOOGLE_PLAY_SERVICE_ACCOUNT_JSON` variable in GitLab CI/CD settings (Settings > CI/CD > Variables). Mark it as **Protected** and **Masked**.
|
||||
|
||||
#### Key Points
|
||||
|
||||
- The job uploads the signed AAB (not APK) since Google Play requires App Bundles
|
||||
- Uploads go directly to the **production** track -- Google's review process still applies before the update reaches users
|
||||
- Metadata, screenshots, and changelogs are managed in the Play Console, not via CI (the job uses `--skip_upload_metadata` etc.)
|
||||
- The same signing keystore used for Zapstore is used here (`ANDROID_KEYSTORE_BASE64`, `KEYSTORE_PASSWORD`, `KEY_PASSWORD`)
|
||||
@@ -1,5 +1,367 @@
|
||||
# Changelog
|
||||
|
||||
## [2.6.6] - 2026-04-12
|
||||
|
||||
### Fixed
|
||||
- Emoji and mention autocomplete dropdowns no longer get clipped by the compose box
|
||||
- Emoji shortcodes now render as color emoji instead of plain text glyphs
|
||||
- Dialogs and input fields on Android are no longer obscured by the virtual keyboard
|
||||
- Signing requests on Android are more reliable and no longer silently fail after switching apps
|
||||
|
||||
## [2.6.5] - 2026-04-11
|
||||
|
||||
### Changed
|
||||
- Apps and games load significantly faster on Android with smarter prefetching and server affinity
|
||||
- Native loading spinners replace HTML-based ones on iOS and Android for a smoother experience
|
||||
|
||||
### Fixed
|
||||
- External API requests on Android no longer fail due to hostname restrictions
|
||||
- iOS App Store compliance issues resolved
|
||||
|
||||
## [2.6.4] - 2026-04-11
|
||||
|
||||
### Added
|
||||
- iCloud Keychain integration on iOS -- your login credentials are now saved and restored automatically across devices
|
||||
|
||||
### Changed
|
||||
- Empty feeds show a friendlier state with a discover button to help you find people to follow
|
||||
- Signup flow simplified -- cleaner profile step with a single Continue button
|
||||
|
||||
### Fixed
|
||||
- Avatar fallback now shows the user's initial instead of a question mark
|
||||
- Android 16+ devices no longer have content hidden behind system bars
|
||||
- Signup dialog background clears properly when switching between light and dark themes
|
||||
- Sticky compose button stays anchored to the bottom even on empty feeds
|
||||
|
||||
## [2.6.3] - 2026-04-10
|
||||
|
||||
### Added
|
||||
- Lightning invoices embedded in posts now render as tappable payment cards
|
||||
- Blobbi companions in the feed reflect their current condition and projected health
|
||||
|
||||
### Changed
|
||||
- Profile headers are cleaner -- lightning addresses and verification badges moved out of the way, and website URLs no longer show a trailing slash
|
||||
- Login credentials are saved to your browser's built-in password manager for easier sign-in across sessions
|
||||
- "Request to Vanish" renamed to "Delete Account" for clarity
|
||||
|
||||
### Fixed
|
||||
- Badge image uploads now show a recommended 1:1 aspect ratio hint so your badges don't get cropped unexpectedly
|
||||
- Security hardening for URLs and styles sourced from the network
|
||||
|
||||
## [2.6.2] - 2026-04-08
|
||||
|
||||
### Added
|
||||
- Share follow packs and follow sets via link -- recipients see an immersive preview with member avatars, a "Follow All" button, and a combined feed from everyone in the pack
|
||||
- Curated home feed with a mix of photos, short videos, livestreams, and music -- content types are spaced out so your timeline stays fresh and varied
|
||||
- "Write a letter" option on profile menus for a more personal way to reach out
|
||||
- Push vs persistent notification delivery option on Android
|
||||
|
||||
### Changed
|
||||
- Webxdc games and apps always open fullscreen for a more immersive experience
|
||||
- Login credentials are now stored in the device's secure keychain on iOS and Android instead of plain local storage
|
||||
- Profile fields now appear inline instead of in a separate right sidebar
|
||||
- Trending hashtags removed from the logged-out homepage for a cleaner first impression
|
||||
|
||||
### Fixed
|
||||
- Webxdc and nsites work natively on iOS and Android without relying on browser sandboxing tricks
|
||||
- File downloads now save directly to Documents on iOS and Android instead of silently failing
|
||||
- Mobile search no longer scrolls the page behind it and properly hides the bottom navigation bar
|
||||
- iOS swipe-back navigation works correctly throughout the app
|
||||
- Blobbi companions appear reliably on profiles instead of sometimes going missing
|
||||
- IndexedDB no longer crashes on devices with Lockdown Mode enabled
|
||||
|
||||
## [2.6.1] - 2026-04-06
|
||||
|
||||
### Added
|
||||
- Manage your interest tabs (hashtags and locations) from the settings page
|
||||
- Edit button on custom profile tabs so you can tweak them without recreating from scratch
|
||||
- Follow packs and follow sets now show author info and action headers in the feed
|
||||
- Posts now show whether they were created or updated, so you can tell when something's been edited
|
||||
|
||||
### Changed
|
||||
- Webxdc games and apps run in a more secure sandbox with stricter content policies and private subdomains
|
||||
- Nsite previews now use the same secure sandbox as webxdc apps
|
||||
- Blobbi items work as instant abilities instead of consumable inventory -- no more fiddly quantity pickers
|
||||
|
||||
### Fixed
|
||||
- Desktop tab bar no longer overflows when you have lots of tabs -- scroll arrows appear automatically
|
||||
- Mobile compose box no longer randomly collapses or becomes unclickable
|
||||
- Profile avatar and banner lightbox no longer hides behind the right sidebar
|
||||
- Infinite scroll on custom profile tab feeds no longer reloads the same content
|
||||
- Reaction emoji are now visible on each row in the interactions modal
|
||||
- Missing bottom border on collapsed thread expand button restored
|
||||
|
||||
## [2.6.0] - 2026-04-05
|
||||
|
||||
### Added
|
||||
- Follow links and QR codes -- share a link or scannable code that lets anyone follow you with one tap, complete with your themed profile preview and recent posts
|
||||
- Immersive Blobbi hatching ceremony -- crack your egg through cinematic stages with shaking animations, a burst of light, sparkles, typewriter dialog, and a naming moment
|
||||
|
||||
### Changed
|
||||
- Footer links redesigned as compact icon chips for a cleaner look
|
||||
- Custom emoji now render crisp at small sizes with pixel-perfect scaling
|
||||
|
||||
### Fixed
|
||||
- Custom themes now apply correctly when logging in on a new device
|
||||
- Settings and preferences sync reliably across devices
|
||||
- Mobile sidebar links no longer clip into the safe area
|
||||
- Blobbi page background overlay now appears properly on custom themes
|
||||
- Blobbi companion state no longer resets unexpectedly from stale cache data
|
||||
- Letter compose picker no longer gets hidden behind the top navigation arc
|
||||
|
||||
## [2.5.2] - 2026-04-04
|
||||
|
||||
### Added
|
||||
- See who voted on each poll option -- tap the vote count to open a voters list with avatar stacks and per-option filter tabs
|
||||
- Poll votes now appear as activity cards in feeds and on detail pages
|
||||
|
||||
### Fixed
|
||||
- Threads and replies load more reliably by following relay and author hints when fetching parent events
|
||||
|
||||
## [2.5.1] - 2026-04-03
|
||||
|
||||
### Fixed
|
||||
- Lightbox now reliably appears above all content, not just when opened from photo galleries
|
||||
|
||||
## [2.5.0] - 2026-04-03
|
||||
|
||||
### Added
|
||||
- Run nsites and web apps directly inside Ditto -- hit the "Run" button on any nsite or app card to preview it in an overlay without leaving your feed
|
||||
- File uploads in the poll composer -- attach images and media to your polls
|
||||
- Blobbi posts now appear in the homepage feed
|
||||
|
||||
### Changed
|
||||
- Profile media sidebar fills remaining slots with photos from text posts when there aren't enough dedicated media posts
|
||||
- App cards now show banner images and improved layout
|
||||
|
||||
### Fixed
|
||||
- Lightbox no longer appears behind the right sidebar
|
||||
- Compose box corners are properly rounded
|
||||
- Clicking buttons or links inside a post card no longer accidentally navigates to the post detail page
|
||||
|
||||
## [2.4.1] - 2026-04-02
|
||||
|
||||
### Added
|
||||
- Rich cards for Zapstore app releases and assets -- see download links, version info, platform badges, and hashes right in your feed
|
||||
|
||||
### Fixed
|
||||
- First-hatch tour now shows for accounts that were onboarded before the tour existed, so no one misses the hatching moment
|
||||
|
||||
## [2.4.0] - 2026-04-02
|
||||
|
||||
### Added
|
||||
- First-hatch tour: a guided experience for hatching your very first Blobbi egg, with progressive crack animations, an inline card flow, and a reveal moment
|
||||
- Customizable bottom bar: rearrange or hide any item in the navigation bar to make Ditto feel like yours
|
||||
- Mission surface card in the feed that surfaces your active quests at a glance
|
||||
|
||||
### Changed
|
||||
- Missions redesigned as a quest board with collapsible cards and a lighter aesthetic
|
||||
- "Edit Profile" mission now completes when you update any profile field, not just wall-specific edits
|
||||
- Media tab on profiles now shows only photos, videos, and other media -- not plain text posts
|
||||
- Blobbi onboarding state now syncs to your profile so it follows you across devices
|
||||
|
||||
### Fixed
|
||||
- Notification dot no longer reappears after you've already marked notifications as read
|
||||
- Dialogs no longer fly up when the mobile keyboard opens
|
||||
|
||||
## [2.3.1] - 2026-04-02
|
||||
|
||||
### Changed
|
||||
- Drafts now save instantly to your device and sync to relays in the background, with a cloud sync indicator so you always know the status
|
||||
|
||||
### Fixed
|
||||
- Dialogs stay visible above the keyboard on mobile instead of getting hidden behind it
|
||||
- Editing an existing article no longer incorrectly warns about a duplicate slug
|
||||
- Switching between rich text and markdown source mode no longer clears your content
|
||||
- Fix crash when editing in markdown source mode
|
||||
|
||||
## [2.3.0] - 2026-04-02
|
||||
|
||||
### Added
|
||||
- In-app article editor with a rich text toolbar, image uploads, auto-saving drafts, and a "My Articles" tab to manage drafts and published articles
|
||||
|
||||
### Fixed
|
||||
- Custom emoji no longer stretch to fill their container
|
||||
- Mobile drawer now closes when tapping footer links like Changelog or Privacy
|
||||
- Logged-out users now default to the global tab on content feeds instead of seeing an empty follows tab
|
||||
|
||||
## [2.2.11] - 2026-04-02
|
||||
|
||||
### Fixed
|
||||
- Fix crash caused by the "What's new" toast firing outside the router
|
||||
|
||||
## [2.2.10] - 2026-04-02
|
||||
|
||||
### Added
|
||||
- App cards for Nostr apps now display in feeds and detail pages with hero images, icons, and quick-launch buttons
|
||||
- "What's new" toast appears after an app update with a changelog preview and link to the full changelog
|
||||
|
||||
### Changed
|
||||
- Changelog page redesigned with a hero section for the latest release, collapsible older entries, and category icons inline with each item
|
||||
|
||||
### Fixed
|
||||
- Compose box now fully resets to its collapsed state after posting, including poll options and media trays
|
||||
|
||||
## [2.2.9] - 2026-04-01
|
||||
|
||||
### Added
|
||||
- Emoji pack creator and editor with drag-and-drop image upload, auto-generated identifiers, and description field
|
||||
- Blobbi companions now appear in feeds and post detail pages
|
||||
|
||||
### Changed
|
||||
- Blobbi shop redesigned with a tile layout and instant buy -- no more categories or accessory tabs
|
||||
- Emoji packs without any valid emojis are now hidden from feeds
|
||||
- Custom emoji shortcode collisions across packs are automatically resolved with pack-prefixed names
|
||||
|
||||
## [2.2.8] - 2026-04-01
|
||||
|
||||
### Added
|
||||
- Full threaded reply trees on post detail pages with collapsible deep branches and "Show X more replies" for sibling threads
|
||||
- Broadcast button in the Event JSON dialog to re-publish any event to your relays
|
||||
|
||||
### Changed
|
||||
- My Badges tab overhauled with drag-and-drop reordering, a scrollable list, and a showcase-style carousel for pending badges
|
||||
- Encrypted letter envelopes now show the mailing side first (sender and recipient), then flip to reveal the wax seal
|
||||
- Blobbi companions are more expressive -- richer status reactions, sleeping visuals, and body effects like dirt and hunger cues
|
||||
|
||||
### Fixed
|
||||
- Notification dot not clearing after marking notifications as read
|
||||
- Followers/following modal staying open after navigating to a profile
|
||||
|
||||
## [2.2.7] - 2026-03-31
|
||||
|
||||
### Fixed
|
||||
- Nushu script in encrypted letters now renders correctly on Android and iOS
|
||||
|
||||
## [2.2.6] - 2026-03-31
|
||||
|
||||
### Added
|
||||
- Encrypted letters now appear as interactive 3D envelopes with Nushu script -- flip and open them to reveal the secret writing inside
|
||||
- Zap receipts and profile metadata events now render in feeds and detail pages
|
||||
- Remote signer callback page for login flows with Amber, Primal, and other signing apps
|
||||
|
||||
### Changed
|
||||
- Post action buttons extracted into a reusable PostActionBar component
|
||||
- Badge detail page streamlined with unified tab bar
|
||||
|
||||
### Fixed
|
||||
- Hashtags now support accented and Unicode characters
|
||||
- Letter compose opens correctly from notifications and the letters page
|
||||
- Letter font picker loads fonts so each option previews in the correct typeface
|
||||
- Zap comment positioned inside the right column instead of floating with offset
|
||||
- Safe-area padding on pinned SubHeaderBar only applies when scrolled to top
|
||||
|
||||
## [2.2.5] - 2026-03-30
|
||||
|
||||
### Fixed
|
||||
- Crash when dragging profile tabs to reorder them
|
||||
|
||||
## [2.2.4] - 2026-03-30
|
||||
|
||||
### Changed
|
||||
- Profiles now have an emoji reaction button instead of a zap button -- express yourself with any emoji or custom emoji right on someone's profile
|
||||
- Zap moved to the profile overflow menu so it's still one tap away
|
||||
|
||||
### Fixed
|
||||
- Crash on the notifications page caused by malformed badge award tags
|
||||
- Deleting a badge now also deletes all awards you issued for it
|
||||
- Custom emoji reactions missing their image tag no longer render as broken shortcodes
|
||||
- Deletion requests for addressable events now include both `e` and `a` tags for broader relay compatibility
|
||||
- Profile reactions no longer collapse into a single grouped notification
|
||||
- Oversized reaction emoji in comment context headers
|
||||
|
||||
## [2.2.3] - 2026-03-30
|
||||
|
||||
### Added
|
||||
- Letters now have an overflow menu, reply button, and a grid layout for browsing
|
||||
- Independent feed toggles for comments and generic reposts in content settings
|
||||
- Sidebar items are now visible to logged-out users so newcomers can explore everything
|
||||
|
||||
### Changed
|
||||
- Compose textarea expands smoothly as you type instead of snapping to a new height
|
||||
- Blobbi stickers auto-shrink near card edges and clip cleanly at rounded boundaries
|
||||
|
||||
### Fixed
|
||||
- Feed gaps when replies are disabled no longer cause missing posts
|
||||
- Avatar shape no longer flashes on load
|
||||
- Top bar arc no longer flickers during navigation transitions
|
||||
- Letter drawing-only sends, sticker drag bounds, and theme event preservation
|
||||
- Notification rendering for badges and letters
|
||||
- Duplicate React keys in content settings
|
||||
- Layout rendering warning when switching views
|
||||
|
||||
## [2.2.2] - 2026-03-29
|
||||
|
||||
### Added
|
||||
- Dedicated photo upload flow for sharing photos
|
||||
- Pull-to-refresh on all feed pages
|
||||
- 3D tilt effect on badge images -- hover over badges to see them pop
|
||||
- Multi-select badge awarding with indicators for already-sent badges
|
||||
- Badge list recovery dialog for restoring profile badge lists
|
||||
- Compact badge row preview in embedded profile badges events
|
||||
- Custom emoji usage tracking so your most-used custom emojis appear in the quick-react bar
|
||||
- Release notes now included in Zapstore publishing
|
||||
- Changelog link in the app footer
|
||||
|
||||
### Changed
|
||||
- "Vines" renamed to "Divines" everywhere in the app
|
||||
- Custom emojis appear first in the emoji picker, right after recent
|
||||
- Threaded comment view now shows the parent event as a NoteCard with kind action headers
|
||||
|
||||
### Fixed
|
||||
- Delete post dialog no longer freezes the feed on desktop
|
||||
- Amber login on Android now properly retries when returning from the background
|
||||
- Key downloads on Android save to the correct location
|
||||
- Custom emoji SVGs render correctly in the emoji-mart picker
|
||||
- Double-tap reactions now properly show the emoji on the post
|
||||
- Emoji shortcode autocomplete text and highlight colors
|
||||
- Profile skeleton no longer flickers for brand-new users with no metadata
|
||||
- Event links now route correctly for all event types
|
||||
- Badge notifications are now clickable
|
||||
- Custom profile tab form no longer retains fields from a previously edited tab
|
||||
- Double line under profile tabs in edit mode
|
||||
- Inconsistent use of "geocache" vs "treasures" terminology
|
||||
- Search page "N new posts" pill no longer shows unfiltered count
|
||||
- Stale-cache overwrites in replaceable event mutations
|
||||
- Click-through on delete confirmation and note menu items
|
||||
|
||||
## [2.2.1] - 2026-03-28
|
||||
|
||||
### Fixed
|
||||
- New posts no longer cause scroll jumps -- they buffer while you're reading and appear with a tap
|
||||
- Mobile header no longer shows double-layered backgrounds on notched devices
|
||||
- Pinned tabs stay properly positioned when scrolling on mobile
|
||||
- Signer approval toasts no longer fire in rapid succession on unstable connections
|
||||
- Toasts are easier to swipe away on mobile
|
||||
- Content warnings now blur thumbnails in the media grid
|
||||
|
||||
## [2.2.0] - 2026-03-28
|
||||
|
||||
### Added
|
||||
- Blobbi virtual pets -- adopt an egg, hatch it, evolve it into one of 16 adult forms, and care for it with feeding, cleaning, medicine, music, and singing
|
||||
- Blobbi companion that follows you around the app, tracks your cursor, blinks, expresses emotions, and reacts to what you're doing
|
||||
- Blobbi shop and inventory system with items that affect your pet's stats
|
||||
- Daily missions with reroll, care streaks, and stage-based rewards
|
||||
- Immersive full-screen divines experience on both mobile and desktop with floating controls
|
||||
- Relay information panel on the network settings page
|
||||
- Link preview cards now display inside quoted posts instead of raw URLs
|
||||
- Nsec paste guard warns you before accidentally pasting private keys outside the login field
|
||||
- Remote signer UX improvements for Amber users on Android
|
||||
- Badge awards now trigger push notifications
|
||||
- Badges display in profile bio section with a "Give badge" option in the profile menu
|
||||
|
||||
### Changed
|
||||
- Notification "Mentions" tab now shows only pure mentions, filtering out replies
|
||||
- Notification preferences ("only from people I follow") now properly apply to push notifications, native Android notifications, and the unread dot
|
||||
- Upgraded from React 18 to React 19
|
||||
- Reduced initial bundle size by ~50% with improved code splitting and lazy loading
|
||||
|
||||
### Fixed
|
||||
- Zapping Primal users no longer produces an error
|
||||
- Hashtag feeds now match case-insensitively for parity with search results
|
||||
- Mobile top bar arc no longer lingers on pages without tabs
|
||||
- Give Badge dialog and profile menu action handlers
|
||||
|
||||
## [2.1.1] - 2026-03-27
|
||||
|
||||
### Added
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
# Contributing to Ditto
|
||||
|
||||
We welcome contributions, but we have high standards. Ditto is a carefully designed product with a specific vision, and every merge request must meet that bar. This guide exists to help you succeed.
|
||||
|
||||
**Required reading before you start:**
|
||||
|
||||
- [Ditto Philosophy](https://about.ditto.pub/philosophy) -- the product vision. Your change must align with it.
|
||||
- [Contributing Guide](https://about.ditto.pub/contributing) -- the upstream contribution process.
|
||||
- `AGENTS.md` in this repo -- the codebase conventions. Your AI tool should load this file.
|
||||
|
||||
## Understanding Ditto
|
||||
|
||||
Ditto is a carnival, not a platform. Before contributing, you need to understand what that means.
|
||||
|
||||
### The product decision filter
|
||||
|
||||
Every change to Ditto should pass this test:
|
||||
|
||||
> *Does this make Ditto more magnetic, more threatening to the status quo, and more peaceful to inhabit?*
|
||||
|
||||
- **Magnetic** -- Ditto attracts through experience, not ideology. People don't need to understand Nostr to love it. They need to feel something they haven't felt online since the early web. Features should be odd, intriguing, and captivating -- not generic social media clones.
|
||||
- **Threatening to the status quo** -- Ditto threatens mainstream platforms when someone opens it and thinks: *"Why can't my platform do this?"* Theming, games, treasure hunts, interoperable micro-apps -- these are things walled gardens can't replicate.
|
||||
- **Peaceful to inhabit** -- Ditto displaces argument with creation, conformity with expression, and consumption with participation. No ads, no engagement-optimized algorithms, no outrage incentives.
|
||||
|
||||
If a change does all three, it belongs. If it only does one, think harder. If it does none, it doesn't belong here.
|
||||
|
||||
### What Ditto is NOT
|
||||
|
||||
- A Twitter/X clone with decentralization bolted on
|
||||
- A place to replicate features that mainstream platforms already do well
|
||||
- A showcase for generic UI components or boilerplate social features
|
||||
|
||||
### What Ditto IS
|
||||
|
||||
- A convergence point for interoperable Nostr experiences (games, treasure hunts, magic decks, themes, color moments, live streams, and things nobody has imagined yet)
|
||||
- A place where profiles feel like worlds, not business cards
|
||||
- The most fun you've had on the internet in years
|
||||
|
||||
Read the [full philosophy](https://about.ditto.pub/philosophy) for the complete vision.
|
||||
|
||||
## What we accept
|
||||
|
||||
### Bug fixes
|
||||
|
||||
One bug, one merge request. Fix exactly one thing. Don't bundle unrelated changes, don't sneak in refactors, don't "clean up while you're in there." Small, focused MRs get reviewed fast. Large ones sit.
|
||||
|
||||
### New features and significant changes
|
||||
|
||||
Every feature MR must link to an existing open issue and clearly align with the [Ditto Philosophy](https://about.ditto.pub/philosophy). The philosophy alignment section in the MR template is where you make the case for why your change belongs in Ditto. If you can't articulate that clearly, the change probably doesn't belong.
|
||||
|
||||
If you have an idea for a feature that doesn't have an issue yet:
|
||||
|
||||
1. Build it as a standalone Nostr app first (see [Contributing Guide](https://about.ditto.pub/contributing)).
|
||||
2. Prove it works and get user feedback.
|
||||
3. Open an issue to discuss integration.
|
||||
|
||||
**Feature MRs that don't link to an issue or don't align with the Ditto Philosophy will be closed.** Our open issues are our internal roadmap -- some require deep product context. If your implementation doesn't match the product vision, it will be closed regardless of code quality.
|
||||
|
||||
## Required tools
|
||||
|
||||
- **Claude Opus 4.6** (or the latest frontier model) -- not Sonnet, not GPT-4o, not local models. Quality depends on model quality.
|
||||
- **An AI coding agent with plan/research mode** -- [OpenCode](https://opencode.ai), [Shakespeare](https://shakespeare.diy), Cursor, or similar.
|
||||
- **Node.js 22+** and npm 10.9.4+.
|
||||
|
||||
## The contribution workflow
|
||||
|
||||
Follow these steps in order. Skipping steps is the most common reason MRs are rejected.
|
||||
|
||||
### 1. Ask: does anyone need this?
|
||||
|
||||
Before writing a single line of code, answer this honestly. For bug fixes this is straightforward -- someone hit the bug. For features, it requires more thought. Is there evidence of real user demand? Is the underlying technology mature enough? A beautifully written feature for a nonexistent user base is the wrong thing to build. If you can't point to a concrete user need, reconsider.
|
||||
|
||||
### 2. Understand the issue
|
||||
|
||||
Read the issue thoroughly. If anything is unclear, ask in the issue comments before writing code. Understand not just *what* to change, but *why* -- what problem does this solve for users?
|
||||
|
||||
### 3. Read the codebase conventions
|
||||
|
||||
Read `AGENTS.md` in the repo root. This is the single source of truth for how code should be written in this project. Your AI tool should load this file automatically. If it doesn't, paste it in or configure your tool to read it.
|
||||
|
||||
### 4. Read the philosophy
|
||||
|
||||
Read the [Ditto Philosophy](https://about.ditto.pub/philosophy). Ditto is a carnival, not a platform. Your change should feel like it belongs in Ditto -- not like it was transplanted from a generic social media template. Apply the product decision filter above.
|
||||
|
||||
### 5. Plan before you code
|
||||
|
||||
Start your AI tool in **plan mode** (or research/think mode). Spend the first few prompts:
|
||||
|
||||
- Exploring the existing codebase to understand how similar features are implemented
|
||||
- Reading the files you'll need to modify
|
||||
- Proposing an approach
|
||||
|
||||
Do not write code until you have a plan. The most expensive mistake is implementing the wrong approach.
|
||||
|
||||
### 6. Implement
|
||||
|
||||
Switch to code mode and implement your plan. Use Opus 4.6 or equivalent.
|
||||
|
||||
### 7. Run the test suite
|
||||
|
||||
```sh
|
||||
npm run test
|
||||
```
|
||||
|
||||
This runs type-checking, linting, unit tests, and a production build. All must pass. Do not submit an MR with a failing test suite.
|
||||
|
||||
### 8. Self-review
|
||||
|
||||
Run this prompt against your diff (copy the full `git diff` output and paste it to your AI tool along with this prompt):
|
||||
|
||||
```
|
||||
Review this diff as if you are a senior maintainer of this codebase who has to
|
||||
maintain it long-term. For each finding, state the file, line, and issue.
|
||||
|
||||
- [ ] Does the diff contain changes that weren't requested? Flag anything out of scope.
|
||||
- [ ] Is there dead code, commented-out blocks, or debug artifacts left in?
|
||||
- [ ] Are there placeholder comments like "// In a real app..." or "// TODO: implement"?
|
||||
- [ ] For every value displayed to a user, can you trace it from source to render without a gap?
|
||||
- [ ] Are error, loading, and empty states all handled -- and in the right order?
|
||||
- [ ] Does a mutation reflect in the UI without requiring a manual refresh?
|
||||
- [ ] Is there a new read/write path that assumes fresh data but could get a stale cache?
|
||||
- [ ] For replaceable/addressable Nostr events: is fetchFreshEvent used before mutation?
|
||||
- [ ] Does anything new block the critical render path or fire N+1 network requests?
|
||||
- [ ] Are Nostr queries efficient (combined kinds, relay-level filtering vs client-side)?
|
||||
- [ ] Are user inputs used in queries or rendered as content without sanitization?
|
||||
- [ ] Were existing patterns/conventions in AGENTS.md ignored in favor of something novel?
|
||||
- [ ] Are secrets, keys, or env-specific values hardcoded?
|
||||
- [ ] Does the code use the `any` type anywhere?
|
||||
- [ ] Is the code Capacitor-compatible (no `<a download>`, no `window.open()`)?
|
||||
- [ ] Are new Nostr event kinds documented in NIP.md with links to relevant specs?
|
||||
- [ ] Are there any new images >100KB or other large binary assets that should be hosted externally?
|
||||
- [ ] Is there any use of dangerouslySetInnerHTML, eval, innerHTML, or SVG string interpolation?
|
||||
- [ ] Is any data from a Nostr event (tags, content, pubkey, URLs) used in a security-sensitive context (href, src, query filter, trust decision) without validation?
|
||||
|
||||
Skip anything a linter or type checker would catch. Focus on logic, data flow, and intent.
|
||||
|
||||
Then answer: "If you were the people who have to maintain this codebase and deal
|
||||
with all long-term issues, what would be your biggest concerns about this
|
||||
implementation?"
|
||||
```
|
||||
|
||||
Address every finding before submitting.
|
||||
|
||||
### 9. Deploy a live preview
|
||||
|
||||
Deploy your branch so reviewers can test it without pulling your code:
|
||||
|
||||
```sh
|
||||
npm run build
|
||||
npx surge dist your-branch-name.surge.sh
|
||||
```
|
||||
|
||||
Or use Netlify, Vercel, or any static hosting. Include the live preview URL in your MR description.
|
||||
|
||||
### 10. Take screenshots
|
||||
|
||||
Capture before and after screenshots of any UI changes. Include them directly in the MR description. If your change has no visual component, state that explicitly.
|
||||
|
||||
### 11. Submit
|
||||
|
||||
Fill out every field in the MR template. Incomplete MRs will not be reviewed.
|
||||
|
||||
## What gets your MR closed without review
|
||||
|
||||
- No linked issue
|
||||
- Feature MRs with no clear alignment with the [Ditto Philosophy](https://about.ditto.pub/philosophy)
|
||||
- Features that fail the product decision filter (not magnetic, not threatening to the status quo, not peaceful)
|
||||
- Incomplete MR template (missing checklist, screenshots, or preview URL)
|
||||
- Changes that go beyond what was asked for (scope creep)
|
||||
- Placeholder code, dead code, or debug artifacts
|
||||
- Evidence of low-quality AI generation ("In a real application..." comments, hallucinated APIs, generic template code)
|
||||
- Failing test suite
|
||||
- No evidence of planning (code-first, think-later approach produces recognizable patterns)
|
||||
- Undocumented Nostr event kinds (new kinds must be in NIP.md)
|
||||
- Large binary assets committed to git (images >100KB, fonts, videos)
|
||||
- Security issues (dangerouslySetInnerHTML, eval, innerHTML, unsanitized user input)
|
||||
|
||||
## MR review process
|
||||
|
||||
1. The CI pipeline validates your MR description automatically. If it fails, read the error message and fix your MR description.
|
||||
2. Maintainers will review your MR when all CI checks pass and the template is complete.
|
||||
3. If changes are requested, address them promptly. Stale MRs will be closed.
|
||||
|
||||
We appreciate your interest in contributing. These standards exist because reviewing a low-quality MR takes 3x longer than doing the work ourselves. Help us help you by following the process.
|
||||
@@ -2,12 +2,31 @@
|
||||
|
||||
## Event Kinds Overview
|
||||
|
||||
### Ditto Kinds
|
||||
|
||||
| Kind | Name | Description |
|
||||
|-------|----------------------|-------------------------------------------------------|
|
||||
| 36767 | Theme Definition | Shareable, named custom UI theme |
|
||||
| 16767 | Active Profile Theme | The user's currently active theme (one per user) |
|
||||
| 16769 | Profile Tabs | The user's custom profile page tabs (one per user) |
|
||||
| 8211 | Encrypted Letter | Encrypted personal letter with visual stationery |
|
||||
|
||||
### Community Kinds
|
||||
|
||||
These event kinds were created by community contributors and are supported by Ditto. Full specifications are maintained by their respective authors.
|
||||
|
||||
| Kind | Name | Description | Spec |
|
||||
|-------|------------------------|------------------------------------------------------------------|-------------------------------------------------------------------------------------------|
|
||||
| 3367 | Color Moment | Color palette post expressing a mood | [NIP](https://gitlab.com/chad.curtis/espy/-/blob/main/NIP.md) |
|
||||
| 4223 | Weather Reading | Sensor readings from a weather station | [Draft NIP](https://github.com/nostr-protocol/nips/pull/2163) |
|
||||
| 7516 | Found Log | Log entry recording a user finding a geocache | [NIP-GC](https://gitlab.com/chad.curtis/treasures/-/blob/main/NIP-GC.md) |
|
||||
| 8211 | Encrypted Letter | Encrypted personal letter with visual stationery | [NIP](https://gitlab.com/chad.curtis/lief/-/blob/main/NIP.md) |
|
||||
| 11125 | Blobbonaut Profile | Owner profile with coins, achievements, and inventory | [NIP-BB](https://github.com/Danidfra/nostr-pet/blob/production/NIP.md) |
|
||||
| 14919 | Blobbi Interaction | Individual pet interaction (feed, play, clean, etc.) | [NIP-BB](https://github.com/Danidfra/nostr-pet/blob/production/NIP.md) |
|
||||
| 14920 | Blobbi Breeding | Breeding event between two adult Blobbis | [NIP-BB](https://github.com/Danidfra/nostr-pet/blob/production/NIP.md) |
|
||||
| 14921 | Blobbi Record | Immutable lifecycle record (birth, evolution, adoption) | [NIP-BB](https://github.com/Danidfra/nostr-pet/blob/production/NIP.md) |
|
||||
| 16158 | Weather Station | Weather station metadata (location, sensors, connectivity) | [Draft NIP](https://github.com/nostr-protocol/nips/pull/2163) |
|
||||
| 31124 | Blobbi Pet State | Current state of a virtual Blobbi pet (addressable) | [NIP-BB](https://github.com/Danidfra/nostr-pet/blob/production/NIP.md) |
|
||||
| 37516 | Geocache | Geocache listing for real-world treasure hunting | [NIP-GC](https://gitlab.com/chad.curtis/treasures/-/blob/main/NIP-GC.md) |
|
||||
|
||||
---
|
||||
|
||||
@@ -294,3 +313,51 @@ The `shape` field is added to the JSON content of a kind 0 event alongside stand
|
||||
- The `shape` field is purely cosmetic and has no protocol-level significance.
|
||||
- Clients MAY choose not to support this extension, in which case avatars render as circles as usual.
|
||||
|
||||
---
|
||||
|
||||
## Community NIP Specifications
|
||||
|
||||
The following specifications are maintained by their respective authors. Ditto implements these kinds but does not own the specs. See each link for the full event structure, tags, and client behavior.
|
||||
|
||||
### Color Moments (Kind 3367)
|
||||
|
||||
**Author:** Chad Curtis
|
||||
**Spec:** https://gitlab.com/chad.curtis/espy/-/blob/main/NIP.md
|
||||
**App:** https://espy.you
|
||||
|
||||
Color palette posts capturing 3-6 colors from a beautiful moment, optionally accompanied by an emoji and layout preference. Supports horizontal, vertical, grid, star, checkerboard, and diagonal stripe layouts. A form of pre-verbal visual communication through color and emotion.
|
||||
|
||||
### Geocaching (Kinds 37516, 7516)
|
||||
|
||||
**Author:** Chad Curtis
|
||||
**Spec:** https://gitlab.com/chad.curtis/treasures/-/blob/main/NIP-GC.md
|
||||
**App:** https://treasures.to
|
||||
|
||||
NIP-GC defines geocaching on Nostr. Kind 37516 (addressable) is a geocache listing with location (geohash), difficulty/terrain scores, size, and type. Kind 7516 is a found log recording a successful visit. The spec also covers comment logs (kind 1111 via NIP-22), verified finds with cryptographic proof (kind 7517), and cache retirement.
|
||||
|
||||
### Personal Letters (Kind 8211)
|
||||
|
||||
**Author:** Chad Curtis
|
||||
**Spec:** https://gitlab.com/chad.curtis/lief/-/blob/main/NIP.md
|
||||
**App:** https://lief.to
|
||||
|
||||
NIP-44 encrypted personal letters with visual stationery, hand-drawn stickers, decorative frames, and custom fonts. Letters render as 5:4 landscape postcards. The privacy model is intentionally postcard-like: sender/recipient metadata is visible, content is encrypted.
|
||||
|
||||
### Weather Station (Kinds 4223, 16158)
|
||||
|
||||
**Author:** Sam Thomson
|
||||
**Spec:** https://github.com/nostr-protocol/nips/pull/2163
|
||||
**App:** https://weather.shakespeare.wtf
|
||||
**Firmware:** https://github.com/samthomson/weather-station
|
||||
|
||||
Kind 16158 (replaceable) describes a weather station's configuration: name, geohash location, elevation, power source, connectivity, and sensor inventory. Kind 4223 (regular) carries individual sensor readings as 3-parameter tags `[sensor_type, value, model]`, enabling historical queries and cross-station comparison. Each station has its own keypair.
|
||||
|
||||
### Blobbi Virtual Pet (Kinds 31124, 14919, 14920, 14921, 11125)
|
||||
|
||||
**Author:** Danifra
|
||||
**Spec:** https://github.com/Danidfra/nostr-pet/blob/production/NIP.md
|
||||
**App:** https://nostr-pet.vercel.app
|
||||
**See also:** [Blobbi tag schema](docs/blobbi/blobbi-tag-schema.md) (Ditto-specific integration details)
|
||||
|
||||
NIP-BB defines a virtual pet lifecycle on Nostr. Kind 31124 (addressable) holds the current pet state across three stages (egg, baby, adult) with stats, appearance, and personality traits. Kind 14919 logs individual interactions, kind 14920 records breeding events, kind 14921 stores immutable lifecycle records, and kind 11125 (replaceable) holds the owner's profile with coins, achievements, and inventory.
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ Made by [Soapbox](https://soapbox.pub).
|
||||
## Features
|
||||
|
||||
- **Theming** -- 9 built-in theme presets, 19 CSS token properties for full customization, and the ability to publish and share themes as Nostr events
|
||||
- **Infinite Content Types** -- Text notes, articles, short-form videos (Vines), live streams, polls, follow packs, color moments, magic decks, geocaching, and Webxdc mini-apps
|
||||
- **Infinite Content Types** -- Text notes, articles, short-form videos (Divines), live streams, polls, follow packs, color moments, magic decks, geocaching, and Webxdc mini-apps
|
||||
- **Lightning Payments** -- Zap posts and profiles with sats via Nostr Wallet Connect (NWC) or WebLN
|
||||
- **Private Messaging** -- End-to-end encrypted DMs (NIP-04 and NIP-17)
|
||||
- **Comments** -- Comment on anything: posts, URLs, profiles, hashtags, books, and more (NIP-22)
|
||||
@@ -138,6 +138,17 @@ src/
|
||||
public/ Static assets, icons, manifest
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
We welcome contributions but have high standards. Please read the full [Contributing Guide](CONTRIBUTING.md) before submitting a merge request. The short version:
|
||||
|
||||
- **Bug fixes**: One bug, one MR. Keep it small and focused.
|
||||
- **New features**: Must link to an existing issue and align with the [Ditto Philosophy](https://about.ditto.pub/philosophy).
|
||||
- **Required**: Live preview URL, before/after screenshots, completed self-review checklist.
|
||||
- **Required tools**: Claude Opus 4.6 (or latest frontier model), an AI coding agent with plan mode.
|
||||
|
||||
Read the [Ditto Philosophy](https://about.ditto.pub/philosophy) to understand what Ditto is and isn't.
|
||||
|
||||
## License
|
||||
|
||||
[AGPL-3.0](LICENSE)
|
||||
|
||||
@@ -14,7 +14,7 @@ android {
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 1
|
||||
versionName "2.1.1"
|
||||
versionName "2.6.6"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
aaptOptions {
|
||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||
@@ -35,8 +35,9 @@ android {
|
||||
buildTypes {
|
||||
release {
|
||||
signingConfig signingConfigs.release
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
minifyEnabled true
|
||||
shrinkResources true
|
||||
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,9 +11,12 @@ apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
|
||||
dependencies {
|
||||
implementation project(':capacitor-app')
|
||||
implementation project(':capacitor-filesystem')
|
||||
implementation project(':capacitor-haptics')
|
||||
implementation project(':capacitor-keyboard')
|
||||
implementation project(':capacitor-local-notifications')
|
||||
implementation project(':capacitor-share')
|
||||
implementation project(':capacitor-status-bar')
|
||||
implementation project(':capgo-capacitor-autofill-save-password')
|
||||
implementation project(':capacitor-secure-storage-plugin')
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -5,12 +5,19 @@
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
# Keep Capacitor classes (WebView JS bridge)
|
||||
-keep class com.getcapacitor.** { *; }
|
||||
-keep class pub.ditto.app.** { *; }
|
||||
|
||||
# Keep WebView JS interfaces
|
||||
-keepclassmembers class * {
|
||||
@android.webkit.JavascriptInterface <methods>;
|
||||
}
|
||||
|
||||
# Keep OkHttp (used by Capacitor)
|
||||
-dontwarn okhttp3.**
|
||||
-dontwarn okio.**
|
||||
-keep class okhttp3.** { *; }
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
package pub.ditto.app;
|
||||
|
||||
import android.content.SharedPreferences;
|
||||
import android.app.ForegroundServiceStartNotAllowedException;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
|
||||
import com.getcapacitor.Plugin;
|
||||
@@ -14,6 +17,10 @@ import org.json.JSONArray;
|
||||
/**
|
||||
* Capacitor plugin that allows the JS layer to configure the native
|
||||
* notification polling service with the user's pubkey and relay URLs.
|
||||
*
|
||||
* Supports two notification styles:
|
||||
* - "push" (default): no foreground service, relies on push notifications
|
||||
* - "persistent": starts NotificationRelayService as a foreground service
|
||||
*/
|
||||
@CapacitorPlugin(name = "DittoNotification")
|
||||
public class DittoNotificationPlugin extends Plugin {
|
||||
@@ -24,7 +31,10 @@ public class DittoNotificationPlugin extends Plugin {
|
||||
@PluginMethod
|
||||
public void configure(PluginCall call) {
|
||||
String userPubkey = call.getString("userPubkey");
|
||||
String notificationStyle = call.getString("notificationStyle", "push");
|
||||
String relayUrlsRaw = null;
|
||||
String enabledKindsRaw = null;
|
||||
String authorsRaw = null;
|
||||
|
||||
try {
|
||||
JSONArray relayUrls = call.getArray("relayUrls");
|
||||
@@ -35,20 +45,80 @@ public class DittoNotificationPlugin extends Plugin {
|
||||
Log.w(TAG, "Failed to read relayUrls", e);
|
||||
}
|
||||
|
||||
try {
|
||||
JSONArray enabledKinds = call.getArray("enabledKinds");
|
||||
if (enabledKinds != null) {
|
||||
enabledKindsRaw = enabledKinds.toString();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "Failed to read enabledKinds", e);
|
||||
}
|
||||
|
||||
try {
|
||||
JSONArray authors = call.getArray("authors");
|
||||
if (authors != null) {
|
||||
authorsRaw = authors.toString();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "Failed to read authors", e);
|
||||
}
|
||||
|
||||
SharedPreferences prefs = getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
|
||||
|
||||
if (userPubkey != null && relayUrlsRaw != null) {
|
||||
prefs.edit()
|
||||
SharedPreferences.Editor editor = prefs.edit()
|
||||
.putString("userPubkey", userPubkey)
|
||||
.putString("relayUrls", relayUrlsRaw)
|
||||
.apply();
|
||||
Log.d(TAG, "Configured: pubkey=" + userPubkey.substring(0, 8) + "..., relays=" + relayUrlsRaw);
|
||||
.putString("notificationStyle", notificationStyle);
|
||||
if (enabledKindsRaw != null) {
|
||||
editor.putString("enabledKinds", enabledKindsRaw);
|
||||
}
|
||||
if (authorsRaw != null) {
|
||||
editor.putString("authors", authorsRaw);
|
||||
} else {
|
||||
editor.remove("authors");
|
||||
}
|
||||
editor.apply();
|
||||
Log.d(TAG, "Configured: pubkey=" + userPubkey.substring(0, 8) + "..., style=" + notificationStyle + ", relays=" + relayUrlsRaw + ", kinds=" + enabledKindsRaw + ", authors=" + (authorsRaw != null ? authorsRaw.length() + " chars" : "all"));
|
||||
} else {
|
||||
// Clear config (user logged out)
|
||||
prefs.edit().clear().apply();
|
||||
Log.d(TAG, "Config cleared (user logged out)");
|
||||
}
|
||||
|
||||
// Start or stop the foreground service based on style
|
||||
manageService(notificationStyle, userPubkey != null && relayUrlsRaw != null);
|
||||
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the foreground service when style is "persistent" and config is valid.
|
||||
* Stop it otherwise.
|
||||
*/
|
||||
private void manageService(String style, boolean hasConfig) {
|
||||
Context ctx = getContext();
|
||||
Intent serviceIntent = new Intent(ctx, NotificationRelayService.class);
|
||||
|
||||
if ("persistent".equals(style) && hasConfig) {
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
ctx.startForegroundService(serviceIntent);
|
||||
} else {
|
||||
ctx.startService(serviceIntent);
|
||||
}
|
||||
Log.d(TAG, "Started NotificationRelayService (persistent mode)");
|
||||
} catch (Exception e) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
|
||||
&& e instanceof ForegroundServiceStartNotAllowedException) {
|
||||
Log.w(TAG, "Could not start foreground service: " + e.getMessage());
|
||||
} else {
|
||||
Log.w(TAG, "Failed to start service", e);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ctx.stopService(serviceIntent);
|
||||
Log.d(TAG, "Stopped NotificationRelayService (push mode or no config)");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package pub.ditto.app;
|
||||
|
||||
import android.app.ForegroundServiceStartNotAllowedException;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
@@ -11,32 +13,36 @@ import com.getcapacitor.BridgeActivity;
|
||||
|
||||
public class MainActivity extends BridgeActivity {
|
||||
|
||||
private static final String PREFS_NAME = "ditto_notification_config";
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
// Register the native notification config plugin before super.onCreate
|
||||
// Register native plugins before super.onCreate.
|
||||
registerPlugin(DittoNotificationPlugin.class);
|
||||
registerPlugin(SandboxPlugin.class);
|
||||
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
// Start the persistent relay connection service.
|
||||
// On Android 12+ (API 31+) the system may throw
|
||||
// ForegroundServiceStartNotAllowedException if the foreground service
|
||||
// time limit for this type has already been exhausted. We catch it so
|
||||
// the app continues to run normally; the alarm inside the service will
|
||||
// retry at the next scheduled interval.
|
||||
try {
|
||||
Intent serviceIntent = new Intent(this, NotificationRelayService.class);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
startForegroundService(serviceIntent);
|
||||
} else {
|
||||
startService(serviceIntent);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
|
||||
&& e instanceof ForegroundServiceStartNotAllowedException) {
|
||||
Log.w("MainActivity", "Could not start NotificationRelayService: " + e.getMessage());
|
||||
} else {
|
||||
throw e;
|
||||
// Only start the foreground service if the user has opted into
|
||||
// "persistent" notification style. Default is "push" (no service).
|
||||
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
|
||||
String style = prefs.getString("notificationStyle", "push");
|
||||
|
||||
if ("persistent".equals(style)) {
|
||||
try {
|
||||
Intent serviceIntent = new Intent(this, NotificationRelayService.class);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
startForegroundService(serviceIntent);
|
||||
} else {
|
||||
startService(serviceIntent);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
|
||||
&& e instanceof ForegroundServiceStartNotAllowedException) {
|
||||
Log.w("MainActivity", "Could not start NotificationRelayService: " + e.getMessage());
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -243,6 +243,8 @@ public class NotificationRelayService extends Service {
|
||||
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
|
||||
String userPubkey = prefs.getString("userPubkey", null);
|
||||
String relayUrlsJson = prefs.getString("relayUrls", null);
|
||||
String enabledKindsJson = prefs.getString("enabledKinds", null);
|
||||
String authorsJson = prefs.getString("authors", null);
|
||||
|
||||
if (userPubkey == null || relayUrlsJson == null) {
|
||||
Log.d(TAG, "No config, skipping fetch");
|
||||
@@ -268,10 +270,17 @@ public class NotificationRelayService extends Service {
|
||||
return;
|
||||
}
|
||||
|
||||
fetch(relayUrls.get(relayIndex), userPubkey);
|
||||
List<Integer> enabledKinds = parseEnabledKinds(enabledKindsJson);
|
||||
if (enabledKinds.isEmpty()) {
|
||||
Log.d(TAG, "No enabled kinds, skipping fetch");
|
||||
releaseFetchWakeLock();
|
||||
return;
|
||||
}
|
||||
List<String> authors = parseAuthors(authorsJson);
|
||||
fetch(relayUrls.get(relayIndex), userPubkey, enabledKinds, authors);
|
||||
}
|
||||
|
||||
private void fetch(String relayUrl, String userPubkey) {
|
||||
private void fetch(String relayUrl, String userPubkey, List<Integer> enabledKinds, List<String> authors) {
|
||||
long since = poller.getLastSeenTimestamp();
|
||||
if (since == 0) {
|
||||
since = (System.currentTimeMillis() / 1000) - 300; // 5 min ago on first run
|
||||
@@ -284,7 +293,9 @@ public class NotificationRelayService extends Service {
|
||||
try {
|
||||
JSONObject filter = new JSONObject();
|
||||
JSONArray kinds = new JSONArray();
|
||||
kinds.put(1); kinds.put(6); kinds.put(16); kinds.put(7); kinds.put(9735); kinds.put(1111); kinds.put(8211);
|
||||
for (int kind : enabledKinds) {
|
||||
kinds.put(kind);
|
||||
}
|
||||
filter.put("kinds", kinds);
|
||||
JSONArray pTags = new JSONArray();
|
||||
pTags.put(userPubkey);
|
||||
@@ -292,6 +303,15 @@ public class NotificationRelayService extends Service {
|
||||
filter.put("since", since + 1);
|
||||
filter.put("limit", FETCH_LIMIT);
|
||||
|
||||
// When "only from people I follow" is enabled, restrict to those authors
|
||||
if (!authors.isEmpty()) {
|
||||
JSONArray authorsArr = new JSONArray();
|
||||
for (String author : authors) {
|
||||
authorsArr.put(author);
|
||||
}
|
||||
filter.put("authors", authorsArr);
|
||||
}
|
||||
|
||||
JSONArray req = new JSONArray();
|
||||
req.put("REQ");
|
||||
req.put(currentSubId);
|
||||
@@ -397,7 +417,8 @@ public class NotificationRelayService extends Service {
|
||||
}
|
||||
|
||||
Log.d(TAG, "Retrying in " + backoffMs + "ms on relay " + relayIndex);
|
||||
Runnable retry = () -> fetch(relayUrls.get(relayIndex), userPubkey);
|
||||
// Re-read config from prefs on retry so enabled kinds stay current.
|
||||
Runnable retry = this::runFetchCycle;
|
||||
handler.postDelayed(retry, backoffMs);
|
||||
backoffMs = Math.min(backoffMs * 2, MAX_BACKOFF_MS);
|
||||
|
||||
@@ -515,6 +536,46 @@ public class NotificationRelayService extends Service {
|
||||
return urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the authors filter from JSON. Returns an empty list when the value
|
||||
* is null or invalid (meaning no author restriction).
|
||||
*/
|
||||
private List<String> parseAuthors(String json) {
|
||||
List<String> authors = new ArrayList<>();
|
||||
if (json != null) {
|
||||
try {
|
||||
JSONArray arr = new JSONArray(json);
|
||||
for (int i = 0; i < arr.length(); i++) {
|
||||
authors.add(arr.getString(i));
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
Log.w(TAG, "Failed to parse authors", e);
|
||||
}
|
||||
}
|
||||
return authors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the enabled notification kinds from JSON. Returns an empty list
|
||||
* when the value is null or invalid — the caller should skip polling
|
||||
* when the list is empty (the JS layer always provides kinds via
|
||||
* DittoNotification.configure in the same write as pubkey/relays).
|
||||
*/
|
||||
private List<Integer> parseEnabledKinds(String json) {
|
||||
List<Integer> kinds = new ArrayList<>();
|
||||
if (json != null) {
|
||||
try {
|
||||
JSONArray arr = new JSONArray(json);
|
||||
for (int i = 0; i < arr.length(); i++) {
|
||||
kinds.add(arr.getInt(i));
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
Log.w(TAG, "Failed to parse enabled kinds", e);
|
||||
}
|
||||
}
|
||||
return kinds;
|
||||
}
|
||||
|
||||
private Notification buildForegroundNotification() {
|
||||
Intent notificationIntent = new Intent(this, MainActivity.class);
|
||||
PendingIntent pendingIntent = PendingIntent.getActivity(
|
||||
|
||||
@@ -0,0 +1,552 @@
|
||||
package pub.ditto.app;
|
||||
|
||||
import android.graphics.Color;
|
||||
import android.graphics.PorterDuff;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.Base64;
|
||||
import android.util.Log;
|
||||
import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.webkit.JavascriptInterface;
|
||||
import android.webkit.WebResourceRequest;
|
||||
import android.webkit.WebResourceResponse;
|
||||
import android.webkit.WebSettings;
|
||||
import android.webkit.WebView;
|
||||
import android.webkit.WebViewClient;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.ProgressBar;
|
||||
import androidx.coordinatorlayout.widget.CoordinatorLayout;
|
||||
|
||||
import com.getcapacitor.JSObject;
|
||||
import com.getcapacitor.Plugin;
|
||||
import com.getcapacitor.PluginCall;
|
||||
import com.getcapacitor.PluginMethod;
|
||||
import com.getcapacitor.annotation.CapacitorPlugin;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* Capacitor plugin that creates isolated Android WebViews for sandboxed content.
|
||||
*
|
||||
* Each sandbox uses shouldInterceptRequest to intercept all requests and forward
|
||||
* them to the JS layer as fetch events — the same protocol iframe.diy uses.
|
||||
* The React code can serve files identically regardless of platform.
|
||||
*/
|
||||
@CapacitorPlugin(name = "SandboxPlugin")
|
||||
public class SandboxPlugin extends Plugin {
|
||||
|
||||
private static final String TAG = "SandboxPlugin";
|
||||
private final Map<String, SandboxInstance> sandboxes = new HashMap<>();
|
||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
|
||||
@PluginMethod
|
||||
public void create(PluginCall call) {
|
||||
String sandboxId = call.getString("id");
|
||||
if (sandboxId == null) {
|
||||
call.reject("Missing required parameter: id");
|
||||
return;
|
||||
}
|
||||
|
||||
JSObject frame = call.getObject("frame");
|
||||
if (frame == null) {
|
||||
call.reject("Missing required parameter: frame");
|
||||
return;
|
||||
}
|
||||
|
||||
int x = frame.optInt("x", 0);
|
||||
int y = frame.optInt("y", 0);
|
||||
int width = frame.optInt("width", 0);
|
||||
int height = frame.optInt("height", 0);
|
||||
|
||||
if (sandboxes.containsKey(sandboxId)) {
|
||||
call.reject("Sandbox already exists: " + sandboxId);
|
||||
return;
|
||||
}
|
||||
|
||||
float density = getActivity().getResources().getDisplayMetrics().density;
|
||||
int pxX = Math.round(x * density);
|
||||
int pxY = Math.round(y * density);
|
||||
int pxWidth = Math.round(width * density);
|
||||
int pxHeight = Math.round(height * density);
|
||||
|
||||
mainHandler.post(() -> {
|
||||
SandboxInstance sandbox = new SandboxInstance(sandboxId, this);
|
||||
sandboxes.put(sandboxId, sandbox);
|
||||
|
||||
// Add the container (WebView + spinner overlay) on top of the
|
||||
// Capacitor WebView. The parent is a CoordinatorLayout — using
|
||||
// the wrong LayoutParams type causes a ClassCastException when
|
||||
// it intercepts touch events.
|
||||
View capWebView = getBridge().getWebView();
|
||||
ViewGroup parent = (ViewGroup) capWebView.getParent();
|
||||
CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams(pxWidth, pxHeight);
|
||||
params.leftMargin = pxX;
|
||||
params.topMargin = pxY;
|
||||
parent.addView(sandbox.container, params);
|
||||
|
||||
// The spinner is now visible. Navigation is deferred until the
|
||||
// JS layer calls navigate() — this allows the caller to
|
||||
// pre-fetch blobs while the spinner animates.
|
||||
|
||||
call.resolve();
|
||||
});
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void navigate(PluginCall call) {
|
||||
String sandboxId = call.getString("id");
|
||||
if (sandboxId == null) {
|
||||
call.reject("Missing required parameter: id");
|
||||
return;
|
||||
}
|
||||
|
||||
mainHandler.post(() -> {
|
||||
SandboxInstance sandbox = sandboxes.get(sandboxId);
|
||||
if (sandbox == null) {
|
||||
call.reject("Sandbox not found: " + sandboxId);
|
||||
return;
|
||||
}
|
||||
|
||||
sandbox.webView.loadUrl("https://" + sandboxId + ".sandbox.native/index.html");
|
||||
call.resolve();
|
||||
});
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void updateFrame(PluginCall call) {
|
||||
String sandboxId = call.getString("id");
|
||||
if (sandboxId == null) {
|
||||
call.reject("Missing required parameter: id");
|
||||
return;
|
||||
}
|
||||
|
||||
JSObject frame = call.getObject("frame");
|
||||
if (frame == null) {
|
||||
call.reject("Missing required parameter: frame");
|
||||
return;
|
||||
}
|
||||
|
||||
int x = frame.optInt("x", 0);
|
||||
int y = frame.optInt("y", 0);
|
||||
int width = frame.optInt("width", 0);
|
||||
int height = frame.optInt("height", 0);
|
||||
|
||||
float density = getActivity().getResources().getDisplayMetrics().density;
|
||||
int pxX = Math.round(x * density);
|
||||
int pxY = Math.round(y * density);
|
||||
int pxWidth = Math.round(width * density);
|
||||
int pxHeight = Math.round(height * density);
|
||||
|
||||
mainHandler.post(() -> {
|
||||
SandboxInstance sandbox = sandboxes.get(sandboxId);
|
||||
if (sandbox == null) {
|
||||
call.reject("Sandbox not found: " + sandboxId);
|
||||
return;
|
||||
}
|
||||
|
||||
CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams(pxWidth, pxHeight);
|
||||
params.leftMargin = pxX;
|
||||
params.topMargin = pxY;
|
||||
sandbox.container.setLayoutParams(params);
|
||||
|
||||
call.resolve();
|
||||
});
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void respondToFetch(PluginCall call) {
|
||||
String sandboxId = call.getString("id");
|
||||
if (sandboxId == null) {
|
||||
call.reject("Missing required parameter: id");
|
||||
return;
|
||||
}
|
||||
String requestId = call.getString("requestId");
|
||||
if (requestId == null) {
|
||||
call.reject("Missing required parameter: requestId");
|
||||
return;
|
||||
}
|
||||
JSObject response = call.getObject("response");
|
||||
if (response == null) {
|
||||
call.reject("Missing required parameter: response");
|
||||
return;
|
||||
}
|
||||
|
||||
SandboxInstance sandbox = sandboxes.get(sandboxId);
|
||||
if (sandbox == null) {
|
||||
call.reject("Sandbox not found: " + sandboxId);
|
||||
return;
|
||||
}
|
||||
|
||||
int status = response.optInt("status", 200);
|
||||
String statusText = response.optString("statusText", "OK");
|
||||
String bodyBase64 = response.optString("body", null);
|
||||
|
||||
Map<String, String> headers = new HashMap<>();
|
||||
JSONObject headersObj = response.optJSONObject("headers");
|
||||
if (headersObj != null) {
|
||||
for (java.util.Iterator<String> it = headersObj.keys(); it.hasNext(); ) {
|
||||
String key = it.next();
|
||||
headers.put(key, headersObj.optString(key));
|
||||
}
|
||||
}
|
||||
|
||||
sandbox.resolveRequest(requestId, status, statusText, headers, bodyBase64);
|
||||
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void postMessage(PluginCall call) {
|
||||
String sandboxId = call.getString("id");
|
||||
if (sandboxId == null) {
|
||||
call.reject("Missing required parameter: id");
|
||||
return;
|
||||
}
|
||||
JSObject message = call.getObject("message");
|
||||
if (message == null) {
|
||||
call.reject("Missing required parameter: message");
|
||||
return;
|
||||
}
|
||||
|
||||
SandboxInstance sandbox = sandboxes.get(sandboxId);
|
||||
if (sandbox == null) {
|
||||
call.reject("Sandbox not found: " + sandboxId);
|
||||
return;
|
||||
}
|
||||
|
||||
mainHandler.post(() -> sandbox.postMessageToWebView(message.toString()));
|
||||
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void destroy(PluginCall call) {
|
||||
String sandboxId = call.getString("id");
|
||||
if (sandboxId == null) {
|
||||
call.reject("Missing required parameter: id");
|
||||
return;
|
||||
}
|
||||
|
||||
mainHandler.post(() -> {
|
||||
SandboxInstance sandbox = sandboxes.remove(sandboxId);
|
||||
if (sandbox != null) {
|
||||
ViewGroup parent = (ViewGroup) sandbox.container.getParent();
|
||||
if (parent != null) {
|
||||
parent.removeView(sandbox.container);
|
||||
}
|
||||
sandbox.webView.destroy();
|
||||
}
|
||||
call.resolve();
|
||||
});
|
||||
}
|
||||
|
||||
void emitFetchRequest(String sandboxId, String requestId, JSObject request) {
|
||||
JSObject data = new JSObject();
|
||||
data.put("id", sandboxId);
|
||||
data.put("requestId", requestId);
|
||||
data.put("request", request);
|
||||
notifyListeners("fetch", data);
|
||||
}
|
||||
|
||||
void emitScriptMessage(String sandboxId, JSObject message) {
|
||||
JSObject data = new JSObject();
|
||||
data.put("id", sandboxId);
|
||||
data.put("message", message);
|
||||
notifyListeners("scriptMessage", data);
|
||||
}
|
||||
|
||||
/**
|
||||
* A single sandboxed WebView instance.
|
||||
*/
|
||||
private static class SandboxInstance {
|
||||
final String id;
|
||||
/** Wrapper layout that holds the WebView and the loading overlay. */
|
||||
final FrameLayout container;
|
||||
final WebView webView;
|
||||
final SandboxPlugin plugin;
|
||||
private final ConcurrentHashMap<String, PendingRequest> pendingRequests = new ConcurrentHashMap<>();
|
||||
/** Native spinner overlay, shown while the sandbox content loads. */
|
||||
private ProgressBar spinner;
|
||||
|
||||
SandboxInstance(String id, SandboxPlugin plugin) {
|
||||
this.id = id;
|
||||
this.plugin = plugin;
|
||||
|
||||
this.container = new FrameLayout(plugin.getActivity());
|
||||
this.webView = new WebView(plugin.getActivity());
|
||||
|
||||
WebSettings settings = webView.getSettings();
|
||||
settings.setJavaScriptEnabled(true);
|
||||
settings.setDomStorageEnabled(true);
|
||||
settings.setAllowFileAccess(false);
|
||||
settings.setAllowContentAccess(false);
|
||||
settings.setDatabaseEnabled(true);
|
||||
|
||||
webView.setBackgroundColor(Color.parseColor("#14161f"));
|
||||
|
||||
// Add JavaScript interface for script->native communication.
|
||||
webView.addJavascriptInterface(new SandboxBridge(this), "__sandboxNative");
|
||||
|
||||
// Inject the bridge script and intercept requests.
|
||||
webView.setWebViewClient(new SandboxWebViewClient(this));
|
||||
|
||||
// Build the container: WebView fills it, spinner overlays on top.
|
||||
container.addView(webView, new FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.MATCH_PARENT));
|
||||
|
||||
// Native spinner overlay — uses the Android indeterminate
|
||||
// ProgressBar which animates on the render thread, so it keeps
|
||||
// spinning even when the main/IO threads are busy.
|
||||
spinner = new ProgressBar(plugin.getActivity());
|
||||
spinner.setIndeterminate(true);
|
||||
spinner.getIndeterminateDrawable().setColorFilter(
|
||||
Color.parseColor("#7c5cdc"), PorterDuff.Mode.SRC_IN);
|
||||
FrameLayout.LayoutParams spinnerParams = new FrameLayout.LayoutParams(
|
||||
dpToPx(plugin, 32), dpToPx(plugin, 32), Gravity.CENTER);
|
||||
container.addView(spinner, spinnerParams);
|
||||
|
||||
// Dark background behind the spinner.
|
||||
View overlay = new View(plugin.getActivity());
|
||||
overlay.setBackgroundColor(Color.parseColor("#14161f"));
|
||||
// Insert the overlay between the WebView (index 0) and spinner (index 1)
|
||||
// so it covers the WebView but sits behind the spinner.
|
||||
container.addView(overlay, 1, new FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.MATCH_PARENT));
|
||||
}
|
||||
|
||||
/** Remove the native loading overlay. Safe to call multiple times. */
|
||||
void hideSpinner() {
|
||||
if (spinner != null) {
|
||||
// Remove spinner and overlay (indices 2 and 1 after WebView at 0).
|
||||
if (container.getChildCount() > 2) container.removeViewAt(2); // spinner
|
||||
if (container.getChildCount() > 1) container.removeViewAt(1); // overlay
|
||||
spinner = null;
|
||||
}
|
||||
}
|
||||
|
||||
private static int dpToPx(SandboxPlugin plugin, int dp) {
|
||||
float density = plugin.getActivity().getResources().getDisplayMetrics().density;
|
||||
return Math.round(dp * density);
|
||||
}
|
||||
|
||||
void postMessageToWebView(String jsonString) {
|
||||
String js = "(function() { " +
|
||||
"if (window.__sandboxBridge && window.__sandboxBridge.onMessage) { " +
|
||||
"window.__sandboxBridge.onMessage(" + jsonString + "); " +
|
||||
"} " +
|
||||
"})();";
|
||||
webView.evaluateJavascript(js, null);
|
||||
}
|
||||
|
||||
void resolveRequest(String requestId, int status, String statusText,
|
||||
Map<String, String> headers, String bodyBase64) {
|
||||
PendingRequest pending = pendingRequests.remove(requestId);
|
||||
if (pending == null) return;
|
||||
|
||||
byte[] bodyBytes = null;
|
||||
if (bodyBase64 != null && !bodyBase64.equals("null")) {
|
||||
try {
|
||||
bodyBytes = Base64.decode(bodyBase64, Base64.DEFAULT);
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "Base64 decode failed for request " + requestId, e);
|
||||
}
|
||||
}
|
||||
|
||||
String contentType = headers.getOrDefault("Content-Type", "application/octet-stream");
|
||||
String encoding = contentType.contains("text/") ? "UTF-8" : null;
|
||||
|
||||
InputStream body = bodyBytes != null
|
||||
? new ByteArrayInputStream(bodyBytes)
|
||||
: new ByteArrayInputStream(new byte[0]);
|
||||
|
||||
WebResourceResponse response = new WebResourceResponse(
|
||||
contentType, encoding, status, statusText, headers, body
|
||||
);
|
||||
|
||||
pending.resolve(response);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* WebViewClient that intercepts all requests and forwards them to JS.
|
||||
*/
|
||||
private static class SandboxWebViewClient extends WebViewClient {
|
||||
private final SandboxInstance sandbox;
|
||||
private boolean bridgeInjected = false;
|
||||
|
||||
SandboxWebViewClient(SandboxInstance sandbox) {
|
||||
this.sandbox = sandbox;
|
||||
}
|
||||
|
||||
@Override
|
||||
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
|
||||
String url = request.getUrl().toString();
|
||||
|
||||
// Only intercept requests to the sandbox domain.
|
||||
if (!url.contains(".sandbox.native")) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
|
||||
// Create a pending request with a blocking latch.
|
||||
PendingRequest pending = new PendingRequest();
|
||||
sandbox.pendingRequests.put(requestId, pending);
|
||||
|
||||
// Rewrite URL to include the sandbox ID for the JS handler.
|
||||
String path = request.getUrl().getPath();
|
||||
if (path == null || path.isEmpty()) path = "/";
|
||||
String rewrittenURL = "https://" + sandbox.id + ".sandbox.native" + path;
|
||||
|
||||
// Serialise the request.
|
||||
JSObject serialisedRequest = new JSObject();
|
||||
serialisedRequest.put("url", rewrittenURL);
|
||||
serialisedRequest.put("method", request.getMethod());
|
||||
|
||||
JSObject headers = new JSObject();
|
||||
for (Map.Entry<String, String> entry : request.getRequestHeaders().entrySet()) {
|
||||
headers.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
serialisedRequest.put("headers", headers);
|
||||
serialisedRequest.put("body", JSONObject.NULL);
|
||||
|
||||
// Emit to JS.
|
||||
sandbox.plugin.emitFetchRequest(sandbox.id, requestId, serialisedRequest);
|
||||
|
||||
// Block until JS responds. Each asset is fetched from a Blossom
|
||||
// server over the network, so we need a generous timeout. The
|
||||
// WebView IO thread pool has ~6 threads; if all are blocked,
|
||||
// subsequent requests queue until a thread frees up.
|
||||
WebResourceResponse response = pending.awaitResponse(60000);
|
||||
|
||||
if (response != null) {
|
||||
return response;
|
||||
}
|
||||
|
||||
// Timeout — return error response.
|
||||
sandbox.pendingRequests.remove(requestId);
|
||||
return new WebResourceResponse(
|
||||
"text/plain", "UTF-8", 504,
|
||||
"Gateway Timeout", new HashMap<>(),
|
||||
new ByteArrayInputStream("Request timed out".getBytes())
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPageFinished(WebView view, String url) {
|
||||
super.onPageFinished(view, url);
|
||||
|
||||
if (!bridgeInjected) {
|
||||
bridgeInjected = true;
|
||||
view.evaluateJavascript(getBridgeScript(), null);
|
||||
}
|
||||
|
||||
// Remove the native spinner once the first page has finished
|
||||
// loading (all initial resources resolved). This runs on the
|
||||
// main thread, so the removal is safe.
|
||||
sandbox.hideSpinner();
|
||||
}
|
||||
|
||||
private String getBridgeScript() {
|
||||
return "(function() {" +
|
||||
"'use strict';" +
|
||||
"var messageListeners = [];" +
|
||||
"window.__sandboxBridge = {" +
|
||||
" onMessage: function(data) {" +
|
||||
" var event = {" +
|
||||
" data: data," +
|
||||
" origin: 'https://" + sandbox.id + ".sandbox.native'," +
|
||||
" source: window.parent," +
|
||||
" type: 'message'" +
|
||||
" };" +
|
||||
" for (var i = 0; i < messageListeners.length; i++) {" +
|
||||
" try { messageListeners[i](event); } catch(e) {}" +
|
||||
" }" +
|
||||
" }" +
|
||||
"};" +
|
||||
"var origAdd = window.addEventListener;" +
|
||||
"window.addEventListener = function(type, fn, opts) {" +
|
||||
" if (type === 'message' && typeof fn === 'function') messageListeners.push(fn);" +
|
||||
" return origAdd.call(window, type, fn, opts);" +
|
||||
"};" +
|
||||
"var origRemove = window.removeEventListener;" +
|
||||
"window.removeEventListener = function(type, fn, opts) {" +
|
||||
" if (type === 'message') {" +
|
||||
" var idx = messageListeners.indexOf(fn);" +
|
||||
" if (idx !== -1) messageListeners.splice(idx, 1);" +
|
||||
" }" +
|
||||
" return origRemove.call(window, type, fn, opts);" +
|
||||
"};" +
|
||||
"if (!window.parent || window.parent === window) window.parent = {};" +
|
||||
"window.parent.postMessage = function(data) {" +
|
||||
" if (data && typeof data === 'object' && data.jsonrpc === '2.0') {" +
|
||||
" try { window.__sandboxNative.postMessage(JSON.stringify(data)); } catch(e) {}" +
|
||||
" }" +
|
||||
"};" +
|
||||
"})();";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* JavaScript interface exposed to the sandbox WebView.
|
||||
*/
|
||||
private static class SandboxBridge {
|
||||
private final SandboxInstance sandbox;
|
||||
|
||||
SandboxBridge(SandboxInstance sandbox) {
|
||||
this.sandbox = sandbox;
|
||||
}
|
||||
|
||||
@JavascriptInterface
|
||||
public void postMessage(String json) {
|
||||
try {
|
||||
JSONObject obj = new JSONObject(json);
|
||||
JSObject jsObj = new JSObject();
|
||||
for (java.util.Iterator<String> it = obj.keys(); it.hasNext(); ) {
|
||||
String key = it.next();
|
||||
jsObj.put(key, obj.get(key));
|
||||
}
|
||||
sandbox.plugin.emitScriptMessage(sandbox.id, jsObj);
|
||||
} catch (JSONException e) {
|
||||
Log.w(TAG, "Failed to parse script message", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A pending request that blocks the WebViewClient IO thread until JS
|
||||
* responds with the complete resource.
|
||||
*/
|
||||
private static class PendingRequest {
|
||||
private volatile WebResourceResponse response;
|
||||
private final CountDownLatch latch = new CountDownLatch(1);
|
||||
|
||||
void resolve(WebResourceResponse response) {
|
||||
this.response = response;
|
||||
latch.countDown();
|
||||
}
|
||||
|
||||
WebResourceResponse awaitResponse(long timeoutMs) {
|
||||
try {
|
||||
latch.await(timeoutMs, TimeUnit.MILLISECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
return response;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,11 +8,20 @@ project(':capacitor-app').projectDir = new File('../node_modules/@capacitor/app/
|
||||
include ':capacitor-filesystem'
|
||||
project(':capacitor-filesystem').projectDir = new File('../node_modules/@capacitor/filesystem/android')
|
||||
|
||||
include ':capacitor-haptics'
|
||||
project(':capacitor-haptics').projectDir = new File('../node_modules/@capacitor/haptics/android')
|
||||
|
||||
include ':capacitor-keyboard'
|
||||
project(':capacitor-keyboard').projectDir = new File('../node_modules/@capacitor/keyboard/android')
|
||||
|
||||
include ':capacitor-local-notifications'
|
||||
project(':capacitor-local-notifications').projectDir = new File('../node_modules/@capacitor/local-notifications/android')
|
||||
|
||||
include ':capacitor-share'
|
||||
project(':capacitor-share').projectDir = new File('../node_modules/@capacitor/share/android')
|
||||
|
||||
include ':capacitor-status-bar'
|
||||
project(':capacitor-status-bar').projectDir = new File('../node_modules/@capacitor/status-bar/android')
|
||||
include ':capgo-capacitor-autofill-save-password'
|
||||
project(':capgo-capacitor-autofill-save-password').projectDir = new File('../node_modules/@capgo/capacitor-autofill-save-password/android')
|
||||
|
||||
include ':capacitor-secure-storage-plugin'
|
||||
project(':capacitor-secure-storage-plugin').projectDir = new File('../node_modules/capacitor-secure-storage-plugin/android')
|
||||
|
||||
@@ -5,8 +5,6 @@ const config: CapacitorConfig = {
|
||||
appName: 'Ditto',
|
||||
webDir: 'dist',
|
||||
server: {
|
||||
// Handle deep links from your domain
|
||||
hostname: 'ditto.pub',
|
||||
androidScheme: 'https',
|
||||
iosScheme: 'https'
|
||||
},
|
||||
@@ -17,9 +15,16 @@ const config: CapacitorConfig = {
|
||||
},
|
||||
ios: {
|
||||
backgroundColor: '#14161f',
|
||||
contentInset: 'automatic',
|
||||
contentInset: 'never',
|
||||
scheme: 'Ditto'
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
SystemBars: {
|
||||
// Inject --safe-area-inset-* CSS variables on Android to work around
|
||||
// a Chromium bug (<140) where env(safe-area-inset-*) reports 0.
|
||||
insetsHandling: 'css',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
|
||||
@@ -60,7 +60,7 @@ const builtinThemes = {
|
||||
};
|
||||
```
|
||||
|
||||
Self-hosters can override these at build time via `ditto.json` (injected through `__DITTO_CONFIG__` in `vite.config.ts`), or at runtime via the `ThemesConfig` in `AppConfig.themes`.
|
||||
Self-hosters can override these at build time via `ditto.json` (injected through `import.meta.env.DITTO_CONFIG` in `vite.config.ts`), or at runtime via the `ThemesConfig` in `AppConfig.themes`.
|
||||
|
||||
### ThemeConfig
|
||||
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
# Blobbi Tag Schema
|
||||
|
||||
> **Product Specification** - This document is the canonical source of truth for Blobbi tag definitions.
|
||||
> The runtime schema at `src/lib/blobbi-tag-schema.ts` MUST align with this spec.
|
||||
|
||||
## Overview
|
||||
|
||||
Blobbi events (Kind 31124) use tags to store all state data. This document defines:
|
||||
- All valid tags and their purposes
|
||||
- Which tags are required vs optional
|
||||
- Which tags persist across stage transitions
|
||||
- Which tags should be removed during transitions
|
||||
- Deprecated tags that should be filtered out
|
||||
|
||||
---
|
||||
|
||||
## Tag Categories
|
||||
|
||||
### 1. System / Metadata Tags
|
||||
|
||||
Core protocol-level tags required for event identification and ecosystem membership.
|
||||
|
||||
| Tag | Required | Stages | Persistent | Source | Format | Description |
|
||||
|-----|----------|--------|------------|--------|--------|-------------|
|
||||
| `d` | **Yes** | egg, baby, adult | Yes | system | `blobbi-{pubkeyPrefix12}-{petId10}` | Unique identifier (addressable event d-tag) |
|
||||
| `b` | **Yes** | egg, baby, adult | Yes | system | `blobbi:ecosystem:v1` | Ecosystem namespace identifier |
|
||||
| `t` | **Yes** | egg, baby, adult | Yes | system | `blobbi` | Topic tag for discoverability |
|
||||
| `client` | No | egg, baby, adult | Yes | system | `blobbi` | Client identifier |
|
||||
|
||||
### 2. Core Identity Tags
|
||||
|
||||
Tags that define the Blobbi's unique identity. These MUST be preserved across all transitions.
|
||||
|
||||
| Tag | Required | Stages | Persistent | Source | Format | Description |
|
||||
|-----|----------|--------|------------|--------|--------|-------------|
|
||||
| `name` | **Yes** | egg, baby, adult | Yes | user | string | Display name (set during adoption) |
|
||||
| `seed` | **Yes** | egg, baby, adult | Yes | system | 64 hex chars | Deterministic seed for visual traits |
|
||||
| `generation` | No | egg, baby, adult | Yes | system | positive integer | Lineage generation (default: 1) |
|
||||
|
||||
**Important**: The `seed` is derived once at creation using `sha256("blobbi:v1|{pubkey}:{d}:{createdAt}")` and MUST NEVER be recomputed.
|
||||
|
||||
### 3. Visual Trait Tags
|
||||
|
||||
Tags derived deterministically from the seed. These are stored explicitly for fast rendering and compatibility.
|
||||
|
||||
| Tag | Required | Stages | Persistent | Source | Format | Description |
|
||||
|-----|----------|--------|------------|--------|--------|-------------|
|
||||
| `base_color` | No | egg, baby, adult | Yes | generated | CSS hex (e.g., `#F59E0B`) | Primary color |
|
||||
| `secondary_color` | No | egg, baby, adult | Yes | generated | CSS hex | Secondary/accent color |
|
||||
| `eye_color` | No | egg, baby, adult | Yes | generated | CSS hex | Eye color |
|
||||
| `pattern` | No | egg, baby, adult | Yes | generated | `solid\|spotted\|striped\|gradient` | Visual pattern type |
|
||||
| `special_mark` | No | egg, baby, adult | Yes | generated | `none\|star\|heart\|sparkle\|blush` | Special decoration |
|
||||
| `size` | No | egg, baby, adult | Yes | generated | `small\|medium\|large` | Size category |
|
||||
|
||||
**Regenerable**: These tags CAN be regenerated from the seed if missing. However, they should be preserved when present.
|
||||
|
||||
### 4. Personality / Trait Tags
|
||||
|
||||
Character traits that define the Blobbi's personality. These are generated at creation and MUST persist.
|
||||
|
||||
| Tag | Required | Stages | Persistent | Source | Format | Description |
|
||||
|-----|----------|--------|------------|--------|--------|-------------|
|
||||
| `personality` | No | egg, baby, adult | Yes | generated | string | Core personality type |
|
||||
| `trait` | No | egg, baby, adult | Yes | generated | string | Character trait modifier |
|
||||
| `favorite_food` | No | egg, baby, adult | Yes | generated | string | Preferred food type |
|
||||
| `voice_type` | No | egg, baby, adult | Yes | generated | string | Voice characteristic |
|
||||
| `mood` | No | egg, baby, adult | Yes | computed | string | Current emotional state |
|
||||
|
||||
**Not Regenerable**: These tags are generated once and MUST be preserved. Do NOT invent values for existing Blobbis that lack these tags.
|
||||
|
||||
### 5. Stat Tags
|
||||
|
||||
Numeric values representing the Blobbi's current condition. These are actively computed and change frequently.
|
||||
|
||||
| Tag | Required | Stages | Persistent | Source | Format | Default | Description |
|
||||
|-----|----------|--------|------------|--------|--------|---------|-------------|
|
||||
| `hunger` | No | egg, baby, adult | No | computed | 1-100 | 100 | Fullness level |
|
||||
| `happiness` | No | egg, baby, adult | No | computed | 1-100 | 100 | Happiness level |
|
||||
| `health` | No | egg, baby, adult | No | computed | 1-100 | 100 | Health level |
|
||||
| `hygiene` | No | egg, baby, adult | No | computed | 1-100 | 100 | Cleanliness level |
|
||||
| `energy` | No | egg, baby, adult | No | computed | 1-100 | 100 | Energy level |
|
||||
|
||||
**Stage Transition Behavior**:
|
||||
- **Hatch (egg → baby)**: `health` inherited from egg, others reset to 100
|
||||
- **Evolve (baby → adult)**: All stats inherited from baby (after decay)
|
||||
|
||||
### 6. State / Lifecycle Tags
|
||||
|
||||
Tags that track the Blobbi's current lifecycle state.
|
||||
|
||||
| Tag | Required | Stages | Persistent | Source | Format | Description |
|
||||
|-----|----------|--------|------------|--------|--------|-------------|
|
||||
| `stage` | **Yes** | egg, baby, adult | No | system | `egg\|baby\|adult` | Current lifecycle stage |
|
||||
| `state` | **Yes** | egg, baby, adult | No | system | `active\|sleeping\|hibernating\|incubating\|evolving` | Activity state |
|
||||
| `last_interaction` | **Yes** | egg, baby, adult | No | system | Unix timestamp | Last user action |
|
||||
| `last_decay_at` | No | egg, baby, adult | No | system | Unix timestamp | Decay checkpoint |
|
||||
|
||||
**State Constraints**:
|
||||
- `incubating` is only valid for `stage: egg`
|
||||
- `evolving` is only valid for `stage: baby`
|
||||
- After hatch/evolve completes, `state` MUST be set to `active`
|
||||
|
||||
### 7. Task System Tags
|
||||
|
||||
Temporary tags used during incubation and evolution processes. These are REMOVED after stage transitions.
|
||||
|
||||
| Tag | Required | Stages | Persistent | Source | Format | Description |
|
||||
|-----|----------|--------|------------|--------|--------|-------------|
|
||||
| `state_started_at` | No | egg, baby | No | system | Unix timestamp | When incubating/evolving started |
|
||||
| `task` | No | egg, baby | No | computed | `["task", "name:value"]` | Task progress (multiple allowed) |
|
||||
| `task_completed` | No | egg, baby | No | computed | `["task_completed", "name"]` | Completed tasks (multiple allowed) |
|
||||
|
||||
**Transition Behavior**: ALL task system tags MUST be removed when hatch or evolve completes.
|
||||
|
||||
### 8. Progression Tags
|
||||
|
||||
Long-term progress tracking that persists across all stages.
|
||||
|
||||
| Tag | Required | Stages | Persistent | Source | Format | Default | Description |
|
||||
|-----|----------|--------|------------|--------|--------|---------|-------------|
|
||||
| `experience` | No | egg, baby, adult | Yes | computed | non-negative int | 0 | Total XP |
|
||||
| `care_streak` | No | egg, baby, adult | Yes | computed | non-negative int | 0 | Consecutive care days |
|
||||
|
||||
### 9. Social / Flag Tags
|
||||
|
||||
User preferences and computed flags.
|
||||
|
||||
| Tag | Required | Stages | Persistent | Source | Format | Default | Description |
|
||||
|-----|----------|--------|------------|--------|--------|---------|-------------|
|
||||
| `breeding_ready` | No | egg, baby, adult | Yes | computed | `true\|false` | false | Breeding eligibility |
|
||||
|
||||
### 10. Evolution Tags
|
||||
|
||||
Tags specific to adult Blobbis.
|
||||
|
||||
| Tag | Required | Stages | Persistent | Source | Format | Description |
|
||||
|-----|----------|--------|------------|--------|--------|-------------|
|
||||
| `adult_type` | No | adult | Yes | computed | string | Evolution form type |
|
||||
|
||||
### 11. Extension Tags
|
||||
|
||||
Optional tags for themes and crossover features.
|
||||
|
||||
| Tag | Required | Stages | Persistent | Source | Format | Description |
|
||||
|-----|----------|--------|------------|--------|--------|-------------|
|
||||
| `theme` | No | egg, baby, adult | Yes | system | string (e.g., `divine`) | Theme variant |
|
||||
| `crossover_app` | No | egg, baby, adult | Yes | system | string (e.g., `divine`) | Crossover app identifier |
|
||||
|
||||
---
|
||||
|
||||
## Deprecated Tags
|
||||
|
||||
These tags are from legacy versions and MUST be removed when republishing events.
|
||||
|
||||
| Tag | Reason | Replaced By |
|
||||
|-----|--------|-------------|
|
||||
| `shell_integrity` | Eggs use standard `health` stat | `health` |
|
||||
| `egg_temperature` | Warmth handled via UI props | N/A |
|
||||
| `incubation_progress` | Replaced by task system | `task`, `task_completed` |
|
||||
| `egg_status` | Replaced by standard state | `state` |
|
||||
| `fees` | Removed | N/A |
|
||||
| `incubation_time` | Uses state_started_at | `state_started_at` |
|
||||
| `start_incubation` | Uses state_started_at | `state_started_at` |
|
||||
| `interact_6_progress` | Legacy interaction tracking | `["task", "interactions:N"]` |
|
||||
|
||||
---
|
||||
|
||||
## Stage Transition Rules
|
||||
|
||||
### Hatch (egg → baby)
|
||||
|
||||
**Tags to REMOVE**:
|
||||
- `task`
|
||||
- `task_completed`
|
||||
- `state_started_at`
|
||||
|
||||
**Tags to UPDATE**:
|
||||
- `stage` → `baby`
|
||||
- `state` → `active`
|
||||
- `hunger` → `100`
|
||||
- `happiness` → `100`
|
||||
- `hygiene` → `100`
|
||||
- `energy` → `100`
|
||||
- `health` → (inherited from egg after decay)
|
||||
- `last_interaction` → current timestamp
|
||||
- `last_decay_at` → current timestamp
|
||||
|
||||
**Tags to PRESERVE (all persistent tags)**:
|
||||
- All system tags (`d`, `b`, `t`, `client`)
|
||||
- All identity tags (`name`, `seed`, `generation`)
|
||||
- All visual tags (colors, pattern, size)
|
||||
- All personality tags (if present)
|
||||
- All progression tags (`experience`, `care_streak`)
|
||||
- All social tags (`breeding_ready`)
|
||||
- All extension tags (`theme`, `crossover_app`)
|
||||
|
||||
### Evolve (baby → adult)
|
||||
|
||||
**Tags to REMOVE**:
|
||||
- `task`
|
||||
- `task_completed`
|
||||
- `state_started_at`
|
||||
|
||||
**Tags to UPDATE**:
|
||||
- `stage` → `adult`
|
||||
- `state` → `active`
|
||||
- All stats → (inherited from baby after decay)
|
||||
- `last_interaction` → current timestamp
|
||||
- `last_decay_at` → current timestamp
|
||||
|
||||
**Tags to PRESERVE (all persistent tags)**:
|
||||
- Same as hatch, plus all stats are inherited (not reset)
|
||||
|
||||
**Tags to ADD (optional)**:
|
||||
- `adult_type` → computed based on care history
|
||||
|
||||
---
|
||||
|
||||
## Migration Rules
|
||||
|
||||
When migrating legacy Blobbis to canonical format:
|
||||
|
||||
1. **Always preserve existing values** - Do not regenerate tags that already exist
|
||||
2. **Generate missing required tags** - Derive `seed` if missing using the legacy event's `created_at`
|
||||
3. **Remove deprecated tags** - Filter out all tags in the deprecated list
|
||||
4. **Repair visual tags** - Regenerate from seed if missing (these are regenerable)
|
||||
5. **Do NOT invent personality tags** - If `personality`, `trait`, etc. don't exist, leave them empty
|
||||
|
||||
---
|
||||
|
||||
## Validation Rules
|
||||
|
||||
A valid Blobbi event MUST have:
|
||||
- `d` tag in canonical format
|
||||
- `b` tag = `blobbi:ecosystem:v1`
|
||||
- `t` tag = `blobbi`
|
||||
- `name` tag (non-empty)
|
||||
- `seed` tag (64 hex chars)
|
||||
- `stage` tag (valid value)
|
||||
- `state` tag (valid value)
|
||||
- `last_interaction` tag (valid timestamp)
|
||||
|
||||
---
|
||||
|
||||
## Implementation Checklist
|
||||
|
||||
When implementing any flow that modifies Blobbi tags:
|
||||
|
||||
- [ ] Start from `canonical.allTags` as the base
|
||||
- [ ] Remove only task-specific tags (`task`, `task_completed`, `state_started_at`)
|
||||
- [ ] Preserve ALL persistent tags (identity, visual, personality, progression, social, extension)
|
||||
- [ ] Filter out deprecated tags
|
||||
- [ ] Update only the tags that need to change
|
||||
- [ ] Validate required tags are present
|
||||
@@ -8,7 +8,7 @@ import htmlParser from "@html-eslint/parser";
|
||||
import customRules from "./eslint-rules/index.js";
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ["dist", "android"] },
|
||||
{ ignores: ["dist", "android", "ios"] },
|
||||
{
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||
files: ["**/*.{ts,tsx}"],
|
||||
@@ -39,6 +39,13 @@ export default tseslint.config(
|
||||
},
|
||||
],
|
||||
"custom/no-placeholder-comments": "error",
|
||||
"no-restricted-syntax": [
|
||||
"error",
|
||||
{
|
||||
"selector": "CallExpression[callee.object.type='MetaProperty'][callee.property.name='glob']",
|
||||
"message": "import.meta.glob is Vite-only and breaks other bundlers. Inline the assets or use standard imports instead.",
|
||||
},
|
||||
],
|
||||
"no-warning-comments": [
|
||||
"error",
|
||||
{ terms: ["fixme"] },
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<title>Ditto — Your content. Your vibe. Your rules.</title>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover, interactive-widget=resizes-content" />
|
||||
<meta name="description" content="Ditto — Your content. Your vibe. Your rules." />
|
||||
|
||||
<!-- Open Graph -->
|
||||
@@ -23,7 +23,7 @@
|
||||
<meta name="twitter:description" content="Your content. Your vibe. Your rules." />
|
||||
<meta name="twitter:image" content="https://ditto.pub/og-image.jpg" />
|
||||
|
||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self' https:; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self' https:; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' blob: https:">
|
||||
<link rel="icon" type="image/svg+xml" href="/logo.svg">
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
||||
<meta name="theme-color" content="#161b2e" media="(prefers-color-scheme: dark)">
|
||||
|
||||
@@ -15,6 +15,9 @@
|
||||
504EC30F1FED79650016851F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30E1FED79650016851F /* Assets.xcassets */; };
|
||||
504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC3101FED79650016851F /* LaunchScreen.storyboard */; };
|
||||
50B271D11FEDC1A000F3C39B /* public in Resources */ = {isa = PBXBuildFile; fileRef = 50B271D01FEDC1A000F3C39B /* public */; };
|
||||
B1A2C3D40001000100000001 /* SandboxPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1A2C3D40001000100000002 /* SandboxPlugin.swift */; };
|
||||
B1A2C3D40002000100000001 /* DittoBridgeViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1A2C3D40002000100000002 /* DittoBridgeViewController.swift */; };
|
||||
B1A2C3D40005000100000001 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = B1A2C3D40005000100000002 /* PrivacyInfo.xcprivacy */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
@@ -28,6 +31,10 @@
|
||||
504EC3131FED79650016851F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
50B271D01FEDC1A000F3C39B /* public */ = {isa = PBXFileReference; lastKnownFileType = folder; path = public; sourceTree = "<group>"; };
|
||||
958DCC722DB07C7200EA8C5F /* debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = debug.xcconfig; path = ../debug.xcconfig; sourceTree = SOURCE_ROOT; };
|
||||
B1A2C3D40001000100000002 /* SandboxPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SandboxPlugin.swift; sourceTree = "<group>"; };
|
||||
B1A2C3D40002000100000002 /* DittoBridgeViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DittoBridgeViewController.swift; sourceTree = "<group>"; };
|
||||
B1A2C3D40004000100000002 /* App.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = App.entitlements; sourceTree = "<group>"; };
|
||||
B1A2C3D40005000100000002 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -63,11 +70,15 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
50379B222058CBB4000EE86E /* capacitor.config.json */,
|
||||
B1A2C3D40004000100000002 /* App.entitlements */,
|
||||
504EC3071FED79650016851F /* AppDelegate.swift */,
|
||||
B1A2C3D40001000100000002 /* SandboxPlugin.swift */,
|
||||
B1A2C3D40002000100000002 /* DittoBridgeViewController.swift */,
|
||||
504EC30B1FED79650016851F /* Main.storyboard */,
|
||||
504EC30E1FED79650016851F /* Assets.xcassets */,
|
||||
504EC3101FED79650016851F /* LaunchScreen.storyboard */,
|
||||
504EC3131FED79650016851F /* Info.plist */,
|
||||
B1A2C3D40005000100000002 /* PrivacyInfo.xcprivacy */,
|
||||
2FAD9762203C412B000D30F8 /* config.xml */,
|
||||
50B271D01FEDC1A000F3C39B /* public */,
|
||||
);
|
||||
@@ -145,6 +156,7 @@
|
||||
50379B232058CBB4000EE86E /* capacitor.config.json in Resources */,
|
||||
504EC30D1FED79650016851F /* Main.storyboard in Resources */,
|
||||
2FAD9763203C412B000D30F8 /* config.xml in Resources */,
|
||||
B1A2C3D40005000100000001 /* PrivacyInfo.xcprivacy in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -156,6 +168,8 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
504EC3081FED79650016851F /* AppDelegate.swift in Sources */,
|
||||
B1A2C3D40001000100000001 /* SandboxPlugin.swift in Sources */,
|
||||
B1A2C3D40002000100000001 /* DittoBridgeViewController.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -295,15 +309,17 @@
|
||||
baseConfigurationReference = 958DCC722DB07C7200EA8C5F /* debug.xcconfig */;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CODE_SIGN_ENTITLEMENTS = App/App.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
DEVELOPMENT_TEAM = GZLTTH5DLM;
|
||||
INFOPLIST_FILE = App/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 2.1.1;
|
||||
MARKETING_VERSION = 2.6.6;
|
||||
OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\"";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = pub.ditto.app;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
@@ -317,15 +333,17 @@
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CODE_SIGN_ENTITLEMENTS = App/App.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
DEVELOPMENT_TEAM = GZLTTH5DLM;
|
||||
INFOPLIST_FILE = App/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 2.1.1;
|
||||
MARKETING_VERSION = 2.6.6;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = pub.ditto.app;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "";
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.developer.associated-domains</key>
|
||||
<array>
|
||||
<string>webcredentials:ditto.pub</string>
|
||||
<string>webcredentials:ditto.pub?mode=developer</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -11,7 +11,7 @@
|
||||
<!--Bridge View Controller-->
|
||||
<scene sceneID="tne-QT-ifu">
|
||||
<objects>
|
||||
<viewController id="BYZ-38-t0r" customClass="CAPBridgeViewController" customModule="Capacitor" sceneMemberID="viewController"/>
|
||||
<viewController id="BYZ-38-t0r" customClass="DittoBridgeViewController" customModule="App" sceneMemberID="viewController"/>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
</scene>
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import UIKit
|
||||
import Capacitor
|
||||
|
||||
class DittoBridgeViewController: CAPBridgeViewController {
|
||||
override func capacitorDidLoad() {
|
||||
super.capacitorDidLoad()
|
||||
webView?.allowsBackForwardNavigationGestures = true
|
||||
}
|
||||
}
|
||||
@@ -47,5 +47,13 @@
|
||||
</array>
|
||||
<key>UIViewControllerBasedStatusBarAppearance</key>
|
||||
<true/>
|
||||
<key>NSPhotoLibraryUsageDescription</key>
|
||||
<string>Ditto needs access to your photo library to upload images to your posts and profile.</string>
|
||||
<key>NSCameraUsageDescription</key>
|
||||
<string>Ditto needs camera access to take photos and videos for your posts.</string>
|
||||
<key>NSMicrophoneUsageDescription</key>
|
||||
<string>Ditto needs access to your microphone to record voice messages.</string>
|
||||
<key>ITSAppUsesNonExemptEncryption</key>
|
||||
<false/>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>NSPrivacyCollectedDataTypes</key>
|
||||
<array>
|
||||
<!-- Crash / performance data via Sentry/GlitchTip -->
|
||||
<dict>
|
||||
<key>NSPrivacyCollectedDataType</key>
|
||||
<string>NSPrivacyCollectedDataTypeCrashData</string>
|
||||
<key>NSPrivacyCollectedDataTypeLinked</key>
|
||||
<false/>
|
||||
<key>NSPrivacyCollectedDataTypeTracking</key>
|
||||
<false/>
|
||||
<key>NSPrivacyCollectedDataTypePurposes</key>
|
||||
<array>
|
||||
<string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>
|
||||
</array>
|
||||
</dict>
|
||||
<!-- Performance / analytics data via Plausible -->
|
||||
<dict>
|
||||
<key>NSPrivacyCollectedDataType</key>
|
||||
<string>NSPrivacyCollectedDataTypePerformanceData</string>
|
||||
<key>NSPrivacyCollectedDataTypeLinked</key>
|
||||
<false/>
|
||||
<key>NSPrivacyCollectedDataTypeTracking</key>
|
||||
<false/>
|
||||
<key>NSPrivacyCollectedDataTypePurposes</key>
|
||||
<array>
|
||||
<string>NSPrivacyCollectedDataTypePurposeAnalytics</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
<key>NSPrivacyTracking</key>
|
||||
<false/>
|
||||
<key>NSPrivacyTrackingDomains</key>
|
||||
<array/>
|
||||
<key>NSPrivacyAccessedAPITypes</key>
|
||||
<array>
|
||||
<!-- UserDefaults — used by Capacitor/WKWebView for localStorage -->
|
||||
<dict>
|
||||
<key>NSPrivacyAccessedAPIType</key>
|
||||
<string>NSPrivacyAccessedAPICategoryUserDefaults</string>
|
||||
<key>NSPrivacyAccessedAPITypeReasons</key>
|
||||
<array>
|
||||
<!-- CA92.1: Access info from same app -->
|
||||
<string>CA92.1</string>
|
||||
</array>
|
||||
</dict>
|
||||
<!-- File timestamp APIs — used by @capacitor/filesystem -->
|
||||
<dict>
|
||||
<key>NSPrivacyAccessedAPIType</key>
|
||||
<string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
|
||||
<key>NSPrivacyAccessedAPITypeReasons</key>
|
||||
<array>
|
||||
<!-- C617.1: Access file timestamps inside app container -->
|
||||
<string>C617.1</string>
|
||||
</array>
|
||||
</dict>
|
||||
<!-- Disk space APIs — used by WKWebView / file operations -->
|
||||
<dict>
|
||||
<key>NSPrivacyAccessedAPIType</key>
|
||||
<string>NSPrivacyAccessedAPICategoryDiskSpace</string>
|
||||
<key>NSPrivacyAccessedAPITypeReasons</key>
|
||||
<array>
|
||||
<!-- E174.1: Check available disk space before writing -->
|
||||
<string>E174.1</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,541 @@
|
||||
import Foundation
|
||||
import Capacitor
|
||||
import WebKit
|
||||
|
||||
// MARK: - Plugin
|
||||
|
||||
/// Capacitor plugin that creates isolated WKWebViews for sandboxed content.
|
||||
///
|
||||
/// Each sandbox gets a unique custom URL scheme (`sbx-<id>://`) so that
|
||||
/// every embedded app has its own origin (separate localStorage, cookies, etc.).
|
||||
/// All requests on the custom scheme are intercepted via `WKURLSchemeHandler`
|
||||
/// and forwarded to the JS layer as fetch events — the same protocol
|
||||
/// iframe.diy uses. This lets the existing React code serve files identically.
|
||||
@objc(SandboxPlugin)
|
||||
public class SandboxPlugin: CAPPlugin, CAPBridgedPlugin {
|
||||
public let identifier = "SandboxPlugin"
|
||||
public let jsName = "SandboxPlugin"
|
||||
public let pluginMethods: [CAPPluginMethod] = [
|
||||
CAPPluginMethod(name: "create", returnType: CAPPluginReturnPromise),
|
||||
CAPPluginMethod(name: "navigate", returnType: CAPPluginReturnPromise),
|
||||
CAPPluginMethod(name: "updateFrame", returnType: CAPPluginReturnPromise),
|
||||
CAPPluginMethod(name: "respondToFetch", returnType: CAPPluginReturnPromise),
|
||||
CAPPluginMethod(name: "postMessage", returnType: CAPPluginReturnPromise),
|
||||
CAPPluginMethod(name: "destroy", returnType: CAPPluginReturnPromise),
|
||||
]
|
||||
|
||||
/// Active sandbox instances, keyed by sandbox ID.
|
||||
private var sandboxes: [String: SandboxInstance] = [:]
|
||||
|
||||
// MARK: - Plugin Methods
|
||||
|
||||
@objc func create(_ call: CAPPluginCall) {
|
||||
guard let sandboxId = call.getString("id") else {
|
||||
call.reject("Missing required parameter: id")
|
||||
return
|
||||
}
|
||||
guard let frame = call.getObject("frame"),
|
||||
let x = frame["x"] as? Double,
|
||||
let y = frame["y"] as? Double,
|
||||
let width = frame["width"] as? Double,
|
||||
let height = frame["height"] as? Double else {
|
||||
call.reject("Missing or invalid parameter: frame")
|
||||
return
|
||||
}
|
||||
|
||||
if sandboxes[sandboxId] != nil {
|
||||
call.reject("Sandbox already exists: \(sandboxId)")
|
||||
return
|
||||
}
|
||||
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self = self else { return }
|
||||
|
||||
let webViewFrame = CGRect(x: x, y: y, width: width, height: height)
|
||||
let sandbox = SandboxInstance(
|
||||
id: sandboxId,
|
||||
frame: webViewFrame,
|
||||
plugin: self
|
||||
)
|
||||
self.sandboxes[sandboxId] = sandbox
|
||||
|
||||
// Add the container (WebView + spinner overlay) on top of
|
||||
// the Capacitor WebView.
|
||||
if let bridge = self.bridge,
|
||||
let webView = bridge.webView {
|
||||
webView.superview?.addSubview(sandbox.containerView)
|
||||
}
|
||||
|
||||
call.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
@objc func navigate(_ call: CAPPluginCall) {
|
||||
guard let sandboxId = call.getString("id") else {
|
||||
call.reject("Missing required parameter: id")
|
||||
return
|
||||
}
|
||||
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let sandbox = self?.sandboxes[sandboxId] else {
|
||||
call.reject("Sandbox not found: \(sandboxId)")
|
||||
return
|
||||
}
|
||||
sandbox.navigateToApp()
|
||||
call.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
@objc func updateFrame(_ call: CAPPluginCall) {
|
||||
guard let sandboxId = call.getString("id") else {
|
||||
call.reject("Missing required parameter: id")
|
||||
return
|
||||
}
|
||||
guard let frame = call.getObject("frame"),
|
||||
let x = frame["x"] as? Double,
|
||||
let y = frame["y"] as? Double,
|
||||
let width = frame["width"] as? Double,
|
||||
let height = frame["height"] as? Double else {
|
||||
call.reject("Missing or invalid parameter: frame")
|
||||
return
|
||||
}
|
||||
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let sandbox = self?.sandboxes[sandboxId] else {
|
||||
call.reject("Sandbox not found: \(sandboxId)")
|
||||
return
|
||||
}
|
||||
sandbox.containerView.frame = CGRect(x: x, y: y, width: width, height: height)
|
||||
call.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
@objc func respondToFetch(_ call: CAPPluginCall) {
|
||||
guard let sandboxId = call.getString("id") else {
|
||||
call.reject("Missing required parameter: id")
|
||||
return
|
||||
}
|
||||
guard let requestId = call.getString("requestId") else {
|
||||
call.reject("Missing required parameter: requestId")
|
||||
return
|
||||
}
|
||||
guard let response = call.getObject("response") else {
|
||||
call.reject("Missing required parameter: response")
|
||||
return
|
||||
}
|
||||
|
||||
guard let sandbox = sandboxes[sandboxId] else {
|
||||
call.reject("Sandbox not found: \(sandboxId)")
|
||||
return
|
||||
}
|
||||
|
||||
sandbox.schemeHandler.resolveRequest(
|
||||
requestId: requestId,
|
||||
status: response["status"] as? Int ?? 200,
|
||||
statusText: response["statusText"] as? String ?? "OK",
|
||||
headers: response["headers"] as? [String: String] ?? [:],
|
||||
bodyBase64: response["body"] as? String
|
||||
)
|
||||
|
||||
call.resolve()
|
||||
}
|
||||
|
||||
@objc func postMessage(_ call: CAPPluginCall) {
|
||||
guard let sandboxId = call.getString("id") else {
|
||||
call.reject("Missing required parameter: id")
|
||||
return
|
||||
}
|
||||
guard let message = call.getObject("message") else {
|
||||
call.reject("Missing required parameter: message")
|
||||
return
|
||||
}
|
||||
|
||||
guard let sandbox = sandboxes[sandboxId] else {
|
||||
call.reject("Sandbox not found: \(sandboxId)")
|
||||
return
|
||||
}
|
||||
|
||||
DispatchQueue.main.async {
|
||||
sandbox.postMessageToWebView(message)
|
||||
}
|
||||
|
||||
call.resolve()
|
||||
}
|
||||
|
||||
@objc func destroy(_ call: CAPPluginCall) {
|
||||
guard let sandboxId = call.getString("id") else {
|
||||
call.reject("Missing required parameter: id")
|
||||
return
|
||||
}
|
||||
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self = self else { return }
|
||||
if let sandbox = self.sandboxes.removeValue(forKey: sandboxId) {
|
||||
sandbox.containerView.removeFromSuperview()
|
||||
sandbox.schemeHandler.cancelAll()
|
||||
}
|
||||
call.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Event Forwarding
|
||||
|
||||
/// Forward a fetch request from the native WebView to JS.
|
||||
func emitFetchRequest(sandboxId: String, requestId: String, request: [String: Any]) {
|
||||
notifyListeners("fetch", data: [
|
||||
"id": sandboxId,
|
||||
"requestId": requestId,
|
||||
"request": request,
|
||||
])
|
||||
}
|
||||
|
||||
/// Forward a script message from the sandbox to JS.
|
||||
func emitScriptMessage(sandboxId: String, message: [String: Any]) {
|
||||
notifyListeners("scriptMessage", data: [
|
||||
"id": sandboxId,
|
||||
"message": message,
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SandboxInstance
|
||||
|
||||
/// Manages a single sandboxed WKWebView instance.
|
||||
private class SandboxInstance: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
|
||||
let id: String
|
||||
let webView: WKWebView
|
||||
let schemeHandler: SandboxSchemeHandler
|
||||
private weak var plugin: SandboxPlugin?
|
||||
private let customScheme: String
|
||||
|
||||
/// Container view that holds the WebView and spinner overlay.
|
||||
let containerView: UIView
|
||||
|
||||
/// Native spinner overlay, removed when the first page finishes loading.
|
||||
private var spinnerOverlay: UIView?
|
||||
|
||||
init(id: String, frame: CGRect, plugin: SandboxPlugin) {
|
||||
self.id = id
|
||||
self.plugin = plugin
|
||||
|
||||
// Each sandbox gets a unique custom URL scheme so that WKWebView
|
||||
// assigns a distinct origin, isolating localStorage/IndexedDB/cookies.
|
||||
self.customScheme = "sbx-\(id)"
|
||||
|
||||
self.schemeHandler = SandboxSchemeHandler(
|
||||
sandboxId: id,
|
||||
scheme: self.customScheme,
|
||||
plugin: plugin
|
||||
)
|
||||
|
||||
let config = WKWebViewConfiguration()
|
||||
config.setURLSchemeHandler(self.schemeHandler, forURLScheme: self.customScheme)
|
||||
|
||||
// Add a script message handler for communication from injected scripts.
|
||||
let userContentController = WKUserContentController()
|
||||
|
||||
// Inject a bridge script that:
|
||||
// 1. Provides window.parent.postMessage()-like functionality
|
||||
// 2. Routes messages through the native bridge
|
||||
let bridgeScript = WKUserScript(
|
||||
source: SandboxInstance.bridgeScript(scheme: self.customScheme),
|
||||
injectionTime: .atDocumentStart,
|
||||
forMainFrameOnly: false
|
||||
)
|
||||
userContentController.addUserScript(bridgeScript)
|
||||
|
||||
config.userContentController = userContentController
|
||||
config.preferences.javaScriptCanOpenWindowsAutomatically = false
|
||||
config.defaultWebpagePreferences.allowsContentJavaScript = true
|
||||
|
||||
// Container view that holds the WebView + spinner overlay.
|
||||
self.containerView = UIView(frame: frame)
|
||||
|
||||
self.webView = WKWebView(frame: containerView.bounds, configuration: config)
|
||||
self.webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
self.webView.isOpaque = false
|
||||
self.webView.backgroundColor = UIColor(red: 0x14/255.0, green: 0x16/255.0, blue: 0x1f/255.0, alpha: 1)
|
||||
self.webView.scrollView.backgroundColor = self.webView.backgroundColor
|
||||
self.webView.scrollView.bounces = false
|
||||
self.containerView.addSubview(self.webView)
|
||||
|
||||
// Dark overlay behind the spinner.
|
||||
let overlay = UIView(frame: containerView.bounds)
|
||||
overlay.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
overlay.backgroundColor = UIColor(red: 0x14/255.0, green: 0x16/255.0, blue: 0x1f/255.0, alpha: 1)
|
||||
self.containerView.addSubview(overlay)
|
||||
|
||||
// Native spinner — uses UIActivityIndicatorView which animates on
|
||||
// the render thread independently of JS/main-thread work.
|
||||
let spinner = UIActivityIndicatorView(style: .medium)
|
||||
spinner.color = UIColor(red: 124/255.0, green: 92/255.0, blue: 220/255.0, alpha: 1)
|
||||
spinner.translatesAutoresizingMaskIntoConstraints = false
|
||||
spinner.startAnimating()
|
||||
overlay.addSubview(spinner)
|
||||
NSLayoutConstraint.activate([
|
||||
spinner.centerXAnchor.constraint(equalTo: overlay.centerXAnchor),
|
||||
spinner.centerYAnchor.constraint(equalTo: overlay.centerYAnchor),
|
||||
])
|
||||
|
||||
self.spinnerOverlay = overlay
|
||||
|
||||
super.init()
|
||||
|
||||
// Register the message handler and navigation delegate after super.init().
|
||||
userContentController.add(self, name: "sandboxBridge")
|
||||
self.webView.navigationDelegate = self
|
||||
}
|
||||
|
||||
/// Navigate the WebView to the sandbox's entry point.
|
||||
func navigateToApp() {
|
||||
let initialURL = URL(string: "\(customScheme)://app/index.html")!
|
||||
webView.load(URLRequest(url: initialURL))
|
||||
}
|
||||
|
||||
/// Remove the native loading overlay. Safe to call multiple times.
|
||||
func hideSpinner() {
|
||||
spinnerOverlay?.removeFromSuperview()
|
||||
spinnerOverlay = nil
|
||||
}
|
||||
|
||||
/// Post a JSON-RPC message to injected scripts inside the WebView.
|
||||
func postMessageToWebView(_ message: [String: Any]) {
|
||||
guard let jsonData = try? JSONSerialization.data(withJSONObject: message),
|
||||
let jsonString = String(data: jsonData, encoding: .utf8) else {
|
||||
return
|
||||
}
|
||||
|
||||
let js = """
|
||||
(function() {
|
||||
if (window.__sandboxBridge && window.__sandboxBridge.onMessage) {
|
||||
window.__sandboxBridge.onMessage(\(jsonString));
|
||||
}
|
||||
})();
|
||||
"""
|
||||
webView.evaluateJavaScript(js, completionHandler: nil)
|
||||
}
|
||||
|
||||
// MARK: - WKScriptMessageHandler
|
||||
|
||||
/// Receive messages from injected scripts via webkit.messageHandlers.sandboxBridge.
|
||||
func userContentController(
|
||||
_ userContentController: WKUserContentController,
|
||||
didReceive message: WKScriptMessage
|
||||
) {
|
||||
guard message.name == "sandboxBridge",
|
||||
let body = message.body as? [String: Any] else {
|
||||
return
|
||||
}
|
||||
plugin?.emitScriptMessage(sandboxId: id, message: body)
|
||||
}
|
||||
|
||||
// MARK: - WKNavigationDelegate
|
||||
|
||||
/// Remove the spinner overlay once the first page finishes loading.
|
||||
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
|
||||
hideSpinner()
|
||||
}
|
||||
|
||||
// MARK: - Bridge Script
|
||||
|
||||
/// JavaScript injected at document start that provides:
|
||||
/// - `window.parent.postMessage()` emulation via WKScriptMessageHandler
|
||||
/// - `window.__sandboxBridge.onMessage()` for receiving messages from parent
|
||||
/// - `window.addEventListener("message", ...)` support for injected scripts
|
||||
private static func bridgeScript(scheme: String) -> String {
|
||||
return """
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
// Message listeners registered by injected scripts.
|
||||
var messageListeners = [];
|
||||
|
||||
// Bridge object for native communication.
|
||||
window.__sandboxBridge = {
|
||||
onMessage: function(data) {
|
||||
// Dispatch to all registered message listeners.
|
||||
var event = {
|
||||
data: data,
|
||||
origin: '\(scheme)://app',
|
||||
source: window.parent,
|
||||
type: 'message'
|
||||
};
|
||||
for (var i = 0; i < messageListeners.length; i++) {
|
||||
try {
|
||||
messageListeners[i](event);
|
||||
} catch (e) {
|
||||
console.error('[SandboxBridge] Listener error:', e);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Override addEventListener to capture "message" listeners.
|
||||
var originalAddEventListener = window.addEventListener;
|
||||
window.addEventListener = function(type, listener, options) {
|
||||
if (type === 'message' && typeof listener === 'function') {
|
||||
messageListeners.push(listener);
|
||||
}
|
||||
return originalAddEventListener.call(window, type, listener, options);
|
||||
};
|
||||
|
||||
var originalRemoveEventListener = window.removeEventListener;
|
||||
window.removeEventListener = function(type, listener, options) {
|
||||
if (type === 'message') {
|
||||
var idx = messageListeners.indexOf(listener);
|
||||
if (idx !== -1) messageListeners.splice(idx, 1);
|
||||
}
|
||||
return originalRemoveEventListener.call(window, type, listener, options);
|
||||
};
|
||||
|
||||
// Emulate window.parent.postMessage for scripts that use it
|
||||
// (e.g. the webxdc bridge script, preview injected script).
|
||||
if (!window.parent || window.parent === window) {
|
||||
window.parent = {};
|
||||
}
|
||||
window.parent.postMessage = function(data, targetOrigin, transfer) {
|
||||
if (data && typeof data === 'object' && data.jsonrpc === '2.0') {
|
||||
try {
|
||||
window.webkit.messageHandlers.sandboxBridge.postMessage(data);
|
||||
} catch (e) {
|
||||
console.error('[SandboxBridge] postMessage failed:', e);
|
||||
}
|
||||
}
|
||||
};
|
||||
})();
|
||||
""";
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SandboxSchemeHandler
|
||||
|
||||
/// WKURLSchemeHandler that intercepts all requests on the sandbox's custom
|
||||
/// URL scheme and forwards them to the JS layer as fetch events.
|
||||
private class SandboxSchemeHandler: NSObject, WKURLSchemeHandler {
|
||||
private let sandboxId: String
|
||||
private let scheme: String
|
||||
private weak var plugin: SandboxPlugin?
|
||||
|
||||
/// Pending scheme tasks waiting for a response from JS.
|
||||
/// Key: requestId (UUID string), Value: the WKURLSchemeTask to respond to.
|
||||
private var pendingTasks: [String: WKURLSchemeTask] = [:]
|
||||
private let lock = NSLock()
|
||||
|
||||
init(sandboxId: String, scheme: String, plugin: SandboxPlugin) {
|
||||
self.sandboxId = sandboxId
|
||||
self.scheme = scheme
|
||||
self.plugin = plugin
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
|
||||
let request = urlSchemeTask.request
|
||||
guard let url = request.url else {
|
||||
urlSchemeTask.didFailWithError(NSError(
|
||||
domain: "SandboxPlugin", code: -1,
|
||||
userInfo: [NSLocalizedDescriptionKey: "No URL in request"]
|
||||
))
|
||||
return
|
||||
}
|
||||
|
||||
let requestId = UUID().uuidString
|
||||
|
||||
lock.lock()
|
||||
pendingTasks[requestId] = urlSchemeTask
|
||||
lock.unlock()
|
||||
|
||||
// Serialise the request for the fetch event.
|
||||
// Rewrite the URL so it looks like a normal HTTP URL to the parent
|
||||
// (e.g. "sbx-abc123://app/index.html" -> "https://<sandboxId>.sandbox.native/index.html")
|
||||
// The JS side only cares about the pathname.
|
||||
var headers: [String: String] = [:]
|
||||
if let allHeaders = request.allHTTPHeaderFields {
|
||||
headers = allHeaders
|
||||
}
|
||||
|
||||
var bodyBase64: String? = nil
|
||||
if let bodyData = request.httpBody {
|
||||
bodyBase64 = bodyData.base64EncodedString()
|
||||
}
|
||||
|
||||
let path = url.path.isEmpty ? "/" : url.path
|
||||
let rewrittenURL = "https://\(sandboxId).sandbox.native\(path)"
|
||||
|
||||
let serialisedRequest: [String: Any] = [
|
||||
"url": rewrittenURL,
|
||||
"method": request.httpMethod ?? "GET",
|
||||
"headers": headers,
|
||||
"body": bodyBase64 as Any,
|
||||
]
|
||||
|
||||
plugin?.emitFetchRequest(
|
||||
sandboxId: sandboxId,
|
||||
requestId: requestId,
|
||||
request: serialisedRequest
|
||||
)
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {
|
||||
// Remove the task from pending — JS response will be ignored if it arrives later.
|
||||
lock.lock()
|
||||
let removed = pendingTasks.first(where: { $0.value === urlSchemeTask })
|
||||
if let key = removed?.key {
|
||||
pendingTasks.removeValue(forKey: key)
|
||||
}
|
||||
lock.unlock()
|
||||
}
|
||||
|
||||
/// Called by the plugin when JS responds to a fetch request.
|
||||
func resolveRequest(
|
||||
requestId: String,
|
||||
status: Int,
|
||||
statusText: String,
|
||||
headers: [String: String],
|
||||
bodyBase64: String?
|
||||
) {
|
||||
lock.lock()
|
||||
guard let task = pendingTasks.removeValue(forKey: requestId) else {
|
||||
lock.unlock()
|
||||
return
|
||||
}
|
||||
lock.unlock()
|
||||
|
||||
// Decode the base64 body.
|
||||
var bodyData: Data? = nil
|
||||
if let b64 = bodyBase64 {
|
||||
bodyData = Data(base64Encoded: b64)
|
||||
}
|
||||
|
||||
// Build the response.
|
||||
// Use the task's original URL for the response.
|
||||
let responseURL = task.request.url ?? URL(string: "\(scheme)://app/")!
|
||||
let response = HTTPURLResponse(
|
||||
url: responseURL,
|
||||
statusCode: status,
|
||||
httpVersion: "HTTP/1.1",
|
||||
headerFields: headers
|
||||
)!
|
||||
|
||||
DispatchQueue.main.async {
|
||||
task.didReceive(response)
|
||||
if let data = bodyData {
|
||||
task.didReceive(data)
|
||||
}
|
||||
task.didFinish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Cancel all pending tasks (called on destroy).
|
||||
func cancelAll() {
|
||||
lock.lock()
|
||||
let tasks = pendingTasks
|
||||
pendingTasks.removeAll()
|
||||
lock.unlock()
|
||||
|
||||
for (_, task) in tasks {
|
||||
task.didFailWithError(NSError(
|
||||
domain: "SandboxPlugin", code: -999,
|
||||
userInfo: [NSLocalizedDescriptionKey: "Sandbox destroyed"]
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,9 +14,12 @@ let package = Package(
|
||||
.package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", exact: "8.2.0"),
|
||||
.package(name: "CapacitorApp", path: "../../../node_modules/@capacitor/app"),
|
||||
.package(name: "CapacitorFilesystem", path: "../../../node_modules/@capacitor/filesystem"),
|
||||
.package(name: "CapacitorHaptics", path: "../../../node_modules/@capacitor/haptics"),
|
||||
.package(name: "CapacitorKeyboard", path: "../../../node_modules/@capacitor/keyboard"),
|
||||
.package(name: "CapacitorLocalNotifications", path: "../../../node_modules/@capacitor/local-notifications"),
|
||||
.package(name: "CapacitorShare", path: "../../../node_modules/@capacitor/share"),
|
||||
.package(name: "CapacitorStatusBar", path: "../../../node_modules/@capacitor/status-bar")
|
||||
.package(name: "CapgoCapacitorAutofillSavePassword", path: "../../../node_modules/@capgo/capacitor-autofill-save-password"),
|
||||
.package(name: "CapacitorSecureStoragePlugin", path: "../../../node_modules/capacitor-secure-storage-plugin")
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
@@ -26,9 +29,12 @@ let package = Package(
|
||||
.product(name: "Cordova", package: "capacitor-swift-pm"),
|
||||
.product(name: "CapacitorApp", package: "CapacitorApp"),
|
||||
.product(name: "CapacitorFilesystem", package: "CapacitorFilesystem"),
|
||||
.product(name: "CapacitorHaptics", package: "CapacitorHaptics"),
|
||||
.product(name: "CapacitorKeyboard", package: "CapacitorKeyboard"),
|
||||
.product(name: "CapacitorLocalNotifications", package: "CapacitorLocalNotifications"),
|
||||
.product(name: "CapacitorShare", package: "CapacitorShare"),
|
||||
.product(name: "CapacitorStatusBar", package: "CapacitorStatusBar")
|
||||
.product(name: "CapgoCapacitorAutofillSavePassword", package: "CapgoCapacitorAutofillSavePassword"),
|
||||
.product(name: "CapacitorSecureStoragePlugin", package: "CapacitorSecureStoragePlugin")
|
||||
]
|
||||
)
|
||||
]
|
||||
|
||||
@@ -1,26 +1,28 @@
|
||||
{
|
||||
"name": "ditto",
|
||||
"private": true,
|
||||
"version": "2.1.1",
|
||||
"version": "2.6.6",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "npm i --silent && vite",
|
||||
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
|
||||
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'",
|
||||
"cap:sync": "npx cap sync && node scripts/patch-cap-config.mjs",
|
||||
"keygen": "keytool -genkey -v -keystore android/app/my-upload-key.keystore -keyalg RSA -keysize 2048 -validity 10000 -alias upload",
|
||||
"icons": "bash scripts/generate-icons.sh"
|
||||
},
|
||||
"engines": {
|
||||
"npm": "10.9.4",
|
||||
"node": "22.x"
|
||||
"node": ">=22"
|
||||
},
|
||||
"dependencies": {
|
||||
"@capacitor/app": "^8.0.0",
|
||||
"@capacitor/core": "^8.1.0",
|
||||
"@capacitor/filesystem": "^8.1.2",
|
||||
"@capacitor/haptics": "^8.0.2",
|
||||
"@capacitor/keyboard": "^8.0.3",
|
||||
"@capacitor/local-notifications": "^8.0.1",
|
||||
"@capacitor/share": "^8.0.1",
|
||||
"@capacitor/status-bar": "^8.0.0",
|
||||
"@capgo/capacitor-autofill-save-password": "^8.0.22",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
@@ -45,6 +47,7 @@
|
||||
"@fontsource/courier-prime": "^5.2.8",
|
||||
"@fontsource/creepster": "^5.2.7",
|
||||
"@fontsource/luckiest-guy": "^5.2.8",
|
||||
"@fontsource/noto-sans-nushu": "^5.2.6",
|
||||
"@fontsource/pacifico": "^5.2.7",
|
||||
"@fontsource/permanent-marker": "^5.2.7",
|
||||
"@fontsource/pirata-one": "^5.2.8",
|
||||
@@ -53,8 +56,19 @@
|
||||
"@fontsource/special-elite": "^5.2.8",
|
||||
"@getalby/sdk": "^5.1.1",
|
||||
"@hookform/resolvers": "^5.2.2",
|
||||
"@nostrify/nostrify": "^0.51.0",
|
||||
"@nostrify/react": "^0.3.1",
|
||||
"@milkdown/core": "^7.20.0",
|
||||
"@milkdown/ctx": "^7.20.0",
|
||||
"@milkdown/plugin-clipboard": "^7.20.0",
|
||||
"@milkdown/plugin-history": "^7.20.0",
|
||||
"@milkdown/plugin-listener": "^7.20.0",
|
||||
"@milkdown/plugin-upload": "^7.20.0",
|
||||
"@milkdown/preset-commonmark": "^7.20.0",
|
||||
"@milkdown/preset-gfm": "^7.20.0",
|
||||
"@milkdown/prose": "^7.20.0",
|
||||
"@milkdown/react": "^7.20.0",
|
||||
"@milkdown/utils": "^7.20.0",
|
||||
"@nostrify/nostrify": "^0.51.1",
|
||||
"@nostrify/react": "^0.5.1",
|
||||
"@nostrify/types": "^0.36.9",
|
||||
"@plausible-analytics/tracker": "^0.4.4",
|
||||
"@radix-ui/react-accordion": "^1.2.0",
|
||||
@@ -63,18 +77,18 @@
|
||||
"@radix-ui/react-avatar": "^1.1.0",
|
||||
"@radix-ui/react-checkbox": "^1.1.1",
|
||||
"@radix-ui/react-collapsible": "^1.1.0",
|
||||
"@radix-ui/react-context-menu": "^2.2.1",
|
||||
"@radix-ui/react-context-menu": "^2.2.16",
|
||||
"@radix-ui/react-dialog": "^1.1.2",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.1",
|
||||
"@radix-ui/react-hover-card": "^1.1.1",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||
"@radix-ui/react-hover-card": "^1.1.15",
|
||||
"@radix-ui/react-label": "^2.1.0",
|
||||
"@radix-ui/react-menubar": "^1.1.1",
|
||||
"@radix-ui/react-navigation-menu": "^1.2.0",
|
||||
"@radix-ui/react-popover": "^1.1.1",
|
||||
"@radix-ui/react-menubar": "^1.1.16",
|
||||
"@radix-ui/react-navigation-menu": "^1.2.14",
|
||||
"@radix-ui/react-popover": "^1.1.15",
|
||||
"@radix-ui/react-progress": "^1.1.0",
|
||||
"@radix-ui/react-radio-group": "^1.2.0",
|
||||
"@radix-ui/react-scroll-area": "^1.1.0",
|
||||
"@radix-ui/react-select": "^2.1.1",
|
||||
"@radix-ui/react-select": "^2.2.6",
|
||||
"@radix-ui/react-separator": "^1.1.0",
|
||||
"@radix-ui/react-slider": "^1.2.0",
|
||||
"@radix-ui/react-slot": "^1.1.0",
|
||||
@@ -83,13 +97,14 @@
|
||||
"@radix-ui/react-toast": "^1.2.1",
|
||||
"@radix-ui/react-toggle": "^1.1.0",
|
||||
"@radix-ui/react-toggle-group": "^1.1.0",
|
||||
"@radix-ui/react-tooltip": "^1.1.4",
|
||||
"@radix-ui/react-tooltip": "^1.2.8",
|
||||
"@sentry/react": "^10.42.0",
|
||||
"@tanstack/react-query": "^5.56.2",
|
||||
"@unhead/addons": "^2.0.10",
|
||||
"@unhead/react": "^2.0.10",
|
||||
"@unhead/addons": "^2.1.13",
|
||||
"@unhead/react": "^2.1.13",
|
||||
"blurhash": "^2.0.5",
|
||||
"buffer": "^6.0.3",
|
||||
"capacitor-secure-storage-plugin": "^0.13.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.0.0",
|
||||
@@ -99,15 +114,16 @@
|
||||
"emoji-mart": "^5.6.0",
|
||||
"fflate": "^0.8.2",
|
||||
"hls.js": "^1.6.15",
|
||||
"html-to-image": "^1.11.13",
|
||||
"idb": "^8.0.3",
|
||||
"input-otp": "^1.2.4",
|
||||
"lucide-react": "^0.462.0",
|
||||
"lucide-react": "^1.8.0",
|
||||
"nostr-tools": "^2.13.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^18.3.1",
|
||||
"react": "^19.2.4",
|
||||
"react-blurhash": "^0.3.0",
|
||||
"react-day-picker": "^8.10.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-day-picker": "^9.14.0",
|
||||
"react-dom": "^19.2.4",
|
||||
"react-easy-crop": "^5.5.6",
|
||||
"react-hook-form": "^7.71.1",
|
||||
"react-intersection-observer": "^9.16.0",
|
||||
@@ -116,11 +132,12 @@
|
||||
"react-router-dom": "^6.26.2",
|
||||
"recharts": "^2.12.7",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"slugify": "^1.6.8",
|
||||
"smol-toml": "^1.6.0",
|
||||
"tailwind-merge": "^2.5.2",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"uri-templates": "^0.2.0",
|
||||
"vaul": "^0.9.3",
|
||||
"vaul": "^1.1.2",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -131,13 +148,14 @@
|
||||
"@html-eslint/eslint-plugin": "^0.41.0",
|
||||
"@html-eslint/parser": "^0.41.0",
|
||||
"@tailwindcss/typography": "^0.5.15",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@testing-library/jest-dom": "^6.6.3",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"@types/dompurify": "^3.0.5",
|
||||
"@types/node": "^22.5.5",
|
||||
"@types/qrcode": "^1.5.5",
|
||||
"@types/react": "^18.3.1",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"@webbtc/webln-types": "^3.0.0",
|
||||
"@webxdc/types": "^2.1.2",
|
||||
@@ -148,10 +166,15 @@
|
||||
"globals": "^15.9.0",
|
||||
"jsdom": "^26.1.0",
|
||||
"postcss": "^8.4.47",
|
||||
"rollup-plugin-visualizer": "^7.0.1",
|
||||
"tailwindcss": "^3.4.11",
|
||||
"typescript": "^5.5.3",
|
||||
"typescript-eslint": "^8.0.1",
|
||||
"vite": "^8.0.0",
|
||||
"vite": "^8.0.3",
|
||||
"vitest": "^3.1.4"
|
||||
},
|
||||
"overrides": {
|
||||
"react": "$react",
|
||||
"react-dom": "$react-dom"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"webcredentials": {
|
||||
"apps": [
|
||||
"GZLTTH5DLM.pub.ditto.app"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,15 @@
|
||||
[{
|
||||
"relation": ["delegate_permission/common.handle_all_urls"],
|
||||
"target": {
|
||||
"namespace": "android_app",
|
||||
"package_name": "pub.ditto.app",
|
||||
"sha256_cert_fingerprints": ["7C:05:A8:5A:07:0F:84:AE:43:DE:85:67:A4:5F:7F:FB:42:0A:05:05:27:CE:B6:8C:DA:AF:A5:E0:12:E0:9E:71"]
|
||||
[
|
||||
{
|
||||
"relation": [
|
||||
"delegate_permission/common.handle_all_urls"
|
||||
],
|
||||
"target": {
|
||||
"namespace": "android_app",
|
||||
"package_name": "pub.ditto.app",
|
||||
"sha256_cert_fingerprints": [
|
||||
"7C:05:A8:5A:07:0F:84:AE:43:DE:85:67:A4:5F:7F:FB:42:0A:05:05:27:CE:B6:8C:DA:AF:A5:E0:12:E0:9E:71",
|
||||
"E5:B1:A9:13:C9:37:35:3C:A5:E7:27:89:C0:9D:3D:0D:A5:4F:F5:26:88:06:BD:24:46:21:AB:61:6B:CC:C5:E5"
|
||||
]
|
||||
}
|
||||
}
|
||||
}]
|
||||
]
|
||||
@@ -1,5 +1,367 @@
|
||||
# Changelog
|
||||
|
||||
## [2.6.6] - 2026-04-12
|
||||
|
||||
### Fixed
|
||||
- Emoji and mention autocomplete dropdowns no longer get clipped by the compose box
|
||||
- Emoji shortcodes now render as color emoji instead of plain text glyphs
|
||||
- Dialogs and input fields on Android are no longer obscured by the virtual keyboard
|
||||
- Signing requests on Android are more reliable and no longer silently fail after switching apps
|
||||
|
||||
## [2.6.5] - 2026-04-11
|
||||
|
||||
### Changed
|
||||
- Apps and games load significantly faster on Android with smarter prefetching and server affinity
|
||||
- Native loading spinners replace HTML-based ones on iOS and Android for a smoother experience
|
||||
|
||||
### Fixed
|
||||
- External API requests on Android no longer fail due to hostname restrictions
|
||||
- iOS App Store compliance issues resolved
|
||||
|
||||
## [2.6.4] - 2026-04-11
|
||||
|
||||
### Added
|
||||
- iCloud Keychain integration on iOS -- your login credentials are now saved and restored automatically across devices
|
||||
|
||||
### Changed
|
||||
- Empty feeds show a friendlier state with a discover button to help you find people to follow
|
||||
- Signup flow simplified -- cleaner profile step with a single Continue button
|
||||
|
||||
### Fixed
|
||||
- Avatar fallback now shows the user's initial instead of a question mark
|
||||
- Android 16+ devices no longer have content hidden behind system bars
|
||||
- Signup dialog background clears properly when switching between light and dark themes
|
||||
- Sticky compose button stays anchored to the bottom even on empty feeds
|
||||
|
||||
## [2.6.3] - 2026-04-10
|
||||
|
||||
### Added
|
||||
- Lightning invoices embedded in posts now render as tappable payment cards
|
||||
- Blobbi companions in the feed reflect their current condition and projected health
|
||||
|
||||
### Changed
|
||||
- Profile headers are cleaner -- lightning addresses and verification badges moved out of the way, and website URLs no longer show a trailing slash
|
||||
- Login credentials are saved to your browser's built-in password manager for easier sign-in across sessions
|
||||
- "Request to Vanish" renamed to "Delete Account" for clarity
|
||||
|
||||
### Fixed
|
||||
- Badge image uploads now show a recommended 1:1 aspect ratio hint so your badges don't get cropped unexpectedly
|
||||
- Security hardening for URLs and styles sourced from the network
|
||||
|
||||
## [2.6.2] - 2026-04-08
|
||||
|
||||
### Added
|
||||
- Share follow packs and follow sets via link -- recipients see an immersive preview with member avatars, a "Follow All" button, and a combined feed from everyone in the pack
|
||||
- Curated home feed with a mix of photos, short videos, livestreams, and music -- content types are spaced out so your timeline stays fresh and varied
|
||||
- "Write a letter" option on profile menus for a more personal way to reach out
|
||||
- Push vs persistent notification delivery option on Android
|
||||
|
||||
### Changed
|
||||
- Webxdc games and apps always open fullscreen for a more immersive experience
|
||||
- Login credentials are now stored in the device's secure keychain on iOS and Android instead of plain local storage
|
||||
- Profile fields now appear inline instead of in a separate right sidebar
|
||||
- Trending hashtags removed from the logged-out homepage for a cleaner first impression
|
||||
|
||||
### Fixed
|
||||
- Webxdc and nsites work natively on iOS and Android without relying on browser sandboxing tricks
|
||||
- File downloads now save directly to Documents on iOS and Android instead of silently failing
|
||||
- Mobile search no longer scrolls the page behind it and properly hides the bottom navigation bar
|
||||
- iOS swipe-back navigation works correctly throughout the app
|
||||
- Blobbi companions appear reliably on profiles instead of sometimes going missing
|
||||
- IndexedDB no longer crashes on devices with Lockdown Mode enabled
|
||||
|
||||
## [2.6.1] - 2026-04-06
|
||||
|
||||
### Added
|
||||
- Manage your interest tabs (hashtags and locations) from the settings page
|
||||
- Edit button on custom profile tabs so you can tweak them without recreating from scratch
|
||||
- Follow packs and follow sets now show author info and action headers in the feed
|
||||
- Posts now show whether they were created or updated, so you can tell when something's been edited
|
||||
|
||||
### Changed
|
||||
- Webxdc games and apps run in a more secure sandbox with stricter content policies and private subdomains
|
||||
- Nsite previews now use the same secure sandbox as webxdc apps
|
||||
- Blobbi items work as instant abilities instead of consumable inventory -- no more fiddly quantity pickers
|
||||
|
||||
### Fixed
|
||||
- Desktop tab bar no longer overflows when you have lots of tabs -- scroll arrows appear automatically
|
||||
- Mobile compose box no longer randomly collapses or becomes unclickable
|
||||
- Profile avatar and banner lightbox no longer hides behind the right sidebar
|
||||
- Infinite scroll on custom profile tab feeds no longer reloads the same content
|
||||
- Reaction emoji are now visible on each row in the interactions modal
|
||||
- Missing bottom border on collapsed thread expand button restored
|
||||
|
||||
## [2.6.0] - 2026-04-05
|
||||
|
||||
### Added
|
||||
- Follow links and QR codes -- share a link or scannable code that lets anyone follow you with one tap, complete with your themed profile preview and recent posts
|
||||
- Immersive Blobbi hatching ceremony -- crack your egg through cinematic stages with shaking animations, a burst of light, sparkles, typewriter dialog, and a naming moment
|
||||
|
||||
### Changed
|
||||
- Footer links redesigned as compact icon chips for a cleaner look
|
||||
- Custom emoji now render crisp at small sizes with pixel-perfect scaling
|
||||
|
||||
### Fixed
|
||||
- Custom themes now apply correctly when logging in on a new device
|
||||
- Settings and preferences sync reliably across devices
|
||||
- Mobile sidebar links no longer clip into the safe area
|
||||
- Blobbi page background overlay now appears properly on custom themes
|
||||
- Blobbi companion state no longer resets unexpectedly from stale cache data
|
||||
- Letter compose picker no longer gets hidden behind the top navigation arc
|
||||
|
||||
## [2.5.2] - 2026-04-04
|
||||
|
||||
### Added
|
||||
- See who voted on each poll option -- tap the vote count to open a voters list with avatar stacks and per-option filter tabs
|
||||
- Poll votes now appear as activity cards in feeds and on detail pages
|
||||
|
||||
### Fixed
|
||||
- Threads and replies load more reliably by following relay and author hints when fetching parent events
|
||||
|
||||
## [2.5.1] - 2026-04-03
|
||||
|
||||
### Fixed
|
||||
- Lightbox now reliably appears above all content, not just when opened from photo galleries
|
||||
|
||||
## [2.5.0] - 2026-04-03
|
||||
|
||||
### Added
|
||||
- Run nsites and web apps directly inside Ditto -- hit the "Run" button on any nsite or app card to preview it in an overlay without leaving your feed
|
||||
- File uploads in the poll composer -- attach images and media to your polls
|
||||
- Blobbi posts now appear in the homepage feed
|
||||
|
||||
### Changed
|
||||
- Profile media sidebar fills remaining slots with photos from text posts when there aren't enough dedicated media posts
|
||||
- App cards now show banner images and improved layout
|
||||
|
||||
### Fixed
|
||||
- Lightbox no longer appears behind the right sidebar
|
||||
- Compose box corners are properly rounded
|
||||
- Clicking buttons or links inside a post card no longer accidentally navigates to the post detail page
|
||||
|
||||
## [2.4.1] - 2026-04-02
|
||||
|
||||
### Added
|
||||
- Rich cards for Zapstore app releases and assets -- see download links, version info, platform badges, and hashes right in your feed
|
||||
|
||||
### Fixed
|
||||
- First-hatch tour now shows for accounts that were onboarded before the tour existed, so no one misses the hatching moment
|
||||
|
||||
## [2.4.0] - 2026-04-02
|
||||
|
||||
### Added
|
||||
- First-hatch tour: a guided experience for hatching your very first Blobbi egg, with progressive crack animations, an inline card flow, and a reveal moment
|
||||
- Customizable bottom bar: rearrange or hide any item in the navigation bar to make Ditto feel like yours
|
||||
- Mission surface card in the feed that surfaces your active quests at a glance
|
||||
|
||||
### Changed
|
||||
- Missions redesigned as a quest board with collapsible cards and a lighter aesthetic
|
||||
- "Edit Profile" mission now completes when you update any profile field, not just wall-specific edits
|
||||
- Media tab on profiles now shows only photos, videos, and other media -- not plain text posts
|
||||
- Blobbi onboarding state now syncs to your profile so it follows you across devices
|
||||
|
||||
### Fixed
|
||||
- Notification dot no longer reappears after you've already marked notifications as read
|
||||
- Dialogs no longer fly up when the mobile keyboard opens
|
||||
|
||||
## [2.3.1] - 2026-04-02
|
||||
|
||||
### Changed
|
||||
- Drafts now save instantly to your device and sync to relays in the background, with a cloud sync indicator so you always know the status
|
||||
|
||||
### Fixed
|
||||
- Dialogs stay visible above the keyboard on mobile instead of getting hidden behind it
|
||||
- Editing an existing article no longer incorrectly warns about a duplicate slug
|
||||
- Switching between rich text and markdown source mode no longer clears your content
|
||||
- Fix crash when editing in markdown source mode
|
||||
|
||||
## [2.3.0] - 2026-04-02
|
||||
|
||||
### Added
|
||||
- In-app article editor with a rich text toolbar, image uploads, auto-saving drafts, and a "My Articles" tab to manage drafts and published articles
|
||||
|
||||
### Fixed
|
||||
- Custom emoji no longer stretch to fill their container
|
||||
- Mobile drawer now closes when tapping footer links like Changelog or Privacy
|
||||
- Logged-out users now default to the global tab on content feeds instead of seeing an empty follows tab
|
||||
|
||||
## [2.2.11] - 2026-04-02
|
||||
|
||||
### Fixed
|
||||
- Fix crash caused by the "What's new" toast firing outside the router
|
||||
|
||||
## [2.2.10] - 2026-04-02
|
||||
|
||||
### Added
|
||||
- App cards for Nostr apps now display in feeds and detail pages with hero images, icons, and quick-launch buttons
|
||||
- "What's new" toast appears after an app update with a changelog preview and link to the full changelog
|
||||
|
||||
### Changed
|
||||
- Changelog page redesigned with a hero section for the latest release, collapsible older entries, and category icons inline with each item
|
||||
|
||||
### Fixed
|
||||
- Compose box now fully resets to its collapsed state after posting, including poll options and media trays
|
||||
|
||||
## [2.2.9] - 2026-04-01
|
||||
|
||||
### Added
|
||||
- Emoji pack creator and editor with drag-and-drop image upload, auto-generated identifiers, and description field
|
||||
- Blobbi companions now appear in feeds and post detail pages
|
||||
|
||||
### Changed
|
||||
- Blobbi shop redesigned with a tile layout and instant buy -- no more categories or accessory tabs
|
||||
- Emoji packs without any valid emojis are now hidden from feeds
|
||||
- Custom emoji shortcode collisions across packs are automatically resolved with pack-prefixed names
|
||||
|
||||
## [2.2.8] - 2026-04-01
|
||||
|
||||
### Added
|
||||
- Full threaded reply trees on post detail pages with collapsible deep branches and "Show X more replies" for sibling threads
|
||||
- Broadcast button in the Event JSON dialog to re-publish any event to your relays
|
||||
|
||||
### Changed
|
||||
- My Badges tab overhauled with drag-and-drop reordering, a scrollable list, and a showcase-style carousel for pending badges
|
||||
- Encrypted letter envelopes now show the mailing side first (sender and recipient), then flip to reveal the wax seal
|
||||
- Blobbi companions are more expressive -- richer status reactions, sleeping visuals, and body effects like dirt and hunger cues
|
||||
|
||||
### Fixed
|
||||
- Notification dot not clearing after marking notifications as read
|
||||
- Followers/following modal staying open after navigating to a profile
|
||||
|
||||
## [2.2.7] - 2026-03-31
|
||||
|
||||
### Fixed
|
||||
- Nushu script in encrypted letters now renders correctly on Android and iOS
|
||||
|
||||
## [2.2.6] - 2026-03-31
|
||||
|
||||
### Added
|
||||
- Encrypted letters now appear as interactive 3D envelopes with Nushu script -- flip and open them to reveal the secret writing inside
|
||||
- Zap receipts and profile metadata events now render in feeds and detail pages
|
||||
- Remote signer callback page for login flows with Amber, Primal, and other signing apps
|
||||
|
||||
### Changed
|
||||
- Post action buttons extracted into a reusable PostActionBar component
|
||||
- Badge detail page streamlined with unified tab bar
|
||||
|
||||
### Fixed
|
||||
- Hashtags now support accented and Unicode characters
|
||||
- Letter compose opens correctly from notifications and the letters page
|
||||
- Letter font picker loads fonts so each option previews in the correct typeface
|
||||
- Zap comment positioned inside the right column instead of floating with offset
|
||||
- Safe-area padding on pinned SubHeaderBar only applies when scrolled to top
|
||||
|
||||
## [2.2.5] - 2026-03-30
|
||||
|
||||
### Fixed
|
||||
- Crash when dragging profile tabs to reorder them
|
||||
|
||||
## [2.2.4] - 2026-03-30
|
||||
|
||||
### Changed
|
||||
- Profiles now have an emoji reaction button instead of a zap button -- express yourself with any emoji or custom emoji right on someone's profile
|
||||
- Zap moved to the profile overflow menu so it's still one tap away
|
||||
|
||||
### Fixed
|
||||
- Crash on the notifications page caused by malformed badge award tags
|
||||
- Deleting a badge now also deletes all awards you issued for it
|
||||
- Custom emoji reactions missing their image tag no longer render as broken shortcodes
|
||||
- Deletion requests for addressable events now include both `e` and `a` tags for broader relay compatibility
|
||||
- Profile reactions no longer collapse into a single grouped notification
|
||||
- Oversized reaction emoji in comment context headers
|
||||
|
||||
## [2.2.3] - 2026-03-30
|
||||
|
||||
### Added
|
||||
- Letters now have an overflow menu, reply button, and a grid layout for browsing
|
||||
- Independent feed toggles for comments and generic reposts in content settings
|
||||
- Sidebar items are now visible to logged-out users so newcomers can explore everything
|
||||
|
||||
### Changed
|
||||
- Compose textarea expands smoothly as you type instead of snapping to a new height
|
||||
- Blobbi stickers auto-shrink near card edges and clip cleanly at rounded boundaries
|
||||
|
||||
### Fixed
|
||||
- Feed gaps when replies are disabled no longer cause missing posts
|
||||
- Avatar shape no longer flashes on load
|
||||
- Top bar arc no longer flickers during navigation transitions
|
||||
- Letter drawing-only sends, sticker drag bounds, and theme event preservation
|
||||
- Notification rendering for badges and letters
|
||||
- Duplicate React keys in content settings
|
||||
- Layout rendering warning when switching views
|
||||
|
||||
## [2.2.2] - 2026-03-29
|
||||
|
||||
### Added
|
||||
- Dedicated photo upload flow for sharing photos
|
||||
- Pull-to-refresh on all feed pages
|
||||
- 3D tilt effect on badge images -- hover over badges to see them pop
|
||||
- Multi-select badge awarding with indicators for already-sent badges
|
||||
- Badge list recovery dialog for restoring profile badge lists
|
||||
- Compact badge row preview in embedded profile badges events
|
||||
- Custom emoji usage tracking so your most-used custom emojis appear in the quick-react bar
|
||||
- Release notes now included in Zapstore publishing
|
||||
- Changelog link in the app footer
|
||||
|
||||
### Changed
|
||||
- "Vines" renamed to "Divines" everywhere in the app
|
||||
- Custom emojis appear first in the emoji picker, right after recent
|
||||
- Threaded comment view now shows the parent event as a NoteCard with kind action headers
|
||||
|
||||
### Fixed
|
||||
- Delete post dialog no longer freezes the feed on desktop
|
||||
- Amber login on Android now properly retries when returning from the background
|
||||
- Key downloads on Android save to the correct location
|
||||
- Custom emoji SVGs render correctly in the emoji-mart picker
|
||||
- Double-tap reactions now properly show the emoji on the post
|
||||
- Emoji shortcode autocomplete text and highlight colors
|
||||
- Profile skeleton no longer flickers for brand-new users with no metadata
|
||||
- Event links now route correctly for all event types
|
||||
- Badge notifications are now clickable
|
||||
- Custom profile tab form no longer retains fields from a previously edited tab
|
||||
- Double line under profile tabs in edit mode
|
||||
- Inconsistent use of "geocache" vs "treasures" terminology
|
||||
- Search page "N new posts" pill no longer shows unfiltered count
|
||||
- Stale-cache overwrites in replaceable event mutations
|
||||
- Click-through on delete confirmation and note menu items
|
||||
|
||||
## [2.2.1] - 2026-03-28
|
||||
|
||||
### Fixed
|
||||
- New posts no longer cause scroll jumps -- they buffer while you're reading and appear with a tap
|
||||
- Mobile header no longer shows double-layered backgrounds on notched devices
|
||||
- Pinned tabs stay properly positioned when scrolling on mobile
|
||||
- Signer approval toasts no longer fire in rapid succession on unstable connections
|
||||
- Toasts are easier to swipe away on mobile
|
||||
- Content warnings now blur thumbnails in the media grid
|
||||
|
||||
## [2.2.0] - 2026-03-28
|
||||
|
||||
### Added
|
||||
- Blobbi virtual pets -- adopt an egg, hatch it, evolve it into one of 16 adult forms, and care for it with feeding, cleaning, medicine, music, and singing
|
||||
- Blobbi companion that follows you around the app, tracks your cursor, blinks, expresses emotions, and reacts to what you're doing
|
||||
- Blobbi shop and inventory system with items that affect your pet's stats
|
||||
- Daily missions with reroll, care streaks, and stage-based rewards
|
||||
- Immersive full-screen divines experience on both mobile and desktop with floating controls
|
||||
- Relay information panel on the network settings page
|
||||
- Link preview cards now display inside quoted posts instead of raw URLs
|
||||
- Nsec paste guard warns you before accidentally pasting private keys outside the login field
|
||||
- Remote signer UX improvements for Amber users on Android
|
||||
- Badge awards now trigger push notifications
|
||||
- Badges display in profile bio section with a "Give badge" option in the profile menu
|
||||
|
||||
### Changed
|
||||
- Notification "Mentions" tab now shows only pure mentions, filtering out replies
|
||||
- Notification preferences ("only from people I follow") now properly apply to push notifications, native Android notifications, and the unread dot
|
||||
- Upgraded from React 18 to React 19
|
||||
- Reduced initial bundle size by ~50% with improved code splitting and lazy loading
|
||||
|
||||
### Fixed
|
||||
- Zapping Primal users no longer produces an error
|
||||
- Hashtag feeds now match case-insensitively for parity with search results
|
||||
- Mobile top bar arc no longer lingers on pages without tabs
|
||||
- Give Badge dialog and profile menu action handlers
|
||||
|
||||
## [2.1.1] - 2026-03-27
|
||||
|
||||
### Added
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* NIP-46 Client-Initiated Auth Script
|
||||
*
|
||||
* Generates an ephemeral client keypair and a `nostrconnect://` URI.
|
||||
* Import the URI into a remote signer app (e.g. Amber) to authorize
|
||||
* the client key. Once authorized, the script outputs:
|
||||
*
|
||||
* - bunker:// URI (for ZAPSTORE_BUNKER_URL)
|
||||
* - client secret key hex (for ZAPSTORE_CLIENT_KEY)
|
||||
*
|
||||
* It also writes the client key to ~/.config/zsp/bunker-keys/<bunkerPubkey>.key
|
||||
* so that `zsp` can use it immediately.
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/nip46-auth.mjs [--relay wss://relay.example.com] [--name MyApp] [--timeout 300]
|
||||
*/
|
||||
|
||||
import { NPool, NRelay1, NConnectSigner, NSecSigner } from '@nostrify/nostrify';
|
||||
import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools';
|
||||
import { bytesToHex } from '@noble/hashes/utils';
|
||||
import QRCode from 'qrcode';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CLI args
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function parseArgs() {
|
||||
const args = process.argv.slice(2);
|
||||
const result = {
|
||||
relays: [],
|
||||
name: 'Ditto',
|
||||
timeout: 300, // seconds
|
||||
};
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
switch (args[i]) {
|
||||
case '--relay':
|
||||
result.relays.push(args[++i]);
|
||||
break;
|
||||
case '--name':
|
||||
result.name = args[++i];
|
||||
break;
|
||||
case '--timeout':
|
||||
result.timeout = parseInt(args[++i], 10);
|
||||
break;
|
||||
case '--help':
|
||||
case '-h':
|
||||
console.log(`Usage: node scripts/nip46-auth.mjs [options]
|
||||
|
||||
Options:
|
||||
--relay <url> Relay URL for NIP-46 communication (repeatable)
|
||||
Default: wss://relay.ditto.pub
|
||||
--name <name> Application name shown to the signer
|
||||
Default: Ditto
|
||||
--timeout <sec> How long to wait for signer approval (seconds)
|
||||
Default: 300 (5 minutes)
|
||||
--help, -h Show this help message
|
||||
`);
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
if (result.relays.length === 0) {
|
||||
result.relays.push('wss://relay.ditto.pub');
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Main
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function main() {
|
||||
const opts = parseArgs();
|
||||
|
||||
// 1. Generate ephemeral client keypair
|
||||
const clientSecretKey = generateSecretKey();
|
||||
const clientPubkey = getPublicKey(clientSecretKey);
|
||||
const clientHex = bytesToHex(clientSecretKey);
|
||||
|
||||
console.log('');
|
||||
console.log('=== NIP-46 Client-Initiated Auth ===');
|
||||
console.log('');
|
||||
console.log(`Client pubkey: ${clientPubkey}`);
|
||||
console.log(`Relay(s): ${opts.relays.join(', ')}`);
|
||||
console.log(`Timeout: ${opts.timeout}s`);
|
||||
console.log('');
|
||||
|
||||
// 2. Generate random secret
|
||||
const randomBytes = new Uint8Array(4);
|
||||
crypto.getRandomValues(randomBytes);
|
||||
const secret = Array.from(randomBytes)
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
|
||||
// 3. Build nostrconnect:// URI
|
||||
const searchParams = new URLSearchParams();
|
||||
for (const relay of opts.relays) {
|
||||
searchParams.append('relay', relay);
|
||||
}
|
||||
searchParams.set('secret', secret);
|
||||
searchParams.set('name', opts.name);
|
||||
|
||||
const nostrConnectURI = `nostrconnect://${clientPubkey}?${searchParams.toString()}`;
|
||||
|
||||
console.log('Scan this QR code with your signer app (e.g. Amber):');
|
||||
console.log('');
|
||||
console.log(await QRCode.toString(nostrConnectURI, { type: 'terminal', small: true }));
|
||||
console.log('Or import this URI manually:');
|
||||
console.log('');
|
||||
console.log(` ${nostrConnectURI}`);
|
||||
console.log('');
|
||||
console.log('Waiting for signer to approve the connection...');
|
||||
console.log('');
|
||||
|
||||
// 4. Set up relay pool
|
||||
const pool = new NPool({
|
||||
open: (url) => new NRelay1(url),
|
||||
reqRouter: async (filters) => new Map(opts.relays.map((r) => [r, filters])),
|
||||
eventRouter: async () => opts.relays,
|
||||
});
|
||||
|
||||
const clientSigner = new NSecSigner(clientSecretKey);
|
||||
const relayGroup = pool.group(opts.relays);
|
||||
|
||||
// 5. Subscribe and wait for the signer's response
|
||||
const signal = AbortSignal.timeout(opts.timeout * 1000);
|
||||
|
||||
const sub = relayGroup.req(
|
||||
[{ kinds: [24133], '#p': [clientPubkey], limit: 1 }],
|
||||
{ signal },
|
||||
);
|
||||
|
||||
let bunkerPubkey;
|
||||
let userPubkey;
|
||||
|
||||
try {
|
||||
for await (const msg of sub) {
|
||||
if (msg[0] === 'CLOSED') {
|
||||
throw new Error('Relay closed the subscription before signer responded');
|
||||
}
|
||||
if (msg[0] === 'EVENT') {
|
||||
const event = msg[2];
|
||||
|
||||
let decrypted;
|
||||
try {
|
||||
decrypted = await clientSigner.nip44.decrypt(event.pubkey, event.content);
|
||||
} catch {
|
||||
// Could not decrypt -- not for us, skip
|
||||
continue;
|
||||
}
|
||||
|
||||
let response;
|
||||
try {
|
||||
response = JSON.parse(decrypted);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (response.result !== secret && response.result !== 'ack') {
|
||||
continue;
|
||||
}
|
||||
|
||||
bunkerPubkey = event.pubkey;
|
||||
|
||||
console.log(`Signer responded! Bunker pubkey: ${bunkerPubkey}`);
|
||||
console.log('');
|
||||
|
||||
// 6. Get user pubkey via the now-established connection
|
||||
const signer = new NConnectSigner({
|
||||
relay: relayGroup,
|
||||
pubkey: bunkerPubkey,
|
||||
signer: clientSigner,
|
||||
timeout: 60_000,
|
||||
});
|
||||
|
||||
console.log('Requesting user public key...');
|
||||
userPubkey = await signer.getPublicKey();
|
||||
console.log(`User pubkey: ${userPubkey}`);
|
||||
console.log('');
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (err.name === 'TimeoutError' || err.name === 'AbortError') {
|
||||
console.error(`Timed out after ${opts.timeout}s waiting for signer approval.`);
|
||||
console.error('Make sure you imported the nostrconnect:// URI into your signer app.');
|
||||
process.exit(1);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (!bunkerPubkey || !userPubkey) {
|
||||
console.error('Failed to establish connection with remote signer.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// 7. Build bunker:// URI (for CI)
|
||||
const bunkerParams = new URLSearchParams();
|
||||
for (const relay of opts.relays) {
|
||||
bunkerParams.append('relay', relay);
|
||||
}
|
||||
const bunkerURI = `bunker://${bunkerPubkey}?${bunkerParams.toString()}`;
|
||||
|
||||
// 8. Write client key to zsp config
|
||||
const zspDir = path.join(os.homedir(), '.config', 'zsp', 'bunker-keys');
|
||||
const zspKeyFile = path.join(zspDir, `${bunkerPubkey}.key`);
|
||||
|
||||
fs.mkdirSync(zspDir, { recursive: true });
|
||||
fs.writeFileSync(zspKeyFile, clientHex + '\n', { mode: 0o600 });
|
||||
|
||||
// 9. Print results
|
||||
console.log('=== Connection Established ===');
|
||||
console.log('');
|
||||
console.log('Bunker URI (ZAPSTORE_BUNKER_URL):');
|
||||
console.log(` ${bunkerURI}`);
|
||||
console.log('');
|
||||
console.log('Client secret key hex (ZAPSTORE_CLIENT_KEY):');
|
||||
console.log(` ${clientHex}`);
|
||||
console.log('');
|
||||
console.log(`User pubkey: ${userPubkey}`);
|
||||
console.log(`User npub: ${nip19.npubEncode(userPubkey)}`);
|
||||
console.log('');
|
||||
console.log(`zsp client key written to: ${zspKeyFile}`);
|
||||
console.log('');
|
||||
console.log('Next steps:');
|
||||
console.log(' 1. Update ZAPSTORE_BUNKER_URL in GitLab CI/CD variables');
|
||||
console.log(' 2. Update ZAPSTORE_CLIENT_KEY in GitLab CI/CD variables');
|
||||
console.log('');
|
||||
|
||||
// Clean up
|
||||
pool.close();
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('Fatal error:', err.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Patch capacitor.config.json to include local (non-SPM) plugin classes.
|
||||
*
|
||||
* `npx cap sync` regenerates the `packageClassList` array from SPM packages
|
||||
* only, so local plugins compiled directly into the app binary (like
|
||||
* SandboxPlugin) are not included. This script appends them after sync so
|
||||
* the Capacitor bridge eagerly registers them at startup.
|
||||
*
|
||||
* Usage: node scripts/patch-cap-config.mjs
|
||||
* Typically run after `npx cap sync`.
|
||||
*/
|
||||
|
||||
import { readFileSync, writeFileSync } from 'fs';
|
||||
import { resolve } from 'path';
|
||||
|
||||
/** Local plugin class names to ensure are registered. */
|
||||
const LOCAL_PLUGINS = ['SandboxPlugin'];
|
||||
|
||||
const platforms = ['ios/App/App', 'android/app/src/main/assets'];
|
||||
|
||||
for (const platform of platforms) {
|
||||
const configPath = resolve(platform, 'capacitor.config.json');
|
||||
|
||||
let config;
|
||||
try {
|
||||
config = JSON.parse(readFileSync(configPath, 'utf-8'));
|
||||
} catch {
|
||||
// Platform may not exist or config not yet generated — skip.
|
||||
continue;
|
||||
}
|
||||
|
||||
const classList = new Set(config.packageClassList ?? []);
|
||||
let changed = false;
|
||||
|
||||
for (const plugin of LOCAL_PLUGINS) {
|
||||
if (!classList.has(plugin)) {
|
||||
classList.add(plugin);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
config.packageClassList = [...classList];
|
||||
writeFileSync(configPath, JSON.stringify(config, null, '\t') + '\n');
|
||||
console.log(`Patched ${configPath}: added ${LOCAL_PLUGINS.join(', ')}`);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
// NOTE: This file should normally not be modified unless you are adding a new provider.
|
||||
// To add new routes, edit the AppRouter.tsx file.
|
||||
|
||||
import { Capacitor } from "@capacitor/core";
|
||||
import { StatusBar, Style } from "@capacitor/status-bar";
|
||||
import { Capacitor, SystemBars, SystemBarsStyle } from "@capacitor/core";
|
||||
import { NostrLoginProvider } from "@nostrify/react/login";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { InferSeoMetaPlugin } from "@unhead/addons";
|
||||
@@ -16,15 +15,20 @@ import NostrProvider from "@/components/NostrProvider";
|
||||
import { NostrSync } from "@/components/NostrSync";
|
||||
import { PlausibleProvider } from "@/components/PlausibleProvider";
|
||||
import { SentryProvider } from "@/components/SentryProvider";
|
||||
import { Toaster } from "@/components/ui/toaster";
|
||||
|
||||
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { useNsecPasteGuard } from "@/hooks/useNsecPasteGuard";
|
||||
import type { AppConfig } from "@/contexts/AppContext";
|
||||
import { NWCProvider } from "@/contexts/NWCContext";
|
||||
import { PROTOCOL_MODE } from "@/lib/dmConstants";
|
||||
import { DittoConfigSchema, type DittoConfig } from "@/lib/schemas";
|
||||
import { secureStorage } from "@/lib/secureStorage";
|
||||
import { EmotionDevProvider } from "@/blobbi/dev/EmotionDevContext";
|
||||
import AppRouter from "./AppRouter";
|
||||
|
||||
const dmConfig: DMConfig = {
|
||||
enabled: true,
|
||||
enabled: false,
|
||||
protocolMode: PROTOCOL_MODE.NIP04_OR_NIP17,
|
||||
};
|
||||
|
||||
@@ -47,6 +51,7 @@ const hardcodedConfig: AppConfig = {
|
||||
appName: "Ditto",
|
||||
appId: "ditto",
|
||||
homePage: "feed",
|
||||
client: "naddr1qvzqqqru7cpzq7q6z5ns2hm5c8msyv83qwzxpxe52j8c4d4q5m92wsp9sflelkh9qqzkg6t5w3hswjl4yp",
|
||||
magicMouse: false,
|
||||
theme: "system",
|
||||
autoShareTheme: true,
|
||||
@@ -57,7 +62,9 @@ const hardcodedConfig: AppConfig = {
|
||||
},
|
||||
feedSettings: {
|
||||
feedIncludePosts: true,
|
||||
feedIncludeComments: true,
|
||||
feedIncludeReposts: true,
|
||||
feedIncludeGenericReposts: true,
|
||||
feedIncludeArticles: true,
|
||||
showArticles: true,
|
||||
showEvents: true,
|
||||
@@ -110,18 +117,18 @@ const hardcodedConfig: AppConfig = {
|
||||
feedIncludeBadgeDefinitions: true,
|
||||
feedIncludeProfileBadges: true,
|
||||
feedIncludeVanish: true,
|
||||
feedIncludeBlobbi: true,
|
||||
followsFeedShowReplies: true,
|
||||
},
|
||||
sidebarOrder: [
|
||||
"feed",
|
||||
"notifications",
|
||||
"search",
|
||||
"bookmarks",
|
||||
"profile",
|
||||
"photos",
|
||||
"videos",
|
||||
"blobbi",
|
||||
"badges",
|
||||
"emojis",
|
||||
"letters",
|
||||
"themes",
|
||||
"theme",
|
||||
"settings",
|
||||
"help",
|
||||
],
|
||||
@@ -142,28 +149,52 @@ const hardcodedConfig: AppConfig = {
|
||||
plausibleEndpoint: import.meta.env.VITE_PLAUSIBLE_ENDPOINT || "",
|
||||
savedFeeds: [],
|
||||
imageQuality: 'compressed',
|
||||
curatorPubkey: '932614571afcbad4d17a191ee281e39eebbb41b93fac8fd87829622aeb112f4d',
|
||||
sandboxDomain: 'iframe.diy',
|
||||
sidebarWidgets: [
|
||||
{ id: 'trends' },
|
||||
{ id: 'hot-posts' },
|
||||
{ id: 'wikipedia' },
|
||||
],
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse and validate build-time ditto.json overrides from the env string.
|
||||
* Returns an empty object when no config file was provided or validation fails.
|
||||
*/
|
||||
function parseDittoConfig(): DittoConfig {
|
||||
try {
|
||||
const json = JSON.parse(import.meta.env.DITTO_CONFIG);
|
||||
if (!json) return {};
|
||||
return DittoConfigSchema.parse(json);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge hardcoded defaults with build-time ditto.json overrides.
|
||||
* Deep-merges feedSettings so a partial override doesn't erase defaults.
|
||||
* Precedence (handled by AppProvider): user localStorage > build-time > hardcoded.
|
||||
*/
|
||||
const dittoConfig = parseDittoConfig();
|
||||
const defaultConfig: AppConfig = {
|
||||
...hardcodedConfig,
|
||||
...(typeof __DITTO_CONFIG__ !== "undefined" && __DITTO_CONFIG__
|
||||
? __DITTO_CONFIG__
|
||||
: {}),
|
||||
...dittoConfig,
|
||||
feedSettings: { ...hardcodedConfig.feedSettings, ...dittoConfig.feedSettings },
|
||||
};
|
||||
|
||||
export function App() {
|
||||
useNsecPasteGuard();
|
||||
|
||||
useEffect(() => {
|
||||
// Initialize StatusBar for mobile apps
|
||||
// Initialize system bars for mobile apps.
|
||||
// On Android 16+ (API 36), edge-to-edge is enforced by the OS so
|
||||
// setOverlaysWebView / setBackgroundColor no longer work. The new
|
||||
// SystemBars API (bundled with @capacitor/core 8+) is the replacement.
|
||||
if (Capacitor.isNativePlatform()) {
|
||||
StatusBar.setStyle({ style: Style.Dark }).catch(() => {
|
||||
// StatusBar may not be available on all platforms
|
||||
});
|
||||
StatusBar.setOverlaysWebView({ overlay: true }).catch(() => {
|
||||
// Ignore errors on unsupported platforms
|
||||
SystemBars.setStyle({ style: SystemBarsStyle.Dark }).catch(() => {
|
||||
// SystemBars may not be available on all platforms
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
@@ -174,18 +205,20 @@ export function App() {
|
||||
<SentryProvider>
|
||||
<PlausibleProvider>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<NostrLoginProvider storageKey="nostr:login">
|
||||
<NostrLoginProvider storageKey="nostr:login" storage={secureStorage}>
|
||||
<NostrProvider>
|
||||
<NostrSync />
|
||||
<NativeNotifications />
|
||||
|
||||
<NWCProvider>
|
||||
<DMProvider config={dmConfig}>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<InitialSyncGate>
|
||||
<AppRouter />
|
||||
</InitialSyncGate>
|
||||
</TooltipProvider>
|
||||
<EmotionDevProvider>
|
||||
<TooltipProvider>
|
||||
<InitialSyncGate>
|
||||
<AppRouter />
|
||||
</InitialSyncGate>
|
||||
</TooltipProvider>
|
||||
</EmotionDevProvider>
|
||||
</DMProvider>
|
||||
</NWCProvider>
|
||||
</NostrProvider>
|
||||
|
||||
@@ -1,62 +1,84 @@
|
||||
import { useState } from "react";
|
||||
import { lazy, Suspense, useState } from "react";
|
||||
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
|
||||
import { AudioNavigationGuard } from "@/components/AudioNavigationGuard";
|
||||
import { DeepLinkHandler } from "@/components/DeepLinkHandler";
|
||||
import { MinimizedAudioBar } from "@/components/MinimizedAudioBar";
|
||||
import { ReplyComposeModal } from "@/components/ReplyComposeModal";
|
||||
import { AudioPlayerProvider } from "@/contexts/AudioPlayerContext";
|
||||
import { BlobbiActionsProvider } from "@/blobbi/companion/interaction/BlobbiActionsProvider";
|
||||
import { sidebarItemIcon } from "@/lib/sidebarItems";
|
||||
import { Toaster } from "./components/ui/toaster";
|
||||
import { MainLayout } from "./components/MainLayout";
|
||||
import { ScrollToTop } from "./components/ScrollToTop";
|
||||
import { VersionCheck } from "./components/VersionCheck";
|
||||
import { useCurrentUser } from "./hooks/useCurrentUser";
|
||||
import { useProfileUrl } from "./hooks/useProfileUrl";
|
||||
import { getExtraKindDef } from "./lib/extraKinds";
|
||||
import { AdvancedSettingsPage } from "./pages/AdvancedSettingsPage";
|
||||
import { AIChatPage } from "./pages/AIChatPage";
|
||||
import { BadgesPage } from "./pages/BadgesPage";
|
||||
import { BookmarksPage } from "./pages/BookmarksPage";
|
||||
import { BooksPage } from "./pages/BooksPage";
|
||||
import { ContentPage } from "./pages/ContentPage";
|
||||
import { ContentSettingsPage } from "./pages/ContentSettingsPage";
|
||||
import { DomainFeedPage } from "./pages/DomainFeedPage";
|
||||
import { EventsFeedPage } from "./pages/EventsFeedPage";
|
||||
import { ExternalContentPage } from "./pages/ExternalContentPage";
|
||||
import { GeotagPage } from "./pages/GeotagPage";
|
||||
import { HashtagPage } from "./pages/HashtagPage";
|
||||
import { HelpPage } from "./pages/HelpPage";
|
||||
import { HomePage } from "./pages/HomePage";
|
||||
|
||||
// Critical-path pages: eagerly loaded (landing + fallback)
|
||||
import Index from "./pages/Index";
|
||||
import { KindFeedPage } from "./pages/KindFeedPage";
|
||||
import { MagicSettingsPage } from "./pages/MagicSettingsPage";
|
||||
import { MusicFeedPage } from "./pages/MusicFeedPage";
|
||||
import { NetworkSettingsPage } from "./pages/NetworkSettingsPage";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
import { NotificationSettings } from "./pages/NotificationSettings";
|
||||
import { NotificationsPage } from "./pages/NotificationsPage";
|
||||
import { PhotosFeedPage } from "./pages/PhotosFeedPage";
|
||||
import { PodcastsFeedPage } from "./pages/PodcastsFeedPage";
|
||||
import { CSAEPolicyPage } from "./pages/CSAEPolicyPage";
|
||||
import { PrivacyPolicyPage } from "./pages/PrivacyPolicyPage";
|
||||
import { ProfileSettings } from "./pages/ProfileSettings";
|
||||
import { RelayPage } from "./pages/RelayPage";
|
||||
import { SearchPage } from "./pages/SearchPage";
|
||||
import { SettingsPage } from "./pages/SettingsPage";
|
||||
import { ThemesPage } from "./pages/ThemesPage";
|
||||
import { TreasuresPage } from "./pages/TreasuresPage";
|
||||
import { TrendsPage } from "./pages/TrendsPage";
|
||||
import { UserListsPage } from "./pages/UserListsPage";
|
||||
import { VideosFeedPage } from "./pages/VideosFeedPage";
|
||||
import { VinesFeedPage } from "./pages/VinesFeedPage";
|
||||
import { WalletSettingsPage } from "./pages/WalletSettingsPage";
|
||||
import { WebxdcFeedPage } from "./pages/WebxdcFeedPage";
|
||||
import { WorldPage } from "./pages/WorldPage";
|
||||
import { ArchivePage } from "./pages/ArchivePage";
|
||||
import { BlueskyPage } from "./pages/BlueskyPage";
|
||||
import { ChangelogPage } from "./pages/ChangelogPage";
|
||||
import { WikipediaPage } from "./pages/WikipediaPage";
|
||||
import { LettersPage } from "./pages/LettersPage";
|
||||
import { LetterPreferencesPage } from "./pages/LetterPreferencesPage";
|
||||
|
||||
// Lazy-loaded companion layer (~450K code-split)
|
||||
const BlobbiCompanionLayer = lazy(() => import("@/blobbi/companion").then(m => ({ default: m.BlobbiCompanionLayer })));
|
||||
|
||||
// Lazy-loaded compose modal (pulls in emoji-mart ~620K)
|
||||
const ReplyComposeModal = lazy(() => import("@/components/ReplyComposeModal").then(m => ({ default: m.ReplyComposeModal })));
|
||||
|
||||
// Lazy-loaded emoji pack dialog
|
||||
const EmojiPackDialog = lazy(() => import("@/components/EmojiPackDialog").then(m => ({ default: m.EmojiPackDialog })));
|
||||
|
||||
// HomePage eagerly imported all page components; now lazy-loaded
|
||||
const HomePage = lazy(() => import("./pages/HomePage").then(m => ({ default: m.HomePage })));
|
||||
|
||||
// All other pages: code-split via React.lazy
|
||||
const AdvancedSettingsPage = lazy(() => import("./pages/AdvancedSettingsPage").then(m => ({ default: m.AdvancedSettingsPage })));
|
||||
const AIChatPage = lazy(() => import("./pages/AIChatPage").then(m => ({ default: m.AIChatPage })));
|
||||
const ArchivePage = lazy(() => import("./pages/ArchivePage").then(m => ({ default: m.ArchivePage })));
|
||||
const ArticleEditorPage = lazy(() => import("./pages/ArticleEditorPage").then(m => ({ default: m.ArticleEditorPage })));
|
||||
const BadgesPage = lazy(() => import("./pages/BadgesPage").then(m => ({ default: m.BadgesPage })));
|
||||
const BlobbiPage = lazy(() => import("./pages/BlobbiPage").then(m => ({ default: m.BlobbiPage })));
|
||||
const BlueskyPage = lazy(() => import("./pages/BlueskyPage").then(m => ({ default: m.BlueskyPage })));
|
||||
const BookmarksPage = lazy(() => import("./pages/BookmarksPage").then(m => ({ default: m.BookmarksPage })));
|
||||
const BooksPage = lazy(() => import("./pages/BooksPage").then(m => ({ default: m.BooksPage })));
|
||||
const ChangelogPage = lazy(() => import("./pages/ChangelogPage").then(m => ({ default: m.ChangelogPage })));
|
||||
const ContentPage = lazy(() => import("./pages/ContentPage").then(m => ({ default: m.ContentPage })));
|
||||
const ContentSettingsPage = lazy(() => import("./pages/ContentSettingsPage").then(m => ({ default: m.ContentSettingsPage })));
|
||||
const CSAEPolicyPage = lazy(() => import("./pages/CSAEPolicyPage").then(m => ({ default: m.CSAEPolicyPage })));
|
||||
const DomainFeedPage = lazy(() => import("./pages/DomainFeedPage").then(m => ({ default: m.DomainFeedPage })));
|
||||
const EventsFeedPage = lazy(() => import("./pages/EventsFeedPage").then(m => ({ default: m.EventsFeedPage })));
|
||||
const ExternalContentPage = lazy(() => import("./pages/ExternalContentPage").then(m => ({ default: m.ExternalContentPage })));
|
||||
const GeotagPage = lazy(() => import("./pages/GeotagPage").then(m => ({ default: m.GeotagPage })));
|
||||
const HashtagPage = lazy(() => import("./pages/HashtagPage").then(m => ({ default: m.HashtagPage })));
|
||||
const HelpPage = lazy(() => import("./pages/HelpPage").then(m => ({ default: m.HelpPage })));
|
||||
const KindFeedPage = lazy(() => import("./pages/KindFeedPage").then(m => ({ default: m.KindFeedPage })));
|
||||
const LetterComposePage = lazy(() => import("./pages/LetterComposePage").then(m => ({ default: m.LetterComposePage })));
|
||||
const LetterPreferencesPage = lazy(() => import("./pages/LetterPreferencesPage").then(m => ({ default: m.LetterPreferencesPage })));
|
||||
const LettersPage = lazy(() => import("./pages/LettersPage").then(m => ({ default: m.LettersPage })));
|
||||
const MagicSettingsPage = lazy(() => import("./pages/MagicSettingsPage").then(m => ({ default: m.MagicSettingsPage })));
|
||||
const MusicFeedPage = lazy(() => import("./pages/MusicFeedPage").then(m => ({ default: m.MusicFeedPage })));
|
||||
const NetworkSettingsPage = lazy(() => import("./pages/NetworkSettingsPage").then(m => ({ default: m.NetworkSettingsPage })));
|
||||
const NIP19Page = lazy(() => import("./pages/NIP19Page").then(m => ({ default: m.NIP19Page })));
|
||||
const NotificationSettings = lazy(() => import("./pages/NotificationSettings").then(m => ({ default: m.NotificationSettings })));
|
||||
const NotificationsPage = lazy(() => import("./pages/NotificationsPage").then(m => ({ default: m.NotificationsPage })));
|
||||
const PhotosFeedPage = lazy(() => import("./pages/PhotosFeedPage").then(m => ({ default: m.PhotosFeedPage })));
|
||||
const PodcastsFeedPage = lazy(() => import("./pages/PodcastsFeedPage").then(m => ({ default: m.PodcastsFeedPage })));
|
||||
const PrivacyPolicyPage = lazy(() => import("./pages/PrivacyPolicyPage").then(m => ({ default: m.PrivacyPolicyPage })));
|
||||
const ProfileSettings = lazy(() => import("./pages/ProfileSettings").then(m => ({ default: m.ProfileSettings })));
|
||||
const RelayPage = lazy(() => import("./pages/RelayPage").then(m => ({ default: m.RelayPage })));
|
||||
const SearchPage = lazy(() => import("./pages/SearchPage").then(m => ({ default: m.SearchPage })));
|
||||
const SettingsPage = lazy(() => import("./pages/SettingsPage").then(m => ({ default: m.SettingsPage })));
|
||||
const ThemesPage = lazy(() => import("./pages/ThemesPage").then(m => ({ default: m.ThemesPage })));
|
||||
const TreasuresPage = lazy(() => import("./pages/TreasuresPage").then(m => ({ default: m.TreasuresPage })));
|
||||
const TrendsPage = lazy(() => import("./pages/TrendsPage").then(m => ({ default: m.TrendsPage })));
|
||||
const UserListsPage = lazy(() => import("./pages/UserListsPage").then(m => ({ default: m.UserListsPage })));
|
||||
const VideosFeedPage = lazy(() => import("./pages/VideosFeedPage").then(m => ({ default: m.VideosFeedPage })));
|
||||
const VinesFeedPage = lazy(() => import("./pages/VinesFeedPage").then(m => ({ default: m.VinesFeedPage })));
|
||||
const WalletSettingsPage = lazy(() => import("./pages/WalletSettingsPage").then(m => ({ default: m.WalletSettingsPage })));
|
||||
const WebxdcFeedPage = lazy(() => import("./pages/WebxdcFeedPage").then(m => ({ default: m.WebxdcFeedPage })));
|
||||
const WikipediaPage = lazy(() => import("./pages/WikipediaPage").then(m => ({ default: m.WikipediaPage })));
|
||||
const WorldPage = lazy(() => import("./pages/WorldPage").then(m => ({ default: m.WorldPage })));
|
||||
const FollowPage = lazy(() => import("./pages/FollowPage").then(m => ({ default: m.FollowPage })));
|
||||
const RemoteLoginSuccessPage = lazy(() => import("./pages/RemoteLoginSuccessPage").then(m => ({ default: m.RemoteLoginSuccessPage })));
|
||||
|
||||
const pollsDef = getExtraKindDef("polls")!;
|
||||
const colorsDef = getExtraKindDef("colors")!;
|
||||
@@ -77,7 +99,31 @@ function PollsFeedPage() {
|
||||
icon={sidebarItemIcon("polls", "size-5")}
|
||||
onFabClick={() => setComposeOpen(true)}
|
||||
/>
|
||||
<ReplyComposeModal open={composeOpen} onOpenChange={setComposeOpen} initialMode="poll" />
|
||||
{composeOpen && (
|
||||
<Suspense fallback={null}>
|
||||
<ReplyComposeModal open={composeOpen} onOpenChange={setComposeOpen} initialMode="poll" />
|
||||
</Suspense>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Emoji feed page with a FAB that opens the emoji pack creation dialog. */
|
||||
function EmojiFeedPage() {
|
||||
const [composeOpen, setComposeOpen] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<KindFeedPage
|
||||
kind={emojisDef.kind}
|
||||
title={emojisDef.label}
|
||||
icon={sidebarItemIcon("emojis", "size-5")}
|
||||
onFabClick={() => setComposeOpen(true)}
|
||||
/>
|
||||
{composeOpen && (
|
||||
<Suspense fallback={null}>
|
||||
<EmojiPackDialog open={composeOpen} onOpenChange={setComposeOpen} />
|
||||
</Suspense>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -94,11 +140,21 @@ export function AppRouter() {
|
||||
return (
|
||||
<AudioPlayerProvider>
|
||||
<BrowserRouter>
|
||||
<Toaster />
|
||||
<VersionCheck />
|
||||
<MinimizedAudioBar />
|
||||
<AudioNavigationGuard />
|
||||
<DeepLinkHandler />
|
||||
<ScrollToTop />
|
||||
<BlobbiActionsProvider>
|
||||
<Suspense fallback={null}>
|
||||
<BlobbiCompanionLayer />
|
||||
</Suspense>
|
||||
</BlobbiActionsProvider>
|
||||
<Routes>
|
||||
{/* Auto-follow deep link: fullscreen immersive (no sidebars/nav) */}
|
||||
<Route path="/follow/:npub" element={<FollowPage />} />
|
||||
|
||||
{/* All routes share the persistent MainLayout (sidebar + nav) */}
|
||||
<Route element={<MainLayout />}>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
@@ -160,6 +216,8 @@ export function AppRouter() {
|
||||
}
|
||||
/>
|
||||
<Route path="/webxdc" element={<WebxdcFeedPage />} />
|
||||
<Route path="/articles/new" element={<ArticleEditorPage />} />
|
||||
<Route path="/articles/edit/:naddr" element={<ArticleEditorPage />} />
|
||||
<Route
|
||||
path="/articles"
|
||||
element={
|
||||
@@ -167,6 +225,7 @@ export function AppRouter() {
|
||||
kind={articlesDef.kind}
|
||||
title={articlesDef.label}
|
||||
icon={sidebarItemIcon("articles", "size-5")}
|
||||
fabHref="/articles/new"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
@@ -180,16 +239,7 @@ export function AppRouter() {
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/emojis"
|
||||
element={
|
||||
<KindFeedPage
|
||||
kind={emojisDef.kind}
|
||||
title={emojisDef.label}
|
||||
icon={sidebarItemIcon("emojis", "size-5")}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Route path="/emojis" element={<EmojiFeedPage />} />
|
||||
<Route
|
||||
path="/development"
|
||||
element={
|
||||
@@ -207,6 +257,7 @@ export function AppRouter() {
|
||||
<Route path="/themes" element={<ThemesPage />} />
|
||||
<Route path="/bookmarks" element={<BookmarksPage />} />
|
||||
<Route path="/ai-chat" element={<AIChatPage />} />
|
||||
<Route path="/blobbi" element={<BlobbiPage />} />
|
||||
<Route path="/world" element={<WorldPage />} />
|
||||
<Route path="/badges" element={<BadgesPage />} />
|
||||
<Route path="/books" element={<BooksPage />} />
|
||||
@@ -214,6 +265,7 @@ export function AppRouter() {
|
||||
<Route path="/bluesky" element={<BlueskyPage />} />
|
||||
<Route path="/wikipedia" element={<WikipediaPage />} />
|
||||
<Route path="/letters" element={<LettersPage />} />
|
||||
<Route path="/letters/compose" element={<LetterComposePage />} />
|
||||
<Route path="/settings/letters" element={<LetterPreferencesPage />} />
|
||||
<Route path="/help" element={<HelpPage />} />
|
||||
<Route path="/privacy" element={<PrivacyPolicyPage />} />
|
||||
@@ -226,6 +278,8 @@ export function AppRouter() {
|
||||
/>
|
||||
<Route path="/i/*" element={<ExternalContentPage />} />
|
||||
|
||||
{/* Callback target for remote signers (e.g. Amber, Primal) after NIP-46 approval */}
|
||||
<Route path="/remoteloginsuccess" element={<RemoteLoginSuccessPage />} />
|
||||
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
|
||||
<Route path="/:nip19" element={<NIP19Page />} />
|
||||
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
// src/blobbi/actions/components/BlobbiActionInventoryModal.tsx
|
||||
|
||||
import { useMemo } from 'react';
|
||||
import { Loader2, X } from 'lucide-react';
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogClose,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
import type { BlobbiCompanion, BlobbonautProfile } from '@/blobbi/core/lib/blobbi';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
import {
|
||||
filterInventoryByAction,
|
||||
previewStatChanges,
|
||||
previewMedicineForEgg,
|
||||
previewCleanForEgg,
|
||||
canUseAction,
|
||||
getStageRestrictionMessage,
|
||||
ACTION_METADATA,
|
||||
type InventoryAction,
|
||||
type ResolvedInventoryItem,
|
||||
type EggStatPreview,
|
||||
} from '../lib/blobbi-action-utils';
|
||||
|
||||
interface BlobbiActionInventoryModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
action: InventoryAction;
|
||||
companion: BlobbiCompanion;
|
||||
profile: BlobbonautProfile | null;
|
||||
/** Called when user taps Use on an item. Always uses once. */
|
||||
onUseItem: (itemId: string) => void;
|
||||
onOpenShop: () => void;
|
||||
isUsingItem: boolean;
|
||||
usingItemId: string | null;
|
||||
}
|
||||
|
||||
export function BlobbiActionInventoryModal({
|
||||
open,
|
||||
onOpenChange,
|
||||
action,
|
||||
companion,
|
||||
profile: _profile,
|
||||
onUseItem,
|
||||
onOpenShop: _onOpenShop,
|
||||
isUsingItem,
|
||||
usingItemId,
|
||||
}: BlobbiActionInventoryModalProps) {
|
||||
const actionMeta = ACTION_METADATA[action];
|
||||
|
||||
// Get all available items for this action from the catalog (not inventory).
|
||||
// Items are abilities/tools — no ownership required.
|
||||
const availableItems = useMemo(() => {
|
||||
return filterInventoryByAction([], action, { stage: companion.stage });
|
||||
}, [action, companion.stage]);
|
||||
|
||||
// Check stage restrictions for this specific action
|
||||
const canUse = canUseAction(companion, action);
|
||||
const stageMessage = getStageRestrictionMessage(companion, action);
|
||||
|
||||
const isEmpty = availableItems.length === 0;
|
||||
|
||||
const handleUseItem = (item: ResolvedInventoryItem) => {
|
||||
if (isUsingItem) return;
|
||||
onUseItem(item.itemId);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md w-[calc(100%-2rem)] max-h-[85vh] flex flex-col p-0 gap-0 [&>button:last-child]:hidden">
|
||||
{/* Header - Sticky */}
|
||||
<DialogHeader className="sticky top-0 z-10 bg-background px-4 sm:px-6 pt-4 sm:pt-6 pb-3 sm:pb-4 border-b">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<div className="size-9 sm:size-10 rounded-xl bg-gradient-to-br from-primary/20 to-primary/5 flex items-center justify-center text-xl sm:text-2xl shrink-0">
|
||||
{actionMeta.icon}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<DialogTitle className="text-lg sm:text-xl">{actionMeta.label}</DialogTitle>
|
||||
<p className="text-xs sm:text-sm text-muted-foreground truncate">
|
||||
{actionMeta.description}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<DialogClose className="rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 shrink-0">
|
||||
<X className="size-5" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogClose>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Content - Scrollable */}
|
||||
<div className="flex-1 min-h-0 overflow-y-auto px-4 sm:px-6 py-3 sm:py-4">
|
||||
{/* Stage Restriction Message */}
|
||||
{!canUse && stageMessage && (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<div className="size-16 rounded-2xl bg-amber-500/10 flex items-center justify-center mb-4">
|
||||
<span className="text-3xl">🥚</span>
|
||||
</div>
|
||||
<h3 className="text-lg font-semibold mb-2">Not Available</h3>
|
||||
<p className="text-sm text-muted-foreground max-w-sm">
|
||||
{stageMessage}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Empty State */}
|
||||
{canUse && isEmpty && (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<div className="size-16 rounded-2xl bg-muted/50 flex items-center justify-center mb-4">
|
||||
<span className="text-3xl">{actionMeta.icon}</span>
|
||||
</div>
|
||||
<h3 className="text-lg font-semibold mb-2">No Items Available</h3>
|
||||
<p className="text-sm text-muted-foreground max-w-sm">
|
||||
No items are available for this action at your Blobbi's current stage.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Item List */}
|
||||
{canUse && !isEmpty && (
|
||||
<div className="grid gap-3">
|
||||
{availableItems.map((item) => (
|
||||
<BlobbiInventoryUseRow
|
||||
key={item.itemId}
|
||||
item={item}
|
||||
companion={companion}
|
||||
action={action}
|
||||
onUse={() => handleUseItem(item)}
|
||||
isUsing={isUsingItem && usingItemId === item.itemId}
|
||||
disabled={isUsingItem}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Inventory Use Row ────────────────────────────────────────────────────────
|
||||
|
||||
interface BlobbiInventoryUseRowProps {
|
||||
item: ResolvedInventoryItem;
|
||||
companion: BlobbiCompanion;
|
||||
action: InventoryAction;
|
||||
onUse: () => void;
|
||||
isUsing: boolean;
|
||||
disabled: boolean;
|
||||
}
|
||||
|
||||
function BlobbiInventoryUseRow({
|
||||
item,
|
||||
companion,
|
||||
action,
|
||||
onUse,
|
||||
isUsing,
|
||||
disabled,
|
||||
}: BlobbiInventoryUseRowProps) {
|
||||
const isEgg = companion.stage === 'egg';
|
||||
const isMedicine = action === 'medicine';
|
||||
const isClean = action === 'clean';
|
||||
|
||||
// Preview stat changes - handle egg-specific preview for medicine and clean
|
||||
const { normalStatChanges, eggStatChanges } = useMemo(() => {
|
||||
if (isEgg && isMedicine) {
|
||||
return {
|
||||
normalStatChanges: [],
|
||||
eggStatChanges: previewMedicineForEgg(companion.stats.health, item.effect),
|
||||
};
|
||||
}
|
||||
if (isEgg && isClean) {
|
||||
return {
|
||||
normalStatChanges: [],
|
||||
eggStatChanges: previewCleanForEgg(
|
||||
{ hygiene: companion.stats.hygiene, happiness: companion.stats.happiness },
|
||||
item.effect
|
||||
),
|
||||
};
|
||||
}
|
||||
return {
|
||||
normalStatChanges: previewStatChanges(companion.stats, item.effect),
|
||||
eggStatChanges: [] as EggStatPreview[],
|
||||
};
|
||||
}, [companion.stats, item.effect, isEgg, isMedicine, isClean]);
|
||||
|
||||
const hasChanges = normalStatChanges.length > 0 || eggStatChanges.length > 0;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-4 p-3 sm:p-4 rounded-xl border bg-card/60 backdrop-blur-sm hover:border-primary/30 transition-colors">
|
||||
{/* Top row on mobile: Icon + Info + Button */}
|
||||
<div className="flex items-center gap-3 sm:contents">
|
||||
{/* Item Icon */}
|
||||
<div className="relative shrink-0">
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-primary/20 to-primary/5 rounded-full blur-xl" />
|
||||
<div className="relative size-10 sm:size-14 rounded-full bg-gradient-to-br from-primary/10 to-primary/5 flex items-center justify-center text-2xl sm:text-3xl">
|
||||
{item.icon}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Item Info */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-0.5 sm:mb-1">
|
||||
<h3 className="font-semibold text-sm sm:text-base truncate">{item.name}</h3>
|
||||
</div>
|
||||
|
||||
{/* Effect Preview - shown inline on desktop */}
|
||||
<div className="hidden sm:block">
|
||||
{hasChanges && (
|
||||
<div className="flex flex-wrap gap-x-3 gap-y-1">
|
||||
{normalStatChanges.map(({ stat, delta }) => (
|
||||
<span key={stat} className="text-xs">
|
||||
<span
|
||||
className={cn(
|
||||
'font-medium',
|
||||
delta > 0
|
||||
? 'text-emerald-600 dark:text-emerald-400'
|
||||
: 'text-red-600 dark:text-red-400'
|
||||
)}
|
||||
>
|
||||
{delta > 0 ? '+' : ''}
|
||||
{delta}
|
||||
</span>{' '}
|
||||
<span className="text-muted-foreground capitalize">
|
||||
{stat.replace('_', ' ')}
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
{eggStatChanges.map(({ stat, delta }) => (
|
||||
<span key={stat} className="text-xs">
|
||||
<span
|
||||
className={cn(
|
||||
'font-medium',
|
||||
delta > 0
|
||||
? 'text-emerald-600 dark:text-emerald-400'
|
||||
: 'text-red-600 dark:text-red-400'
|
||||
)}
|
||||
>
|
||||
{delta > 0 ? '+' : ''}
|
||||
{delta}
|
||||
</span>{' '}
|
||||
<span className="text-muted-foreground capitalize">
|
||||
{stat.replace('_', ' ')}
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Use Button */}
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={onUse}
|
||||
disabled={disabled}
|
||||
className="shrink-0"
|
||||
>
|
||||
{isUsing ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
'Use'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Effect Preview - shown below on mobile */}
|
||||
{hasChanges && (
|
||||
<div className="sm:hidden flex flex-wrap gap-x-3 gap-y-1 pl-13">
|
||||
{normalStatChanges.map(({ stat, delta }) => (
|
||||
<span key={stat} className="text-xs">
|
||||
<span
|
||||
className={cn(
|
||||
'font-medium',
|
||||
delta > 0
|
||||
? 'text-emerald-600 dark:text-emerald-400'
|
||||
: 'text-red-600 dark:text-red-400'
|
||||
)}
|
||||
>
|
||||
{delta > 0 ? '+' : ''}
|
||||
{delta}
|
||||
</span>{' '}
|
||||
<span className="text-muted-foreground capitalize">
|
||||
{stat.replace('_', ' ')}
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
{eggStatChanges.map(({ stat, delta }) => (
|
||||
<span key={stat} className="text-xs">
|
||||
<span
|
||||
className={cn(
|
||||
'font-medium',
|
||||
delta > 0
|
||||
? 'text-emerald-600 dark:text-emerald-400'
|
||||
: 'text-red-600 dark:text-red-400'
|
||||
)}
|
||||
>
|
||||
{delta > 0 ? '+' : ''}
|
||||
{delta}
|
||||
</span>{' '}
|
||||
<span className="text-muted-foreground capitalize">
|
||||
{stat.replace('_', ' ')}
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
// src/blobbi/actions/components/BlobbiActionsModal.tsx
|
||||
|
||||
import { Loader2, Moon, Sun, Utensils, Gamepad2, Sparkles as SparklesIcon, Pill, Music, Mic, X } from 'lucide-react';
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogClose,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
import type { BlobbiCompanion } from '@/blobbi/core/lib/blobbi';
|
||||
import type { InventoryAction, DirectAction } from '../lib/blobbi-action-utils';
|
||||
|
||||
interface BlobbiActionsModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
companion: BlobbiCompanion;
|
||||
onRest: () => void;
|
||||
onInventoryAction: (action: InventoryAction) => void;
|
||||
onDirectAction: (action: DirectAction) => void;
|
||||
actionInProgress: string | null;
|
||||
isPublishing: boolean;
|
||||
}
|
||||
|
||||
export function BlobbiActionsModal({
|
||||
open,
|
||||
onOpenChange,
|
||||
companion,
|
||||
onRest,
|
||||
onInventoryAction,
|
||||
onDirectAction,
|
||||
actionInProgress,
|
||||
isPublishing,
|
||||
}: BlobbiActionsModalProps) {
|
||||
const isSleeping = companion.state === 'sleeping';
|
||||
const isDisabled = isPublishing || actionInProgress !== null;
|
||||
const isEgg = companion.stage === 'egg';
|
||||
|
||||
const handleAction = (action: () => void) => {
|
||||
action();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-sm w-[calc(100%-2rem)] max-h-[85vh] flex flex-col p-0 gap-0 [&>button:last-child]:hidden">
|
||||
{/* Header - Sticky */}
|
||||
<DialogHeader className="sticky top-0 z-10 bg-background px-4 sm:px-6 pt-4 sm:pt-6 pb-3 sm:pb-4 border-b">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<DialogTitle>Blobbi Actions</DialogTitle>
|
||||
<p className="text-sm text-muted-foreground">{companion.name}</p>
|
||||
</div>
|
||||
<DialogClose className="rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2">
|
||||
<X className="size-5" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogClose>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
{/* Content - Scrollable */}
|
||||
<div className="flex-1 min-h-0 overflow-y-auto px-4 sm:px-6 py-3 sm:py-4">
|
||||
<div className="grid gap-3">
|
||||
{/* Feed Action - hidden for eggs */}
|
||||
{!isEgg && (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start gap-3 h-14"
|
||||
onClick={() => handleAction(() => onInventoryAction('feed'))}
|
||||
disabled={isDisabled}
|
||||
>
|
||||
<Utensils className="size-5 text-orange-500" />
|
||||
<div className="text-left">
|
||||
<p className="font-medium">Feed</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Give your Blobbi something to eat
|
||||
</p>
|
||||
</div>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Play Action - hidden for eggs */}
|
||||
{!isEgg && (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start gap-3 h-14"
|
||||
onClick={() => handleAction(() => onInventoryAction('play'))}
|
||||
disabled={isDisabled}
|
||||
>
|
||||
<Gamepad2 className="size-5 text-yellow-500" />
|
||||
<div className="text-left">
|
||||
<p className="font-medium">Play</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Play with toys to make your Blobbi happy
|
||||
</p>
|
||||
</div>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Clean Action - available for all stages */}
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start gap-3 h-14"
|
||||
onClick={() => handleAction(() => onInventoryAction('clean'))}
|
||||
disabled={isDisabled}
|
||||
>
|
||||
<SparklesIcon className="size-5 text-blue-500" />
|
||||
<div className="text-left">
|
||||
<p className="font-medium">Clean</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{isEgg
|
||||
? 'Keep your egg clean and fresh'
|
||||
: 'Keep your Blobbi clean and fresh'}
|
||||
</p>
|
||||
</div>
|
||||
</Button>
|
||||
|
||||
{/* Medicine Action - available for all stages */}
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start gap-3 h-14"
|
||||
onClick={() => handleAction(() => onInventoryAction('medicine'))}
|
||||
disabled={isDisabled}
|
||||
>
|
||||
<Pill className="size-5 text-green-500" />
|
||||
<div className="text-left">
|
||||
<p className="font-medium">Medicine</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{isEgg
|
||||
? 'Keep your egg healthy'
|
||||
: 'Heal your Blobbi'}
|
||||
</p>
|
||||
</div>
|
||||
</Button>
|
||||
|
||||
{/* Play Music Action - available for all stages */}
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start gap-3 h-14"
|
||||
onClick={() => handleAction(() => onDirectAction('play_music'))}
|
||||
disabled={isDisabled}
|
||||
>
|
||||
<Music className="size-5 text-pink-500" />
|
||||
<div className="text-left">
|
||||
<p className="font-medium">Play Music</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{isEgg
|
||||
? 'Play soothing music for your egg'
|
||||
: 'Play music for your Blobbi'}
|
||||
</p>
|
||||
</div>
|
||||
</Button>
|
||||
|
||||
{/* Sing Action - available for all stages */}
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start gap-3 h-14"
|
||||
onClick={() => handleAction(() => onDirectAction('sing'))}
|
||||
disabled={isDisabled}
|
||||
>
|
||||
<Mic className="size-5 text-purple-500" />
|
||||
<div className="text-left">
|
||||
<p className="font-medium">Sing</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{isEgg
|
||||
? 'Sing a lullaby to your egg'
|
||||
: 'Sing to your Blobbi'}
|
||||
</p>
|
||||
</div>
|
||||
</Button>
|
||||
|
||||
{/* Sleep/Wake Action - hidden for eggs */}
|
||||
{!isEgg && (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start gap-3 h-14"
|
||||
onClick={() => handleAction(onRest)}
|
||||
disabled={isDisabled}
|
||||
>
|
||||
{actionInProgress === 'rest' ? (
|
||||
<Loader2 className="size-5 animate-spin" />
|
||||
) : isSleeping ? (
|
||||
<Sun className="size-5 text-amber-500" />
|
||||
) : (
|
||||
<Moon className="size-5 text-violet-500" />
|
||||
)}
|
||||
<div className="text-left">
|
||||
<p className="font-medium">{isSleeping ? 'Wake Up' : 'Sleep'}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{isSleeping ? 'Wake your Blobbi up' : 'Put your Blobbi to sleep'}
|
||||
</p>
|
||||
</div>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,538 @@
|
||||
// src/blobbi/actions/components/BlobbiMissionsModal.tsx
|
||||
|
||||
/**
|
||||
* Missions modal for Blobbi — card-grid quest board.
|
||||
*
|
||||
* Layout:
|
||||
* 1. Sticky header with title, subtitle, legend help button, close
|
||||
* 2. Current Focus section (hatch / evolve) — collapsible, default open
|
||||
* 3. Daily Bounties section — collapsible, default open
|
||||
* 4. Settings row — low emphasis toggle (not collapsible)
|
||||
*
|
||||
* Both main sections use lightweight Radix Collapsible wrappers.
|
||||
* Collapsed headers still show summary info (progress / coins).
|
||||
*/
|
||||
|
||||
import {
|
||||
Loader2,
|
||||
XCircle,
|
||||
AlertTriangle,
|
||||
X,
|
||||
Eye,
|
||||
Scroll,
|
||||
Compass,
|
||||
HelpCircle,
|
||||
ChevronDown,
|
||||
} from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Dialog, DialogContent, DialogClose } from '@/components/ui/dialog';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { useState } from 'react';
|
||||
|
||||
import type { BlobbiCompanion } from '@/blobbi/core/lib/blobbi';
|
||||
import type { HatchTasksResult } from '../hooks/useHatchTasks';
|
||||
import type { EvolveTasksResult } from '../hooks/useEvolveTasks';
|
||||
import { TasksPanel } from './TasksPanel';
|
||||
import { DailyMissionsPanel } from './DailyMissionsPanel';
|
||||
import { useDailyMissions } from '../hooks/useDailyMissions';
|
||||
import { useRerollMission } from '../hooks/useRerollMission';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface BlobbiMissionsModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
companion: BlobbiCompanion;
|
||||
hatchTasks: HatchTasksResult;
|
||||
evolveTasks: EvolveTasksResult;
|
||||
onOpenPostModal: () => void;
|
||||
onHatch: () => void;
|
||||
isHatching: boolean;
|
||||
onEvolve: () => void;
|
||||
isEvolving: boolean;
|
||||
onStopIncubation: () => Promise<void>;
|
||||
isStoppingIncubation: boolean;
|
||||
onStopEvolution: () => Promise<void>;
|
||||
isStoppingEvolution: boolean;
|
||||
availableStages?: ('egg' | 'baby' | 'adult')[];
|
||||
showMissionCard?: boolean;
|
||||
onToggleMissionCard?: (visible: boolean) => void;
|
||||
}
|
||||
|
||||
// ─── Section Chevron ─────────────────────────────────────────────────────────
|
||||
|
||||
function SectionChevron({ open }: { open: boolean }) {
|
||||
return (
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
'size-4 text-muted-foreground/60 transition-transform duration-200',
|
||||
open && 'rotate-180',
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Mission Type Legend ──────────────────────────────────────────────────────
|
||||
|
||||
function MissionTypeLegend() {
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-full p-1.5 opacity-50 hover:opacity-100 hover:bg-muted transition-all"
|
||||
aria-label="Mission types legend"
|
||||
>
|
||||
<HelpCircle className="size-4" />
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent side="bottom" align="end" className="w-56 p-3">
|
||||
<p className="text-xs font-semibold mb-2">Mission Types</p>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="size-5 rounded-full bg-amber-500/15 flex items-center justify-center shrink-0">
|
||||
<Scroll className="size-3 text-amber-500" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium">Daily Bounty</p>
|
||||
<p className="text-[10px] text-muted-foreground">Resets every day</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="size-5 rounded-full bg-sky-500/15 flex items-center justify-center shrink-0">
|
||||
<span className="text-xs">🥚</span>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium">Hatch Task</p>
|
||||
<p className="text-[10px] text-muted-foreground">Egg progression</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="size-5 rounded-full bg-violet-500/15 flex items-center justify-center shrink-0">
|
||||
<span className="text-xs">🐣</span>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium">Evolve Task</p>
|
||||
<p className="text-[10px] text-muted-foreground">Baby progression</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Daily Missions Section ───────────────────────────────────────────────────
|
||||
|
||||
interface DailyMissionsSectionProps {
|
||||
availableStages?: ('egg' | 'baby' | 'adult')[];
|
||||
disabled?: boolean;
|
||||
defaultOpen?: boolean;
|
||||
}
|
||||
|
||||
function DailyMissionsSection({
|
||||
availableStages,
|
||||
disabled,
|
||||
defaultOpen = true,
|
||||
}: DailyMissionsSectionProps) {
|
||||
const [isOpen, setIsOpen] = useState(defaultOpen);
|
||||
|
||||
const {
|
||||
missions,
|
||||
todayXp,
|
||||
allComplete,
|
||||
bonusUnlocked,
|
||||
bonusXp,
|
||||
noMissionsAvailable,
|
||||
rerollsRemaining,
|
||||
} = useDailyMissions({ availableStages });
|
||||
|
||||
const { mutate: rerollMission, isPending: isRerolling } = useRerollMission();
|
||||
|
||||
const completedCount = missions.filter((m) => m.complete).length;
|
||||
|
||||
return (
|
||||
<Collapsible open={isOpen} onOpenChange={setIsOpen}>
|
||||
{/* Section header — tappable */}
|
||||
<CollapsibleTrigger className="w-full">
|
||||
<div className="flex items-center justify-between py-1 group">
|
||||
<div className="flex items-center gap-2">
|
||||
<Scroll className="size-4 text-amber-500 dark:text-amber-400 shrink-0" />
|
||||
<h3 className="font-semibold text-sm">Daily Bounties</h3>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{/* Summary pill — always visible */}
|
||||
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<span className="tabular-nums">
|
||||
{completedCount} / {missions.length}
|
||||
</span>
|
||||
{allComplete && (
|
||||
<span className="size-4 rounded-full bg-emerald-500 text-white text-[10px] font-bold flex items-center justify-center shrink-0">
|
||||
✓
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<SectionChevron open={isOpen} />
|
||||
</div>
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
|
||||
<CollapsibleContent className="overflow-hidden data-[state=open]:animate-collapsible-down data-[state=closed]:animate-collapsible-up">
|
||||
<div className="pt-3">
|
||||
<DailyMissionsPanel
|
||||
missions={missions}
|
||||
onRerollMission={(id) => rerollMission({ missionId: id, availableStages })}
|
||||
todayXp={todayXp}
|
||||
disabled={disabled || isRerolling}
|
||||
bonusUnlocked={bonusUnlocked}
|
||||
bonusXp={bonusXp}
|
||||
noMissionsAvailable={noMissionsAvailable}
|
||||
rerollsRemaining={rerollsRemaining}
|
||||
isRerolling={isRerolling}
|
||||
/>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Stop Process Confirmation Dialog ─────────────────────────────────────────
|
||||
|
||||
interface StopConfirmationDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
companionName: string;
|
||||
processType: 'incubation' | 'evolution';
|
||||
onConfirm: () => Promise<void>;
|
||||
isPending: boolean;
|
||||
}
|
||||
|
||||
function StopConfirmationDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
companionName,
|
||||
processType,
|
||||
onConfirm,
|
||||
isPending,
|
||||
}: StopConfirmationDialogProps) {
|
||||
const handleConfirm = async () => {
|
||||
await onConfirm();
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const label = processType === 'incubation' ? 'Incubation' : 'Evolution';
|
||||
|
||||
return (
|
||||
<AlertDialog open={open} onOpenChange={onOpenChange}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="flex items-center gap-2">
|
||||
<AlertTriangle className="size-5 text-amber-500" />
|
||||
Stop {label}?
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription className="space-y-2">
|
||||
<p>
|
||||
Are you sure you want to stop {processType === 'incubation' ? 'incubating' : 'evolving'}{' '}
|
||||
<strong>{companionName}</strong>?
|
||||
</p>
|
||||
<p>
|
||||
This will interrupt the {processType} process and clear all task progress.
|
||||
You can restart {processType} later, but you'll need to complete the tasks again.
|
||||
</p>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isPending}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleConfirm}
|
||||
disabled={isPending}
|
||||
className="bg-destructive hover:bg-destructive/90"
|
||||
>
|
||||
{isPending ? (
|
||||
<>
|
||||
<Loader2 className="size-4 mr-2 animate-spin" />
|
||||
Stopping...
|
||||
</>
|
||||
) : (
|
||||
`Stop ${label}`
|
||||
)}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Current Focus Section (Hatch / Evolve) ──────────────────────────────────
|
||||
|
||||
interface CurrentFocusSectionProps {
|
||||
companion: BlobbiCompanion;
|
||||
tasks: HatchTasksResult | EvolveTasksResult;
|
||||
processType: 'incubation' | 'evolution';
|
||||
onOpenPostModal: () => void;
|
||||
onComplete: () => void;
|
||||
isCompleting: boolean;
|
||||
onStop: () => Promise<void>;
|
||||
isStopping: boolean;
|
||||
defaultOpen?: boolean;
|
||||
}
|
||||
|
||||
function CurrentFocusSection({
|
||||
companion,
|
||||
tasks,
|
||||
processType,
|
||||
onOpenPostModal,
|
||||
onComplete,
|
||||
isCompleting,
|
||||
onStop,
|
||||
isStopping,
|
||||
defaultOpen = true,
|
||||
}: CurrentFocusSectionProps) {
|
||||
const [isOpen, setIsOpen] = useState(defaultOpen);
|
||||
const [showStopConfirmation, setShowStopConfirmation] = useState(false);
|
||||
|
||||
const isIncubation = processType === 'incubation';
|
||||
const title = isIncubation ? 'Hatch Tasks' : 'Evolve Tasks';
|
||||
const completeLabel = isIncubation ? 'Hatch Your Blobbi!' : 'Evolve Your Blobbi!';
|
||||
const completingLabel = isIncubation ? 'Hatching...' : 'Evolving...';
|
||||
const completeEmoji = isIncubation ? '🐣' : '✨';
|
||||
const stopLabel = isIncubation ? 'Stop Incubation' : 'Stop Evolution';
|
||||
const badgeLabel = isIncubation ? 'Hatch' : 'Evolve';
|
||||
const category = isIncubation ? ('hatch' as const) : ('evolve' as const);
|
||||
|
||||
const completedCount = tasks.tasks.filter((t) => t.completed).length;
|
||||
const totalTasks = tasks.tasks.length;
|
||||
|
||||
return (
|
||||
<Collapsible open={isOpen} onOpenChange={setIsOpen}>
|
||||
{/* Section header — tappable */}
|
||||
<CollapsibleTrigger className="w-full">
|
||||
<div className="flex items-center justify-between py-1 group">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className={cn(
|
||||
'text-xs font-semibold px-2 py-0.5',
|
||||
isIncubation
|
||||
? 'bg-sky-500/15 text-sky-600 dark:text-sky-400'
|
||||
: 'bg-violet-500/15 text-violet-600 dark:text-violet-400',
|
||||
)}
|
||||
>
|
||||
{badgeLabel}
|
||||
</Badge>
|
||||
<span className="text-sm font-semibold">{title}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span
|
||||
className={cn(
|
||||
'text-xs font-medium tabular-nums',
|
||||
tasks.allCompleted
|
||||
? 'text-emerald-600 dark:text-emerald-400'
|
||||
: 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{completedCount} / {totalTasks}
|
||||
</span>
|
||||
<SectionChevron open={isOpen} />
|
||||
</div>
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
|
||||
<CollapsibleContent className="overflow-hidden data-[state=open]:animate-collapsible-down data-[state=closed]:animate-collapsible-up">
|
||||
<div className="pt-3">
|
||||
{/* Task card grid */}
|
||||
<TasksPanel
|
||||
tasks={tasks.tasks}
|
||||
allCompleted={tasks.allCompleted}
|
||||
isLoading={tasks.isLoading}
|
||||
onOpenPostModal={onOpenPostModal}
|
||||
onComplete={onComplete}
|
||||
isCompleting={isCompleting}
|
||||
completeLabel={completeLabel}
|
||||
completingLabel={completingLabel}
|
||||
completeEmoji={completeEmoji}
|
||||
category={category}
|
||||
/>
|
||||
|
||||
{/* Stop process — low emphasis */}
|
||||
<div className="mt-3 flex justify-center">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setShowStopConfirmation(true)}
|
||||
disabled={isStopping || isCompleting}
|
||||
className="text-xs text-muted-foreground hover:text-destructive hover:bg-destructive/10 h-8 px-3"
|
||||
>
|
||||
{isStopping ? (
|
||||
<>
|
||||
<Loader2 className="size-3.5 mr-1.5 animate-spin" />
|
||||
Stopping...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<XCircle className="size-3.5 mr-1.5" />
|
||||
{stopLabel}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
|
||||
<StopConfirmationDialog
|
||||
open={showStopConfirmation}
|
||||
onOpenChange={setShowStopConfirmation}
|
||||
companionName={companion.name}
|
||||
processType={processType}
|
||||
onConfirm={onStop}
|
||||
isPending={isStopping}
|
||||
/>
|
||||
</Collapsible>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Empty Focus State ────────────────────────────────────────────────────────
|
||||
|
||||
function EmptyFocusState() {
|
||||
return (
|
||||
<div className="py-6 text-center">
|
||||
<Compass className="size-5 text-muted-foreground/50 mx-auto mb-2" />
|
||||
<p className="text-sm text-muted-foreground">No active progression right now</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Main Modal ───────────────────────────────────────────────────────────────
|
||||
|
||||
export function BlobbiMissionsModal({
|
||||
open,
|
||||
onOpenChange,
|
||||
companion,
|
||||
hatchTasks,
|
||||
evolveTasks,
|
||||
onOpenPostModal,
|
||||
onHatch,
|
||||
isHatching,
|
||||
onEvolve,
|
||||
isEvolving,
|
||||
onStopIncubation,
|
||||
isStoppingIncubation,
|
||||
onStopEvolution,
|
||||
isStoppingEvolution,
|
||||
availableStages,
|
||||
showMissionCard,
|
||||
onToggleMissionCard,
|
||||
}: BlobbiMissionsModalProps) {
|
||||
const isIncubating = companion.state === 'incubating';
|
||||
const isEvolvingState = companion.state === 'evolving';
|
||||
const isEgg = companion.stage === 'egg';
|
||||
const isBaby = companion.stage === 'baby';
|
||||
|
||||
const hasActiveProcess = (isIncubating && isEgg) || (isEvolvingState && isBaby);
|
||||
const isProcessBusy = isHatching || isEvolving || isStoppingIncubation || isStoppingEvolution;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-lg w-[calc(100%-2rem)] max-h-[85vh] flex flex-col p-0 gap-0 overflow-hidden [&>button:last-child]:hidden">
|
||||
{/* ── Sticky Header ── */}
|
||||
<div className="sticky top-0 z-10 bg-background px-4 sm:px-5 pt-4 pb-3 border-b border-border/60">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-base font-bold tracking-tight">Missions</h2>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
Quests & bounties for {companion.name}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-0.5 shrink-0">
|
||||
<MissionTypeLegend />
|
||||
<DialogClose className="rounded-full p-1.5 opacity-60 hover:opacity-100 hover:bg-muted transition-all">
|
||||
<X className="size-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogClose>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── Scrollable Content ── */}
|
||||
<div className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden px-4 sm:px-5 py-4 space-y-5">
|
||||
{/* 1. Current Focus */}
|
||||
{hasActiveProcess ? (
|
||||
<>
|
||||
{isIncubating && isEgg ? (
|
||||
<CurrentFocusSection
|
||||
companion={companion}
|
||||
tasks={hatchTasks}
|
||||
processType="incubation"
|
||||
onOpenPostModal={onOpenPostModal}
|
||||
onComplete={onHatch}
|
||||
isCompleting={isHatching}
|
||||
onStop={onStopIncubation}
|
||||
isStopping={isStoppingIncubation}
|
||||
/>
|
||||
) : isEvolvingState && isBaby ? (
|
||||
<CurrentFocusSection
|
||||
companion={companion}
|
||||
tasks={evolveTasks}
|
||||
processType="evolution"
|
||||
onOpenPostModal={onOpenPostModal}
|
||||
onComplete={onEvolve}
|
||||
isCompleting={isEvolving}
|
||||
onStop={onStopEvolution}
|
||||
isStopping={isStoppingEvolution}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<EmptyFocusState />
|
||||
)}
|
||||
|
||||
{/* Divider */}
|
||||
<div className="h-px bg-border/60" />
|
||||
|
||||
{/* 2. Daily Bounties */}
|
||||
<DailyMissionsSection
|
||||
availableStages={availableStages}
|
||||
disabled={isProcessBusy}
|
||||
/>
|
||||
|
||||
{/* 3. Settings */}
|
||||
{onToggleMissionCard !== undefined && showMissionCard !== undefined && (
|
||||
<>
|
||||
<div className="h-px bg-border/40" />
|
||||
<div className="flex items-center justify-between py-1">
|
||||
<Label
|
||||
htmlFor="mission-card-toggle"
|
||||
className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer"
|
||||
>
|
||||
<Eye className="size-3.5" />
|
||||
Show mission card on main page
|
||||
</Label>
|
||||
<Switch
|
||||
id="mission-card-toggle"
|
||||
checked={showMissionCard}
|
||||
onCheckedChange={onToggleMissionCard}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
// src/blobbi/actions/components/BlobbiPostModal.tsx
|
||||
|
||||
/**
|
||||
* Modal for creating a Blobbi post (hatch or evolve).
|
||||
*
|
||||
* Requirements:
|
||||
* - Prefilled with stage-aware text:
|
||||
* - Hatch: "Hello Nostr! Posting to hatch #<blobbiName> #blobbi #ditto #nostr"
|
||||
* - Evolve: "Hello Nostr! Posting to evolve #<blobbiName> #blobbi #ditto #nostr"
|
||||
* - User can ADD text but CANNOT delete the prefix or required hashtags
|
||||
* - Blobbi name is sanitized into a valid hashtag format
|
||||
* - Enforced programmatically
|
||||
*/
|
||||
|
||||
import { useState, useCallback, useEffect, useMemo } from 'react';
|
||||
import { X, Loader2, AlertCircle } from 'lucide-react';
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { toast } from '@/hooks/useToast';
|
||||
|
||||
import {
|
||||
BLOBBI_POST_REQUIRED_HASHTAGS,
|
||||
buildHatchPhrase,
|
||||
} from '../hooks/useHatchTasks';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** The process type for the post */
|
||||
export type BlobbiPostProcess = 'hatch' | 'evolve';
|
||||
|
||||
interface BlobbiPostModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** The Blobbi's name (will be converted to hashtag) */
|
||||
blobbiName: string;
|
||||
/** The process type - 'hatch' for incubation, 'evolve' for evolution */
|
||||
process?: BlobbiPostProcess;
|
||||
onSuccess?: () => void;
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Build the required prefix text based on process type.
|
||||
*/
|
||||
function buildPrefix(process: BlobbiPostProcess): string {
|
||||
return process === 'evolve'
|
||||
? 'Posting to evolve'
|
||||
: 'Posting to hatch';
|
||||
}
|
||||
|
||||
// ─── Main Component ───────────────────────────────────────────────────────────
|
||||
|
||||
export function BlobbiPostModal({
|
||||
open,
|
||||
onOpenChange,
|
||||
blobbiName,
|
||||
process = 'hatch',
|
||||
onSuccess,
|
||||
}: BlobbiPostModalProps) {
|
||||
const { user } = useCurrentUser();
|
||||
const { mutateAsync: createEvent, isPending } = useNostrPublish();
|
||||
|
||||
// Compute the required elements based on props
|
||||
const prefix = useMemo(() => buildPrefix(process), [process]);
|
||||
const capitalizedName = useMemo(() => blobbiName.charAt(0).toUpperCase() + blobbiName.slice(1), [blobbiName]);
|
||||
|
||||
// The required phrase that must appear in the post
|
||||
const requiredPhrase = useMemo(() =>
|
||||
process === 'hatch'
|
||||
? buildHatchPhrase(blobbiName)
|
||||
: `${prefix} ${capitalizedName} #blobbi`,
|
||||
[process, blobbiName, prefix, capitalizedName]
|
||||
);
|
||||
|
||||
// Build default content (the phrase itself is enough)
|
||||
const defaultContent = useMemo(() => requiredPhrase, [requiredPhrase]);
|
||||
|
||||
const [content, setContent] = useState(defaultContent);
|
||||
const [validationError, setValidationError] = useState<string | null>(null);
|
||||
|
||||
// Reset content when modal opens or props change
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setContent(defaultContent);
|
||||
setValidationError(null);
|
||||
}
|
||||
}, [open, defaultContent]);
|
||||
|
||||
/**
|
||||
* Validate that the content contains the required phrase.
|
||||
*/
|
||||
const validateContent = useCallback((text: string): string | null => {
|
||||
if (!text.includes(requiredPhrase)) {
|
||||
return `The post must contain: "${requiredPhrase}"`;
|
||||
}
|
||||
return null;
|
||||
}, [requiredPhrase]);
|
||||
|
||||
/**
|
||||
* Handle content change with validation.
|
||||
* Prevents deletion of required content.
|
||||
*/
|
||||
const handleContentChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const newContent = e.target.value;
|
||||
|
||||
// Allow content changes only if it preserves the required elements
|
||||
const error = validateContent(newContent);
|
||||
|
||||
if (error) {
|
||||
setValidationError(error);
|
||||
// Still update content but show error
|
||||
// This allows the user to see what they're trying to do
|
||||
// but the post button will be disabled
|
||||
} else {
|
||||
setValidationError(null);
|
||||
}
|
||||
|
||||
setContent(newContent);
|
||||
}, [validateContent]);
|
||||
|
||||
/**
|
||||
* Handle post creation.
|
||||
*/
|
||||
const handlePost = useCallback(async () => {
|
||||
if (!user?.pubkey) {
|
||||
toast({
|
||||
title: 'Not logged in',
|
||||
description: 'Please log in to create a post',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Final validation
|
||||
const error = validateContent(content);
|
||||
if (error) {
|
||||
setValidationError(error);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Build tags for the post: extract all hashtags from content
|
||||
const tags: string[][] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
// Always include BLOBBI_POST_REQUIRED_HASHTAGS as t tags
|
||||
for (const hashtag of BLOBBI_POST_REQUIRED_HASHTAGS) {
|
||||
const lower = hashtag.toLowerCase();
|
||||
if (!seen.has(lower)) {
|
||||
tags.push(['t', lower]);
|
||||
seen.add(lower);
|
||||
}
|
||||
}
|
||||
|
||||
// Extract any additional hashtags from the content
|
||||
const contentHashtags = content.match(/#(\w+)/g) || [];
|
||||
for (const tag of contentHashtags) {
|
||||
const tagValue = tag.slice(1).toLowerCase();
|
||||
if (!seen.has(tagValue)) {
|
||||
tags.push(['t', tagValue]);
|
||||
seen.add(tagValue);
|
||||
}
|
||||
}
|
||||
|
||||
await createEvent({
|
||||
kind: 1,
|
||||
content,
|
||||
tags,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Post created!',
|
||||
description: process === 'evolve'
|
||||
? 'Your Blobbi evolution post has been published.'
|
||||
: 'Your Blobbi hatch post has been published.',
|
||||
});
|
||||
|
||||
onOpenChange(false);
|
||||
onSuccess?.();
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Failed to create post',
|
||||
description: error instanceof Error ? error.message : 'Unknown error',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
}, [user, content, validateContent, createEvent, onOpenChange, onSuccess, process]);
|
||||
|
||||
const canPost = !validationError && content.trim().length > 0;
|
||||
|
||||
const dialogTitle = process === 'evolve' ? 'Blobbi Evolution Post' : 'Blobbi Hatch Post';
|
||||
const alertText = process === 'evolve'
|
||||
? "This special post announces your Blobbi's evolution! The highlighted text must remain in your post."
|
||||
: "This special post announces your Blobbi's hatching journey! The highlighted text must remain in your post.";
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-lg p-0 gap-0">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-4 h-14 border-b">
|
||||
<DialogTitle className="text-base font-semibold">
|
||||
{dialogTitle}
|
||||
</DialogTitle>
|
||||
<button
|
||||
onClick={() => onOpenChange(false)}
|
||||
className="p-1.5 -mr-1.5 rounded-full text-muted-foreground hover:text-foreground hover:bg-secondary/60 transition-colors"
|
||||
>
|
||||
<X className="size-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="p-4 space-y-4">
|
||||
{/* Info alert */}
|
||||
<Alert className="border-primary/20 bg-primary/5">
|
||||
<AlertDescription className="text-sm">
|
||||
{alertText}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
{/* Textarea */}
|
||||
<div className="space-y-2">
|
||||
<Textarea
|
||||
value={content}
|
||||
onChange={handleContentChange}
|
||||
placeholder="Write your post..."
|
||||
className="min-h-[150px] resize-none"
|
||||
disabled={isPending}
|
||||
/>
|
||||
|
||||
{/* Character count and validation */}
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<div>
|
||||
{validationError && (
|
||||
<span className="text-destructive flex items-center gap-1">
|
||||
<AlertCircle className="size-3.5" />
|
||||
{validationError}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-muted-foreground">
|
||||
{content.length} characters
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Preview of required content */}
|
||||
<div className="p-3 rounded-lg bg-muted/50 border border-dashed">
|
||||
<p className="text-xs text-muted-foreground mb-1">Required phrase:</p>
|
||||
<p className="text-sm font-medium text-primary">
|
||||
{requiredPhrase}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="flex items-center justify-end gap-2 px-4 py-3 border-t bg-muted/30">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={isPending}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handlePost}
|
||||
disabled={!canPost || isPending}
|
||||
className="min-w-24"
|
||||
>
|
||||
{isPending ? (
|
||||
<>
|
||||
<Loader2 className="size-4 mr-2 animate-spin" />
|
||||
Posting...
|
||||
</>
|
||||
) : (
|
||||
'Post'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
/**
|
||||
* DailyMissionsPanel — card-grid layout for daily bounties.
|
||||
*
|
||||
* Each mission is a compact card in a 2-col grid.
|
||||
* Tapping a card expands it to show progress and reroll.
|
||||
* Only one card expanded at a time.
|
||||
* Completion is implicit (derived from progress vs target).
|
||||
*/
|
||||
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
Check,
|
||||
Sparkles,
|
||||
Gift,
|
||||
Egg,
|
||||
Trophy,
|
||||
RefreshCw,
|
||||
Heart,
|
||||
Utensils,
|
||||
Droplets,
|
||||
Moon,
|
||||
Camera,
|
||||
Mic,
|
||||
Music,
|
||||
Pill,
|
||||
CircleDot,
|
||||
Zap,
|
||||
} from 'lucide-react';
|
||||
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { cn, formatCompactNumber } from '@/lib/utils';
|
||||
import type { DailyMissionAction } from '../lib/daily-missions';
|
||||
import type { DailyMissionView } from '../hooks/useDailyMissions';
|
||||
import {
|
||||
ExpandableMissionCard,
|
||||
MissionDescription,
|
||||
MissionProgress,
|
||||
} from './ExpandableMissionCard';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface DailyMissionsPanelProps {
|
||||
missions: DailyMissionView[];
|
||||
onRerollMission?: (missionId: string) => void;
|
||||
todayXp: number;
|
||||
disabled?: boolean;
|
||||
bonusUnlocked?: boolean;
|
||||
bonusXp?: number;
|
||||
noMissionsAvailable?: boolean;
|
||||
rerollsRemaining?: number;
|
||||
isRerolling?: boolean;
|
||||
}
|
||||
|
||||
// ─── Daily Mission Icon Mapping ───────────────────────────────────────────────
|
||||
|
||||
function DailyMissionIcon({ action }: { action: DailyMissionAction }) {
|
||||
const cls = 'size-5';
|
||||
switch (action) {
|
||||
case 'interact':
|
||||
return <Heart className={cls} />;
|
||||
case 'feed':
|
||||
return <Utensils className={cls} />;
|
||||
case 'clean':
|
||||
return <Droplets className={cls} />;
|
||||
case 'sleep':
|
||||
return <Moon className={cls} />;
|
||||
case 'take_photo':
|
||||
return <Camera className={cls} />;
|
||||
case 'sing':
|
||||
return <Mic className={cls} />;
|
||||
case 'play_music':
|
||||
return <Music className={cls} />;
|
||||
case 'medicine':
|
||||
return <Pill className={cls} />;
|
||||
default:
|
||||
return <CircleDot className={cls} />;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Bonus Card ───────────────────────────────────────────────────────────────
|
||||
|
||||
interface BonusCardProps {
|
||||
isUnlocked: boolean;
|
||||
xp: number;
|
||||
isExpanded: boolean;
|
||||
onToggle: (id: string) => void;
|
||||
}
|
||||
|
||||
function BonusCard({ isUnlocked, xp, isExpanded, onToggle }: BonusCardProps) {
|
||||
return (
|
||||
<ExpandableMissionCard
|
||||
id="bonus"
|
||||
category="daily"
|
||||
icon={<Trophy className="size-5" />}
|
||||
title="Daily Champion"
|
||||
completed={isUnlocked}
|
||||
progress={isUnlocked ? 1 : 0}
|
||||
isExpanded={isExpanded}
|
||||
onToggle={onToggle}
|
||||
>
|
||||
<MissionDescription>
|
||||
{isUnlocked
|
||||
? 'Bonus XP for completing all daily missions!'
|
||||
: 'Complete all missions to unlock this bonus'}
|
||||
</MissionDescription>
|
||||
|
||||
<div className="flex items-center gap-1 text-xs font-medium text-violet-600 dark:text-violet-400">
|
||||
<Zap className="size-3" />
|
||||
+{formatCompactNumber(xp)} XP
|
||||
</div>
|
||||
</ExpandableMissionCard>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Empty / Done States ──────────────────────────────────────────────────────
|
||||
|
||||
function NoMissionsState() {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-2 py-6 text-center">
|
||||
<Egg className="size-5 text-muted-foreground/50" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">Hatch your Blobbi first</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
Daily missions unlock after hatching
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AllCompleteState({ todayXp }: { todayXp: number }) {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-2 py-6 text-center">
|
||||
<Sparkles className="size-5 text-primary/60" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">All done for today</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
Earned{' '}
|
||||
<span className="font-medium text-violet-600 dark:text-violet-400">
|
||||
{formatCompactNumber(todayXp)} XP
|
||||
</span>{' '}
|
||||
— come back tomorrow!
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Reroll Counter ───────────────────────────────────────────────────────────
|
||||
|
||||
function RerollCounter({ remaining }: { remaining: number }) {
|
||||
const text =
|
||||
remaining === 0
|
||||
? 'No rerolls left'
|
||||
: remaining === 1
|
||||
? '1 reroll left'
|
||||
: `${remaining} rerolls left`;
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-end gap-1 text-[11px] text-muted-foreground col-span-full">
|
||||
<RefreshCw className="size-2.5" />
|
||||
<span>{text}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Main Component ───────────────────────────────────────────────────────────
|
||||
|
||||
export function DailyMissionsPanel({
|
||||
missions,
|
||||
onRerollMission,
|
||||
todayXp,
|
||||
disabled,
|
||||
bonusUnlocked = false,
|
||||
bonusXp = 50,
|
||||
noMissionsAvailable = false,
|
||||
rerollsRemaining = 0,
|
||||
isRerolling = false,
|
||||
}: DailyMissionsPanelProps) {
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null);
|
||||
|
||||
if (noMissionsAvailable) return <NoMissionsState />;
|
||||
|
||||
const allComplete = missions.every((m) => m.complete);
|
||||
if (allComplete && bonusUnlocked) return <AllCompleteState todayXp={todayXp} />;
|
||||
|
||||
const canReroll = rerollsRemaining > 0 && !!onRerollMission;
|
||||
|
||||
const handleToggle = (id: string) => {
|
||||
setExpandedId((prev) => (prev === id ? null : id));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
|
||||
{/* Reroll counter */}
|
||||
{onRerollMission && <RerollCounter remaining={rerollsRemaining} />}
|
||||
|
||||
{/* Regular mission cards */}
|
||||
{missions.map((mission) => {
|
||||
const progressFrac = mission.target > 0 ? mission.progress / mission.target : 0;
|
||||
const showReroll = onRerollMission && !mission.complete && canReroll;
|
||||
|
||||
return (
|
||||
<ExpandableMissionCard
|
||||
key={mission.id}
|
||||
id={mission.id}
|
||||
category="daily"
|
||||
icon={<DailyMissionIcon action={mission.action} />}
|
||||
title={mission.title}
|
||||
completed={mission.complete}
|
||||
progress={Math.min(progressFrac, 1)}
|
||||
isExpanded={expandedId === mission.id}
|
||||
onToggle={handleToggle}
|
||||
>
|
||||
{/* Description */}
|
||||
<MissionDescription>{mission.description}</MissionDescription>
|
||||
|
||||
{/* Progress */}
|
||||
{!mission.complete && (
|
||||
<MissionProgress
|
||||
current={mission.progress}
|
||||
required={mission.target}
|
||||
completed={mission.complete}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* XP + reroll row */}
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="inline-flex items-center gap-0.5 text-xs font-medium text-violet-600 dark:text-violet-400">
|
||||
<Zap className="size-3" />
|
||||
{formatCompactNumber(mission.xp)} XP
|
||||
</span>
|
||||
|
||||
{showReroll && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onRerollMission(mission.id);
|
||||
}}
|
||||
disabled={disabled || isRerolling}
|
||||
className="p-1 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-40"
|
||||
>
|
||||
<RefreshCw className={cn('size-3', isRerolling && 'animate-spin')} />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="left">
|
||||
<p>Replace mission</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
|
||||
{mission.complete && (
|
||||
<span className="inline-flex items-center gap-0.5 text-[10px] font-medium text-primary">
|
||||
<Check className="size-2.5" />
|
||||
Done
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Complete indicator */}
|
||||
{mission.complete && (
|
||||
<div className="flex items-center gap-1 text-xs text-emerald-600 dark:text-emerald-400">
|
||||
<Gift className="size-3.5" />
|
||||
+{formatCompactNumber(mission.xp)} XP earned
|
||||
</div>
|
||||
)}
|
||||
</ExpandableMissionCard>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Bonus card */}
|
||||
<BonusCard
|
||||
isUnlocked={bonusUnlocked}
|
||||
xp={bonusXp}
|
||||
isExpanded={expandedId === 'bonus'}
|
||||
onToggle={handleToggle}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
// src/blobbi/actions/components/ExpandableMissionCard.tsx
|
||||
|
||||
/**
|
||||
* Expandable mission card for the quest-board grid.
|
||||
*
|
||||
* Collapsed: compact square-ish card showing icon, title, and a tiny
|
||||
* progress ring / checkmark.
|
||||
* Expanded: full-width row that reveals description, progress bar,
|
||||
* action link, claim button, dynamic hints, etc.
|
||||
*
|
||||
* Only one card is expanded at a time per section (controlled by parent).
|
||||
*/
|
||||
|
||||
import type { ReactNode } from 'react';
|
||||
import { Check, ChevronRight, ExternalLink, AlertCircle } from 'lucide-react';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export type MissionCategory = 'daily' | 'hatch' | 'evolve';
|
||||
|
||||
export interface ExpandableMissionCardProps {
|
||||
/** Unique id used to track which card is expanded */
|
||||
id: string;
|
||||
/** Mission category for visual styling */
|
||||
category: MissionCategory;
|
||||
/** Icon rendered in the compact card (ReactNode — usually a lucide icon or emoji span) */
|
||||
icon: ReactNode;
|
||||
/** Short title */
|
||||
title: string;
|
||||
/** Whether the mission is complete */
|
||||
completed: boolean;
|
||||
/** Progress fraction 0-1 (used for the tiny ring in compact mode) */
|
||||
progress: number;
|
||||
/** Whether this card is currently expanded */
|
||||
isExpanded: boolean;
|
||||
/** Parent calls this to toggle expansion */
|
||||
onToggle: (id: string) => void;
|
||||
/** Content rendered only when expanded */
|
||||
children: ReactNode;
|
||||
/** Optional extra className on the outer wrapper */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
// ─── Tiny Progress Ring ───────────────────────────────────────────────────────
|
||||
|
||||
function ProgressRing({ progress, completed, category }: { progress: number; completed: boolean; category: MissionCategory }) {
|
||||
const size = 28;
|
||||
const stroke = 2.5;
|
||||
const radius = (size - stroke) / 2;
|
||||
const circumference = 2 * Math.PI * radius;
|
||||
const offset = circumference - progress * circumference;
|
||||
|
||||
if (completed) {
|
||||
return (
|
||||
<div className="size-7 rounded-full bg-emerald-500/20 flex items-center justify-center">
|
||||
<Check className="size-3.5 text-emerald-600 dark:text-emerald-400" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ringColor =
|
||||
category === 'hatch'
|
||||
? 'text-sky-500'
|
||||
: category === 'evolve'
|
||||
? 'text-violet-500'
|
||||
: 'text-amber-500';
|
||||
|
||||
return (
|
||||
<svg width={size} height={size} className={cn('shrink-0 -rotate-90', ringColor)}>
|
||||
<circle
|
||||
cx={size / 2}
|
||||
cy={size / 2}
|
||||
r={radius}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={stroke}
|
||||
opacity={0.15}
|
||||
/>
|
||||
<circle
|
||||
cx={size / 2}
|
||||
cy={size / 2}
|
||||
r={radius}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={stroke}
|
||||
strokeDasharray={circumference}
|
||||
strokeDashoffset={offset}
|
||||
strokeLinecap="round"
|
||||
className="transition-all duration-300"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Accent colors per category ───────────────────────────────────────────────
|
||||
|
||||
const CATEGORY_STYLES: Record<MissionCategory, { bg: string; expandedBg: string; border: string }> = {
|
||||
daily: {
|
||||
bg: 'bg-amber-500/[0.06] hover:bg-amber-500/10',
|
||||
expandedBg: 'bg-amber-500/[0.06]',
|
||||
border: 'ring-amber-500/20',
|
||||
},
|
||||
hatch: {
|
||||
bg: 'bg-sky-500/[0.06] hover:bg-sky-500/10',
|
||||
expandedBg: 'bg-sky-500/[0.06]',
|
||||
border: 'ring-sky-500/20',
|
||||
},
|
||||
evolve: {
|
||||
bg: 'bg-violet-500/[0.06] hover:bg-violet-500/10',
|
||||
expandedBg: 'bg-violet-500/[0.06]',
|
||||
border: 'ring-violet-500/20',
|
||||
},
|
||||
};
|
||||
|
||||
// ─── Component ────────────────────────────────────────────────────────────────
|
||||
|
||||
export function ExpandableMissionCard({
|
||||
id,
|
||||
category,
|
||||
icon,
|
||||
title,
|
||||
completed,
|
||||
progress,
|
||||
isExpanded,
|
||||
onToggle,
|
||||
children,
|
||||
className,
|
||||
}: ExpandableMissionCardProps) {
|
||||
const styles = CATEGORY_STYLES[category];
|
||||
|
||||
// ── Collapsed card ──
|
||||
if (!isExpanded) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onToggle(id)}
|
||||
className={cn(
|
||||
'flex flex-col items-center gap-1.5 rounded-xl p-3 transition-all text-center cursor-pointer select-none',
|
||||
'ring-1 ring-transparent',
|
||||
completed ? 'bg-emerald-500/[0.06] hover:bg-emerald-500/10' : styles.bg,
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{/* Icon */}
|
||||
<div className="text-lg leading-none">{icon}</div>
|
||||
|
||||
{/* Title — 2 lines max */}
|
||||
<span className={cn(
|
||||
'text-[11px] font-medium leading-tight line-clamp-2 min-h-[2lh]',
|
||||
completed && 'text-emerald-600 dark:text-emerald-400',
|
||||
)}>
|
||||
{title}
|
||||
</span>
|
||||
|
||||
{/* Progress ring / check */}
|
||||
<ProgressRing progress={progress} completed={completed} category={category} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Expanded card (spans full row) ──
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'col-span-full rounded-xl ring-1 transition-all overflow-hidden',
|
||||
completed ? 'bg-emerald-500/[0.06] ring-emerald-500/20' : cn(styles.expandedBg, styles.border),
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{/* Compact header — click to collapse */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onToggle(id)}
|
||||
className="w-full flex items-center gap-3 p-3 text-left cursor-pointer select-none"
|
||||
>
|
||||
<div className="text-lg leading-none shrink-0">{icon}</div>
|
||||
<span className={cn(
|
||||
'text-sm font-medium flex-1 min-w-0',
|
||||
completed && 'text-emerald-600 dark:text-emerald-400',
|
||||
)}>
|
||||
{title}
|
||||
</span>
|
||||
<ProgressRing progress={progress} completed={completed} category={category} />
|
||||
</button>
|
||||
|
||||
{/* Expanded details */}
|
||||
<div className="px-3 pb-3 pt-0 space-y-2">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Shared detail sub-components ─────────────────────────────────────────────
|
||||
|
||||
/** Description text */
|
||||
export function MissionDescription({ children }: { children: ReactNode }) {
|
||||
return <p className="text-xs text-muted-foreground leading-snug">{children}</p>;
|
||||
}
|
||||
|
||||
/** Progress bar with fraction label */
|
||||
export function MissionProgress({ current, required, completed }: { current: number; required: number; completed: boolean }) {
|
||||
const pct = required > 0 ? Math.round((current / required) * 100) : 0;
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between text-[11px] text-muted-foreground mb-1">
|
||||
<span className="tabular-nums">{current} / {required}</span>
|
||||
<span className="tabular-nums">{pct}%</span>
|
||||
</div>
|
||||
<Progress value={pct} className={cn('h-1.5', completed && '[&>div]:bg-emerald-500')} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Inline action link (navigate, external, modal) */
|
||||
export function MissionAction({
|
||||
label,
|
||||
type,
|
||||
onClick,
|
||||
}: {
|
||||
label: string;
|
||||
type: 'navigate' | 'external_link' | 'open_modal';
|
||||
onClick: () => void;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"
|
||||
>
|
||||
{label}
|
||||
{type === 'external_link' ? (
|
||||
<ExternalLink className="size-3" />
|
||||
) : (
|
||||
<ChevronRight className="size-3" />
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** Dynamic / live task hint */
|
||||
export function DynamicHint({ current, required }: { current: number; required: number }) {
|
||||
return (
|
||||
<div className="flex items-center gap-1.5 text-[11px] text-amber-600/80 dark:text-amber-400/80">
|
||||
<AlertCircle className="size-3 shrink-0" />
|
||||
<span>Lowest stat: {current}% (need {required}%+)</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
// src/blobbi/actions/components/HatchTasksPanel.tsx
|
||||
|
||||
/**
|
||||
* UI component for displaying hatch task progress.
|
||||
* Shows a list of tasks with progress indicators and action buttons.
|
||||
*/
|
||||
|
||||
import { ExternalLink, Check, Loader2, ChevronRight } from 'lucide-react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { openUrl } from '@/lib/downloadFile';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
import type { HatchTask } from '../hooks/useHatchTasks';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface HatchTasksPanelProps {
|
||||
tasks: HatchTask[];
|
||||
allCompleted: boolean;
|
||||
isLoading: boolean;
|
||||
/** Called when user clicks "Create Post" action */
|
||||
onOpenPostModal: () => void;
|
||||
/** Called when all tasks are complete and user clicks "Hatch" */
|
||||
onHatch: () => void;
|
||||
/** Whether hatching is in progress */
|
||||
isHatching?: boolean;
|
||||
}
|
||||
|
||||
// ─── Task Row Component ───────────────────────────────────────────────────────
|
||||
|
||||
interface TaskRowProps {
|
||||
task: HatchTask;
|
||||
onOpenPostModal: () => void;
|
||||
}
|
||||
|
||||
function TaskRow({ task, onOpenPostModal }: TaskRowProps) {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleAction = () => {
|
||||
if (!task.action || !task.actionTarget) return;
|
||||
|
||||
switch (task.action) {
|
||||
case 'navigate':
|
||||
navigate(task.actionTarget);
|
||||
break;
|
||||
case 'external_link':
|
||||
openUrl(task.actionTarget);
|
||||
break;
|
||||
case 'open_modal':
|
||||
if (task.actionTarget === 'blobbi_post') {
|
||||
onOpenPostModal();
|
||||
}
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const progress = task.required > 1
|
||||
? Math.round((task.current / task.required) * 100)
|
||||
: task.completed ? 100 : 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-4 p-4 rounded-xl border transition-all",
|
||||
task.completed
|
||||
? "bg-emerald-500/5 border-emerald-500/20"
|
||||
: "bg-card/60 border-border hover:border-primary/30"
|
||||
)}
|
||||
>
|
||||
{/* Status indicator */}
|
||||
<div className={cn(
|
||||
"size-10 rounded-full flex items-center justify-center shrink-0",
|
||||
task.completed
|
||||
? "bg-emerald-500/20 text-emerald-600 dark:text-emerald-400"
|
||||
: "bg-muted text-muted-foreground"
|
||||
)}>
|
||||
{task.completed ? (
|
||||
<Check className="size-5" />
|
||||
) : task.required > 1 ? (
|
||||
<span className="text-sm font-medium">{task.current}/{task.required}</span>
|
||||
) : (
|
||||
<span className="text-lg">○</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Task info */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<h4 className={cn(
|
||||
"font-medium",
|
||||
task.completed && "text-emerald-600 dark:text-emerald-400"
|
||||
)}>
|
||||
{task.name}
|
||||
</h4>
|
||||
{task.completed && (
|
||||
<Badge variant="secondary" className="bg-emerald-500/20 text-emerald-700 dark:text-emerald-300 text-xs">
|
||||
Complete
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{task.description}
|
||||
</p>
|
||||
|
||||
{/* Progress bar for multi-step tasks */}
|
||||
{task.required > 1 && !task.completed && (
|
||||
<Progress value={progress} className="h-1.5 mt-2" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Action button */}
|
||||
{task.action && task.actionLabel && !task.completed && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleAction}
|
||||
className="shrink-0 gap-2"
|
||||
>
|
||||
{task.actionLabel}
|
||||
{task.action === 'external_link' ? (
|
||||
<ExternalLink className="size-3.5" />
|
||||
) : (
|
||||
<ChevronRight className="size-3.5" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Main Component ───────────────────────────────────────────────────────────
|
||||
|
||||
export function HatchTasksPanel({
|
||||
tasks,
|
||||
allCompleted,
|
||||
isLoading,
|
||||
onOpenPostModal,
|
||||
onHatch,
|
||||
isHatching = false,
|
||||
}: HatchTasksPanelProps) {
|
||||
const completedCount = tasks.filter(t => t.completed).length;
|
||||
const totalTasks = tasks.length;
|
||||
const overallProgress = Math.round((completedCount / totalTasks) * 100);
|
||||
|
||||
return (
|
||||
<Card className="border-primary/20 bg-gradient-to-br from-primary/5 to-transparent">
|
||||
<CardHeader className="pb-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<span className="text-2xl">🥚</span>
|
||||
Hatch Tasks
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Complete these tasks to hatch your Blobbi
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Badge variant="outline" className="text-base px-3 py-1">
|
||||
{completedCount}/{totalTasks}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{/* Overall progress */}
|
||||
<div className="mt-4">
|
||||
<div className="flex items-center justify-between text-sm mb-2">
|
||||
<span className="text-muted-foreground">Overall progress</span>
|
||||
<span className="font-medium">{overallProgress}%</span>
|
||||
</div>
|
||||
<Progress value={overallProgress} className="h-2" />
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-3">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="size-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{tasks.map(task => (
|
||||
<TaskRow
|
||||
key={task.id}
|
||||
task={task}
|
||||
onOpenPostModal={onOpenPostModal}
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* Hatch button - only visible when all tasks complete */}
|
||||
{allCompleted && (
|
||||
<div className="pt-4 border-t border-border mt-4">
|
||||
<Button
|
||||
onClick={onHatch}
|
||||
disabled={isHatching}
|
||||
size="lg"
|
||||
className="w-full gap-2 bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600 text-white"
|
||||
>
|
||||
{isHatching ? (
|
||||
<>
|
||||
<Loader2 className="size-5 animate-spin" />
|
||||
Hatching...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-xl">🐣</span>
|
||||
Hatch Your Blobbi!
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
// src/blobbi/actions/components/InlineMusicPlayer.tsx
|
||||
|
||||
import { useCallback, useEffect } from 'react';
|
||||
import { Music, Play, Pause, RotateCcw, MoreHorizontal, Loader2, AlertCircle, X, Volume2, VolumeX } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Slider } from '@/components/ui/slider';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
import { useAudioPlayback } from '../hooks/useAudioPlayback';
|
||||
import type { SelectedTrack } from './PlayMusicModal';
|
||||
|
||||
// Re-export for external use
|
||||
export type { SelectedTrack } from './PlayMusicModal';
|
||||
|
||||
interface InlineMusicPlayerProps {
|
||||
/** The selected track */
|
||||
selection: SelectedTrack;
|
||||
/** Called when user wants to change the track */
|
||||
onChangeTrack: () => void;
|
||||
/** Called when user closes the player */
|
||||
onClose: () => void;
|
||||
/** Called when playback starts (for Blobbi reaction state) */
|
||||
onPlaybackStart?: () => void;
|
||||
/** Called when playback stops/pauses (for Blobbi reaction state) */
|
||||
onPlaybackStop?: () => void;
|
||||
/** Whether the action has been published (playback only starts after publish) */
|
||||
isPublished: boolean;
|
||||
/** Whether publishing is in progress */
|
||||
isPublishing: boolean;
|
||||
}
|
||||
|
||||
// ─── Component ────────────────────────────────────────────────────────────────
|
||||
|
||||
export function InlineMusicPlayer({
|
||||
selection,
|
||||
onChangeTrack,
|
||||
onClose,
|
||||
onPlaybackStart,
|
||||
onPlaybackStop,
|
||||
isPublished,
|
||||
isPublishing,
|
||||
}: InlineMusicPlayerProps) {
|
||||
const {
|
||||
state: playbackState,
|
||||
error: playbackError,
|
||||
load,
|
||||
toggle,
|
||||
restart,
|
||||
stop,
|
||||
isPlaying,
|
||||
volume,
|
||||
setVolume,
|
||||
cleanup,
|
||||
} = useAudioPlayback({
|
||||
onEnded: () => {
|
||||
onPlaybackStop?.();
|
||||
},
|
||||
});
|
||||
|
||||
// Auto-start playback when first published (idle -> playing)
|
||||
// Note: 'stopped' state is NOT included here - stop is a terminal state
|
||||
// that requires explicit user action (play button) to restart
|
||||
useEffect(() => {
|
||||
if (isPublished && playbackState === 'idle') {
|
||||
load(selection.url, true);
|
||||
onPlaybackStart?.();
|
||||
}
|
||||
}, [isPublished, playbackState, selection.url, load, onPlaybackStart]);
|
||||
|
||||
// Force reload when source URL changes while already playing/paused
|
||||
useEffect(() => {
|
||||
// Only trigger reload if we're in an active playback state with a different URL
|
||||
if (isPublished && (playbackState === 'playing' || playbackState === 'paused')) {
|
||||
// The load function will check if URL changed and reload if needed
|
||||
load(selection.url, true);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- Only react to selection.url changes
|
||||
}, [selection.url]);
|
||||
|
||||
// Notify on playback state changes
|
||||
useEffect(() => {
|
||||
if (isPlaying) {
|
||||
onPlaybackStart?.();
|
||||
} else if (playbackState === 'paused' || playbackState === 'stopped') {
|
||||
onPlaybackStop?.();
|
||||
}
|
||||
}, [isPlaying, playbackState, onPlaybackStart, onPlaybackStop]);
|
||||
|
||||
// Cleanup on close
|
||||
const handleClose = useCallback(() => {
|
||||
stop();
|
||||
cleanup();
|
||||
onPlaybackStop?.();
|
||||
onClose();
|
||||
}, [stop, cleanup, onPlaybackStop, onClose]);
|
||||
|
||||
// Handle play/pause toggle
|
||||
const handleToggle = useCallback(async () => {
|
||||
if (playbackState === 'idle' || playbackState === 'stopped') {
|
||||
load(selection.url, true);
|
||||
} else {
|
||||
await toggle();
|
||||
}
|
||||
}, [playbackState, selection.url, load, toggle]);
|
||||
|
||||
// Track info
|
||||
const trackTitle = selection.track.title;
|
||||
const trackArtist = selection.track.artist;
|
||||
|
||||
const isLoading = playbackState === 'loading' || isPublishing;
|
||||
const hasError = playbackState === 'error';
|
||||
|
||||
return (
|
||||
<div className="mx-4 sm:mx-6 mb-4">
|
||||
<div className={cn(
|
||||
"rounded-xl border bg-card/80 backdrop-blur-sm overflow-hidden",
|
||||
"shadow-sm transition-all",
|
||||
isPlaying && "ring-2 ring-pink-500/30"
|
||||
)}>
|
||||
{/* Main content row */}
|
||||
<div className="flex items-center gap-3 p-3">
|
||||
{/* Music icon / Now Playing indicator */}
|
||||
<div className={cn(
|
||||
"size-10 rounded-lg flex items-center justify-center shrink-0",
|
||||
isPlaying
|
||||
? "bg-pink-500/20"
|
||||
: "bg-muted"
|
||||
)}>
|
||||
<Music className={cn(
|
||||
"size-5",
|
||||
isPlaying ? "text-pink-500 animate-pulse" : "text-muted-foreground"
|
||||
)} />
|
||||
</div>
|
||||
|
||||
{/* Track info */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-sm truncate">{trackTitle}</p>
|
||||
{trackArtist && (
|
||||
<p className="text-xs text-muted-foreground truncate">{trackArtist}</p>
|
||||
)}
|
||||
{!trackArtist && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{isPlaying ? 'Now playing...' : isPublishing ? 'Starting...' : 'Ready to play'}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Controls */}
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
{/* Play/Pause button */}
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
onClick={handleToggle}
|
||||
disabled={isLoading || !isPublished}
|
||||
className="size-9 rounded-full"
|
||||
>
|
||||
{isLoading ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : isPlaying ? (
|
||||
<Pause className="size-4" />
|
||||
) : (
|
||||
<Play className="size-4 ml-0.5" />
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* Restart button - only show when actively playing or paused */}
|
||||
{isPublished && (playbackState === 'playing' || playbackState === 'paused') && (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
restart();
|
||||
}}
|
||||
className="size-9 rounded-full"
|
||||
title="Restart from beginning"
|
||||
>
|
||||
<RotateCcw className="size-3.5" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Volume control */}
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="size-9 rounded-full"
|
||||
title={volume === 0 ? 'Unmute' : 'Volume'}
|
||||
>
|
||||
{volume === 0 ? (
|
||||
<VolumeX className="size-4" />
|
||||
) : (
|
||||
<Volume2 className="size-4" />
|
||||
)}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
side="top"
|
||||
align="center"
|
||||
className="w-32 p-3"
|
||||
>
|
||||
<Slider
|
||||
value={[volume * 100]}
|
||||
onValueChange={([val]) => setVolume(val / 100)}
|
||||
max={100}
|
||||
step={1}
|
||||
className="w-full"
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{/* Change track button */}
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
onClick={onChangeTrack}
|
||||
disabled={isPublishing}
|
||||
className="size-9 rounded-full"
|
||||
>
|
||||
<MoreHorizontal className="size-4" />
|
||||
</Button>
|
||||
|
||||
{/* Close button */}
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
onClick={handleClose}
|
||||
disabled={isPublishing}
|
||||
className="size-9 rounded-full text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<X className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error message */}
|
||||
{hasError && playbackError && (
|
||||
<div className="px-3 pb-3">
|
||||
<div className="flex items-start gap-2 p-2 rounded-lg bg-amber-500/10 text-amber-600 dark:text-amber-400">
|
||||
<AlertCircle className="size-4 mt-0.5 shrink-0" />
|
||||
<p className="text-xs">{playbackError.message}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
// src/blobbi/actions/components/InlineSingCard.tsx
|
||||
|
||||
import { useState, useRef, useCallback, useEffect } from 'react';
|
||||
import {
|
||||
Mic,
|
||||
Play,
|
||||
Pause,
|
||||
Square,
|
||||
FileText,
|
||||
Check,
|
||||
X,
|
||||
Loader2,
|
||||
AlertCircle,
|
||||
RefreshCw,
|
||||
} from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
import { useAudioPlayback } from '../hooks/useAudioPlayback';
|
||||
import { getRandomLyrics, type LyricsEntry } from '../lib/blobbi-random-lyrics';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
type RecordingState = 'idle' | 'requesting' | 'recording' | 'recorded' | 'error';
|
||||
|
||||
interface InlineSingCardProps {
|
||||
/** Called when user confirms the singing action (publish the action) */
|
||||
onConfirm: () => Promise<void>;
|
||||
/** Called when user closes the sing card */
|
||||
onClose: () => void;
|
||||
/** Called when recording starts (for Blobbi reaction) */
|
||||
onRecordingStart?: () => void;
|
||||
/** Called when recording stops (for Blobbi reaction) */
|
||||
onRecordingStop?: () => void;
|
||||
/** Whether publishing is in progress */
|
||||
isPublishing: boolean;
|
||||
}
|
||||
|
||||
// ─── MIME Type Selection ──────────────────────────────────────────────────────
|
||||
|
||||
const AUDIO_MIME_CANDIDATES = [
|
||||
'audio/webm;codecs=opus',
|
||||
'audio/webm',
|
||||
'audio/mp4',
|
||||
'audio/ogg;codecs=opus',
|
||||
'audio/ogg',
|
||||
] as const;
|
||||
|
||||
function getSupportedAudioMimeType(): string | undefined {
|
||||
if (typeof MediaRecorder === 'undefined') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
for (const mimeType of AUDIO_MIME_CANDIDATES) {
|
||||
if (MediaRecorder.isTypeSupported(mimeType)) {
|
||||
return mimeType;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// ─── Component ────────────────────────────────────────────────────────────────
|
||||
|
||||
export function InlineSingCard({
|
||||
onConfirm,
|
||||
onClose,
|
||||
onRecordingStart,
|
||||
onRecordingStop,
|
||||
isPublishing,
|
||||
}: InlineSingCardProps) {
|
||||
// Recording state
|
||||
const [recordingState, setRecordingState] = useState<RecordingState>('idle');
|
||||
const [recordingError, setRecordingError] = useState<string | null>(null);
|
||||
const [recordingDuration, setRecordingDuration] = useState(0);
|
||||
const [audioUrl, setAudioUrl] = useState<string | null>(null);
|
||||
|
||||
// Lyrics state
|
||||
const [currentLyrics, setCurrentLyrics] = useState<LyricsEntry | null>(null);
|
||||
const [showLyrics, setShowLyrics] = useState(false);
|
||||
|
||||
// Refs
|
||||
const mediaRecorderRef = useRef<MediaRecorder | null>(null);
|
||||
const chunksRef = useRef<Blob[]>([]);
|
||||
const streamRef = useRef<MediaStream | null>(null);
|
||||
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const actualMimeTypeRef = useRef<string | undefined>(undefined);
|
||||
|
||||
// Audio playback for preview
|
||||
const {
|
||||
state: playbackState,
|
||||
error: playbackError,
|
||||
load: loadAudio,
|
||||
toggle: togglePlayback,
|
||||
stop: stopPlayback,
|
||||
isPlaying,
|
||||
cleanup: cleanupPlayback,
|
||||
} = useAudioPlayback();
|
||||
|
||||
// Cleanup all resources
|
||||
const cleanupAll = useCallback(() => {
|
||||
// Stop timer
|
||||
if (timerRef.current) {
|
||||
clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
}
|
||||
|
||||
// Stop media recorder
|
||||
if (mediaRecorderRef.current && mediaRecorderRef.current.state !== 'inactive') {
|
||||
try {
|
||||
mediaRecorderRef.current.stop();
|
||||
} catch {
|
||||
// Ignore errors during cleanup
|
||||
}
|
||||
}
|
||||
mediaRecorderRef.current = null;
|
||||
|
||||
// Stop stream tracks
|
||||
if (streamRef.current) {
|
||||
streamRef.current.getTracks().forEach(track => track.stop());
|
||||
streamRef.current = null;
|
||||
}
|
||||
|
||||
// Cleanup playback
|
||||
cleanupPlayback();
|
||||
|
||||
// Revoke URL
|
||||
if (audioUrl) {
|
||||
URL.revokeObjectURL(audioUrl);
|
||||
}
|
||||
}, [audioUrl, cleanupPlayback]);
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
cleanupAll();
|
||||
};
|
||||
}, [cleanupAll]);
|
||||
|
||||
// Reset recording
|
||||
const resetRecording = useCallback(() => {
|
||||
cleanupAll();
|
||||
setRecordingState('idle');
|
||||
setRecordingError(null);
|
||||
setRecordingDuration(0);
|
||||
setAudioUrl(null);
|
||||
chunksRef.current = [];
|
||||
actualMimeTypeRef.current = undefined;
|
||||
// Keep lyrics
|
||||
}, [cleanupAll]);
|
||||
|
||||
// Check browser support
|
||||
const checkRecordingSupport = (): boolean => {
|
||||
if (typeof navigator === 'undefined') return false;
|
||||
if (!navigator.mediaDevices) return false;
|
||||
if (!navigator.mediaDevices.getUserMedia) return false;
|
||||
if (typeof MediaRecorder === 'undefined') return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
// Start recording
|
||||
const startRecording = useCallback(async () => {
|
||||
if (!checkRecordingSupport()) {
|
||||
setRecordingError('Audio recording is not supported in this browser.');
|
||||
setRecordingState('error');
|
||||
return;
|
||||
}
|
||||
|
||||
setRecordingState('requesting');
|
||||
setRecordingError(null);
|
||||
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: {
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true,
|
||||
}
|
||||
});
|
||||
|
||||
streamRef.current = stream;
|
||||
chunksRef.current = [];
|
||||
|
||||
// Get supported MIME type
|
||||
const supportedMimeType = getSupportedAudioMimeType();
|
||||
|
||||
// Create MediaRecorder
|
||||
let mediaRecorder: MediaRecorder;
|
||||
if (supportedMimeType) {
|
||||
mediaRecorder = new MediaRecorder(stream, { mimeType: supportedMimeType });
|
||||
} else {
|
||||
mediaRecorder = new MediaRecorder(stream);
|
||||
}
|
||||
|
||||
actualMimeTypeRef.current = mediaRecorder.mimeType || supportedMimeType;
|
||||
mediaRecorderRef.current = mediaRecorder;
|
||||
|
||||
mediaRecorder.ondataavailable = (event) => {
|
||||
if (event.data.size > 0) {
|
||||
chunksRef.current.push(event.data);
|
||||
}
|
||||
};
|
||||
|
||||
mediaRecorder.onstop = () => {
|
||||
const blobMimeType = actualMimeTypeRef.current || 'audio/webm';
|
||||
const blob = new Blob(chunksRef.current, { type: blobMimeType });
|
||||
const url = URL.createObjectURL(blob);
|
||||
setAudioUrl(url);
|
||||
setRecordingState('recorded');
|
||||
|
||||
if (streamRef.current) {
|
||||
streamRef.current.getTracks().forEach(track => track.stop());
|
||||
streamRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
mediaRecorder.onerror = () => {
|
||||
setRecordingError('Recording failed. Please try again.');
|
||||
setRecordingState('error');
|
||||
};
|
||||
|
||||
mediaRecorder.start(100);
|
||||
setRecordingState('recording');
|
||||
setRecordingDuration(0);
|
||||
|
||||
// Notify parent that recording started (for Blobbi reaction)
|
||||
onRecordingStart?.();
|
||||
|
||||
timerRef.current = setInterval(() => {
|
||||
setRecordingDuration(prev => prev + 1);
|
||||
}, 1000);
|
||||
|
||||
} catch (err) {
|
||||
if (err instanceof Error) {
|
||||
if (err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError') {
|
||||
setRecordingError('Microphone access was denied.');
|
||||
} else if (err.name === 'NotFoundError') {
|
||||
setRecordingError('No microphone found.');
|
||||
} else {
|
||||
setRecordingError(err.message);
|
||||
}
|
||||
} else {
|
||||
setRecordingError('Failed to access microphone.');
|
||||
}
|
||||
setRecordingState('error');
|
||||
}
|
||||
}, [onRecordingStart]);
|
||||
|
||||
// Stop recording
|
||||
const stopRecording = useCallback(() => {
|
||||
if (timerRef.current) {
|
||||
clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
}
|
||||
|
||||
if (mediaRecorderRef.current && mediaRecorderRef.current.state !== 'inactive') {
|
||||
mediaRecorderRef.current.stop();
|
||||
}
|
||||
|
||||
// Notify parent that recording stopped (for Blobbi reaction)
|
||||
onRecordingStop?.();
|
||||
}, [onRecordingStop]);
|
||||
|
||||
// Handle preview playback
|
||||
const handlePreview = useCallback(() => {
|
||||
if (!audioUrl) return;
|
||||
|
||||
if (playbackState === 'idle') {
|
||||
loadAudio(audioUrl, true);
|
||||
} else {
|
||||
togglePlayback();
|
||||
}
|
||||
}, [audioUrl, playbackState, loadAudio, togglePlayback]);
|
||||
|
||||
// Handle confirm
|
||||
const handleConfirm = useCallback(async () => {
|
||||
stopPlayback();
|
||||
await onConfirm();
|
||||
// After successful publish, close the card
|
||||
onClose();
|
||||
}, [stopPlayback, onConfirm, onClose]);
|
||||
|
||||
// Handle close
|
||||
const handleClose = useCallback(() => {
|
||||
cleanupAll();
|
||||
onClose();
|
||||
}, [cleanupAll, onClose]);
|
||||
|
||||
// Handle lyrics toggle
|
||||
const handleLyricsToggle = useCallback(() => {
|
||||
if (!currentLyrics && !showLyrics) {
|
||||
// Generate lyrics on first open
|
||||
setCurrentLyrics(getRandomLyrics());
|
||||
}
|
||||
setShowLyrics(!showLyrics);
|
||||
}, [currentLyrics, showLyrics]);
|
||||
|
||||
// Get new lyrics
|
||||
const handleNewLyrics = useCallback(() => {
|
||||
setCurrentLyrics(getRandomLyrics());
|
||||
}, []);
|
||||
|
||||
// Format duration
|
||||
const formatDuration = (seconds: number) => {
|
||||
const mins = Math.floor(seconds / 60);
|
||||
const secs = seconds % 60;
|
||||
return `${mins}:${secs.toString().padStart(2, '0')}`;
|
||||
};
|
||||
|
||||
const hasRecording = recordingState === 'recorded';
|
||||
const isRecording = recordingState === 'recording';
|
||||
const canConfirm = hasRecording && !isPublishing;
|
||||
|
||||
return (
|
||||
<div className="mx-4 sm:mx-6 mb-4">
|
||||
<div className={cn(
|
||||
"rounded-xl border bg-card/80 backdrop-blur-sm overflow-hidden",
|
||||
"shadow-sm transition-all",
|
||||
isRecording && "ring-2 ring-red-500/30"
|
||||
)}>
|
||||
{/* Lyrics panel (expands upward visually by being above controls) */}
|
||||
{showLyrics && currentLyrics && (
|
||||
<div className="px-3 pt-3 pb-2 border-b border-border/50">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="text-sm font-medium">{currentLyrics.title}</span>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
onClick={handleNewLyrics}
|
||||
className="size-7 rounded-full"
|
||||
>
|
||||
<RefreshCw className="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="p-3 rounded-lg bg-muted/50 text-sm leading-relaxed whitespace-pre-line max-h-32 overflow-y-auto">
|
||||
{currentLyrics.lines.join('\n')}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Status row (recording/recorded info) */}
|
||||
{(isRecording || hasRecording) && (
|
||||
<div className="px-3 pt-3 pb-2 border-b border-border/50">
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
{isRecording && (
|
||||
<>
|
||||
<div className="size-2 rounded-full bg-red-500 animate-pulse" />
|
||||
<span className="text-sm font-mono font-medium text-red-500">
|
||||
{formatDuration(recordingDuration)}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">Recording...</span>
|
||||
</>
|
||||
)}
|
||||
{hasRecording && !isRecording && (
|
||||
<>
|
||||
<Check className="size-4 text-purple-500" />
|
||||
<span className="text-sm font-mono font-medium text-purple-500">
|
||||
{formatDuration(recordingDuration)}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">Recorded</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error message */}
|
||||
{(recordingError || playbackError) && (
|
||||
<div className="px-3 pt-2">
|
||||
<div className="flex items-start gap-2 p-2 rounded-lg bg-amber-500/10 text-amber-600 dark:text-amber-400">
|
||||
<AlertCircle className="size-4 mt-0.5 shrink-0" />
|
||||
<p className="text-xs">{recordingError || playbackError?.message}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Main controls row */}
|
||||
<div className="flex items-center justify-between gap-2 p-3">
|
||||
{/* Left: Lyrics button */}
|
||||
<Button
|
||||
size="icon"
|
||||
variant={showLyrics ? "secondary" : "ghost"}
|
||||
onClick={handleLyricsToggle}
|
||||
className="size-10 rounded-full shrink-0"
|
||||
>
|
||||
<FileText className="size-4" />
|
||||
</Button>
|
||||
|
||||
{/* Center: Record/Stop button */}
|
||||
<div className="flex items-center gap-2">
|
||||
{!isRecording && !hasRecording && (
|
||||
<Button
|
||||
onClick={startRecording}
|
||||
disabled={isPublishing}
|
||||
className="rounded-full px-6 bg-purple-500 hover:bg-purple-600"
|
||||
>
|
||||
<Mic className="size-4 mr-2" />
|
||||
Sing
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{isRecording && (
|
||||
<Button
|
||||
onClick={stopRecording}
|
||||
variant="destructive"
|
||||
className="rounded-full px-6"
|
||||
>
|
||||
<Square className="size-4 mr-2" />
|
||||
Stop
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{hasRecording && !isRecording && (
|
||||
<>
|
||||
<Button
|
||||
onClick={resetRecording}
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="size-10 rounded-full"
|
||||
>
|
||||
<RefreshCw className="size-4" />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={handleConfirm}
|
||||
disabled={!canConfirm}
|
||||
className="rounded-full px-6 bg-purple-500 hover:bg-purple-600"
|
||||
>
|
||||
{isPublishing ? (
|
||||
<Loader2 className="size-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Check className="size-4 mr-2" />
|
||||
)}
|
||||
{isPublishing ? 'Singing...' : 'Sing for Blobbi'}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Right: Preview button (when recording exists) */}
|
||||
{hasRecording ? (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
onClick={handlePreview}
|
||||
disabled={isPublishing}
|
||||
className="size-10 rounded-full shrink-0"
|
||||
>
|
||||
{isPlaying ? (
|
||||
<Pause className="size-4" />
|
||||
) : (
|
||||
<Play className="size-4 ml-0.5" />
|
||||
)}
|
||||
</Button>
|
||||
) : (
|
||||
/* Close button when no recording */
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
onClick={handleClose}
|
||||
className="size-10 rounded-full shrink-0 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<X className="size-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Close button row when recording exists */}
|
||||
{hasRecording && (
|
||||
<div className="px-3 pb-3 pt-0 flex justify-end">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={handleClose}
|
||||
disabled={isPublishing}
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<X className="size-3 mr-1" />
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
// src/blobbi/actions/components/PlayMusicModal.tsx
|
||||
|
||||
import { useState, useRef, useCallback, useEffect } from 'react';
|
||||
import { Music, Play, Pause, Check, Loader2, Volume2, AlertCircle } from 'lucide-react';
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
import {
|
||||
getAllTracks,
|
||||
formatTrackDuration,
|
||||
type BlobbiTrack,
|
||||
} from '../lib/blobbi-track-catalog';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Selected track for the music player
|
||||
*/
|
||||
export interface SelectedTrack {
|
||||
track: BlobbiTrack;
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface PlayMusicModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** Called with the selected track when user confirms */
|
||||
onConfirm: (selection: SelectedTrack) => void;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
// ─── Component ────────────────────────────────────────────────────────────────
|
||||
|
||||
export function PlayMusicModal({
|
||||
open,
|
||||
onOpenChange,
|
||||
onConfirm,
|
||||
isLoading,
|
||||
}: PlayMusicModalProps) {
|
||||
const [selectedTrack, setSelectedTrack] = useState<SelectedTrack | null>(null);
|
||||
const [isPlaying, setIsPlaying] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null);
|
||||
|
||||
// Track the current audio source URL to detect changes
|
||||
const currentAudioUrlRef = useRef<string | null>(null);
|
||||
|
||||
const tracks = getAllTracks();
|
||||
|
||||
// Cleanup audio on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause();
|
||||
audioRef.current = null;
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Reset state when modal opens
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setSelectedTrack(null);
|
||||
setIsPlaying(false);
|
||||
setError(null);
|
||||
currentAudioUrlRef.current = null;
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
// Handle selecting a track
|
||||
const handleSelectTrack = useCallback((track: BlobbiTrack) => {
|
||||
// Stop current playback
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause();
|
||||
setIsPlaying(false);
|
||||
}
|
||||
|
||||
setSelectedTrack({ track, url: track.url });
|
||||
setError(null);
|
||||
}, []);
|
||||
|
||||
// Handle play/pause preview
|
||||
const handleTogglePlay = useCallback(() => {
|
||||
if (!selectedTrack) return;
|
||||
|
||||
const audioUrl = selectedTrack.url;
|
||||
|
||||
// Check if we need to create a new Audio instance (source changed or first time)
|
||||
const needsNewAudio = !audioRef.current || currentAudioUrlRef.current !== audioUrl;
|
||||
|
||||
if (needsNewAudio) {
|
||||
// Stop and cleanup old audio if exists
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause();
|
||||
audioRef.current.onended = null;
|
||||
audioRef.current.onerror = null;
|
||||
}
|
||||
|
||||
// Create new Audio instance with the correct source
|
||||
audioRef.current = new Audio(audioUrl);
|
||||
currentAudioUrlRef.current = audioUrl;
|
||||
|
||||
audioRef.current.onended = () => setIsPlaying(false);
|
||||
audioRef.current.onerror = () => {
|
||||
setError('Failed to load this track. Please try another one.');
|
||||
setIsPlaying(false);
|
||||
};
|
||||
}
|
||||
|
||||
if (isPlaying && !needsNewAudio) {
|
||||
// Pause current playback
|
||||
audioRef.current?.pause();
|
||||
setIsPlaying(false);
|
||||
} else {
|
||||
// Start playback (either new source or resuming)
|
||||
audioRef.current?.play().catch(() => {
|
||||
setError('Failed to play this track. Please try another one.');
|
||||
setIsPlaying(false);
|
||||
});
|
||||
setIsPlaying(true);
|
||||
}
|
||||
}, [selectedTrack, isPlaying]);
|
||||
|
||||
// Handle confirm
|
||||
const handleConfirm = useCallback(() => {
|
||||
if (!selectedTrack) return;
|
||||
|
||||
// Stop playback
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause();
|
||||
setIsPlaying(false);
|
||||
}
|
||||
onConfirm(selectedTrack);
|
||||
}, [selectedTrack, onConfirm]);
|
||||
|
||||
// Handle close
|
||||
const handleClose = useCallback((isOpen: boolean) => {
|
||||
if (!isOpen && audioRef.current) {
|
||||
audioRef.current.pause();
|
||||
setIsPlaying(false);
|
||||
}
|
||||
onOpenChange(isOpen);
|
||||
}, [onOpenChange]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<DialogContent className="max-w-md max-h-[85vh] flex flex-col p-0">
|
||||
{/* Header */}
|
||||
<DialogHeader className="px-6 pt-6 pb-4 border-b">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="size-10 rounded-xl bg-gradient-to-br from-pink-500/20 to-pink-500/5 flex items-center justify-center">
|
||||
<Music className="size-5 text-pink-500" />
|
||||
</div>
|
||||
<div>
|
||||
<DialogTitle className="text-xl">Play Music</DialogTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Choose a track to play for your Blobbi
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Content - Track List */}
|
||||
<div className="flex-1 overflow-y-auto px-6 py-4">
|
||||
<div className="grid gap-2">
|
||||
{tracks.map((track) => (
|
||||
<TrackRow
|
||||
key={track.id}
|
||||
track={track}
|
||||
isSelected={selectedTrack?.track.id === track.id}
|
||||
onSelect={() => handleSelectTrack(track)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{error && (
|
||||
<div className="mt-4 p-3 rounded-lg bg-amber-500/10 border border-amber-500/30">
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertCircle className="size-4 text-amber-500 mt-0.5 shrink-0" />
|
||||
<p className="text-sm text-amber-600 dark:text-amber-400">{error}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="px-6 py-4 border-t bg-muted/30">
|
||||
{/* Preview Controls */}
|
||||
{selectedTrack && (
|
||||
<div className="mb-4 p-3 rounded-lg bg-card border">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button
|
||||
size="icon"
|
||||
variant="outline"
|
||||
onClick={handleTogglePlay}
|
||||
className="size-10 rounded-full shrink-0"
|
||||
>
|
||||
{isPlaying ? (
|
||||
<Pause className="size-4" />
|
||||
) : (
|
||||
<Play className="size-4 ml-0.5" />
|
||||
)}
|
||||
</Button>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium truncate text-sm">{selectedTrack.track.title}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{isPlaying ? 'Now playing...' : 'Click to preview'}
|
||||
</p>
|
||||
</div>
|
||||
{isPlaying && (
|
||||
<Volume2 className="size-4 text-primary animate-pulse shrink-0" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleClose(false)}
|
||||
className="flex-1"
|
||||
disabled={isLoading}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleConfirm}
|
||||
disabled={!selectedTrack || isLoading}
|
||||
className="flex-1"
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="size-4 mr-2 animate-spin" />
|
||||
Playing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Music className="size-4 mr-2" />
|
||||
Play for Blobbi
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Track Row Component ──────────────────────────────────────────────────────
|
||||
|
||||
interface TrackRowProps {
|
||||
track: BlobbiTrack;
|
||||
isSelected: boolean;
|
||||
onSelect: () => void;
|
||||
}
|
||||
|
||||
function TrackRow({ track, isSelected, onSelect }: TrackRowProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onSelect}
|
||||
className={cn(
|
||||
"w-full p-3 rounded-xl text-left transition-all",
|
||||
"border hover:border-primary/30",
|
||||
isSelected
|
||||
? "border-primary bg-primary/5 ring-2 ring-primary/20"
|
||||
: "border-border bg-card/60"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={cn(
|
||||
"size-10 rounded-lg flex items-center justify-center",
|
||||
isSelected ? "bg-primary/20" : "bg-muted"
|
||||
)}>
|
||||
<Music className={cn(
|
||||
"size-5",
|
||||
isSelected ? "text-primary" : "text-muted-foreground"
|
||||
)} />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium truncate">{track.title}</p>
|
||||
<p className="text-sm text-muted-foreground">{track.artist}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{formatTrackDuration(track.durationSeconds)}
|
||||
</span>
|
||||
{isSelected && <Check className="size-4 text-primary" />}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,601 @@
|
||||
// src/blobbi/actions/components/SingModal.tsx
|
||||
|
||||
import { useState, useRef, useCallback, useEffect } from 'react';
|
||||
import { Mic, MicOff, Play, Pause, Square, Loader2, AlertCircle, RotateCcw, Sparkles, ChevronDown, ChevronUp } from 'lucide-react';
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
import { getRandomLyrics, type LyricsEntry } from '../lib/blobbi-random-lyrics';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface SingModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onConfirm: () => void;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
type RecordingState = 'idle' | 'requesting' | 'recording' | 'recorded' | 'playing' | 'error';
|
||||
|
||||
// ─── MIME Type Selection Helper ───────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Ordered list of MIME types to try for audio recording.
|
||||
* The first supported type will be used.
|
||||
*/
|
||||
const AUDIO_MIME_CANDIDATES = [
|
||||
'audio/webm;codecs=opus',
|
||||
'audio/webm',
|
||||
'audio/mp4',
|
||||
'audio/ogg;codecs=opus',
|
||||
'audio/ogg',
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Get the first supported MIME type for MediaRecorder.
|
||||
* Returns undefined if no explicit MIME type is supported (let browser decide).
|
||||
*/
|
||||
function getSupportedAudioMimeType(): string | undefined {
|
||||
if (typeof MediaRecorder === 'undefined') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
for (const mimeType of AUDIO_MIME_CANDIDATES) {
|
||||
if (MediaRecorder.isTypeSupported(mimeType)) {
|
||||
return mimeType;
|
||||
}
|
||||
}
|
||||
|
||||
// No explicit MIME type supported, let browser use default
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// ─── Component ────────────────────────────────────────────────────────────────
|
||||
|
||||
export function SingModal({
|
||||
open,
|
||||
onOpenChange,
|
||||
onConfirm,
|
||||
isLoading,
|
||||
}: SingModalProps) {
|
||||
const [recordingState, setRecordingState] = useState<RecordingState>('idle');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [playbackError, setPlaybackError] = useState<string | null>(null);
|
||||
const [recordingDuration, setRecordingDuration] = useState(0);
|
||||
const [audioUrl, setAudioUrl] = useState<string | null>(null);
|
||||
const [currentLyrics, setCurrentLyrics] = useState<LyricsEntry | null>(null);
|
||||
const [showLyrics, setShowLyrics] = useState(false);
|
||||
|
||||
const mediaRecorderRef = useRef<MediaRecorder | null>(null);
|
||||
const chunksRef = useRef<Blob[]>([]);
|
||||
const streamRef = useRef<MediaStream | null>(null);
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null);
|
||||
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
// Track the actual MIME type used by the recorder
|
||||
const actualMimeTypeRef = useRef<string | undefined>(undefined);
|
||||
|
||||
const cleanup = useCallback(() => {
|
||||
// Stop timer
|
||||
if (timerRef.current) {
|
||||
clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
}
|
||||
|
||||
// Stop media recorder
|
||||
if (mediaRecorderRef.current && mediaRecorderRef.current.state !== 'inactive') {
|
||||
mediaRecorderRef.current.stop();
|
||||
}
|
||||
mediaRecorderRef.current = null;
|
||||
|
||||
// Stop stream tracks
|
||||
if (streamRef.current) {
|
||||
streamRef.current.getTracks().forEach(track => track.stop());
|
||||
streamRef.current = null;
|
||||
}
|
||||
|
||||
// Stop audio playback
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause();
|
||||
audioRef.current = null;
|
||||
}
|
||||
|
||||
// Revoke URL
|
||||
if (audioUrl) {
|
||||
URL.revokeObjectURL(audioUrl);
|
||||
}
|
||||
}, [audioUrl]);
|
||||
|
||||
const resetRecording = useCallback(() => {
|
||||
cleanup();
|
||||
setRecordingState('idle');
|
||||
setError(null);
|
||||
setPlaybackError(null);
|
||||
setRecordingDuration(0);
|
||||
setAudioUrl(null);
|
||||
chunksRef.current = [];
|
||||
currentPlaybackUrlRef.current = null;
|
||||
actualMimeTypeRef.current = undefined;
|
||||
// Keep lyrics when re-recording so user can sing the same song
|
||||
}, [cleanup]);
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
cleanup();
|
||||
};
|
||||
}, [cleanup]);
|
||||
|
||||
// Reset state when modal opens
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
resetRecording();
|
||||
} else {
|
||||
cleanup();
|
||||
}
|
||||
}, [open, cleanup, resetRecording]);
|
||||
|
||||
// Handle getting random lyrics
|
||||
const handleRandomLyrics = useCallback(() => {
|
||||
const lyrics = getRandomLyrics();
|
||||
setCurrentLyrics(lyrics);
|
||||
setShowLyrics(true);
|
||||
}, []);
|
||||
|
||||
// Check if browser supports media recording
|
||||
const checkRecordingSupport = (): boolean => {
|
||||
if (typeof navigator === 'undefined') return false;
|
||||
if (!navigator.mediaDevices) return false;
|
||||
if (!navigator.mediaDevices.getUserMedia) return false;
|
||||
if (typeof MediaRecorder === 'undefined') return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
// Start recording
|
||||
const startRecording = useCallback(async () => {
|
||||
if (!checkRecordingSupport()) {
|
||||
setError('Audio recording is not supported in this browser.');
|
||||
setRecordingState('error');
|
||||
return;
|
||||
}
|
||||
|
||||
setRecordingState('requesting');
|
||||
setError(null);
|
||||
setPlaybackError(null);
|
||||
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: {
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true,
|
||||
}
|
||||
});
|
||||
|
||||
streamRef.current = stream;
|
||||
chunksRef.current = [];
|
||||
|
||||
// Get the first supported MIME type using our helper
|
||||
const supportedMimeType = getSupportedAudioMimeType();
|
||||
|
||||
// Create MediaRecorder with or without explicit MIME type
|
||||
let mediaRecorder: MediaRecorder;
|
||||
if (supportedMimeType) {
|
||||
mediaRecorder = new MediaRecorder(stream, { mimeType: supportedMimeType });
|
||||
} else {
|
||||
// Let browser choose default MIME type
|
||||
mediaRecorder = new MediaRecorder(stream);
|
||||
}
|
||||
|
||||
// Store the actual MIME type being used (may differ from what we requested)
|
||||
actualMimeTypeRef.current = mediaRecorder.mimeType || supportedMimeType;
|
||||
mediaRecorderRef.current = mediaRecorder;
|
||||
|
||||
mediaRecorder.ondataavailable = (event) => {
|
||||
if (event.data.size > 0) {
|
||||
chunksRef.current.push(event.data);
|
||||
}
|
||||
};
|
||||
|
||||
mediaRecorder.onstop = () => {
|
||||
// Create blob from chunks using the actual MIME type used by the recorder
|
||||
const blobMimeType = actualMimeTypeRef.current || 'audio/webm';
|
||||
const blob = new Blob(chunksRef.current, { type: blobMimeType });
|
||||
const url = URL.createObjectURL(blob);
|
||||
setAudioUrl(url);
|
||||
setRecordingState('recorded');
|
||||
|
||||
// Stop stream tracks
|
||||
if (streamRef.current) {
|
||||
streamRef.current.getTracks().forEach(track => track.stop());
|
||||
streamRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
mediaRecorder.onerror = () => {
|
||||
setError('Recording failed. Please try again.');
|
||||
setRecordingState('error');
|
||||
};
|
||||
|
||||
// Start recording
|
||||
mediaRecorder.start(100); // Collect data every 100ms
|
||||
setRecordingState('recording');
|
||||
setRecordingDuration(0);
|
||||
|
||||
// Start timer
|
||||
timerRef.current = setInterval(() => {
|
||||
setRecordingDuration(prev => prev + 1);
|
||||
}, 1000);
|
||||
|
||||
} catch (err) {
|
||||
if (err instanceof Error) {
|
||||
if (err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError') {
|
||||
setError('Microphone access was denied. Please allow microphone access and try again.');
|
||||
} else if (err.name === 'NotFoundError') {
|
||||
setError('No microphone found. Please connect a microphone and try again.');
|
||||
} else {
|
||||
setError(`Failed to access microphone: ${err.message}`);
|
||||
}
|
||||
} else {
|
||||
setError('Failed to access microphone. Please try again.');
|
||||
}
|
||||
setRecordingState('error');
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Stop recording
|
||||
const stopRecording = useCallback(() => {
|
||||
if (timerRef.current) {
|
||||
clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
}
|
||||
|
||||
if (mediaRecorderRef.current && mediaRecorderRef.current.state !== 'inactive') {
|
||||
mediaRecorderRef.current.stop();
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Track the current audio URL to detect changes
|
||||
const currentPlaybackUrlRef = useRef<string | null>(null);
|
||||
|
||||
// Play/pause preview
|
||||
const togglePlayback = useCallback(() => {
|
||||
if (!audioUrl) return;
|
||||
|
||||
// Clear previous playback error when attempting to play
|
||||
setPlaybackError(null);
|
||||
|
||||
if (recordingState === 'playing') {
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause();
|
||||
}
|
||||
setRecordingState('recorded');
|
||||
} else {
|
||||
// Check if we need to create a new Audio instance (URL changed or first time)
|
||||
const needsNewAudio = !audioRef.current || currentPlaybackUrlRef.current !== audioUrl;
|
||||
|
||||
if (needsNewAudio) {
|
||||
// Cleanup old audio if exists
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause();
|
||||
audioRef.current.onended = null;
|
||||
audioRef.current.onerror = null;
|
||||
}
|
||||
|
||||
// Create new Audio instance with the recorded audio URL
|
||||
audioRef.current = new Audio(audioUrl);
|
||||
currentPlaybackUrlRef.current = audioUrl;
|
||||
audioRef.current.onended = () => setRecordingState('recorded');
|
||||
|
||||
// Handle playback errors with user-visible message
|
||||
audioRef.current.onerror = () => {
|
||||
setPlaybackError('This browser could not play the recorded audio preview. Your recording was still created successfully.');
|
||||
setRecordingState('recorded');
|
||||
};
|
||||
}
|
||||
|
||||
audioRef.current?.play()
|
||||
.then(() => {
|
||||
setRecordingState('playing');
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('Failed to play recording:', err);
|
||||
// Provide user-friendly error message
|
||||
if (err.name === 'NotSupportedError') {
|
||||
setPlaybackError('Recording was created, but playback preview is not supported in this browser.');
|
||||
} else if (err.name === 'NotAllowedError') {
|
||||
setPlaybackError('Playback was blocked. Try interacting with the page first.');
|
||||
} else {
|
||||
setPlaybackError('Could not play the recording preview. Your recording was still created successfully.');
|
||||
}
|
||||
setRecordingState('recorded');
|
||||
});
|
||||
}
|
||||
}, [audioUrl, recordingState]);
|
||||
|
||||
// Handle confirm
|
||||
const handleConfirm = useCallback(() => {
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause();
|
||||
}
|
||||
onConfirm();
|
||||
}, [onConfirm]);
|
||||
|
||||
// Handle close
|
||||
const handleClose = useCallback((isOpen: boolean) => {
|
||||
if (!isOpen) {
|
||||
cleanup();
|
||||
}
|
||||
onOpenChange(isOpen);
|
||||
}, [onOpenChange, cleanup]);
|
||||
|
||||
// Format duration
|
||||
const formatDuration = (seconds: number) => {
|
||||
const mins = Math.floor(seconds / 60);
|
||||
const secs = seconds % 60;
|
||||
return `${mins}:${secs.toString().padStart(2, '0')}`;
|
||||
};
|
||||
|
||||
const hasRecording = recordingState === 'recorded' || recordingState === 'playing';
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<DialogContent className="max-w-md max-h-[85vh] flex flex-col p-0">
|
||||
{/* Header */}
|
||||
<DialogHeader className="px-6 pt-6 pb-4 border-b">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="size-10 rounded-xl bg-gradient-to-br from-purple-500/20 to-purple-500/5 flex items-center justify-center">
|
||||
<Mic className="size-5 text-purple-500" />
|
||||
</div>
|
||||
<div>
|
||||
<DialogTitle className="text-xl">Sing</DialogTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Record yourself singing for your Blobbi
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 px-6 py-8">
|
||||
<div className="flex flex-col items-center justify-center gap-6">
|
||||
{/* Recording Visualization */}
|
||||
<div className={cn(
|
||||
"relative size-40 rounded-full flex items-center justify-center transition-all",
|
||||
recordingState === 'recording' && "animate-pulse",
|
||||
recordingState === 'recording'
|
||||
? "bg-red-500/10 ring-4 ring-red-500/30"
|
||||
: hasRecording
|
||||
? "bg-purple-500/10 ring-4 ring-purple-500/30"
|
||||
: "bg-muted"
|
||||
)}>
|
||||
{/* Animated rings for recording */}
|
||||
{recordingState === 'recording' && (
|
||||
<>
|
||||
<div className="absolute inset-0 rounded-full bg-red-500/10 animate-ping" />
|
||||
<div className="absolute inset-4 rounded-full bg-red-500/10 animate-ping animation-delay-150" />
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Icon */}
|
||||
<div className={cn(
|
||||
"relative size-20 rounded-full flex items-center justify-center",
|
||||
recordingState === 'recording'
|
||||
? "bg-red-500 text-white"
|
||||
: hasRecording
|
||||
? "bg-purple-500 text-white"
|
||||
: "bg-muted-foreground/20"
|
||||
)}>
|
||||
{recordingState === 'requesting' ? (
|
||||
<Loader2 className="size-8 animate-spin" />
|
||||
) : recordingState === 'recording' ? (
|
||||
<Mic className="size-8" />
|
||||
) : hasRecording ? (
|
||||
recordingState === 'playing' ? (
|
||||
<Pause className="size-8" />
|
||||
) : (
|
||||
<Play className="size-8 ml-1" />
|
||||
)
|
||||
) : (
|
||||
<MicOff className="size-8 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Duration / Status */}
|
||||
<div className="text-center">
|
||||
{recordingState === 'idle' && (
|
||||
<p className="text-muted-foreground">Tap the button below to start recording</p>
|
||||
)}
|
||||
{recordingState === 'requesting' && (
|
||||
<p className="text-muted-foreground">Requesting microphone access...</p>
|
||||
)}
|
||||
{recordingState === 'recording' && (
|
||||
<>
|
||||
<p className="text-3xl font-mono font-bold text-red-500">
|
||||
{formatDuration(recordingDuration)}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">Recording...</p>
|
||||
</>
|
||||
)}
|
||||
{hasRecording && (
|
||||
<>
|
||||
<p className="text-3xl font-mono font-bold text-purple-500">
|
||||
{formatDuration(recordingDuration)}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{recordingState === 'playing' ? 'Playing...' : 'Tap to preview'}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
{recordingState === 'error' && (
|
||||
<p className="text-destructive">Recording failed</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Error Message */}
|
||||
{error && (
|
||||
<div className="w-full p-3 rounded-lg bg-destructive/10 border border-destructive/30">
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertCircle className="size-4 text-destructive mt-0.5 shrink-0" />
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Playback Error Message (non-fatal, recording still works) */}
|
||||
{playbackError && (
|
||||
<div className="w-full p-3 rounded-lg bg-amber-500/10 border border-amber-500/30">
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertCircle className="size-4 text-amber-500 mt-0.5 shrink-0" />
|
||||
<p className="text-sm text-amber-600 dark:text-amber-400">{playbackError}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Lyrics Helper */}
|
||||
<div className="w-full">
|
||||
{!currentLyrics ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleRandomLyrics}
|
||||
className="w-full gap-2"
|
||||
>
|
||||
<Sparkles className="size-4" />
|
||||
Need lyrics? Get random lyrics
|
||||
</Button>
|
||||
) : (
|
||||
<div className="rounded-lg border bg-card/60">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowLyrics(!showLyrics)}
|
||||
className="w-full flex items-center justify-between p-3 text-left"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Sparkles className="size-4 text-purple-500" />
|
||||
<span className="font-medium text-sm">{currentLyrics.title}</span>
|
||||
</div>
|
||||
{showLyrics ? (
|
||||
<ChevronUp className="size-4 text-muted-foreground" />
|
||||
) : (
|
||||
<ChevronDown className="size-4 text-muted-foreground" />
|
||||
)}
|
||||
</button>
|
||||
{showLyrics && (
|
||||
<div className="px-3 pb-3 pt-0">
|
||||
<div className="p-3 rounded-md bg-muted/50 text-sm leading-relaxed whitespace-pre-line">
|
||||
{currentLyrics.lines.join('\n')}
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleRandomLyrics}
|
||||
className="w-full mt-2 gap-2 text-muted-foreground"
|
||||
>
|
||||
<RotateCcw className="size-3" />
|
||||
Get different lyrics
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Recording Controls */}
|
||||
<div className="flex items-center gap-3">
|
||||
{recordingState === 'idle' || recordingState === 'error' ? (
|
||||
<Button
|
||||
size="lg"
|
||||
onClick={startRecording}
|
||||
className="rounded-full px-8 bg-purple-500 hover:bg-purple-600"
|
||||
>
|
||||
<Mic className="size-5 mr-2" />
|
||||
Start Recording
|
||||
</Button>
|
||||
) : recordingState === 'recording' ? (
|
||||
<Button
|
||||
size="lg"
|
||||
variant="destructive"
|
||||
onClick={stopRecording}
|
||||
className="rounded-full px-8"
|
||||
>
|
||||
<Square className="size-5 mr-2" />
|
||||
Stop
|
||||
</Button>
|
||||
) : hasRecording ? (
|
||||
<>
|
||||
<Button
|
||||
size="lg"
|
||||
variant="outline"
|
||||
onClick={togglePlayback}
|
||||
className="rounded-full"
|
||||
>
|
||||
{recordingState === 'playing' ? (
|
||||
<>
|
||||
<Pause className="size-5 mr-2" />
|
||||
Pause
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Play className="size-5 mr-2" />
|
||||
Preview
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
size="lg"
|
||||
variant="ghost"
|
||||
onClick={resetRecording}
|
||||
className="rounded-full"
|
||||
>
|
||||
<RotateCcw className="size-5 mr-2" />
|
||||
Re-record
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="px-6 py-4 border-t bg-muted/30">
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleClose(false)}
|
||||
className="flex-1"
|
||||
disabled={isLoading}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleConfirm}
|
||||
disabled={!hasRecording || isLoading}
|
||||
className="flex-1"
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="size-4 mr-2 animate-spin" />
|
||||
Singing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Mic className="size-4 mr-2" />
|
||||
Sing for Blobbi
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// src/blobbi/actions/components/StartEvolutionDialog.tsx
|
||||
|
||||
/**
|
||||
* Dialog for confirming start of evolution.
|
||||
*
|
||||
* Evolution is simpler than incubation:
|
||||
* - Only baby Blobbis can evolve
|
||||
* - Shows restart confirmation if already evolving
|
||||
* - Otherwise shows normal start confirmation
|
||||
*/
|
||||
|
||||
import { Loader2, AlertTriangle, Sparkles } from 'lucide-react';
|
||||
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
|
||||
import type { BlobbiCompanion } from '@/blobbi/core/lib/blobbi';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface StartEvolutionDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** The companion to start evolving */
|
||||
companion: BlobbiCompanion | null;
|
||||
/** Called when confirmed */
|
||||
onConfirm: () => void;
|
||||
isPending: boolean;
|
||||
}
|
||||
|
||||
// ─── Main Component ───────────────────────────────────────────────────────────
|
||||
|
||||
export function StartEvolutionDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
companion,
|
||||
onConfirm,
|
||||
isPending,
|
||||
}: StartEvolutionDialogProps) {
|
||||
// Check if the current Blobbi is already evolving
|
||||
const isAlreadyEvolving = companion?.state === 'evolving';
|
||||
|
||||
// Determine title and description based on state
|
||||
const getDialogContent = () => {
|
||||
if (isAlreadyEvolving) {
|
||||
return {
|
||||
title: 'Restart Evolution?',
|
||||
icon: <AlertTriangle className="size-5 text-amber-500" />,
|
||||
description: (
|
||||
<>
|
||||
<strong>{companion?.name}</strong> is already evolving. Starting over will{' '}
|
||||
<strong>reset all task progress</strong> and begin from the beginning.
|
||||
<br /><br />
|
||||
Are you sure you want to restart?
|
||||
</>
|
||||
),
|
||||
buttonText: 'Restart Evolution',
|
||||
buttonClass: 'bg-amber-500 hover:bg-amber-600 text-white',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
title: 'Start Evolution',
|
||||
icon: <Sparkles className="size-5 text-primary" />,
|
||||
description: (
|
||||
<>
|
||||
Starting evolution begins <strong>{companion?.name}</strong>'s transformation journey.
|
||||
Complete all the tasks to evolve your baby Blobbi into an adult!
|
||||
<br /><br />
|
||||
Ready to begin?
|
||||
</>
|
||||
),
|
||||
buttonText: 'Start Evolution',
|
||||
buttonClass: 'bg-gradient-to-r from-violet-500 to-purple-500 hover:from-violet-600 hover:to-purple-600 text-white',
|
||||
};
|
||||
};
|
||||
|
||||
const content = getDialogContent();
|
||||
|
||||
return (
|
||||
<AlertDialog open={open} onOpenChange={onOpenChange}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="flex items-center gap-2">
|
||||
{content.icon}
|
||||
{content.title}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{content.description}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isPending}>
|
||||
Cancel
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
onConfirm();
|
||||
}}
|
||||
disabled={isPending}
|
||||
className={content.buttonClass}
|
||||
>
|
||||
{isPending ? (
|
||||
<>
|
||||
<Loader2 className="size-4 mr-2 animate-spin" />
|
||||
Starting...
|
||||
</>
|
||||
) : (
|
||||
content.buttonText
|
||||
)}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
// src/blobbi/actions/components/StartIncubationDialog.tsx
|
||||
|
||||
/**
|
||||
* Dialog for confirming start of incubation.
|
||||
*
|
||||
* Determines the mode and passes it explicitly to the confirm callback:
|
||||
* - 'start': Normal start, no other Blobbi incubating
|
||||
* - 'restart': Restart same Blobbi (already incubating)
|
||||
* - 'switch': Stop another Blobbi first, then start this one
|
||||
*
|
||||
* The mode is determined by UI state, NOT auto-detected by the hook.
|
||||
* This makes the flow explicit and predictable.
|
||||
*/
|
||||
|
||||
import { useMemo } from 'react';
|
||||
import { Loader2, AlertTriangle, ArrowRightLeft } from 'lucide-react';
|
||||
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
|
||||
import type { BlobbiCompanion } from '@/blobbi/core/lib/blobbi';
|
||||
import type { StartIncubationMode } from '../hooks/useBlobbiIncubation';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface StartIncubationDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** The companion to start incubating */
|
||||
companion: BlobbiCompanion | null;
|
||||
/** All companions in the collection (to check for other incubating Blobbis) */
|
||||
companions?: BlobbiCompanion[];
|
||||
/** Called with explicit mode and optional stopOtherD when confirmed */
|
||||
onConfirm: (mode: StartIncubationMode, stopOtherD?: string) => void;
|
||||
isPending: boolean;
|
||||
}
|
||||
|
||||
// ─── Main Component ───────────────────────────────────────────────────────────
|
||||
|
||||
export function StartIncubationDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
companion,
|
||||
companions = [],
|
||||
onConfirm,
|
||||
isPending,
|
||||
}: StartIncubationDialogProps) {
|
||||
// Check if the current Blobbi is already in a task state
|
||||
const isAlreadyInTaskState = companion?.state === 'incubating' || companion?.state === 'evolving';
|
||||
|
||||
// Check if another Blobbi (not this one) is currently incubating
|
||||
const otherIncubatingBlobbi = useMemo(() => {
|
||||
if (!companion) return null;
|
||||
return companions.find(c =>
|
||||
c.d !== companion.d &&
|
||||
c.state === 'incubating' &&
|
||||
c.stage === 'egg'
|
||||
) ?? null;
|
||||
}, [companion, companions]);
|
||||
|
||||
// Determine the mode based on current state
|
||||
const mode: StartIncubationMode = useMemo(() => {
|
||||
if (isAlreadyInTaskState) return 'restart';
|
||||
if (otherIncubatingBlobbi) return 'switch';
|
||||
return 'start';
|
||||
}, [isAlreadyInTaskState, otherIncubatingBlobbi]);
|
||||
|
||||
// Handle confirm with explicit mode
|
||||
const handleConfirm = () => {
|
||||
if (mode === 'switch' && otherIncubatingBlobbi) {
|
||||
onConfirm(mode, otherIncubatingBlobbi.d);
|
||||
} else {
|
||||
onConfirm(mode);
|
||||
}
|
||||
};
|
||||
|
||||
// Determine title and description based on mode
|
||||
const getDialogContent = () => {
|
||||
if (mode === 'restart') {
|
||||
return {
|
||||
title: 'Restart Incubation?',
|
||||
icon: <AlertTriangle className="size-5 text-amber-500" />,
|
||||
description: (
|
||||
<>
|
||||
Your Blobbi is already {companion?.state}. Starting over will{' '}
|
||||
<strong>reset all task progress</strong> and begin from the beginning.
|
||||
<br /><br />
|
||||
Are you sure you want to restart?
|
||||
</>
|
||||
),
|
||||
buttonText: 'Restart Incubation',
|
||||
buttonClass: 'bg-amber-500 hover:bg-amber-600 text-white',
|
||||
};
|
||||
}
|
||||
|
||||
if (mode === 'switch') {
|
||||
return {
|
||||
title: 'Switch Incubation?',
|
||||
icon: <ArrowRightLeft className="size-5 text-amber-500" />,
|
||||
description: (
|
||||
<>
|
||||
<strong>{otherIncubatingBlobbi?.name}</strong> is currently incubating.
|
||||
Only one Blobbi can incubate at a time.
|
||||
<br /><br />
|
||||
Starting incubation for <strong>{companion?.name}</strong> will{' '}
|
||||
<strong>stop {otherIncubatingBlobbi?.name}'s incubation</strong> and{' '}
|
||||
reset their task progress.
|
||||
<br /><br />
|
||||
Do you want to switch?
|
||||
</>
|
||||
),
|
||||
buttonText: 'Switch & Start',
|
||||
buttonClass: 'bg-amber-500 hover:bg-amber-600 text-white',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
title: 'Start Incubation',
|
||||
icon: null,
|
||||
description: (
|
||||
<>
|
||||
Starting incubation begins your Blobbi's hatching journey.
|
||||
Complete all the tasks to hatch your egg into a baby Blobbi!
|
||||
<br /><br />
|
||||
Ready to begin?
|
||||
</>
|
||||
),
|
||||
buttonText: 'Start Incubation',
|
||||
buttonClass: undefined,
|
||||
};
|
||||
};
|
||||
|
||||
const content = getDialogContent();
|
||||
|
||||
return (
|
||||
<AlertDialog open={open} onOpenChange={onOpenChange}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="flex items-center gap-2">
|
||||
{content.icon}
|
||||
{content.title}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{content.description}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isPending}>
|
||||
Cancel
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
handleConfirm();
|
||||
}}
|
||||
disabled={isPending}
|
||||
className={content.buttonClass}
|
||||
>
|
||||
{isPending ? (
|
||||
<>
|
||||
<Loader2 className="size-4 mr-2 animate-spin" />
|
||||
Starting...
|
||||
</>
|
||||
) : (
|
||||
content.buttonText
|
||||
)}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
// src/blobbi/actions/components/TasksPanel.tsx
|
||||
|
||||
/**
|
||||
* Card-grid presentation for hatch / evolve tasks.
|
||||
*
|
||||
* Each task is a compact card in a 2-column grid.
|
||||
* Tapping a card expands it inline (full row) to reveal details.
|
||||
* Only one card is expanded at a time.
|
||||
*/
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
Palette,
|
||||
Droplets,
|
||||
MessageSquare,
|
||||
Heart,
|
||||
UserPen,
|
||||
Activity,
|
||||
Loader2,
|
||||
HelpCircle,
|
||||
} from 'lucide-react';
|
||||
import { openUrl } from '@/lib/downloadFile';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
import type { HatchTask } from '../hooks/useHatchTasks';
|
||||
import type { MissionCategory } from './ExpandableMissionCard';
|
||||
import {
|
||||
ExpandableMissionCard,
|
||||
MissionDescription,
|
||||
MissionProgress,
|
||||
MissionAction,
|
||||
DynamicHint,
|
||||
} from './ExpandableMissionCard';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface TasksPanelProps {
|
||||
tasks: HatchTask[];
|
||||
allCompleted: boolean;
|
||||
isLoading: boolean;
|
||||
onOpenPostModal: () => void;
|
||||
onComplete: () => void;
|
||||
isCompleting?: boolean;
|
||||
completeLabel: string;
|
||||
completingLabel: string;
|
||||
completeEmoji: string;
|
||||
/** Mission category for styling the cards */
|
||||
category?: MissionCategory;
|
||||
}
|
||||
|
||||
// ─── Task Icon Mapping ────────────────────────────────────────────────────────
|
||||
|
||||
/** Map task ids to lucide icons. Falls back to a generic icon. */
|
||||
function TaskIcon({ taskId }: { taskId: string }) {
|
||||
const iconClass = 'size-5';
|
||||
|
||||
switch (taskId) {
|
||||
case 'create_themes':
|
||||
return <Palette className={iconClass} />;
|
||||
case 'color_moments':
|
||||
return <Droplets className={iconClass} />;
|
||||
case 'create_posts':
|
||||
return <MessageSquare className={iconClass} />;
|
||||
case 'interactions':
|
||||
return <Heart className={iconClass} />;
|
||||
case 'edit_profile':
|
||||
return <UserPen className={iconClass} />;
|
||||
case 'maintain_stats':
|
||||
return <Activity className={iconClass} />;
|
||||
default:
|
||||
return <HelpCircle className={iconClass} />;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Main Component ───────────────────────────────────────────────────────────
|
||||
|
||||
export function TasksPanel({
|
||||
tasks,
|
||||
allCompleted,
|
||||
isLoading,
|
||||
onOpenPostModal,
|
||||
onComplete,
|
||||
isCompleting = false,
|
||||
completeLabel,
|
||||
completingLabel,
|
||||
completeEmoji,
|
||||
category = 'hatch',
|
||||
}: TasksPanelProps) {
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleToggle = (id: string) => {
|
||||
setExpandedId((prev) => (prev === id ? null : id));
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="size-5 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Card grid */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
|
||||
{tasks.map((task) => {
|
||||
const isDynamic = task.type === 'dynamic';
|
||||
const progress =
|
||||
task.required > 0 ? task.current / task.required : task.completed ? 1 : 0;
|
||||
|
||||
const handleAction = () => {
|
||||
if (!task.action || !task.actionTarget) return;
|
||||
switch (task.action) {
|
||||
case 'navigate':
|
||||
navigate(task.actionTarget);
|
||||
break;
|
||||
case 'external_link':
|
||||
openUrl(task.actionTarget);
|
||||
break;
|
||||
case 'open_modal':
|
||||
if (task.actionTarget === 'blobbi_post') onOpenPostModal();
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ExpandableMissionCard
|
||||
key={task.id}
|
||||
id={task.id}
|
||||
category={category}
|
||||
icon={<TaskIcon taskId={task.id} />}
|
||||
title={task.name}
|
||||
completed={task.completed}
|
||||
progress={Math.min(progress, 1)}
|
||||
isExpanded={expandedId === task.id}
|
||||
onToggle={handleToggle}
|
||||
>
|
||||
{/* Expanded content */}
|
||||
<MissionDescription>{task.description}</MissionDescription>
|
||||
|
||||
{/* Progress bar for multi-step tasks */}
|
||||
{task.required > 1 && !isDynamic && (
|
||||
<MissionProgress
|
||||
current={task.current}
|
||||
required={task.required}
|
||||
completed={task.completed}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Dynamic stat hint */}
|
||||
{isDynamic && !task.completed && (
|
||||
<DynamicHint current={task.current} required={task.required} />
|
||||
)}
|
||||
|
||||
{/* Action link */}
|
||||
{task.action && task.actionLabel && !task.completed && (
|
||||
<MissionAction
|
||||
label={task.actionLabel}
|
||||
type={task.action}
|
||||
onClick={handleAction}
|
||||
/>
|
||||
)}
|
||||
</ExpandableMissionCard>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* CTA button when all tasks are done */}
|
||||
{allCompleted && (
|
||||
<Button
|
||||
onClick={onComplete}
|
||||
disabled={isCompleting}
|
||||
size="lg"
|
||||
className="w-full gap-2 bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600 text-white shadow-sm"
|
||||
>
|
||||
{isCompleting ? (
|
||||
<>
|
||||
<Loader2 className="size-5 animate-spin" />
|
||||
{completingLabel}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-lg">{completeEmoji}</span>
|
||||
{completeLabel}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
// src/blobbi/actions/hooks/useActiveTaskProcess.ts
|
||||
|
||||
/**
|
||||
* Central abstraction for the active task process (hatch or evolve).
|
||||
*
|
||||
* This hook consolidates all scattered if/else logic for determining:
|
||||
* - Which process is active (incubating vs evolving)
|
||||
* - Which tasks to use (hatch vs evolve)
|
||||
* - Thresholds and configuration
|
||||
* - Badge-related computed values
|
||||
*
|
||||
* ARCHITECTURE RULES:
|
||||
* - Computed tasks remain the source of truth
|
||||
* - Tags are cache only for PERSISTENT tasks
|
||||
* - Dynamic tasks are NEVER persisted
|
||||
* - Badge counts ALL incomplete tasks (persistent + dynamic)
|
||||
*/
|
||||
|
||||
import { useMemo } from 'react';
|
||||
import type { BlobbiCompanion } from '@/blobbi/core/lib/blobbi';
|
||||
import type { HatchTask, HatchTasksResult } from './useHatchTasks';
|
||||
import type { EvolveTasksResult } from './useEvolveTasks';
|
||||
import { HATCH_REQUIRED_INTERACTIONS } from './useHatchTasks';
|
||||
import { EVOLVE_REQUIRED_INTERACTIONS } from './useEvolveTasks';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** The type of task process currently active */
|
||||
export type TaskProcessType = 'hatch' | 'evolve' | null;
|
||||
|
||||
/**
|
||||
* Configuration for the active task process.
|
||||
* This provides a unified interface regardless of whether
|
||||
* the process is hatch or evolve.
|
||||
*/
|
||||
export interface TaskProcessConfig {
|
||||
/** The type of process ('hatch' | 'evolve' | null) */
|
||||
type: TaskProcessType;
|
||||
/** Whether there is an active task process */
|
||||
isActive: boolean;
|
||||
/** Required interactions threshold for the current process */
|
||||
interactionThreshold: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of the active task process hook.
|
||||
* Provides unified access to all task-related state.
|
||||
*/
|
||||
export interface ActiveTaskProcessResult {
|
||||
/** Configuration for the current process */
|
||||
config: TaskProcessConfig;
|
||||
|
||||
/** All tasks for the current process (empty if no active process) */
|
||||
tasks: HatchTask[];
|
||||
/** Whether tasks are still loading */
|
||||
isLoading: boolean;
|
||||
/** Whether all tasks (persistent + dynamic) are complete */
|
||||
allCompleted: boolean;
|
||||
/** Whether all persistent tasks are complete */
|
||||
persistentTasksComplete: boolean;
|
||||
/** Whether the dynamic task is complete */
|
||||
dynamicTaskComplete: boolean;
|
||||
|
||||
/** Refetch function for current tasks */
|
||||
refetch: () => void;
|
||||
|
||||
// ─── Badge-related computed values ───
|
||||
|
||||
/**
|
||||
* Count of ALL remaining incomplete tasks (persistent + dynamic).
|
||||
* This is used for the badge display.
|
||||
* Dynamic tasks ARE counted here but are NEVER synced to tags.
|
||||
*/
|
||||
remainingTasksCount: number;
|
||||
|
||||
/**
|
||||
* Only persistent tasks that are incomplete.
|
||||
* Used for sync logic - dynamic tasks must NEVER be synced.
|
||||
*/
|
||||
incompletePersistentTasks: HatchTask[];
|
||||
|
||||
/**
|
||||
* Only persistent tasks that are complete.
|
||||
* Used for sync logic.
|
||||
*/
|
||||
completedPersistentTasks: HatchTask[];
|
||||
|
||||
/**
|
||||
* Stable string key of completed persistent task IDs.
|
||||
* Used for sync anti-loop protection.
|
||||
*/
|
||||
completedPersistentTaskIds: string;
|
||||
|
||||
/**
|
||||
* Tasks to sync (persistent only, with completion status).
|
||||
* Dynamic tasks are excluded.
|
||||
*/
|
||||
tasksToSync: Array<{ taskId: string; completed: boolean }>;
|
||||
}
|
||||
|
||||
// ─── Helper Functions ─────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Filter tasks to only persistent tasks.
|
||||
* Dynamic tasks must NEVER be synced to tags.
|
||||
*/
|
||||
export function filterPersistentTasks(tasks: HatchTask[]): HatchTask[] {
|
||||
return tasks.filter(t => t.type === 'persistent');
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter tasks to only dynamic tasks.
|
||||
*/
|
||||
export function filterDynamicTasks(tasks: HatchTask[]): HatchTask[] {
|
||||
return tasks.filter(t => t.type === 'dynamic');
|
||||
}
|
||||
|
||||
// ─── Main Hook ────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Hook that provides a unified interface for the active task process.
|
||||
*
|
||||
* Usage:
|
||||
* ```ts
|
||||
* const taskProcess = useActiveTaskProcess(companion, hatchTasks, evolveTasks);
|
||||
*
|
||||
* // Access unified data
|
||||
* taskProcess.config.type // 'hatch' | 'evolve' | null
|
||||
* taskProcess.tasks // current tasks
|
||||
* taskProcess.remainingTasksCount // for badge (includes dynamic)
|
||||
* taskProcess.tasksToSync // for sync (excludes dynamic)
|
||||
* ```
|
||||
*/
|
||||
export function useActiveTaskProcess(
|
||||
companion: BlobbiCompanion | null,
|
||||
hatchTasks: HatchTasksResult,
|
||||
evolveTasks: EvolveTasksResult
|
||||
): ActiveTaskProcessResult {
|
||||
// Determine which process is active
|
||||
const processType = useMemo((): TaskProcessType => {
|
||||
if (!companion) return null;
|
||||
if (companion.state === 'incubating') return 'hatch';
|
||||
if (companion.state === 'evolving') return 'evolve';
|
||||
return null;
|
||||
}, [companion]);
|
||||
|
||||
// Build configuration
|
||||
const config = useMemo((): TaskProcessConfig => {
|
||||
const isActive = processType !== null;
|
||||
const interactionThreshold = processType === 'hatch'
|
||||
? HATCH_REQUIRED_INTERACTIONS
|
||||
: processType === 'evolve'
|
||||
? EVOLVE_REQUIRED_INTERACTIONS
|
||||
: 0;
|
||||
|
||||
return {
|
||||
type: processType,
|
||||
isActive,
|
||||
interactionThreshold,
|
||||
};
|
||||
}, [processType]);
|
||||
|
||||
// Get the active tasks result based on process type
|
||||
const activeResult = useMemo(() => {
|
||||
if (processType === 'hatch') return hatchTasks;
|
||||
if (processType === 'evolve') return evolveTasks;
|
||||
return null;
|
||||
}, [processType, hatchTasks, evolveTasks]);
|
||||
|
||||
// Extract tasks and state from active result
|
||||
const tasks = useMemo(() => activeResult?.tasks ?? [], [activeResult]);
|
||||
const isLoading = activeResult?.isLoading ?? false;
|
||||
const allCompleted = activeResult?.allCompleted ?? false;
|
||||
const persistentTasksComplete = activeResult?.persistentTasksComplete ?? false;
|
||||
const dynamicTaskComplete = activeResult?.dynamicTaskComplete ?? false;
|
||||
const refetch = activeResult?.refetch ?? (() => {});
|
||||
|
||||
// Compute persistent task list (dynamic tasks computed for badge count directly from tasks array)
|
||||
const persistentTasks = useMemo(() => filterPersistentTasks(tasks), [tasks]);
|
||||
|
||||
// Compute incomplete tasks (for badge - includes BOTH persistent and dynamic)
|
||||
const remainingTasksCount = useMemo(() => {
|
||||
// Count ALL incomplete tasks - persistent AND dynamic
|
||||
// Dynamic tasks are included in badge count but NEVER synced to tags
|
||||
return tasks.filter(t => !t.completed).length;
|
||||
}, [tasks]);
|
||||
|
||||
// Compute persistent task lists for sync
|
||||
const incompletePersistentTasks = useMemo(() =>
|
||||
persistentTasks.filter(t => !t.completed),
|
||||
[persistentTasks]
|
||||
);
|
||||
|
||||
const completedPersistentTasks = useMemo(() =>
|
||||
persistentTasks.filter(t => t.completed),
|
||||
[persistentTasks]
|
||||
);
|
||||
|
||||
// Compute stable string key for completed persistent tasks (anti-loop)
|
||||
const completedPersistentTaskIds = useMemo(() => {
|
||||
if (!completedPersistentTasks.length) return '';
|
||||
return completedPersistentTasks
|
||||
.map(t => t.id)
|
||||
.sort()
|
||||
.join(',');
|
||||
}, [completedPersistentTasks]);
|
||||
|
||||
// Compute tasks to sync (persistent only)
|
||||
// CRITICAL: Dynamic tasks must NEVER be included here
|
||||
const tasksToSync = useMemo(() => {
|
||||
if (!persistentTasks.length) return [];
|
||||
return persistentTasks.map(t => ({
|
||||
taskId: t.id,
|
||||
completed: t.completed,
|
||||
}));
|
||||
}, [persistentTasks]);
|
||||
|
||||
return {
|
||||
config,
|
||||
tasks,
|
||||
isLoading,
|
||||
allCompleted,
|
||||
persistentTasksComplete,
|
||||
dynamicTaskComplete,
|
||||
refetch,
|
||||
remainingTasksCount,
|
||||
incompletePersistentTasks,
|
||||
completedPersistentTasks,
|
||||
completedPersistentTaskIds,
|
||||
tasksToSync,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
// src/blobbi/actions/hooks/useAudioPlayback.ts
|
||||
|
||||
import { useState, useRef, useCallback, useEffect } from 'react';
|
||||
|
||||
/**
|
||||
* Audio playback state
|
||||
* - idle: No audio loaded
|
||||
* - loading: Audio is being loaded
|
||||
* - playing: Audio is playing
|
||||
* - paused: Audio is paused (can resume)
|
||||
* - stopped: Audio was stopped (must reload to play again)
|
||||
* - error: An error occurred
|
||||
*/
|
||||
export type PlaybackState = 'idle' | 'loading' | 'playing' | 'paused' | 'stopped' | 'error';
|
||||
|
||||
/**
|
||||
* Audio playback error info
|
||||
*/
|
||||
export interface PlaybackError {
|
||||
message: string;
|
||||
code?: string;
|
||||
}
|
||||
|
||||
/** Default volume level (0-1) */
|
||||
const DEFAULT_VOLUME = 0.8;
|
||||
|
||||
/**
|
||||
* Options for the useAudioPlayback hook
|
||||
*/
|
||||
export interface UseAudioPlaybackOptions {
|
||||
/** Called when playback ends naturally */
|
||||
onEnded?: () => void;
|
||||
/** Called when an error occurs */
|
||||
onError?: (error: PlaybackError) => void;
|
||||
/** Initial volume level (0-1), defaults to 0.8 */
|
||||
initialVolume?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return type for useAudioPlayback hook
|
||||
*/
|
||||
export interface UseAudioPlaybackReturn {
|
||||
/** Current playback state */
|
||||
state: PlaybackState;
|
||||
/** Current error (if any) */
|
||||
error: PlaybackError | null;
|
||||
/** Current audio URL being played */
|
||||
currentUrl: string | null;
|
||||
/** Load and optionally start playing an audio URL */
|
||||
load: (url: string, autoplay?: boolean) => void;
|
||||
/** Play the current audio */
|
||||
play: () => Promise<void>;
|
||||
/** Pause the current audio */
|
||||
pause: () => void;
|
||||
/** Stop playback and reset */
|
||||
stop: () => void;
|
||||
/** Restart playback from the beginning */
|
||||
restart: () => Promise<void>;
|
||||
/** Toggle play/pause */
|
||||
toggle: () => Promise<void>;
|
||||
/** Whether audio is currently playing */
|
||||
isPlaying: boolean;
|
||||
/** Current volume level (0-1) */
|
||||
volume: number;
|
||||
/** Set volume level (0-1) */
|
||||
setVolume: (volume: number) => void;
|
||||
/** Cleanup function to release resources */
|
||||
cleanup: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reusable hook for audio playback.
|
||||
* Handles Audio element lifecycle, error handling, and state management.
|
||||
*/
|
||||
export function useAudioPlayback(options: UseAudioPlaybackOptions = {}): UseAudioPlaybackReturn {
|
||||
const { onEnded, onError, initialVolume = DEFAULT_VOLUME } = options;
|
||||
|
||||
const [state, setState] = useState<PlaybackState>('idle');
|
||||
const [error, setError] = useState<PlaybackError | null>(null);
|
||||
const [currentUrl, setCurrentUrl] = useState<string | null>(null);
|
||||
const [volume, setVolumeState] = useState<number>(initialVolume);
|
||||
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null);
|
||||
const currentUrlRef = useRef<string | null>(null);
|
||||
const volumeRef = useRef<number>(initialVolume);
|
||||
|
||||
// Cleanup audio element
|
||||
const cleanup = useCallback(() => {
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause();
|
||||
audioRef.current.onended = null;
|
||||
audioRef.current.onerror = null;
|
||||
audioRef.current.oncanplay = null;
|
||||
audioRef.current.onplaying = null;
|
||||
audioRef.current = null;
|
||||
}
|
||||
currentUrlRef.current = null;
|
||||
setState('idle');
|
||||
setCurrentUrl(null);
|
||||
setError(null);
|
||||
}, []);
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
cleanup();
|
||||
};
|
||||
}, [cleanup]);
|
||||
|
||||
// Load audio from URL
|
||||
const load = useCallback((url: string, autoplay = false) => {
|
||||
// If same URL, don't reload
|
||||
if (currentUrlRef.current === url && audioRef.current) {
|
||||
if (autoplay) {
|
||||
audioRef.current.play().catch(() => {});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Cleanup previous audio
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause();
|
||||
audioRef.current.onended = null;
|
||||
audioRef.current.onerror = null;
|
||||
audioRef.current.oncanplay = null;
|
||||
audioRef.current.onplaying = null;
|
||||
}
|
||||
|
||||
setState('loading');
|
||||
setError(null);
|
||||
setCurrentUrl(url);
|
||||
currentUrlRef.current = url;
|
||||
|
||||
const audio = new Audio(url);
|
||||
audio.volume = volumeRef.current; // Apply current volume to new audio
|
||||
audioRef.current = audio;
|
||||
|
||||
audio.oncanplay = () => {
|
||||
if (autoplay) {
|
||||
audio.play().catch((err) => {
|
||||
const playbackError: PlaybackError = {
|
||||
message: getPlaybackErrorMessage(err),
|
||||
code: err.name,
|
||||
};
|
||||
setError(playbackError);
|
||||
setState('error');
|
||||
onError?.(playbackError);
|
||||
});
|
||||
} else {
|
||||
setState('paused');
|
||||
}
|
||||
};
|
||||
|
||||
audio.onplaying = () => {
|
||||
setState('playing');
|
||||
};
|
||||
|
||||
audio.onpause = () => {
|
||||
if (state === 'playing') {
|
||||
setState('paused');
|
||||
}
|
||||
};
|
||||
|
||||
audio.onended = () => {
|
||||
setState('paused');
|
||||
onEnded?.();
|
||||
};
|
||||
|
||||
audio.onerror = () => {
|
||||
const playbackError: PlaybackError = {
|
||||
message: 'Failed to load audio. The format may not be supported.',
|
||||
code: 'MEDIA_ERR',
|
||||
};
|
||||
setError(playbackError);
|
||||
setState('error');
|
||||
onError?.(playbackError);
|
||||
};
|
||||
|
||||
// Start loading
|
||||
audio.load();
|
||||
}, [onEnded, onError, state]);
|
||||
|
||||
// Play current audio
|
||||
const play = useCallback(async () => {
|
||||
if (!audioRef.current) return;
|
||||
|
||||
try {
|
||||
setError(null);
|
||||
await audioRef.current.play();
|
||||
setState('playing');
|
||||
} catch (err) {
|
||||
const playbackError: PlaybackError = {
|
||||
message: getPlaybackErrorMessage(err),
|
||||
code: err instanceof Error ? err.name : 'UNKNOWN',
|
||||
};
|
||||
setError(playbackError);
|
||||
setState('error');
|
||||
onError?.(playbackError);
|
||||
}
|
||||
}, [onError]);
|
||||
|
||||
// Pause current audio
|
||||
const pause = useCallback(() => {
|
||||
if (!audioRef.current) return;
|
||||
audioRef.current.pause();
|
||||
setState('paused');
|
||||
}, []);
|
||||
|
||||
// Stop playback completely (requires reload to play again)
|
||||
const stop = useCallback(() => {
|
||||
if (!audioRef.current) return;
|
||||
audioRef.current.pause();
|
||||
audioRef.current.currentTime = 0;
|
||||
// Clear URL ref so next load() will actually reload
|
||||
currentUrlRef.current = null;
|
||||
setState('stopped');
|
||||
}, []);
|
||||
|
||||
// Restart playback from the beginning
|
||||
const restart = useCallback(async () => {
|
||||
if (!audioRef.current) return;
|
||||
audioRef.current.currentTime = 0;
|
||||
try {
|
||||
await audioRef.current.play();
|
||||
setState('playing');
|
||||
} catch (err) {
|
||||
const playbackError: PlaybackError = {
|
||||
message: getPlaybackErrorMessage(err),
|
||||
code: err instanceof Error ? err.name : 'UNKNOWN',
|
||||
};
|
||||
setError(playbackError);
|
||||
setState('error');
|
||||
onError?.(playbackError);
|
||||
}
|
||||
}, [onError]);
|
||||
|
||||
// Toggle play/pause
|
||||
const toggle = useCallback(async () => {
|
||||
if (state === 'playing') {
|
||||
pause();
|
||||
} else {
|
||||
await play();
|
||||
}
|
||||
}, [state, play, pause]);
|
||||
|
||||
// Set volume (0-1)
|
||||
const setVolume = useCallback((newVolume: number) => {
|
||||
const clampedVolume = Math.max(0, Math.min(1, newVolume));
|
||||
volumeRef.current = clampedVolume;
|
||||
setVolumeState(clampedVolume);
|
||||
if (audioRef.current) {
|
||||
audioRef.current.volume = clampedVolume;
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
state,
|
||||
error,
|
||||
currentUrl,
|
||||
load,
|
||||
play,
|
||||
pause,
|
||||
stop,
|
||||
restart,
|
||||
toggle,
|
||||
isPlaying: state === 'playing',
|
||||
volume,
|
||||
setVolume,
|
||||
cleanup,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a user-friendly error message for playback errors
|
||||
*/
|
||||
function getPlaybackErrorMessage(err: unknown): string {
|
||||
if (err instanceof Error) {
|
||||
if (err.name === 'NotSupportedError') {
|
||||
return 'This audio format is not supported by your browser.';
|
||||
}
|
||||
if (err.name === 'NotAllowedError') {
|
||||
return 'Playback was blocked. Try interacting with the page first.';
|
||||
}
|
||||
return err.message;
|
||||
}
|
||||
return 'An unknown error occurred during playback.';
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
/**
|
||||
* useBlobbiCareActivity - Hook for registering care activity and updating streaks
|
||||
*
|
||||
* This hook provides a centralized way to register care activity for a Blobbi companion.
|
||||
* It handles:
|
||||
* - Calculating streak updates based on the last activity day
|
||||
* - Publishing updated Blobbi state to Nostr
|
||||
* - Updating local cache
|
||||
*
|
||||
* Use this hook whenever care activity should count toward the streak:
|
||||
* - Opening the Blobbi page (page check-in)
|
||||
* - Performing care actions (feed, clean, play, etc.)
|
||||
* - Any other care interaction
|
||||
*
|
||||
* The streak only increments once per calendar day, regardless of how many
|
||||
* activities are performed.
|
||||
*/
|
||||
|
||||
import { useCallback, useRef } from 'react';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
import type { BlobbiCompanion } from '@/blobbi/core/lib/blobbi';
|
||||
import {
|
||||
KIND_BLOBBI_STATE,
|
||||
updateBlobbiTags,
|
||||
isValidBlobbiEvent,
|
||||
parseBlobbiEvent,
|
||||
} from '@/blobbi/core/lib/blobbi';
|
||||
|
||||
import { getStreakTagUpdates, calculateStreakUpdate, type StreakUpdateResult } from '../lib/blobbi-streak';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface UseBlobbiCareActivityParams {
|
||||
companion: BlobbiCompanion | null;
|
||||
/** Update companion event in local cache */
|
||||
updateCompanionEvent: (event: NostrEvent) => void;
|
||||
}
|
||||
|
||||
export interface CareActivityResult {
|
||||
/** Whether the streak was updated */
|
||||
wasUpdated: boolean;
|
||||
/** The new streak value */
|
||||
newStreak: number;
|
||||
/** Description of what happened */
|
||||
action: StreakUpdateResult['action'];
|
||||
}
|
||||
|
||||
// ─── Hook ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Hook to register care activity and update streaks.
|
||||
*
|
||||
* Returns a function to register activity and a mutation for the actual update.
|
||||
* The register function is idempotent - calling it multiple times on the same day
|
||||
* will only update once.
|
||||
*/
|
||||
export function useBlobbiCareActivity({
|
||||
companion,
|
||||
updateCompanionEvent,
|
||||
}: UseBlobbiCareActivityParams) {
|
||||
const { nostr } = useNostr();
|
||||
const { user } = useCurrentUser();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
|
||||
// Track if we've already registered activity this session to avoid duplicate calls
|
||||
// This is a performance optimization - the actual idempotency is handled by day comparison
|
||||
const lastRegisteredDay = useRef<string | null>(null);
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: async (): Promise<CareActivityResult> => {
|
||||
if (!user?.pubkey) {
|
||||
throw new Error('You must be logged in to register care activity');
|
||||
}
|
||||
|
||||
if (!companion) {
|
||||
throw new Error('No companion available');
|
||||
}
|
||||
|
||||
// Fetch fresh companion from relays (read-modify-write pattern)
|
||||
const freshEvents = await nostr.query([{
|
||||
kinds: [KIND_BLOBBI_STATE],
|
||||
authors: [user.pubkey],
|
||||
'#d': [companion.d],
|
||||
}]);
|
||||
const freshCompanion = freshEvents
|
||||
.filter(isValidBlobbiEvent)
|
||||
.sort((a, b) => b.created_at - a.created_at)
|
||||
.map(e => parseBlobbiEvent(e))
|
||||
.find(Boolean) ?? companion;
|
||||
|
||||
const now = new Date();
|
||||
|
||||
// Calculate what the streak update should be using fresh data
|
||||
const result = calculateStreakUpdate(
|
||||
freshCompanion.careStreak,
|
||||
freshCompanion.careStreakLastDay,
|
||||
now
|
||||
);
|
||||
|
||||
// If no update needed (same day), return early without publishing
|
||||
if (!result.wasUpdated) {
|
||||
return {
|
||||
wasUpdated: false,
|
||||
newStreak: result.newStreak,
|
||||
action: result.action,
|
||||
};
|
||||
}
|
||||
|
||||
// Get the tag updates using fresh data
|
||||
const streakUpdates = getStreakTagUpdates(freshCompanion, now);
|
||||
|
||||
if (!streakUpdates) {
|
||||
// Shouldn't happen if wasUpdated is true, but handle gracefully
|
||||
return {
|
||||
wasUpdated: false,
|
||||
newStreak: freshCompanion.careStreak ?? 0,
|
||||
action: 'same_day',
|
||||
};
|
||||
}
|
||||
|
||||
// Build updated tags from fresh data
|
||||
const updatedTags = updateBlobbiTags(freshCompanion.allTags, streakUpdates);
|
||||
|
||||
// Publish the updated event
|
||||
const event = await publishEvent({
|
||||
kind: KIND_BLOBBI_STATE,
|
||||
content: freshCompanion.event.content,
|
||||
tags: updatedTags,
|
||||
});
|
||||
|
||||
// Update local cache (optimistic — no invalidation needed)
|
||||
updateCompanionEvent(event);
|
||||
|
||||
// Update session tracker
|
||||
lastRegisteredDay.current = result.newLastDay;
|
||||
|
||||
// Log for debugging (dev only)
|
||||
if (import.meta.env.DEV) {
|
||||
console.log('[CareActivity] Streak updated:', {
|
||||
action: result.action,
|
||||
previousStreak: freshCompanion.careStreak,
|
||||
newStreak: result.newStreak,
|
||||
lastDay: freshCompanion.careStreakLastDay,
|
||||
newDay: result.newLastDay,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
wasUpdated: true,
|
||||
newStreak: result.newStreak,
|
||||
action: result.action,
|
||||
};
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
console.error('[CareActivity] Failed to update streak:', error);
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Register care activity. Call this when care-related activity happens.
|
||||
* Safe to call multiple times - only updates streak once per day.
|
||||
*
|
||||
* @returns Promise with the result of the activity registration
|
||||
*/
|
||||
const registerCareActivity = useCallback(async (): Promise<CareActivityResult | null> => {
|
||||
if (!companion) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Quick check if we've already registered for this companion's last day (session cache)
|
||||
// This is an optimization to avoid unnecessary mutation calls
|
||||
if (lastRegisteredDay.current === companion.careStreakLastDay) {
|
||||
// Already processed this day in this session, skip
|
||||
return {
|
||||
wasUpdated: false,
|
||||
newStreak: companion.careStreak ?? 0,
|
||||
action: 'same_day',
|
||||
};
|
||||
}
|
||||
|
||||
return mutation.mutateAsync();
|
||||
}, [companion, mutation]);
|
||||
|
||||
return {
|
||||
/** Register care activity - call when page opens or care action happens */
|
||||
registerCareActivity,
|
||||
/** Whether an update is currently in progress */
|
||||
isUpdating: mutation.isPending,
|
||||
/** The last update result */
|
||||
lastResult: mutation.data,
|
||||
/** Any error from the last update attempt */
|
||||
error: mutation.error,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
// src/blobbi/actions/hooks/useBlobbiDirectAction.ts
|
||||
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { toast } from '@/hooks/useToast';
|
||||
|
||||
import type { BlobbiCompanion } from '@/blobbi/core/lib/blobbi';
|
||||
import {
|
||||
KIND_BLOBBI_STATE,
|
||||
updateBlobbiTags,
|
||||
} from '@/blobbi/core/lib/blobbi';
|
||||
import { applyBlobbiDecay } from '@/blobbi/core/lib/blobbi-decay';
|
||||
import {
|
||||
clampStat,
|
||||
applyStat,
|
||||
DIRECT_ACTION_METADATA,
|
||||
incrementInteractionTaskTags,
|
||||
type DirectAction,
|
||||
} from '../lib/blobbi-action-utils';
|
||||
import { trackMultipleDailyMissionActions } from '../lib/daily-mission-tracker';
|
||||
import type { DailyMissionAction } from '../lib/daily-missions';
|
||||
import { getStreakTagUpdates } from '../lib/blobbi-streak';
|
||||
import { calculateActionXP, applyXPGain, formatXPGain } from '../lib/blobbi-xp';
|
||||
import { HATCH_REQUIRED_INTERACTIONS } from './useHatchTasks';
|
||||
import { EVOLVE_REQUIRED_INTERACTIONS } from './useEvolveTasks';
|
||||
|
||||
// Import NostrEvent type
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
/**
|
||||
* Configuration for direct action happiness effects.
|
||||
* These are the happiness deltas for each direct action.
|
||||
*/
|
||||
export const DIRECT_ACTION_HAPPINESS_EFFECTS: Record<DirectAction, number> = {
|
||||
play_music: 15,
|
||||
sing: 20,
|
||||
};
|
||||
|
||||
/**
|
||||
* Request payload for executing a direct action
|
||||
*/
|
||||
export interface DirectActionRequest {
|
||||
action: DirectAction;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of executing a direct action
|
||||
*/
|
||||
export interface DirectActionResult {
|
||||
action: DirectAction;
|
||||
happinessChange: number;
|
||||
xpGained: number;
|
||||
newXP: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parameters for the useBlobbiDirectAction hook
|
||||
*/
|
||||
export interface UseBlobbiDirectActionParams {
|
||||
companion: BlobbiCompanion | null;
|
||||
/** Called after ensuring companion is canonical (from migration helper) */
|
||||
ensureCanonicalBeforeAction: () => Promise<{
|
||||
companion: BlobbiCompanion;
|
||||
content: string;
|
||||
allTags: string[][];
|
||||
wasMigrated: boolean;
|
||||
} | null>;
|
||||
/** Update companion event in local cache */
|
||||
updateCompanionEvent: (event: NostrEvent) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to execute a direct action on a Blobbi companion.
|
||||
* Direct actions (play_music, sing) don't require selecting an item.
|
||||
* They directly affect happiness stat.
|
||||
*
|
||||
* This hook:
|
||||
* 1. Validates the companion exists
|
||||
* 2. Ensures canonical format before action
|
||||
* 3. Applies accumulated decay
|
||||
* 4. Applies happiness boost
|
||||
* 5. Updates Blobbi state (kind 31124)
|
||||
* 6. Invalidates relevant queries
|
||||
*/
|
||||
export function useBlobbiDirectAction({
|
||||
companion,
|
||||
ensureCanonicalBeforeAction,
|
||||
updateCompanionEvent,
|
||||
}: UseBlobbiDirectActionParams) {
|
||||
const { user } = useCurrentUser();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ action }: DirectActionRequest): Promise<DirectActionResult> => {
|
||||
// ─── Validation ───
|
||||
if (!user?.pubkey) {
|
||||
throw new Error('You must be logged in to perform actions');
|
||||
}
|
||||
|
||||
if (!companion) {
|
||||
throw new Error('No companion selected');
|
||||
}
|
||||
|
||||
// ─── Ensure Canonical Before Action ───
|
||||
const canonical = await ensureCanonicalBeforeAction();
|
||||
if (!canonical) {
|
||||
throw new Error('Failed to prepare companion for action');
|
||||
}
|
||||
|
||||
// ─── Apply Accumulated Decay First ───
|
||||
// CRITICAL: Use canonical.companion for decay calculations, not the stale outer companion
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const decayResult = applyBlobbiDecay({
|
||||
stage: canonical.companion.stage,
|
||||
state: canonical.companion.state,
|
||||
stats: canonical.companion.stats,
|
||||
lastDecayAt: canonical.companion.lastDecayAt,
|
||||
now,
|
||||
});
|
||||
|
||||
const statsAfterDecay = decayResult.stats;
|
||||
|
||||
// ─── Apply Happiness Effect ───
|
||||
const happinessDelta = DIRECT_ACTION_HAPPINESS_EFFECTS[action];
|
||||
const newHappiness = applyStat(statsAfterDecay.happiness, happinessDelta);
|
||||
|
||||
// Track if happiness actually changed
|
||||
const happinessChanged = newHappiness !== statsAfterDecay.happiness;
|
||||
|
||||
// Build stats update
|
||||
const isEgg = canonical.companion.stage === 'egg';
|
||||
const statsUpdate: Record<string, string> = {
|
||||
happiness: newHappiness.toString(),
|
||||
health: statsAfterDecay.health.toString(),
|
||||
hygiene: statsAfterDecay.hygiene.toString(),
|
||||
};
|
||||
|
||||
if (isEgg) {
|
||||
// Eggs have fixed hunger and energy
|
||||
statsUpdate.hunger = '100';
|
||||
statsUpdate.energy = '100';
|
||||
} else {
|
||||
statsUpdate.hunger = clampStat(statsAfterDecay.hunger).toString();
|
||||
statsUpdate.energy = clampStat(statsAfterDecay.energy).toString();
|
||||
}
|
||||
|
||||
// ─── Update Blobbi State Event (kind 31124) ───
|
||||
const nowStr = now.toString();
|
||||
|
||||
// If incubating or evolving, increment the interaction counter for tasks
|
||||
const companionState = canonical.companion.state;
|
||||
let updatedTags = canonical.allTags;
|
||||
if (companionState === 'incubating') {
|
||||
updatedTags = incrementInteractionTaskTags(canonical.allTags, HATCH_REQUIRED_INTERACTIONS).updatedTags;
|
||||
} else if (companionState === 'evolving') {
|
||||
updatedTags = incrementInteractionTaskTags(canonical.allTags, EVOLVE_REQUIRED_INTERACTIONS).updatedTags;
|
||||
}
|
||||
|
||||
// Get streak updates (will only update if needed based on day)
|
||||
const streakUpdates = getStreakTagUpdates(canonical.companion) ?? {};
|
||||
|
||||
// ─── Apply XP Gain (ONLY if happiness actually changed) ───
|
||||
// Direct actions modify happiness. Only grant XP if happiness actually increased.
|
||||
const xpGained = happinessChanged ? calculateActionXP(action) : 0;
|
||||
const currentXP = canonical.companion.experience ?? 0;
|
||||
const newXP = applyXPGain(currentXP, xpGained);
|
||||
|
||||
const blobbiTags = updateBlobbiTags(updatedTags, {
|
||||
...statsUpdate,
|
||||
...streakUpdates,
|
||||
experience: newXP.toString(),
|
||||
last_interaction: nowStr,
|
||||
last_decay_at: nowStr,
|
||||
});
|
||||
|
||||
const blobbiEvent = await publishEvent({
|
||||
kind: KIND_BLOBBI_STATE,
|
||||
content: canonical.content,
|
||||
tags: blobbiTags,
|
||||
});
|
||||
|
||||
updateCompanionEvent(blobbiEvent);
|
||||
|
||||
return {
|
||||
action,
|
||||
happinessChange: happinessDelta,
|
||||
xpGained,
|
||||
newXP,
|
||||
};
|
||||
},
|
||||
onSuccess: ({ action, happinessChange, xpGained }) => {
|
||||
const actionMeta = DIRECT_ACTION_METADATA[action];
|
||||
const xpText = formatXPGain(xpGained);
|
||||
toast({
|
||||
title: `${actionMeta.label} complete!`,
|
||||
description: `Your Blobbi's happiness increased by ${happinessChange}! ${xpText}`,
|
||||
});
|
||||
|
||||
// Track daily mission progress
|
||||
// 'interact' is always tracked, plus the specific action
|
||||
const dailyActions: DailyMissionAction[] = ['interact'];
|
||||
if (action === 'sing') dailyActions.push('sing');
|
||||
if (action === 'play_music') dailyActions.push('play_music');
|
||||
trackMultipleDailyMissionActions(dailyActions, user?.pubkey);
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast({
|
||||
title: 'Action failed',
|
||||
description: error.message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,880 @@
|
||||
// src/blobbi/actions/hooks/useBlobbiIncubation.ts
|
||||
|
||||
/**
|
||||
* Hooks for Blobbi incubation task system.
|
||||
*
|
||||
* When a user starts incubation:
|
||||
* 1. Apply accumulated decay from last_decay_at to now
|
||||
* 2. Set state to 'incubating'
|
||||
* 3. Add state_started_at timestamp
|
||||
* 4. Update last_decay_at to the same timestamp
|
||||
* 5. Clear any previous task progress
|
||||
*
|
||||
* Tasks are computed from Nostr events with created_at >= state_started_at
|
||||
*/
|
||||
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { toast } from '@/hooks/useToast';
|
||||
|
||||
import type { BlobbiCompanion, BlobbonautProfile } from '@/blobbi/core/lib/blobbi';
|
||||
import {
|
||||
KIND_BLOBBI_STATE,
|
||||
updateBlobbiTags,
|
||||
} from '@/blobbi/core/lib/blobbi';
|
||||
import { applyBlobbiDecay } from '@/blobbi/core/lib/blobbi-decay';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Mode for starting incubation.
|
||||
* This makes the intent explicit rather than auto-detecting behavior.
|
||||
*/
|
||||
export type StartIncubationMode =
|
||||
| 'start' // Normal start (no other Blobbi incubating)
|
||||
| 'restart' // Restart same Blobbi (already incubating)
|
||||
| 'switch'; // Switch from another incubating Blobbi
|
||||
|
||||
/**
|
||||
* Request to start incubation with explicit mode.
|
||||
*/
|
||||
export interface StartIncubationRequest {
|
||||
/** Explicit mode for this operation */
|
||||
mode: StartIncubationMode;
|
||||
/** The d-tag of the other Blobbi to stop (required when mode === 'switch') */
|
||||
stopOtherD?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parameters for start incubation hook.
|
||||
*/
|
||||
export interface UseStartIncubationParams {
|
||||
companion: BlobbiCompanion | null;
|
||||
profile: BlobbonautProfile | null;
|
||||
/** Called to ensure companion is canonical (from migration helper) */
|
||||
ensureCanonicalBeforeAction: () => Promise<{
|
||||
companion: BlobbiCompanion;
|
||||
content: string;
|
||||
allTags: string[][];
|
||||
wasMigrated: boolean;
|
||||
profileAllTags: string[][];
|
||||
profileStorage: import('@/blobbi/core/lib/blobbi').StorageItem[];
|
||||
} | null>;
|
||||
/** Update companion event in local cache */
|
||||
updateCompanionEvent: (event: NostrEvent) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of starting incubation.
|
||||
*/
|
||||
export interface StartIncubationResult {
|
||||
/** The Blobbi's name */
|
||||
name: string;
|
||||
/** Timestamp when incubation started */
|
||||
stateStartedAt: number;
|
||||
/** Mode that was used */
|
||||
mode: StartIncubationMode;
|
||||
/** Name of other Blobbi that was stopped (if mode === 'switch') */
|
||||
stoppedOtherName?: string;
|
||||
}
|
||||
|
||||
// ─── Start Incubation Hook ────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Hook to start the incubation process for an egg.
|
||||
*
|
||||
* This sets the Blobbi state to 'incubating' and records the start timestamp.
|
||||
* Tasks will be computed based on events created after this timestamp.
|
||||
*
|
||||
* IMPORTANT: The mode must be explicitly specified by the caller (UI).
|
||||
* This hook does NOT auto-detect whether to switch or restart.
|
||||
* The UI dialog determines the mode and passes it explicitly.
|
||||
*
|
||||
* Modes:
|
||||
* - 'start': Normal start, no other Blobbi incubating
|
||||
* - 'restart': Restart same Blobbi (already incubating), resets task progress
|
||||
* - 'switch': Stop another Blobbi first, then start this one
|
||||
*
|
||||
* Requirements:
|
||||
* - Blobbi must be in egg stage
|
||||
* - User must be logged in
|
||||
*/
|
||||
export function useStartIncubation({
|
||||
companion,
|
||||
profile,
|
||||
ensureCanonicalBeforeAction,
|
||||
updateCompanionEvent,
|
||||
}: UseStartIncubationParams) {
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (request: StartIncubationRequest): Promise<StartIncubationResult> => {
|
||||
const { mode, stopOtherD } = request;
|
||||
|
||||
// ─── Validation ───
|
||||
if (!user?.pubkey) {
|
||||
throw new Error('You must be logged in to start incubation');
|
||||
}
|
||||
|
||||
if (!companion) {
|
||||
throw new Error('No companion selected');
|
||||
}
|
||||
|
||||
if (!profile) {
|
||||
throw new Error('Profile not found');
|
||||
}
|
||||
|
||||
if (companion.stage !== 'egg') {
|
||||
throw new Error('Only eggs can be incubated');
|
||||
}
|
||||
|
||||
// Validate switch mode requires stopOtherD
|
||||
if (mode === 'switch' && !stopOtherD) {
|
||||
throw new Error('Switch mode requires stopOtherD parameter');
|
||||
}
|
||||
|
||||
let stoppedOtherName: string | undefined;
|
||||
|
||||
// ─── Stop Other Incubating Blobbi (switch mode only) ───
|
||||
if (mode === 'switch' && stopOtherD) {
|
||||
// Fetch the current event for the other Blobbi
|
||||
const [otherEvent] = await nostr.query([{
|
||||
kinds: [KIND_BLOBBI_STATE],
|
||||
authors: [user.pubkey],
|
||||
'#d': [stopOtherD],
|
||||
limit: 1,
|
||||
}]);
|
||||
|
||||
if (otherEvent) {
|
||||
// Get name from the event for the result
|
||||
const nameTag = otherEvent.tags.find(t => t[0] === 'name');
|
||||
stoppedOtherName = nameTag?.[1] ?? stopOtherD;
|
||||
|
||||
// Stop the other Blobbi's incubation
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const nowStr = now.toString();
|
||||
|
||||
// Parse stats from the event
|
||||
const getTagValue = (tags: string[][], name: string): number =>
|
||||
parseInt(tags.find(t => t[0] === name)?.[1] ?? '50', 10);
|
||||
|
||||
const otherStats = {
|
||||
hunger: getTagValue(otherEvent.tags, 'hunger'),
|
||||
happiness: getTagValue(otherEvent.tags, 'happiness'),
|
||||
health: getTagValue(otherEvent.tags, 'health'),
|
||||
hygiene: getTagValue(otherEvent.tags, 'hygiene'),
|
||||
energy: getTagValue(otherEvent.tags, 'energy'),
|
||||
};
|
||||
const otherLastDecayAt = getTagValue(otherEvent.tags, 'last_decay_at') || now;
|
||||
|
||||
// Apply decay to the other Blobbi
|
||||
const otherDecayResult = applyBlobbiDecay({
|
||||
stage: 'egg',
|
||||
state: 'incubating',
|
||||
stats: otherStats,
|
||||
lastDecayAt: otherLastDecayAt,
|
||||
now,
|
||||
});
|
||||
|
||||
// Remove task tags and state_started_at from the other Blobbi
|
||||
const otherCleanedTags = otherEvent.tags.filter(tag =>
|
||||
tag[0] !== 'task' &&
|
||||
tag[0] !== 'task_completed' &&
|
||||
tag[0] !== 'state_started_at'
|
||||
);
|
||||
|
||||
const otherNewTags = updateBlobbiTags(otherCleanedTags, {
|
||||
health: otherDecayResult.stats.health.toString(),
|
||||
hygiene: otherDecayResult.stats.hygiene.toString(),
|
||||
happiness: otherDecayResult.stats.happiness.toString(),
|
||||
hunger: '100',
|
||||
energy: '100',
|
||||
state: 'active',
|
||||
last_interaction: nowStr,
|
||||
last_decay_at: nowStr,
|
||||
});
|
||||
|
||||
// Publish the stop event for the other Blobbi
|
||||
const stopEvent = await publishEvent({
|
||||
kind: KIND_BLOBBI_STATE,
|
||||
content: otherEvent.content,
|
||||
tags: otherNewTags,
|
||||
});
|
||||
|
||||
// Update the cache for the stopped Blobbi
|
||||
updateCompanionEvent(stopEvent);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Ensure Canonical Before Action ───
|
||||
const canonical = await ensureCanonicalBeforeAction();
|
||||
if (!canonical) {
|
||||
throw new Error('Failed to prepare companion for incubation');
|
||||
}
|
||||
|
||||
// ─── Apply Accumulated Decay ───
|
||||
// CRITICAL: Apply decay from last_decay_at to now before changing state
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const nowStr = now.toString();
|
||||
|
||||
const decayResult = applyBlobbiDecay({
|
||||
stage: canonical.companion.stage,
|
||||
state: canonical.companion.state,
|
||||
stats: canonical.companion.stats,
|
||||
lastDecayAt: canonical.companion.lastDecayAt,
|
||||
now,
|
||||
});
|
||||
|
||||
// ─── Build Updated Tags ───
|
||||
// Remove any existing task tags when starting fresh (for all modes)
|
||||
const cleanedTags = canonical.allTags.filter(tag =>
|
||||
tag[0] !== 'task' && tag[0] !== 'task_completed'
|
||||
);
|
||||
|
||||
// Build stats update with decayed values
|
||||
// Eggs have fixed hunger and energy at 100
|
||||
const statsUpdate: Record<string, string> = {
|
||||
health: decayResult.stats.health.toString(),
|
||||
hygiene: decayResult.stats.hygiene.toString(),
|
||||
happiness: decayResult.stats.happiness.toString(),
|
||||
hunger: '100',
|
||||
energy: '100',
|
||||
};
|
||||
|
||||
const newTags = updateBlobbiTags(cleanedTags, {
|
||||
...statsUpdate,
|
||||
state: 'incubating',
|
||||
state_started_at: nowStr,
|
||||
last_interaction: nowStr,
|
||||
last_decay_at: nowStr,
|
||||
});
|
||||
|
||||
// ─── Publish Event ───
|
||||
const event = await publishEvent({
|
||||
kind: KIND_BLOBBI_STATE,
|
||||
content: canonical.content,
|
||||
tags: newTags,
|
||||
});
|
||||
|
||||
updateCompanionEvent(event);
|
||||
|
||||
return {
|
||||
name: canonical.companion.name,
|
||||
stateStartedAt: now,
|
||||
mode,
|
||||
stoppedOtherName,
|
||||
};
|
||||
},
|
||||
onSuccess: ({ name, mode, stoppedOtherName }) => {
|
||||
if (mode === 'switch' && stoppedOtherName) {
|
||||
toast({
|
||||
title: 'Switched incubation!',
|
||||
description: `Stopped ${stoppedOtherName}, now incubating ${name}.`,
|
||||
});
|
||||
} else if (mode === 'restart') {
|
||||
toast({
|
||||
title: 'Incubation restarted!',
|
||||
description: `${name}'s task progress has been reset.`,
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
title: 'Incubation started!',
|
||||
description: `${name} is now incubating. Complete the tasks to hatch!`,
|
||||
});
|
||||
}
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast({
|
||||
title: 'Failed to start incubation',
|
||||
description: error.message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Stop Incubation Hook ─────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Parameters for stop incubation hook.
|
||||
*/
|
||||
export interface UseStopIncubationParams {
|
||||
companion: BlobbiCompanion | null;
|
||||
/** Called to ensure companion is canonical (from migration helper) */
|
||||
ensureCanonicalBeforeAction: () => Promise<{
|
||||
companion: BlobbiCompanion;
|
||||
content: string;
|
||||
allTags: string[][];
|
||||
wasMigrated: boolean;
|
||||
profileAllTags: string[][];
|
||||
profileStorage: import('@/blobbi/core/lib/blobbi').StorageItem[];
|
||||
} | null>;
|
||||
/** Update companion event in local cache */
|
||||
updateCompanionEvent: (event: NostrEvent) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of stopping incubation.
|
||||
*/
|
||||
export interface StopIncubationResult {
|
||||
/** The Blobbi's name */
|
||||
name: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to stop/cancel the incubation process for a Blobbi.
|
||||
*
|
||||
* This resets the Blobbi state to 'active' and clears all task progress tags.
|
||||
* The user can restart incubation later, but will need to complete tasks again.
|
||||
*
|
||||
* When stopping incubation:
|
||||
* - Apply accumulated decay first
|
||||
* - Set state back to 'active'
|
||||
* - Remove state_started_at tag
|
||||
* - Remove all task and task_completed tags
|
||||
*
|
||||
* Requirements:
|
||||
* - Blobbi must be in incubating state
|
||||
* - User must be logged in
|
||||
*/
|
||||
export function useStopIncubation({
|
||||
companion,
|
||||
ensureCanonicalBeforeAction,
|
||||
updateCompanionEvent,
|
||||
}: UseStopIncubationParams) {
|
||||
const { user } = useCurrentUser();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (): Promise<StopIncubationResult> => {
|
||||
// ─── Validation ───
|
||||
if (!user?.pubkey) {
|
||||
throw new Error('You must be logged in to stop incubation');
|
||||
}
|
||||
|
||||
if (!companion) {
|
||||
throw new Error('No companion selected');
|
||||
}
|
||||
|
||||
if (companion.state !== 'incubating') {
|
||||
throw new Error('This Blobbi is not incubating');
|
||||
}
|
||||
|
||||
// ─── Ensure Canonical Before Action ───
|
||||
const canonical = await ensureCanonicalBeforeAction();
|
||||
if (!canonical) {
|
||||
throw new Error('Failed to prepare companion');
|
||||
}
|
||||
|
||||
// ─── Apply Accumulated Decay ───
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const nowStr = now.toString();
|
||||
|
||||
const decayResult = applyBlobbiDecay({
|
||||
stage: canonical.companion.stage,
|
||||
state: canonical.companion.state,
|
||||
stats: canonical.companion.stats,
|
||||
lastDecayAt: canonical.companion.lastDecayAt,
|
||||
now,
|
||||
});
|
||||
|
||||
// ─── Build Updated Tags ───
|
||||
// Remove task tags and state_started_at
|
||||
const cleanedTags = canonical.allTags.filter(tag =>
|
||||
tag[0] !== 'task' &&
|
||||
tag[0] !== 'task_completed' &&
|
||||
tag[0] !== 'state_started_at'
|
||||
);
|
||||
|
||||
// Build stats update with decayed values
|
||||
// Eggs have fixed hunger and energy at 100
|
||||
const statsUpdate: Record<string, string> = {
|
||||
health: decayResult.stats.health.toString(),
|
||||
hygiene: decayResult.stats.hygiene.toString(),
|
||||
happiness: decayResult.stats.happiness.toString(),
|
||||
hunger: '100',
|
||||
energy: '100',
|
||||
};
|
||||
|
||||
const newTags = updateBlobbiTags(cleanedTags, {
|
||||
...statsUpdate,
|
||||
state: 'active',
|
||||
last_interaction: nowStr,
|
||||
last_decay_at: nowStr,
|
||||
});
|
||||
|
||||
// ─── Publish Event ───
|
||||
const event = await publishEvent({
|
||||
kind: KIND_BLOBBI_STATE,
|
||||
content: canonical.content,
|
||||
tags: newTags,
|
||||
});
|
||||
|
||||
updateCompanionEvent(event);
|
||||
|
||||
return {
|
||||
name: canonical.companion.name,
|
||||
};
|
||||
},
|
||||
onSuccess: ({ name }) => {
|
||||
toast({
|
||||
title: 'Incubation stopped',
|
||||
description: `${name} is no longer incubating. Task progress has been reset.`,
|
||||
});
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast({
|
||||
title: 'Failed to stop incubation',
|
||||
description: error.message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Start Evolution Hook ─────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Parameters for start evolution hook.
|
||||
*/
|
||||
export interface UseStartEvolutionParams {
|
||||
companion: BlobbiCompanion | null;
|
||||
/** Called to ensure companion is canonical (from migration helper) */
|
||||
ensureCanonicalBeforeAction: () => Promise<{
|
||||
companion: BlobbiCompanion;
|
||||
content: string;
|
||||
allTags: string[][];
|
||||
wasMigrated: boolean;
|
||||
profileAllTags: string[][];
|
||||
profileStorage: import('@/blobbi/core/lib/blobbi').StorageItem[];
|
||||
} | null>;
|
||||
/** Update companion event in local cache */
|
||||
updateCompanionEvent: (event: NostrEvent) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of starting evolution.
|
||||
*/
|
||||
export interface StartEvolutionResult {
|
||||
/** The Blobbi's name */
|
||||
name: string;
|
||||
/** Timestamp when evolution started */
|
||||
stateStartedAt: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to start the evolution process for a baby Blobbi.
|
||||
*
|
||||
* This sets the Blobbi state to 'evolving' and records the start timestamp.
|
||||
* Tasks will be computed based on events created after this timestamp.
|
||||
*
|
||||
* Requirements:
|
||||
* - Blobbi must be in baby stage
|
||||
* - Blobbi must not already be evolving
|
||||
* - User must be logged in
|
||||
*/
|
||||
export function useStartEvolution({
|
||||
companion,
|
||||
ensureCanonicalBeforeAction,
|
||||
updateCompanionEvent,
|
||||
}: UseStartEvolutionParams) {
|
||||
const { user } = useCurrentUser();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (): Promise<StartEvolutionResult> => {
|
||||
// ─── Validation ───
|
||||
if (!user?.pubkey) {
|
||||
throw new Error('You must be logged in to start evolution');
|
||||
}
|
||||
|
||||
if (!companion) {
|
||||
throw new Error('No companion selected');
|
||||
}
|
||||
|
||||
if (companion.stage !== 'baby') {
|
||||
throw new Error('Only baby Blobbis can evolve');
|
||||
}
|
||||
|
||||
if (companion.state === 'evolving') {
|
||||
throw new Error('This Blobbi is already evolving');
|
||||
}
|
||||
|
||||
// ─── Ensure Canonical Before Action ───
|
||||
const canonical = await ensureCanonicalBeforeAction();
|
||||
if (!canonical) {
|
||||
throw new Error('Failed to prepare companion for evolution');
|
||||
}
|
||||
|
||||
// ─── Apply Accumulated Decay ───
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const nowStr = now.toString();
|
||||
|
||||
const decayResult = applyBlobbiDecay({
|
||||
stage: canonical.companion.stage,
|
||||
state: canonical.companion.state,
|
||||
stats: canonical.companion.stats,
|
||||
lastDecayAt: canonical.companion.lastDecayAt,
|
||||
now,
|
||||
});
|
||||
|
||||
// ─── Build Updated Tags ───
|
||||
// Remove any existing task tags when starting fresh
|
||||
const cleanedTags = canonical.allTags.filter(tag =>
|
||||
tag[0] !== 'task' && tag[0] !== 'task_completed'
|
||||
);
|
||||
|
||||
// Build stats update with decayed values
|
||||
const statsUpdate: Record<string, string> = {
|
||||
health: decayResult.stats.health.toString(),
|
||||
hygiene: decayResult.stats.hygiene.toString(),
|
||||
happiness: decayResult.stats.happiness.toString(),
|
||||
hunger: decayResult.stats.hunger.toString(),
|
||||
energy: decayResult.stats.energy.toString(),
|
||||
};
|
||||
|
||||
const newTags = updateBlobbiTags(cleanedTags, {
|
||||
...statsUpdate,
|
||||
state: 'evolving',
|
||||
state_started_at: nowStr,
|
||||
last_interaction: nowStr,
|
||||
last_decay_at: nowStr,
|
||||
});
|
||||
|
||||
// ─── Publish Event ───
|
||||
const event = await publishEvent({
|
||||
kind: KIND_BLOBBI_STATE,
|
||||
content: canonical.content,
|
||||
tags: newTags,
|
||||
});
|
||||
|
||||
updateCompanionEvent(event);
|
||||
|
||||
return {
|
||||
name: canonical.companion.name,
|
||||
stateStartedAt: now,
|
||||
};
|
||||
},
|
||||
onSuccess: ({ name }) => {
|
||||
toast({
|
||||
title: 'Evolution started!',
|
||||
description: `${name} is now working towards evolution. Complete the tasks to evolve!`,
|
||||
});
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast({
|
||||
title: 'Failed to start evolution',
|
||||
description: error.message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Stop Evolution Hook ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Parameters for stop evolution hook.
|
||||
*/
|
||||
export interface UseStopEvolutionParams {
|
||||
companion: BlobbiCompanion | null;
|
||||
/** Called to ensure companion is canonical (from migration helper) */
|
||||
ensureCanonicalBeforeAction: () => Promise<{
|
||||
companion: BlobbiCompanion;
|
||||
content: string;
|
||||
allTags: string[][];
|
||||
wasMigrated: boolean;
|
||||
profileAllTags: string[][];
|
||||
profileStorage: import('@/blobbi/core/lib/blobbi').StorageItem[];
|
||||
} | null>;
|
||||
/** Update companion event in local cache */
|
||||
updateCompanionEvent: (event: NostrEvent) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of stopping evolution.
|
||||
*/
|
||||
export interface StopEvolutionResult {
|
||||
/** The Blobbi's name */
|
||||
name: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to stop/cancel the evolution process for a Blobbi.
|
||||
*
|
||||
* This resets the Blobbi state to 'active' and clears all task progress tags.
|
||||
* The user can restart evolution later, but will need to complete tasks again.
|
||||
*
|
||||
* When stopping evolution:
|
||||
* - Apply accumulated decay first
|
||||
* - Set state back to 'active'
|
||||
* - Remove state_started_at tag
|
||||
* - Remove all task and task_completed tags
|
||||
*
|
||||
* Requirements:
|
||||
* - Blobbi must be in evolving state
|
||||
* - User must be logged in
|
||||
*/
|
||||
export function useStopEvolution({
|
||||
companion,
|
||||
ensureCanonicalBeforeAction,
|
||||
updateCompanionEvent,
|
||||
}: UseStopEvolutionParams) {
|
||||
const { user } = useCurrentUser();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (): Promise<StopEvolutionResult> => {
|
||||
// ─── Validation ───
|
||||
if (!user?.pubkey) {
|
||||
throw new Error('You must be logged in to stop evolution');
|
||||
}
|
||||
|
||||
if (!companion) {
|
||||
throw new Error('No companion selected');
|
||||
}
|
||||
|
||||
if (companion.state !== 'evolving') {
|
||||
throw new Error('This Blobbi is not evolving');
|
||||
}
|
||||
|
||||
// ─── Ensure Canonical Before Action ───
|
||||
const canonical = await ensureCanonicalBeforeAction();
|
||||
if (!canonical) {
|
||||
throw new Error('Failed to prepare companion');
|
||||
}
|
||||
|
||||
// ─── Apply Accumulated Decay ───
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const nowStr = now.toString();
|
||||
|
||||
const decayResult = applyBlobbiDecay({
|
||||
stage: canonical.companion.stage,
|
||||
state: canonical.companion.state,
|
||||
stats: canonical.companion.stats,
|
||||
lastDecayAt: canonical.companion.lastDecayAt,
|
||||
now,
|
||||
});
|
||||
|
||||
// ─── Build Updated Tags ───
|
||||
// Remove task tags and state_started_at
|
||||
const cleanedTags = canonical.allTags.filter(tag =>
|
||||
tag[0] !== 'task' &&
|
||||
tag[0] !== 'task_completed' &&
|
||||
tag[0] !== 'state_started_at'
|
||||
);
|
||||
|
||||
// Build stats update with decayed values
|
||||
const statsUpdate: Record<string, string> = {
|
||||
health: decayResult.stats.health.toString(),
|
||||
hygiene: decayResult.stats.hygiene.toString(),
|
||||
happiness: decayResult.stats.happiness.toString(),
|
||||
hunger: decayResult.stats.hunger.toString(),
|
||||
energy: decayResult.stats.energy.toString(),
|
||||
};
|
||||
|
||||
const newTags = updateBlobbiTags(cleanedTags, {
|
||||
...statsUpdate,
|
||||
state: 'active',
|
||||
last_interaction: nowStr,
|
||||
last_decay_at: nowStr,
|
||||
});
|
||||
|
||||
// ─── Publish Event ───
|
||||
const event = await publishEvent({
|
||||
kind: KIND_BLOBBI_STATE,
|
||||
content: canonical.content,
|
||||
tags: newTags,
|
||||
});
|
||||
|
||||
updateCompanionEvent(event);
|
||||
|
||||
return {
|
||||
name: canonical.companion.name,
|
||||
};
|
||||
},
|
||||
onSuccess: ({ name }) => {
|
||||
toast({
|
||||
title: 'Evolution stopped',
|
||||
description: `${name} is no longer evolving. Task progress has been reset.`,
|
||||
});
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast({
|
||||
title: 'Failed to stop evolution',
|
||||
description: error.message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Sync Task Completions Hook ───────────────────────────────────────────────
|
||||
|
||||
/** Enable debug logging in development only */
|
||||
const DEBUG_TASK_SYNC = import.meta.env.DEV;
|
||||
|
||||
/**
|
||||
* Parameters for syncing task completions (works for both hatch and evolve).
|
||||
*/
|
||||
export interface UseSyncTaskCompletionsParams {
|
||||
companion: BlobbiCompanion | null;
|
||||
/** Called to ensure companion is canonical */
|
||||
ensureCanonicalBeforeAction: () => Promise<{
|
||||
companion: BlobbiCompanion;
|
||||
content: string;
|
||||
allTags: string[][];
|
||||
wasMigrated: boolean;
|
||||
profileAllTags: string[][];
|
||||
profileStorage: import('@/blobbi/core/lib/blobbi').StorageItem[];
|
||||
} | null>;
|
||||
/** Update companion event in local cache */
|
||||
updateCompanionEvent: (event: NostrEvent) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Task completions to sync (from useHatchTasks or useEvolveTasks).
|
||||
*/
|
||||
export interface TaskCompletionToSync {
|
||||
taskId: string;
|
||||
completed: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of sync operation.
|
||||
*/
|
||||
export interface SyncTaskCompletionsResult {
|
||||
/** Task IDs that were synced (empty if nothing needed) */
|
||||
synced: string[];
|
||||
/** Whether sync was skipped (no diff) */
|
||||
skipped: boolean;
|
||||
/** Reason for skip (for debugging) */
|
||||
skipReason?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to sync persistent task completions to kind 31124 tags.
|
||||
* Works for both hatch (incubating) and evolve (evolving) processes.
|
||||
*
|
||||
* CRITICAL: This is a cache-only sync. It must be:
|
||||
* 1. Fully idempotent - calling multiple times with same data = no-op
|
||||
* 2. Diff-based - only publish when tags would actually change
|
||||
* 3. Safe - no last_interaction update (this is cache sync, not user action)
|
||||
* 4. Only sync PERSISTENT tasks - dynamic tasks must NEVER be synced
|
||||
*
|
||||
* Source of truth = computed task state from Nostr events.
|
||||
* Tags = cache layer for faster access.
|
||||
*/
|
||||
export function useSyncTaskCompletions({
|
||||
companion,
|
||||
ensureCanonicalBeforeAction,
|
||||
updateCompanionEvent,
|
||||
}: UseSyncTaskCompletionsParams) {
|
||||
const { user } = useCurrentUser();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (tasksToSync: TaskCompletionToSync[]): Promise<SyncTaskCompletionsResult> => {
|
||||
// ─── Early Guards ───
|
||||
if (!user?.pubkey) {
|
||||
return { synced: [], skipped: true, skipReason: 'no_user' };
|
||||
}
|
||||
|
||||
if (!companion) {
|
||||
return { synced: [], skipped: true, skipReason: 'no_companion' };
|
||||
}
|
||||
|
||||
// Must be in an active task process (incubating or evolving)
|
||||
if (companion.state !== 'incubating' && companion.state !== 'evolving') {
|
||||
return { synced: [], skipped: true, skipReason: 'not_in_task_process' };
|
||||
}
|
||||
|
||||
// ─── Compute Diff ───
|
||||
// Get cached completions from companion.tasksCompleted (parsed from tags)
|
||||
const cachedCompletions = new Set(companion.tasksCompleted);
|
||||
|
||||
// Get computed completions from tasks (works for both hatch and evolve)
|
||||
const computedCompletions = tasksToSync
|
||||
.filter(t => t.completed)
|
||||
.map(t => t.taskId);
|
||||
|
||||
// Find tasks that are computed as complete but NOT in cache
|
||||
const missingFromCache = computedCompletions.filter(id => !cachedCompletions.has(id));
|
||||
|
||||
if (DEBUG_TASK_SYNC) {
|
||||
console.log('[TaskSync] Diff check:', {
|
||||
cachedCompletions: Array.from(cachedCompletions),
|
||||
computedCompletions,
|
||||
missingFromCache,
|
||||
});
|
||||
}
|
||||
|
||||
// If no diff, skip entirely
|
||||
if (missingFromCache.length === 0) {
|
||||
if (DEBUG_TASK_SYNC) {
|
||||
console.log('[TaskSync] Skipped: no diff between computed and cached');
|
||||
}
|
||||
return { synced: [], skipped: true, skipReason: 'no_diff' };
|
||||
}
|
||||
|
||||
// ─── Ensure Canonical ───
|
||||
const canonical = await ensureCanonicalBeforeAction();
|
||||
if (!canonical) {
|
||||
return { synced: [], skipped: true, skipReason: 'canonical_failed' };
|
||||
}
|
||||
|
||||
// ─── Build Updated Tags ───
|
||||
// Re-check against canonical.allTags (may have updated since companion was parsed)
|
||||
const existingCompletionTags = new Set(
|
||||
canonical.allTags
|
||||
.filter(tag => tag[0] === 'task_completed')
|
||||
.map(tag => tag[1])
|
||||
);
|
||||
|
||||
// Filter to only truly missing tags
|
||||
const tagsToAdd = missingFromCache.filter(id => !existingCompletionTags.has(id));
|
||||
|
||||
if (tagsToAdd.length === 0) {
|
||||
if (DEBUG_TASK_SYNC) {
|
||||
console.log('[TaskSync] Skipped: all tags already exist in canonical');
|
||||
}
|
||||
return { synced: [], skipped: true, skipReason: 'tags_already_exist' };
|
||||
}
|
||||
|
||||
// Add only the missing task_completed tags
|
||||
// CRITICAL: Do NOT update last_interaction - this is cache sync, not user action
|
||||
const updatedTags = [
|
||||
...canonical.allTags,
|
||||
...tagsToAdd.map(id => ['task_completed', id]),
|
||||
];
|
||||
|
||||
if (DEBUG_TASK_SYNC) {
|
||||
console.log('[TaskSync] Publishing:', {
|
||||
tagsToAdd,
|
||||
totalTags: updatedTags.length,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Publish ───
|
||||
const event = await publishEvent({
|
||||
kind: KIND_BLOBBI_STATE,
|
||||
content: canonical.content,
|
||||
tags: updatedTags,
|
||||
});
|
||||
|
||||
updateCompanionEvent(event);
|
||||
|
||||
if (DEBUG_TASK_SYNC) {
|
||||
console.log('[TaskSync] Published successfully:', tagsToAdd);
|
||||
}
|
||||
|
||||
return { synced: tagsToAdd, skipped: false };
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
// src/blobbi/actions/hooks/useBlobbiStageTransition.ts
|
||||
|
||||
/**
|
||||
* Hooks for Blobbi stage transitions (hatch, evolve).
|
||||
*
|
||||
* Both transitions follow the same decay pattern:
|
||||
* 1. Apply accumulated decay from `last_decay_at` to `now`
|
||||
* 2. Use decayed stats as the source of truth for the transition
|
||||
* 3. Publish new event with decayed stats + new stage
|
||||
* 4. Reset `last_decay_at` to current timestamp
|
||||
*
|
||||
* @see docs/blobbi/decay-system.md
|
||||
*/
|
||||
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { toast } from '@/hooks/useToast';
|
||||
|
||||
import type { BlobbiCompanion, BlobbonautProfile, BlobbiStage } from '@/blobbi/core/lib/blobbi';
|
||||
import {
|
||||
KIND_BLOBBI_STATE,
|
||||
STAT_MAX,
|
||||
updateBlobbiTags,
|
||||
} from '@/blobbi/core/lib/blobbi';
|
||||
import { applyBlobbiDecay } from '@/blobbi/core/lib/blobbi-decay';
|
||||
import { validateAndRepairBlobbiTags } from '@/blobbi/core/lib/blobbi-tag-schema';
|
||||
import { getStreakTagUpdates } from '../lib/blobbi-streak';
|
||||
|
||||
// ─── Content Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Generate the content string for a Blobbi at a given stage.
|
||||
* Format: "{name} is a {stage} Blobbi."
|
||||
*
|
||||
* Uses correct grammar: "an egg" vs "a baby/adult"
|
||||
*/
|
||||
function generateBlobbiContent(name: string, stage: BlobbiStage): string {
|
||||
const article = stage === 'egg' ? 'an' : 'a';
|
||||
return `${name} is ${article} ${stage} Blobbi.`;
|
||||
}
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Result of ensuring canonical companion before action.
|
||||
* This is the same interface used by useBlobbiUseInventoryItem.
|
||||
*/
|
||||
export interface CanonicalActionResult {
|
||||
companion: BlobbiCompanion;
|
||||
content: string;
|
||||
allTags: string[][];
|
||||
wasMigrated: boolean;
|
||||
/** Latest profile tags after migration */
|
||||
profileAllTags: string[][];
|
||||
/** Latest profile storage after migration */
|
||||
profileStorage: import('@/blobbi/core/lib/blobbi').StorageItem[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Parameters for stage transition hooks.
|
||||
*/
|
||||
export interface UseBlobbiStageTransitionParams {
|
||||
companion: BlobbiCompanion | null;
|
||||
profile: BlobbonautProfile | null;
|
||||
/** Called to ensure companion is canonical (from migration helper) */
|
||||
ensureCanonicalBeforeAction: () => Promise<CanonicalActionResult | null>;
|
||||
/** Update companion event in local cache */
|
||||
updateCompanionEvent: (event: NostrEvent) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of a stage transition.
|
||||
*/
|
||||
export interface StageTransitionResult {
|
||||
/** Previous stage before transition */
|
||||
previousStage: BlobbiStage;
|
||||
/** New stage after transition */
|
||||
newStage: BlobbiStage;
|
||||
/** The Blobbi's name */
|
||||
name: string;
|
||||
/** Stats after decay was applied (before any transition bonuses) */
|
||||
decayedStats: {
|
||||
hunger: number;
|
||||
happiness: number;
|
||||
health: number;
|
||||
hygiene: number;
|
||||
energy: number;
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Hatch Hook ───────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Hook to hatch an egg into a baby Blobbi.
|
||||
*
|
||||
* Transition: egg -> baby
|
||||
*
|
||||
* Requirements:
|
||||
* - Blobbi must be in egg stage
|
||||
* - Applies accumulated decay before transition
|
||||
* - Resets stats to healthy baby defaults (inherits health from egg)
|
||||
* - Sets last_decay_at to current timestamp
|
||||
*/
|
||||
export function useBlobbiHatch({
|
||||
companion,
|
||||
profile,
|
||||
ensureCanonicalBeforeAction,
|
||||
updateCompanionEvent,
|
||||
}: UseBlobbiStageTransitionParams) {
|
||||
const { user } = useCurrentUser();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (): Promise<StageTransitionResult> => {
|
||||
// ─── Validation ───
|
||||
if (!user?.pubkey) {
|
||||
throw new Error('You must be logged in to hatch');
|
||||
}
|
||||
|
||||
if (!companion) {
|
||||
throw new Error('No companion selected');
|
||||
}
|
||||
|
||||
if (!profile) {
|
||||
throw new Error('Profile not found');
|
||||
}
|
||||
|
||||
if (companion.stage !== 'egg') {
|
||||
throw new Error('Only eggs can be hatched');
|
||||
}
|
||||
|
||||
// ─── Ensure Canonical Before Action ───
|
||||
const canonical = await ensureCanonicalBeforeAction();
|
||||
if (!canonical) {
|
||||
throw new Error('Failed to prepare companion for hatching');
|
||||
}
|
||||
|
||||
// ─── Apply Accumulated Decay First ───
|
||||
// Per decay-system.md: Always apply accumulated decay from persisted state
|
||||
// before any stage transition.
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const decayResult = applyBlobbiDecay({
|
||||
stage: canonical.companion.stage,
|
||||
state: canonical.companion.state,
|
||||
stats: canonical.companion.stats,
|
||||
lastDecayAt: canonical.companion.lastDecayAt,
|
||||
now,
|
||||
});
|
||||
|
||||
// ─── Calculate Baby Stats ───
|
||||
// All stats reset to 100 when hatching — the baby starts fresh
|
||||
const babyStats = {
|
||||
hunger: STAT_MAX,
|
||||
happiness: STAT_MAX,
|
||||
health: STAT_MAX,
|
||||
hygiene: STAT_MAX,
|
||||
energy: STAT_MAX,
|
||||
};
|
||||
|
||||
// ─── Build Updated Tags ───
|
||||
// CRITICAL: Start from canonical.allTags and only remove task/state-specific tags
|
||||
// This preserves ALL identity attributes (personality, trait, favorite_food, etc.)
|
||||
const nowStr = now.toString();
|
||||
|
||||
// Build the updated tags using the central merge function
|
||||
// Get streak updates (hatching counts as care activity!)
|
||||
const streakUpdates = getStreakTagUpdates(canonical.companion) ?? {};
|
||||
|
||||
const mergedTags = updateBlobbiTags(canonical.allTags, {
|
||||
stage: 'baby',
|
||||
state: 'active', // Newly hatched babies are awake
|
||||
hunger: babyStats.hunger.toString(),
|
||||
happiness: babyStats.happiness.toString(),
|
||||
health: babyStats.health.toString(),
|
||||
hygiene: babyStats.hygiene.toString(),
|
||||
energy: babyStats.energy.toString(),
|
||||
...streakUpdates,
|
||||
last_interaction: nowStr,
|
||||
last_decay_at: nowStr,
|
||||
});
|
||||
|
||||
// ─── Validate and Repair Tags ───
|
||||
// Use the tag integrity guard to ensure all persistent tags are preserved
|
||||
// and task-related tags are properly cleaned up for stage transitions
|
||||
const repairResult = validateAndRepairBlobbiTags(
|
||||
mergedTags,
|
||||
canonical.allTags,
|
||||
{ cleanupTaskTags: true }
|
||||
);
|
||||
|
||||
if (repairResult.errors.length > 0) {
|
||||
console.error('[Hatch] Tag validation errors:', repairResult.errors);
|
||||
throw new Error(`Tag validation failed: ${repairResult.errors.join(', ')}`);
|
||||
}
|
||||
|
||||
if (repairResult.repaired && import.meta.env.DEV) {
|
||||
console.log('[Hatch] Tag repairs applied:', repairResult.repairs);
|
||||
}
|
||||
|
||||
const newTags = repairResult.tags;
|
||||
|
||||
// ─── Generate New Content for Baby Stage ───
|
||||
// CRITICAL: Content must reflect the new stage
|
||||
const newContent = generateBlobbiContent(canonical.companion.name, 'baby');
|
||||
|
||||
// ─── Publish Event ───
|
||||
const event = await publishEvent({
|
||||
kind: KIND_BLOBBI_STATE,
|
||||
content: newContent,
|
||||
tags: newTags,
|
||||
});
|
||||
|
||||
updateCompanionEvent(event);
|
||||
|
||||
return {
|
||||
previousStage: 'egg',
|
||||
newStage: 'baby',
|
||||
name: canonical.companion.name,
|
||||
decayedStats: decayResult.stats,
|
||||
};
|
||||
},
|
||||
onSuccess: ({ name }) => {
|
||||
toast({
|
||||
title: 'Your egg hatched!',
|
||||
description: `${name} is now a baby Blobbi! Take good care of them.`,
|
||||
});
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast({
|
||||
title: 'Failed to hatch',
|
||||
description: error.message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Evolve Hook ──────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Hook to evolve a baby Blobbi into an adult.
|
||||
*
|
||||
* Transition: baby -> adult
|
||||
*
|
||||
* Requirements:
|
||||
* - Blobbi must be in baby stage
|
||||
* - Applies accumulated decay before transition
|
||||
* - Preserves all stats (decay already applied)
|
||||
* - Sets last_decay_at to current timestamp
|
||||
*/
|
||||
export function useBlobbiEvolve({
|
||||
companion,
|
||||
profile,
|
||||
ensureCanonicalBeforeAction,
|
||||
updateCompanionEvent,
|
||||
}: UseBlobbiStageTransitionParams) {
|
||||
const { user } = useCurrentUser();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (): Promise<StageTransitionResult> => {
|
||||
// ─── Validation ───
|
||||
if (!user?.pubkey) {
|
||||
throw new Error('You must be logged in to evolve');
|
||||
}
|
||||
|
||||
if (!companion) {
|
||||
throw new Error('No companion selected');
|
||||
}
|
||||
|
||||
if (!profile) {
|
||||
throw new Error('Profile not found');
|
||||
}
|
||||
|
||||
if (companion.stage !== 'baby') {
|
||||
if (companion.stage === 'egg') {
|
||||
throw new Error('Eggs must hatch before they can evolve');
|
||||
}
|
||||
if (companion.stage === 'adult') {
|
||||
throw new Error('This Blobbi is already fully evolved');
|
||||
}
|
||||
throw new Error('Only baby Blobbis can evolve');
|
||||
}
|
||||
|
||||
// ─── Ensure Canonical Before Action ───
|
||||
const canonical = await ensureCanonicalBeforeAction();
|
||||
if (!canonical) {
|
||||
throw new Error('Failed to prepare companion for evolution');
|
||||
}
|
||||
|
||||
// ─── Apply Accumulated Decay First ───
|
||||
// Per decay-system.md: Always apply accumulated decay from persisted state
|
||||
// before any stage transition.
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const decayResult = applyBlobbiDecay({
|
||||
stage: canonical.companion.stage,
|
||||
state: canonical.companion.state,
|
||||
stats: canonical.companion.stats,
|
||||
lastDecayAt: canonical.companion.lastDecayAt,
|
||||
now,
|
||||
});
|
||||
|
||||
// ─── Adult Stats ───
|
||||
// Adult inherits all decayed stats from baby
|
||||
// No stat reset - evolution preserves current condition
|
||||
const adultStats = decayResult.stats;
|
||||
|
||||
// ─── Build Updated Tags ───
|
||||
// CRITICAL: Start from canonical.allTags and only remove task/state-specific tags
|
||||
// This preserves ALL identity attributes (personality, trait, favorite_food, etc.)
|
||||
const nowStr = now.toString();
|
||||
|
||||
// Get streak updates (evolving counts as care activity!)
|
||||
const streakUpdates = getStreakTagUpdates(canonical.companion) ?? {};
|
||||
|
||||
// Build the updated tags using the central merge function
|
||||
const mergedTags = updateBlobbiTags(canonical.allTags, {
|
||||
stage: 'adult',
|
||||
state: 'active', // Evolution completes with active state
|
||||
hunger: adultStats.hunger.toString(),
|
||||
happiness: adultStats.happiness.toString(),
|
||||
health: adultStats.health.toString(),
|
||||
hygiene: adultStats.hygiene.toString(),
|
||||
energy: adultStats.energy.toString(),
|
||||
...streakUpdates,
|
||||
last_interaction: nowStr,
|
||||
last_decay_at: nowStr,
|
||||
});
|
||||
|
||||
// ─── Validate and Repair Tags ───
|
||||
// Use the tag integrity guard to ensure all persistent tags are preserved
|
||||
// and task-related tags are properly cleaned up for stage transitions
|
||||
const repairResult = validateAndRepairBlobbiTags(
|
||||
mergedTags,
|
||||
canonical.allTags,
|
||||
{ cleanupTaskTags: true }
|
||||
);
|
||||
|
||||
if (repairResult.errors.length > 0) {
|
||||
console.error('[Evolve] Tag validation errors:', repairResult.errors);
|
||||
throw new Error(`Tag validation failed: ${repairResult.errors.join(', ')}`);
|
||||
}
|
||||
|
||||
if (repairResult.repaired && import.meta.env.DEV) {
|
||||
console.log('[Evolve] Tag repairs applied:', repairResult.repairs);
|
||||
}
|
||||
|
||||
const newTags = repairResult.tags;
|
||||
|
||||
// ─── Generate New Content for Adult Stage ───
|
||||
// CRITICAL: Content must reflect the new stage
|
||||
const newContent = generateBlobbiContent(canonical.companion.name, 'adult');
|
||||
|
||||
// ─── Publish Event ───
|
||||
const event = await publishEvent({
|
||||
kind: KIND_BLOBBI_STATE,
|
||||
content: newContent,
|
||||
tags: newTags,
|
||||
});
|
||||
|
||||
updateCompanionEvent(event);
|
||||
|
||||
return {
|
||||
previousStage: 'baby',
|
||||
newStage: 'adult',
|
||||
name: canonical.companion.name,
|
||||
decayedStats: decayResult.stats,
|
||||
};
|
||||
},
|
||||
onSuccess: ({ name }) => {
|
||||
toast({
|
||||
title: 'Evolution complete!',
|
||||
description: `${name} has evolved into an adult Blobbi!`,
|
||||
});
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast({
|
||||
title: 'Failed to evolve',
|
||||
description: error.message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
// src/blobbi/actions/hooks/useBlobbiUseInventoryItem.ts
|
||||
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { toast } from '@/hooks/useToast';
|
||||
|
||||
import type { BlobbiCompanion, BlobbonautProfile } from '@/blobbi/core/lib/blobbi';
|
||||
import {
|
||||
KIND_BLOBBI_STATE,
|
||||
updateBlobbiTags,
|
||||
} from '@/blobbi/core/lib/blobbi';
|
||||
import { applyBlobbiDecay } from '@/blobbi/core/lib/blobbi-decay';
|
||||
import { getShopItemById } from '@/blobbi/shop/lib/blobbi-shop-items';
|
||||
import {
|
||||
applyItemEffects,
|
||||
canUseAction,
|
||||
getStageRestrictionMessage,
|
||||
clampStat,
|
||||
applyStat,
|
||||
hasMedicineEffectForEgg,
|
||||
hasHygieneEffectForEgg,
|
||||
incrementInteractionTaskTags,
|
||||
type InventoryAction,
|
||||
ACTION_METADATA,
|
||||
} from '../lib/blobbi-action-utils';
|
||||
import { trackMultipleDailyMissionActions } from '../lib/daily-mission-tracker';
|
||||
import type { DailyMissionAction } from '../lib/daily-missions';
|
||||
import { getStreakTagUpdates } from '../lib/blobbi-streak';
|
||||
import { calculateInventoryActionXP, applyXPGain, formatXPGain } from '../lib/blobbi-xp';
|
||||
import { HATCH_REQUIRED_INTERACTIONS } from './useHatchTasks';
|
||||
import { EVOLVE_REQUIRED_INTERACTIONS } from './useEvolveTasks';
|
||||
|
||||
/**
|
||||
* Request payload for using an item on a Blobbi companion
|
||||
*/
|
||||
export interface UseItemRequest {
|
||||
itemId: string;
|
||||
action: InventoryAction;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of using an item on a Blobbi companion
|
||||
*/
|
||||
export interface UseItemResult {
|
||||
itemName: string;
|
||||
action: InventoryAction;
|
||||
statsChanged: Record<string, number>;
|
||||
xpGained: number;
|
||||
newXP: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parameters for the useBlobbiUseInventoryItem hook
|
||||
*/
|
||||
export interface UseBlobbiUseInventoryItemParams {
|
||||
companion: BlobbiCompanion | null;
|
||||
profile: BlobbonautProfile | null;
|
||||
/** Called after ensuring companion is canonical (from migration helper) */
|
||||
ensureCanonicalBeforeAction: () => Promise<{
|
||||
companion: BlobbiCompanion;
|
||||
content: string;
|
||||
allTags: string[][];
|
||||
wasMigrated: boolean;
|
||||
/** Latest profile tags after migration */
|
||||
profileAllTags: string[][];
|
||||
/** Latest profile storage after migration */
|
||||
profileStorage: import('@/blobbi/core/lib/blobbi').StorageItem[];
|
||||
} | null>;
|
||||
/** Update companion event in local cache */
|
||||
updateCompanionEvent: (event: NostrEvent) => void;
|
||||
/** Update profile event in local cache */
|
||||
updateProfileEvent: (event: NostrEvent) => void;
|
||||
}
|
||||
|
||||
// Import NostrEvent type
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
/**
|
||||
* Hook to use an item on a Blobbi companion.
|
||||
*
|
||||
* Items are reusable abilities sourced from the shop catalog — no
|
||||
* inventory ownership or quantity is required.
|
||||
*
|
||||
* This hook:
|
||||
* 1. Validates the companion and item compatibility
|
||||
* 2. Ensures canonical format before action
|
||||
* 3. Applies accumulated decay, then item effects to Blobbi stats
|
||||
* 4. Updates Blobbi state (kind 31124)
|
||||
*/
|
||||
export function useBlobbiUseInventoryItem({
|
||||
companion,
|
||||
profile,
|
||||
ensureCanonicalBeforeAction,
|
||||
updateCompanionEvent,
|
||||
updateProfileEvent: _updateProfileEvent,
|
||||
}: UseBlobbiUseInventoryItemParams) {
|
||||
const { user } = useCurrentUser();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ itemId, action }: UseItemRequest): Promise<UseItemResult> => {
|
||||
// ─── Validation ───
|
||||
if (!user?.pubkey) {
|
||||
throw new Error('You must be logged in to use items');
|
||||
}
|
||||
|
||||
if (!companion) {
|
||||
throw new Error('No companion selected');
|
||||
}
|
||||
|
||||
if (!profile) {
|
||||
throw new Error('Profile not found');
|
||||
}
|
||||
|
||||
// Check stage restrictions for this specific action
|
||||
if (!canUseAction(companion, action)) {
|
||||
const message = getStageRestrictionMessage(companion, action);
|
||||
throw new Error(message ?? 'This companion cannot use this item');
|
||||
}
|
||||
|
||||
// Validate item exists in shop catalog
|
||||
const shopItem = getShopItemById(itemId);
|
||||
if (!shopItem) {
|
||||
throw new Error('Item not found in catalog');
|
||||
}
|
||||
|
||||
// Validate item has effects
|
||||
if (!shopItem.effect) {
|
||||
throw new Error('This item has no effect');
|
||||
}
|
||||
|
||||
// For eggs, validate that items have applicable effects
|
||||
const isEgg = companion.stage === 'egg';
|
||||
if (isEgg && action === 'medicine' && !hasMedicineEffectForEgg(shopItem.effect)) {
|
||||
throw new Error('This medicine has no effect on eggs');
|
||||
}
|
||||
if (isEgg && action === 'clean' && !hasHygieneEffectForEgg(shopItem.effect)) {
|
||||
throw new Error('This item has no cleaning effect on eggs');
|
||||
}
|
||||
|
||||
// ─── Ensure Canonical Before Action ───
|
||||
const canonical = await ensureCanonicalBeforeAction();
|
||||
if (!canonical) {
|
||||
throw new Error('Failed to prepare companion for action');
|
||||
}
|
||||
|
||||
// ─── Apply Accumulated Decay First ───
|
||||
// Per decay-system.md: Always apply accumulated decay from persisted state
|
||||
// before any user interaction updates stats.
|
||||
// CRITICAL: Use canonical.companion for decay calculations, not the stale outer companion
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const decayResult = applyBlobbiDecay({
|
||||
stage: canonical.companion.stage,
|
||||
state: canonical.companion.state,
|
||||
stats: canonical.companion.stats,
|
||||
lastDecayAt: canonical.companion.lastDecayAt,
|
||||
now,
|
||||
});
|
||||
|
||||
// Start with decayed stats as the base
|
||||
const statsAfterDecay = decayResult.stats;
|
||||
|
||||
// ─── Validate Play Energy Requirements ───
|
||||
// For play actions, validate the Blobbi has enough energy AFTER decay
|
||||
if (action === 'play') {
|
||||
const energyCost = Math.abs(shopItem.effect.energy ?? 0);
|
||||
const currentEnergy = statsAfterDecay.energy;
|
||||
|
||||
if (energyCost > 0 && currentEnergy < energyCost) {
|
||||
throw new Error(
|
||||
`Your Blobbi needs at least ${energyCost} energy to play with this toy (current: ${currentEnergy})`
|
||||
);
|
||||
}
|
||||
|
||||
// Also check if playing would have any effect at all
|
||||
// If happiness is maxed AND we can't spend energy, playing is pointless
|
||||
const happinessGain = shopItem.effect.happiness ?? 0;
|
||||
const currentHappiness = statsAfterDecay.happiness;
|
||||
const wouldGainHappiness = happinessGain > 0 && currentHappiness < 100;
|
||||
const wouldSpendEnergy = energyCost > 0 && currentEnergy >= energyCost;
|
||||
|
||||
if (!wouldGainHappiness && !wouldSpendEnergy) {
|
||||
throw new Error(
|
||||
'Playing would have no effect - your Blobbi is already at maximum happiness and has no energy to spend'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Apply Item Effects (single use) ───
|
||||
const isEggCompanion = canonical.companion.stage === 'egg';
|
||||
const statsUpdate: Record<string, string> = {};
|
||||
const statsChanged: Record<string, number> = {};
|
||||
|
||||
if (isEggCompanion && action === 'medicine') {
|
||||
const healthDelta = shopItem.effect.health ?? 0;
|
||||
const currentHealth = applyStat(statsAfterDecay.health ?? 0, healthDelta);
|
||||
|
||||
statsUpdate.health = currentHealth.toString();
|
||||
statsChanged.health = currentHealth - (statsAfterDecay.health ?? 0);
|
||||
|
||||
statsUpdate.hygiene = (statsAfterDecay.hygiene ?? 0).toString();
|
||||
statsUpdate.happiness = (statsAfterDecay.happiness ?? 0).toString();
|
||||
statsUpdate.hunger = '100';
|
||||
statsUpdate.energy = '100';
|
||||
} else if (isEggCompanion && action === 'clean') {
|
||||
const currentHygiene = applyStat(statsAfterDecay.hygiene ?? 0, shopItem.effect.hygiene ?? 0);
|
||||
const currentHappiness = applyStat(statsAfterDecay.happiness ?? 0, shopItem.effect.happiness ?? 0);
|
||||
|
||||
statsUpdate.hygiene = currentHygiene.toString();
|
||||
statsChanged.hygiene = currentHygiene - (statsAfterDecay.hygiene ?? 0);
|
||||
|
||||
statsUpdate.happiness = currentHappiness.toString();
|
||||
const totalHappinessChange = currentHappiness - (statsAfterDecay.happiness ?? 0);
|
||||
if (totalHappinessChange !== 0) {
|
||||
statsChanged.happiness = totalHappinessChange;
|
||||
}
|
||||
|
||||
statsUpdate.health = (statsAfterDecay.health ?? 0).toString();
|
||||
statsUpdate.hunger = '100';
|
||||
statsUpdate.energy = '100';
|
||||
} else {
|
||||
// Normal stats application for baby/adult — apply once
|
||||
const currentStats = applyItemEffects({ ...statsAfterDecay }, shopItem.effect);
|
||||
|
||||
statsUpdate.hunger = clampStat(currentStats.hunger).toString();
|
||||
statsChanged.hunger = (currentStats.hunger ?? 0) - (statsAfterDecay.hunger ?? 0);
|
||||
|
||||
statsUpdate.happiness = clampStat(currentStats.happiness).toString();
|
||||
statsChanged.happiness = (currentStats.happiness ?? 0) - (statsAfterDecay.happiness ?? 0);
|
||||
|
||||
statsUpdate.energy = clampStat(currentStats.energy).toString();
|
||||
statsChanged.energy = (currentStats.energy ?? 0) - (statsAfterDecay.energy ?? 0);
|
||||
|
||||
statsUpdate.hygiene = clampStat(currentStats.hygiene).toString();
|
||||
statsChanged.hygiene = (currentStats.hygiene ?? 0) - (statsAfterDecay.hygiene ?? 0);
|
||||
|
||||
statsUpdate.health = clampStat(currentStats.health).toString();
|
||||
statsChanged.health = (currentStats.health ?? 0) - (statsAfterDecay.health ?? 0);
|
||||
}
|
||||
|
||||
// ─── Update Blobbi State Event (kind 31124) ───
|
||||
const nowStr = now.toString();
|
||||
|
||||
// If incubating or evolving, increment the interaction counter for tasks
|
||||
const companionState = canonical.companion.state;
|
||||
let updatedTags = canonical.allTags;
|
||||
if (companionState === 'incubating') {
|
||||
updatedTags = incrementInteractionTaskTags(canonical.allTags, HATCH_REQUIRED_INTERACTIONS).updatedTags;
|
||||
} else if (companionState === 'evolving') {
|
||||
updatedTags = incrementInteractionTaskTags(canonical.allTags, EVOLVE_REQUIRED_INTERACTIONS).updatedTags;
|
||||
}
|
||||
|
||||
// Get streak updates (will only update if needed based on day)
|
||||
const streakUpdates = getStreakTagUpdates(canonical.companion) ?? {};
|
||||
|
||||
// ─── Apply XP Gain ───
|
||||
const xpGained = calculateInventoryActionXP(action, 1);
|
||||
const currentXP = canonical.companion.experience ?? 0;
|
||||
const newXP = applyXPGain(currentXP, xpGained);
|
||||
|
||||
const blobbiTags = updateBlobbiTags(updatedTags, {
|
||||
...statsUpdate,
|
||||
...streakUpdates,
|
||||
experience: newXP.toString(),
|
||||
last_interaction: nowStr,
|
||||
last_decay_at: nowStr,
|
||||
});
|
||||
|
||||
const blobbiEvent = await publishEvent({
|
||||
kind: KIND_BLOBBI_STATE,
|
||||
content: canonical.content,
|
||||
tags: blobbiTags,
|
||||
});
|
||||
|
||||
updateCompanionEvent(blobbiEvent);
|
||||
|
||||
// Items are free to use — no storage decrement needed.
|
||||
// No query invalidation needed — the optimistic update above keeps the
|
||||
// cache correct, and ensureCanonicalBeforeAction fetches fresh from relays
|
||||
// before every mutation (read-modify-write pattern).
|
||||
|
||||
return {
|
||||
itemName: shopItem.name,
|
||||
action,
|
||||
statsChanged,
|
||||
xpGained,
|
||||
newXP,
|
||||
};
|
||||
},
|
||||
onSuccess: ({ itemName, action, xpGained }) => {
|
||||
const actionMeta = ACTION_METADATA[action];
|
||||
const xpText = formatXPGain(xpGained);
|
||||
toast({
|
||||
title: `${actionMeta.label} successful!`,
|
||||
description: `Used ${itemName} on your Blobbi. ${xpText}`,
|
||||
});
|
||||
|
||||
// Track daily mission progress
|
||||
// 'interact' is always tracked, plus the specific action if it maps to a daily mission
|
||||
const dailyActions: DailyMissionAction[] = ['interact'];
|
||||
if (action === 'feed') dailyActions.push('feed');
|
||||
if (action === 'clean') dailyActions.push('clean');
|
||||
trackMultipleDailyMissionActions(dailyActions, user?.pubkey);
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast({
|
||||
title: 'Failed to use item',
|
||||
description: error.message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* useAwardDailyXp - Award XP for completed daily missions
|
||||
*
|
||||
* Completion is implicit (derived from progress vs target).
|
||||
* This hook calculates the total XP earned today and persists
|
||||
* the updated XP total to kind 11125 tags.
|
||||
*
|
||||
* Uses fetchFreshEvent to avoid stale-read overwrites when
|
||||
* multiple mutations race (e.g. item use XP + daily XP).
|
||||
*/
|
||||
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { toast } from '@/hooks/useToast';
|
||||
import { fetchFreshEvent } from '@/lib/fetchFreshEvent';
|
||||
|
||||
import {
|
||||
KIND_BLOBBONAUT_PROFILE,
|
||||
updateBlobbonautTags,
|
||||
parseBlobbonautEvent,
|
||||
} from '@/blobbi/core/lib/blobbi';
|
||||
import { buildXpTagUpdates } from '@/blobbi/core/lib/progression';
|
||||
import { serializeProfileContent } from '@/blobbi/core/lib/missions';
|
||||
import type { MissionsContent } from '@/blobbi/core/lib/missions';
|
||||
import { totalDailyXp } from '../lib/daily-missions';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface AwardDailyXpRequest {
|
||||
/** Current missions state to calculate XP from */
|
||||
missions: MissionsContent;
|
||||
}
|
||||
|
||||
export interface AwardDailyXpResult {
|
||||
xpAwarded: number;
|
||||
newTotalXp: number;
|
||||
}
|
||||
|
||||
// ─── Hook ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Hook to award XP for completed daily missions.
|
||||
*
|
||||
* @param updateProfileEvent - Callback to update profile in query cache
|
||||
*/
|
||||
export function useAwardDailyXp(
|
||||
updateProfileEvent: (event: import('@nostrify/nostrify').NostrEvent) => void,
|
||||
) {
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ missions }: AwardDailyXpRequest): Promise<AwardDailyXpResult> => {
|
||||
if (!user?.pubkey) throw new Error('Must be logged in');
|
||||
|
||||
const xpToAward = totalDailyXp(missions);
|
||||
if (xpToAward <= 0) return { xpAwarded: 0, newTotalXp: 0 };
|
||||
|
||||
// Fetch fresh profile from relays to avoid stale-read overwrites
|
||||
const prev = await fetchFreshEvent(nostr, {
|
||||
kinds: [KIND_BLOBBONAUT_PROFILE],
|
||||
authors: [user.pubkey],
|
||||
});
|
||||
|
||||
const freshProfile = prev ? parseBlobbonautEvent(prev) : undefined;
|
||||
const currentXp = freshProfile?.xp ?? 0;
|
||||
const newTotalXp = currentXp + xpToAward;
|
||||
|
||||
// Update XP and level tags on the fresh event's tags
|
||||
const updatedTags = updateBlobbonautTags(
|
||||
prev?.tags ?? [],
|
||||
buildXpTagUpdates(newTotalXp),
|
||||
);
|
||||
|
||||
// Persist missions state to content field
|
||||
const content = serializeProfileContent(
|
||||
prev?.content ?? '',
|
||||
{ missions },
|
||||
);
|
||||
|
||||
const event = await publishEvent({
|
||||
kind: KIND_BLOBBONAUT_PROFILE,
|
||||
content,
|
||||
tags: updatedTags,
|
||||
prev: prev ?? undefined,
|
||||
});
|
||||
|
||||
updateProfileEvent(event);
|
||||
|
||||
return { xpAwarded: xpToAward, newTotalXp };
|
||||
},
|
||||
onSuccess: ({ xpAwarded }) => {
|
||||
if (user?.pubkey) {
|
||||
queryClient.invalidateQueries({ queryKey: ['blobbonaut-profile', user.pubkey] });
|
||||
}
|
||||
if (xpAwarded > 0) {
|
||||
toast({
|
||||
title: 'XP Earned!',
|
||||
description: `You earned ${xpAwarded} XP from daily missions.`,
|
||||
});
|
||||
}
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast({
|
||||
title: 'Failed to Award XP',
|
||||
description: error.message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Legacy export name for backward compatibility during migration
|
||||
export const useClaimMissionReward = useAwardDailyXp;
|
||||
export type ClaimMissionRequest = AwardDailyXpRequest;
|
||||
export type ClaimMissionResult = AwardDailyXpResult;
|
||||
@@ -0,0 +1,209 @@
|
||||
/**
|
||||
* useDailyMissions - Hook for reading daily mission state
|
||||
*
|
||||
* Provides reactive access to the current day's missions.
|
||||
* Progress tracking is done via the tracker module (non-React).
|
||||
* Completion is implicit (derived from count/events vs target).
|
||||
* XP is awarded automatically when missions complete.
|
||||
*
|
||||
* State lives in a pubkey-scoped in-memory Map. On mount or account
|
||||
* switch, hydrates from kind 11125 content JSON if the session store
|
||||
* is empty. Completed missions are persisted by `useAwardDailyXp`;
|
||||
* intermediate progress resets on page refresh.
|
||||
*/
|
||||
|
||||
import { useMemo, useEffect, useState, useCallback, useRef } from 'react';
|
||||
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
|
||||
import type { MissionsContent } from '@/blobbi/core/lib/missions';
|
||||
import { isMissionComplete, missionProgress } from '@/blobbi/core/lib/missions';
|
||||
import { parseProfileContent } from '@/blobbi/core/lib/missions';
|
||||
|
||||
import {
|
||||
type BlobbiStage,
|
||||
type DailyMissionAction,
|
||||
getTodayDateString,
|
||||
needsDailyReset,
|
||||
createDailyMissionsContent,
|
||||
areAllDailyComplete,
|
||||
totalDailyXp,
|
||||
getDefinition,
|
||||
MAX_DAILY_REROLLS,
|
||||
DAILY_BONUS_XP,
|
||||
} from '../lib/daily-missions';
|
||||
|
||||
import {
|
||||
readMissionsFromStorage,
|
||||
writeMissionsToStorage,
|
||||
hydrateFromPersisted,
|
||||
} from '../lib/daily-mission-tracker';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface DailyMissionView {
|
||||
/** Mission ID (matches pool definition) */
|
||||
id: string;
|
||||
/** Display title */
|
||||
title: string;
|
||||
/** Description */
|
||||
description: string;
|
||||
/** Action type */
|
||||
action: DailyMissionAction;
|
||||
/** Required count */
|
||||
target: number;
|
||||
/** Current progress */
|
||||
progress: number;
|
||||
/** Whether mission is complete */
|
||||
complete: boolean;
|
||||
/** XP reward */
|
||||
xp: number;
|
||||
}
|
||||
|
||||
export interface UseDailyMissionsOptions {
|
||||
/** Available Blobbi stages the user has (filters eligible missions) */
|
||||
availableStages?: BlobbiStage[];
|
||||
/**
|
||||
* Raw content string from the kind 11125 profile event.
|
||||
* Pass `profile.content` here. The hook parses it to extract
|
||||
* persisted missions and hydrates the session store on first load.
|
||||
*/
|
||||
profileContent?: string;
|
||||
}
|
||||
|
||||
export interface UseDailyMissionsResult {
|
||||
/** Today's daily missions with computed progress */
|
||||
missions: DailyMissionView[];
|
||||
/** The raw missions content (for persistence/mutation hooks) */
|
||||
raw: MissionsContent | undefined;
|
||||
/** Whether all daily missions are complete */
|
||||
allComplete: boolean;
|
||||
/** Total XP earned today (completed missions + bonus) */
|
||||
todayXp: number;
|
||||
/** Whether the daily bonus is unlocked (all missions complete) */
|
||||
bonusUnlocked: boolean;
|
||||
/** Bonus XP amount */
|
||||
bonusXp: number;
|
||||
/** Whether user has no eligible missions */
|
||||
noMissionsAvailable: boolean;
|
||||
/** Rerolls remaining today */
|
||||
rerollsRemaining: number;
|
||||
/** Max rerolls per day */
|
||||
maxRerolls: number;
|
||||
/** Force refresh missions (testing) */
|
||||
forceReset: () => void;
|
||||
}
|
||||
|
||||
// ─── Hook ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useDailyMissions(options: UseDailyMissionsOptions = {}): UseDailyMissionsResult {
|
||||
const { availableStages, profileContent } = options;
|
||||
const { user } = useCurrentUser();
|
||||
const pubkey = user?.pubkey;
|
||||
|
||||
// Version counter to trigger re-reads from session store
|
||||
const [version, setVersion] = useState(0);
|
||||
|
||||
// Track whether we've hydrated for this pubkey
|
||||
const hydratedRef = useRef<string | null>(null);
|
||||
|
||||
// Hydrate session store from kind 11125 content on mount / account switch
|
||||
useEffect(() => {
|
||||
if (!pubkey || !profileContent) return;
|
||||
if (hydratedRef.current === pubkey) return; // already hydrated this session
|
||||
|
||||
// Check if session store already has data for this pubkey
|
||||
const existing = readMissionsFromStorage(pubkey);
|
||||
if (existing) {
|
||||
hydratedRef.current = pubkey;
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse persisted missions from profile content
|
||||
const parsed = parseProfileContent(profileContent);
|
||||
if (parsed.missions && !needsDailyReset(parsed.missions)) {
|
||||
hydrateFromPersisted(parsed.missions, pubkey);
|
||||
hydratedRef.current = pubkey;
|
||||
setVersion((v) => v + 1);
|
||||
} else {
|
||||
hydratedRef.current = pubkey;
|
||||
}
|
||||
}, [pubkey, profileContent]);
|
||||
|
||||
// Listen for tracker events
|
||||
useEffect(() => {
|
||||
const handler = () => setVersion((v) => v + 1);
|
||||
window.addEventListener('daily-missions-updated', handler);
|
||||
return () => window.removeEventListener('daily-missions-updated', handler);
|
||||
}, []);
|
||||
|
||||
// Stable stages key for deps
|
||||
const stagesKey = availableStages?.sort().join(',') ?? '';
|
||||
|
||||
// Read and ensure current state
|
||||
const raw = useMemo((): MissionsContent | undefined => {
|
||||
const stored = readMissionsFromStorage(pubkey);
|
||||
|
||||
if (!needsDailyReset(stored)) return stored;
|
||||
|
||||
// Reset for new day, preserve evolution missions
|
||||
const fresh = createDailyMissionsContent(
|
||||
getTodayDateString(),
|
||||
stored?.evolution ?? [],
|
||||
pubkey,
|
||||
availableStages,
|
||||
);
|
||||
writeMissionsToStorage(fresh, pubkey);
|
||||
return fresh;
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [version, pubkey, stagesKey]);
|
||||
|
||||
// Build view models
|
||||
const missions: DailyMissionView[] = useMemo(() => {
|
||||
if (!raw?.daily) return [];
|
||||
return raw.daily.map((m) => {
|
||||
const def = getDefinition(m.id);
|
||||
return {
|
||||
id: m.id,
|
||||
title: def?.title ?? m.id,
|
||||
description: def?.description ?? '',
|
||||
action: def?.action ?? 'interact',
|
||||
target: m.target,
|
||||
progress: missionProgress(m),
|
||||
complete: isMissionComplete(m),
|
||||
xp: def?.xp ?? 0,
|
||||
};
|
||||
});
|
||||
}, [raw]);
|
||||
|
||||
const allComplete = raw ? areAllDailyComplete(raw) : false;
|
||||
const todayXp = raw ? totalDailyXp(raw) : 0;
|
||||
const bonusUnlocked = allComplete;
|
||||
const noMissionsAvailable = missions.length === 0;
|
||||
const rerollsRemaining = raw?.rerolls ?? MAX_DAILY_REROLLS;
|
||||
|
||||
const forceReset = useCallback(() => {
|
||||
const fresh = createDailyMissionsContent(
|
||||
getTodayDateString(),
|
||||
raw?.evolution ?? [],
|
||||
pubkey,
|
||||
availableStages,
|
||||
);
|
||||
writeMissionsToStorage(fresh, pubkey);
|
||||
setVersion((v) => v + 1);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [pubkey, stagesKey, raw?.evolution]);
|
||||
|
||||
return {
|
||||
missions,
|
||||
raw,
|
||||
allComplete,
|
||||
todayXp,
|
||||
bonusUnlocked,
|
||||
bonusXp: DAILY_BONUS_XP,
|
||||
noMissionsAvailable,
|
||||
rerollsRemaining,
|
||||
maxRerolls: MAX_DAILY_REROLLS,
|
||||
forceReset,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
// src/blobbi/actions/hooks/useEvolveTasks.ts
|
||||
|
||||
/**
|
||||
* Hook to compute evolve task progress from Nostr events and current stats.
|
||||
*
|
||||
* CRITICAL ARCHITECTURE:
|
||||
* - PERSISTENT TASKS: Based on Nostr events, can be cached in tags
|
||||
* - DYNAMIC TASKS: Based on current stats, NEVER stored in tags
|
||||
*
|
||||
* Tags are only cache for persistent tasks. Source of truth = Nostr events.
|
||||
*/
|
||||
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import type { NostrEvent, NostrFilter } from '@nostrify/nostrify';
|
||||
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import type { BlobbiCompanion } from '@/blobbi/core/lib/blobbi';
|
||||
|
||||
import {
|
||||
KIND_THEME_DEFINITION,
|
||||
KIND_COLOR_MOMENT,
|
||||
KIND_PROFILE_METADATA,
|
||||
KIND_SHORT_TEXT_NOTE,
|
||||
BLOBBI_POST_REQUIRED_HASHTAGS,
|
||||
sanitizeToHashtag,
|
||||
type HatchTask,
|
||||
type TaskType,
|
||||
} from './useHatchTasks';
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Kind for custom profile tabs event */
|
||||
export const KIND_PROFILE_TABS = 16769;
|
||||
|
||||
/** Required themes for evolve task */
|
||||
export const EVOLVE_REQUIRED_THEMES = 3;
|
||||
|
||||
/** Required color moments for evolve task */
|
||||
export const EVOLVE_REQUIRED_COLOR_MOMENTS = 3;
|
||||
|
||||
/** Required posts for evolve task (lighter than hatch - just 1 evolve-specific post) */
|
||||
export const EVOLVE_REQUIRED_POSTS = 1;
|
||||
|
||||
/** Required interactions for evolve task */
|
||||
export const EVOLVE_REQUIRED_INTERACTIONS = 21;
|
||||
|
||||
/** Prefix text for Blobbi evolve post */
|
||||
export const BLOBBI_EVOLVE_POST_PREFIX = 'Hello Nostr! Posting to evolve';
|
||||
|
||||
/** Stat threshold for evolve dynamic task (all stats >= 80) */
|
||||
export const EVOLVE_STAT_THRESHOLD = 80;
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
// Re-export task types for convenience
|
||||
export type { HatchTask as EvolveTask, TaskType };
|
||||
|
||||
/**
|
||||
* Result of computing evolve tasks.
|
||||
*/
|
||||
export interface EvolveTasksResult {
|
||||
tasks: HatchTask[];
|
||||
/** All persistent tasks are complete */
|
||||
persistentTasksComplete: boolean;
|
||||
/** Dynamic stat task is complete */
|
||||
dynamicTaskComplete: boolean;
|
||||
/** All tasks (persistent + dynamic) are complete - required to evolve */
|
||||
allCompleted: boolean;
|
||||
isLoading: boolean;
|
||||
error: Error | null;
|
||||
/** Refetch task progress */
|
||||
refetch: () => void;
|
||||
}
|
||||
|
||||
// ─── Helper Functions ─────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Check if a post is a valid Blobbi evolve post.
|
||||
* Must contain the evolve prefix and all required hashtags including the Blobbi name.
|
||||
*
|
||||
* @param event - The Nostr event to validate
|
||||
* @param blobbiName - The Blobbi's name (will be sanitized and checked as hashtag)
|
||||
*/
|
||||
export function isValidEvolvePost(event: NostrEvent, blobbiName: string): boolean {
|
||||
// Check content starts with evolve prefix
|
||||
if (!event.content.startsWith(BLOBBI_EVOLVE_POST_PREFIX)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check for required hashtags in tags
|
||||
const hashtags = event.tags
|
||||
.filter(tag => tag[0] === 't')
|
||||
.map(tag => tag[1]?.toLowerCase());
|
||||
|
||||
// All required hashtags must be present
|
||||
const hasRequiredHashtags = BLOBBI_POST_REQUIRED_HASHTAGS.every(required =>
|
||||
hashtags.includes(required.toLowerCase())
|
||||
);
|
||||
|
||||
if (!hasRequiredHashtags) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Blobbi name hashtag must also be present
|
||||
const blobbiHashtag = sanitizeToHashtag(blobbiName);
|
||||
return hashtags.includes(blobbiHashtag);
|
||||
}
|
||||
|
||||
// ─── Main Hook ────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Hook to compute evolve task progress from Nostr events and current stats.
|
||||
*
|
||||
* PERSISTENT TASKS (event-based, can be cached):
|
||||
* 1. Create 3 Themes (kind 36767)
|
||||
* 2. Create 3 Color Moments (kind 3367)
|
||||
* 3. Create 1 Evolve Post (kind 1) - lighter than hatch, evolve-specific
|
||||
* 4. Interact 21 times (tracked via companion.tasks cache)
|
||||
* 5. Edit Profile once (kind 0 profile metadata OR kind 16769 custom tabs)
|
||||
*
|
||||
* DYNAMIC TASK (stat-based, NEVER cached):
|
||||
* 6. Maintain All Stats >= 80
|
||||
*
|
||||
* @param companion - The Blobbi companion (must be in evolving state)
|
||||
* @param interactionCount - Current interaction count from companion tasks cache
|
||||
*/
|
||||
export function useEvolveTasks(
|
||||
companion: BlobbiCompanion | null,
|
||||
interactionCount?: number
|
||||
): EvolveTasksResult {
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
|
||||
const pubkey = user?.pubkey;
|
||||
const stateStartedAt = companion?.stateStartedAt;
|
||||
const isEvolving = companion?.state === 'evolving';
|
||||
|
||||
// Query for all relevant events
|
||||
const { data, isLoading, error, refetch } = useQuery({
|
||||
queryKey: ['evolve-tasks', pubkey, stateStartedAt],
|
||||
queryFn: async () => {
|
||||
if (!pubkey || !stateStartedAt) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Build filters for events we need
|
||||
const filters: NostrFilter[] = [
|
||||
// Theme definitions after start
|
||||
{
|
||||
kinds: [KIND_THEME_DEFINITION],
|
||||
authors: [pubkey],
|
||||
since: stateStartedAt,
|
||||
},
|
||||
// Color moments after start
|
||||
{
|
||||
kinds: [KIND_COLOR_MOMENT],
|
||||
authors: [pubkey],
|
||||
since: stateStartedAt,
|
||||
},
|
||||
// Posts after start (will filter for valid evolve posts)
|
||||
{
|
||||
kinds: [KIND_SHORT_TEXT_NOTE],
|
||||
authors: [pubkey],
|
||||
since: stateStartedAt,
|
||||
limit: 50, // Only need 1 valid evolve post
|
||||
},
|
||||
// Custom profile tabs after start
|
||||
{
|
||||
kinds: [KIND_PROFILE_TABS],
|
||||
authors: [pubkey],
|
||||
since: stateStartedAt,
|
||||
limit: 1, // Only need 1
|
||||
},
|
||||
// Profile metadata after start (for Blobbi shape check + profile edit mission)
|
||||
{
|
||||
kinds: [KIND_PROFILE_METADATA],
|
||||
authors: [pubkey],
|
||||
since: stateStartedAt,
|
||||
limit: 1,
|
||||
},
|
||||
];
|
||||
|
||||
// Execute all queries
|
||||
const events = await nostr.query(filters);
|
||||
|
||||
// Categorize events
|
||||
const themeEvents = events.filter(e =>
|
||||
e.kind === KIND_THEME_DEFINITION && e.created_at >= stateStartedAt
|
||||
);
|
||||
|
||||
const colorMomentEvents = events.filter(e =>
|
||||
e.kind === KIND_COLOR_MOMENT && e.created_at >= stateStartedAt
|
||||
);
|
||||
|
||||
const postEvents = events.filter(e =>
|
||||
e.kind === KIND_SHORT_TEXT_NOTE && e.created_at >= stateStartedAt
|
||||
);
|
||||
|
||||
const profileTabsEvents = events.filter(e =>
|
||||
e.kind === KIND_PROFILE_TABS && e.created_at >= stateStartedAt
|
||||
);
|
||||
|
||||
// Get latest profile after start
|
||||
const profileEvents = events.filter(e => e.kind === KIND_PROFILE_METADATA);
|
||||
const profileAfter = profileEvents
|
||||
.filter(e => e.created_at >= stateStartedAt)
|
||||
.sort((a, b) => b.created_at - a.created_at)[0];
|
||||
|
||||
return {
|
||||
themeEvents,
|
||||
colorMomentEvents,
|
||||
postEvents,
|
||||
profileTabsEvents,
|
||||
profileAfter,
|
||||
};
|
||||
},
|
||||
enabled: !!pubkey && !!stateStartedAt && isEvolving,
|
||||
staleTime: 30_000, // 30 seconds
|
||||
refetchInterval: 60_000, // Refetch every minute
|
||||
});
|
||||
|
||||
// ─── Compute PERSISTENT Tasks ───
|
||||
const tasks: HatchTask[] = [];
|
||||
|
||||
// 1. Create 3 Themes (PERSISTENT)
|
||||
const themeCount = data?.themeEvents?.length ?? 0;
|
||||
const themesCompleted = themeCount >= EVOLVE_REQUIRED_THEMES;
|
||||
tasks.push({
|
||||
id: 'create_themes',
|
||||
name: 'Create Themes',
|
||||
description: `Create ${EVOLVE_REQUIRED_THEMES} custom themes`,
|
||||
current: Math.min(themeCount, EVOLVE_REQUIRED_THEMES),
|
||||
required: EVOLVE_REQUIRED_THEMES,
|
||||
completed: themesCompleted,
|
||||
type: 'persistent',
|
||||
action: 'navigate',
|
||||
actionTarget: '/themes',
|
||||
actionLabel: 'Create Theme',
|
||||
});
|
||||
|
||||
// 2. Create 3 Color Moments (PERSISTENT)
|
||||
const colorMomentCount = data?.colorMomentEvents?.length ?? 0;
|
||||
const colorMomentsCompleted = colorMomentCount >= EVOLVE_REQUIRED_COLOR_MOMENTS;
|
||||
tasks.push({
|
||||
id: 'color_moments',
|
||||
name: 'Color Moments',
|
||||
description: `Share ${EVOLVE_REQUIRED_COLOR_MOMENTS} color moments on espy`,
|
||||
current: Math.min(colorMomentCount, EVOLVE_REQUIRED_COLOR_MOMENTS),
|
||||
required: EVOLVE_REQUIRED_COLOR_MOMENTS,
|
||||
completed: colorMomentsCompleted,
|
||||
type: 'persistent',
|
||||
action: 'external_link',
|
||||
actionTarget: 'https://espy.you/',
|
||||
actionLabel: 'Open espy',
|
||||
});
|
||||
|
||||
// 3. Create 1 Evolve Post (PERSISTENT) - lighter than hatch
|
||||
const blobbiName = companion?.name ?? '';
|
||||
const validPosts = data?.postEvents?.filter(e => isValidEvolvePost(e, blobbiName)) ?? [];
|
||||
const postCount = validPosts.length;
|
||||
const postsCompleted = postCount >= EVOLVE_REQUIRED_POSTS;
|
||||
tasks.push({
|
||||
id: 'create_posts',
|
||||
name: 'Share Evolution',
|
||||
description: 'Post about your Blobbi evolving',
|
||||
current: Math.min(postCount, EVOLVE_REQUIRED_POSTS),
|
||||
required: EVOLVE_REQUIRED_POSTS,
|
||||
completed: postsCompleted,
|
||||
type: 'persistent',
|
||||
action: 'open_modal',
|
||||
actionTarget: 'blobbi_post',
|
||||
actionLabel: 'Create Post',
|
||||
});
|
||||
|
||||
// 4. Interact 21 times (PERSISTENT)
|
||||
const interactions = interactionCount ?? 0;
|
||||
const interactionsCompleted = interactions >= EVOLVE_REQUIRED_INTERACTIONS;
|
||||
tasks.push({
|
||||
id: 'interactions',
|
||||
name: 'Interact with Blobbi',
|
||||
description: `Care for your Blobbi ${EVOLVE_REQUIRED_INTERACTIONS} times`,
|
||||
current: Math.min(interactions, EVOLVE_REQUIRED_INTERACTIONS),
|
||||
required: EVOLVE_REQUIRED_INTERACTIONS,
|
||||
completed: interactionsCompleted,
|
||||
type: 'persistent',
|
||||
// No action - just interact with Blobbi
|
||||
});
|
||||
|
||||
// 5. Edit Profile once (PERSISTENT) — kind 0 profile metadata OR kind 16769 custom tabs
|
||||
const hasTabsEdit = (data?.profileTabsEvents?.length ?? 0) >= 1;
|
||||
const hasMetadataEdit = !!data?.profileAfter;
|
||||
const hasProfileEdit = hasTabsEdit || hasMetadataEdit;
|
||||
tasks.push({
|
||||
id: 'edit_profile',
|
||||
name: 'Edit Your Profile',
|
||||
description: 'Update your profile info or customize your profile tabs',
|
||||
current: hasProfileEdit ? 1 : 0,
|
||||
required: 1,
|
||||
completed: hasProfileEdit,
|
||||
type: 'persistent',
|
||||
action: 'navigate',
|
||||
actionTarget: '/settings/profile',
|
||||
actionLabel: 'Edit Profile',
|
||||
});
|
||||
|
||||
// ─── Compute DYNAMIC Task (stat-based, NEVER cached) ───
|
||||
// 7. Maintain All Stats >= 80
|
||||
const stats = companion?.stats ?? {};
|
||||
const hunger = stats.hunger ?? 0;
|
||||
const happiness = stats.happiness ?? 0;
|
||||
const health = stats.health ?? 0;
|
||||
const hygiene = stats.hygiene ?? 0;
|
||||
const energy = stats.energy ?? 0;
|
||||
|
||||
const statsOk =
|
||||
hunger >= EVOLVE_STAT_THRESHOLD &&
|
||||
happiness >= EVOLVE_STAT_THRESHOLD &&
|
||||
health >= EVOLVE_STAT_THRESHOLD &&
|
||||
hygiene >= EVOLVE_STAT_THRESHOLD &&
|
||||
energy >= EVOLVE_STAT_THRESHOLD;
|
||||
|
||||
// Calculate minimum stat for progress display
|
||||
const minStat = Math.min(hunger, happiness, health, hygiene, energy);
|
||||
|
||||
tasks.push({
|
||||
id: 'maintain_stats',
|
||||
name: 'Peak Condition',
|
||||
description: `Keep all stats above ${EVOLVE_STAT_THRESHOLD}`,
|
||||
current: statsOk ? EVOLVE_STAT_THRESHOLD : minStat,
|
||||
required: EVOLVE_STAT_THRESHOLD,
|
||||
completed: statsOk,
|
||||
type: 'dynamic', // CRITICAL: Never persist this task
|
||||
// No action - just care for your Blobbi
|
||||
});
|
||||
|
||||
// ─── Compute Completion States ───
|
||||
const persistentTasks = tasks.filter(t => t.type === 'persistent');
|
||||
const dynamicTasks = tasks.filter(t => t.type === 'dynamic');
|
||||
|
||||
const persistentTasksComplete = persistentTasks.every(t => t.completed);
|
||||
const dynamicTaskComplete = dynamicTasks.every(t => t.completed);
|
||||
const allCompleted = persistentTasksComplete && dynamicTaskComplete;
|
||||
|
||||
return {
|
||||
tasks,
|
||||
persistentTasksComplete,
|
||||
dynamicTaskComplete,
|
||||
allCompleted,
|
||||
isLoading,
|
||||
error: error as Error | null,
|
||||
refetch,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current interaction count for evolve from companion task cache.
|
||||
*/
|
||||
export function getEvolveInteractionCount(companion: BlobbiCompanion | null): number {
|
||||
if (!companion) return 0;
|
||||
const interactionTask = companion.tasks.find(t => t.name === 'interactions');
|
||||
return interactionTask?.value ?? 0;
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
// src/blobbi/actions/hooks/useHatchTasks.ts
|
||||
|
||||
/**
|
||||
* Hook to compute hatch task progress from Nostr events.
|
||||
*
|
||||
* CRITICAL ARCHITECTURE:
|
||||
* - PERSISTENT TASKS: Based on Nostr events, can be cached in tags
|
||||
*
|
||||
* Tags are only cache for persistent tasks. Source of truth = Nostr events.
|
||||
* All persistent tasks are computed dynamically from events with created_at >= state_started_at.
|
||||
*
|
||||
* Note: Egg stats no longer decay, so there are no dynamic tasks for hatching.
|
||||
*/
|
||||
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import type { NostrEvent, NostrFilter } from '@nostrify/nostrify';
|
||||
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import type { BlobbiCompanion } from '@/blobbi/core/lib/blobbi';
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Kind for theme definition events */
|
||||
export const KIND_THEME_DEFINITION = 36767;
|
||||
/** Kind for color moment events (espy.you) */
|
||||
export const KIND_COLOR_MOMENT = 3367;
|
||||
/** Kind for profile metadata */
|
||||
export const KIND_PROFILE_METADATA = 0;
|
||||
/** Kind for short text notes */
|
||||
export const KIND_SHORT_TEXT_NOTE = 1;
|
||||
|
||||
/** Required interactions to complete the hatch interactions task */
|
||||
export const HATCH_REQUIRED_INTERACTIONS = 7;
|
||||
|
||||
/** Required hashtags for the Blobbi post (excludes Blobbi name, which is dynamic) */
|
||||
export const BLOBBI_POST_REQUIRED_HASHTAGS = ['blobbi'];
|
||||
|
||||
/** Prefix text for Blobbi hatch post (the Blobbi name is appended after this) */
|
||||
export const BLOBBI_POST_PREFIX = 'Posting to hatch';
|
||||
|
||||
// Legacy export for backwards compatibility
|
||||
export const REQUIRED_INTERACTIONS = HATCH_REQUIRED_INTERACTIONS;
|
||||
|
||||
/**
|
||||
* Sanitize a name into a valid hashtag format.
|
||||
* Must match the implementation in BlobbiPostModal.tsx.
|
||||
*/
|
||||
export function sanitizeToHashtag(name: string): string {
|
||||
return name
|
||||
.toLowerCase()
|
||||
// Remove emojis and special characters, keep letters, numbers, underscores
|
||||
.replace(/[^\p{L}\p{N}_]/gu, '')
|
||||
// Ensure it starts with a letter (prepend 'blobbi' if it starts with number)
|
||||
.replace(/^(\d)/, 'blobbi$1')
|
||||
// Limit length
|
||||
.slice(0, 30)
|
||||
// Fallback if empty
|
||||
|| 'myblobbi';
|
||||
}
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Task type classification.
|
||||
* - persistent: Based on Nostr events, can be cached in tags
|
||||
* - dynamic: Based on current stats, NEVER stored in tags
|
||||
*/
|
||||
export type TaskType = 'persistent' | 'dynamic';
|
||||
|
||||
/**
|
||||
* Individual task definition.
|
||||
*/
|
||||
export interface HatchTask {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
/** Current progress value */
|
||||
current: number;
|
||||
/** Required value for completion */
|
||||
required: number;
|
||||
/** Whether the task is complete */
|
||||
completed: boolean;
|
||||
/** Task type - persistent (event-based) or dynamic (stat-based) */
|
||||
type: TaskType;
|
||||
/** Action to perform (if applicable) */
|
||||
action?: 'navigate' | 'open_modal' | 'external_link';
|
||||
/** Target for the action */
|
||||
actionTarget?: string;
|
||||
/** Button label */
|
||||
actionLabel?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of computing hatch tasks.
|
||||
*/
|
||||
export interface HatchTasksResult {
|
||||
tasks: HatchTask[];
|
||||
/** All persistent tasks are complete */
|
||||
persistentTasksComplete: boolean;
|
||||
/** Dynamic stat task is complete */
|
||||
dynamicTaskComplete: boolean;
|
||||
/** All tasks (persistent + dynamic) are complete - required to hatch */
|
||||
allCompleted: boolean;
|
||||
isLoading: boolean;
|
||||
error: Error | null;
|
||||
/** Refetch task progress */
|
||||
refetch: () => void;
|
||||
}
|
||||
|
||||
// ─── Helper Functions ─────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Build the required phrase for a hatch post.
|
||||
* Format: "Posting to hatch {CapitalizedName} #blobbi"
|
||||
*/
|
||||
export function buildHatchPhrase(blobbiName: string): string {
|
||||
const capitalized = blobbiName.charAt(0).toUpperCase() + blobbiName.slice(1);
|
||||
return `${BLOBBI_POST_PREFIX} ${capitalized} #blobbi`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a post is a valid Blobbi hatch post.
|
||||
* The post must contain the required phrase: "Posting to hatch {Name} #blobbi"
|
||||
* The user may add extra text before or after it.
|
||||
*
|
||||
* @param event - The Nostr event to validate
|
||||
* @param blobbiName - The Blobbi's name
|
||||
*/
|
||||
export function isValidHatchPost(event: NostrEvent, blobbiName: string): boolean {
|
||||
const phrase = buildHatchPhrase(blobbiName);
|
||||
|
||||
// The phrase must appear somewhere in the content
|
||||
if (!event.content.includes(phrase)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check for required hashtags in tags
|
||||
const hashtags = event.tags
|
||||
.filter(tag => tag[0] === 't')
|
||||
.map(tag => tag[1]?.toLowerCase());
|
||||
|
||||
// All required hashtags must be present as t tags
|
||||
const hasRequiredHashtags = BLOBBI_POST_REQUIRED_HASHTAGS.every(required =>
|
||||
hashtags.includes(required.toLowerCase())
|
||||
);
|
||||
|
||||
return hasRequiredHashtags;
|
||||
}
|
||||
|
||||
// Legacy function name for backwards compatibility
|
||||
export const isValidBlobbiPost = isValidHatchPost;
|
||||
|
||||
// ─── Main Hook ────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Hook to compute hatch task progress from Nostr events and current stats.
|
||||
*
|
||||
* PERSISTENT TASKS (event-based, can be cached):
|
||||
* 1. Create Theme (kind 36767) - ≥1 event after start
|
||||
* 2. Color Moment (kind 3367) - ≥1 event after start
|
||||
* 3. Create Post (kind 1) - ≥1 valid Blobbi hatch post after start
|
||||
* 4. Interactions - 7 total (tracked via companion.tasks cache)
|
||||
*
|
||||
* Note: Egg stats no longer decay, so the "maintain stats" dynamic task
|
||||
* has been removed. The baby/adult evolve equivalent is still in useEvolveTasks.
|
||||
*
|
||||
* @param companion - The Blobbi companion (must be incubating)
|
||||
* @param interactionCount - Current interaction count from companion tasks cache
|
||||
*/
|
||||
export function useHatchTasks(
|
||||
companion: BlobbiCompanion | null,
|
||||
interactionCount?: number
|
||||
): HatchTasksResult {
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
|
||||
const pubkey = user?.pubkey;
|
||||
const stateStartedAt = companion?.stateStartedAt;
|
||||
const isIncubating = companion?.state === 'incubating';
|
||||
|
||||
// Query for all relevant events
|
||||
const { data, isLoading, error, refetch } = useQuery({
|
||||
queryKey: ['hatch-tasks', pubkey, stateStartedAt],
|
||||
queryFn: async () => {
|
||||
if (!pubkey || !stateStartedAt) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Build filters for events we need
|
||||
const filters: NostrFilter[] = [
|
||||
// Theme definitions after start
|
||||
{
|
||||
kinds: [KIND_THEME_DEFINITION],
|
||||
authors: [pubkey],
|
||||
since: stateStartedAt,
|
||||
},
|
||||
// Color moments after start
|
||||
{
|
||||
kinds: [KIND_COLOR_MOMENT],
|
||||
authors: [pubkey],
|
||||
since: stateStartedAt,
|
||||
},
|
||||
// Posts after start (will filter for valid Blobbi posts)
|
||||
{
|
||||
kinds: [KIND_SHORT_TEXT_NOTE],
|
||||
authors: [pubkey],
|
||||
since: stateStartedAt,
|
||||
limit: 50, // Reasonable limit
|
||||
},
|
||||
// Profile metadata - need both before and after start
|
||||
// Get latest before start
|
||||
{
|
||||
kinds: [KIND_PROFILE_METADATA],
|
||||
authors: [pubkey],
|
||||
until: stateStartedAt,
|
||||
limit: 1,
|
||||
},
|
||||
// Get latest after start
|
||||
{
|
||||
kinds: [KIND_PROFILE_METADATA],
|
||||
authors: [pubkey],
|
||||
since: stateStartedAt,
|
||||
limit: 1,
|
||||
},
|
||||
];
|
||||
|
||||
// Execute all queries
|
||||
const events = await nostr.query(filters);
|
||||
|
||||
// Categorize events
|
||||
const themeEvents = events.filter(e =>
|
||||
e.kind === KIND_THEME_DEFINITION && e.created_at >= stateStartedAt
|
||||
);
|
||||
|
||||
const colorMomentEvents = events.filter(e =>
|
||||
e.kind === KIND_COLOR_MOMENT && e.created_at >= stateStartedAt
|
||||
);
|
||||
|
||||
const postEvents = events.filter(e =>
|
||||
e.kind === KIND_SHORT_TEXT_NOTE && e.created_at >= stateStartedAt
|
||||
);
|
||||
|
||||
// Separate profile events into before and after
|
||||
const profileEvents = events.filter(e => e.kind === KIND_PROFILE_METADATA);
|
||||
const profileBefore = profileEvents
|
||||
.filter(e => e.created_at < stateStartedAt)
|
||||
.sort((a, b) => b.created_at - a.created_at)[0];
|
||||
const profileAfter = profileEvents
|
||||
.filter(e => e.created_at >= stateStartedAt)
|
||||
.sort((a, b) => b.created_at - a.created_at)[0];
|
||||
|
||||
return {
|
||||
themeEvents,
|
||||
colorMomentEvents,
|
||||
postEvents,
|
||||
profileBefore,
|
||||
profileAfter,
|
||||
};
|
||||
},
|
||||
enabled: !!pubkey && !!stateStartedAt && isIncubating,
|
||||
staleTime: 30_000, // 30 seconds
|
||||
refetchInterval: 60_000, // Refetch every minute
|
||||
});
|
||||
|
||||
// ─── Compute PERSISTENT Tasks ───
|
||||
const tasks: HatchTask[] = [];
|
||||
|
||||
// 1. Create Theme (PERSISTENT)
|
||||
const hasTheme = (data?.themeEvents?.length ?? 0) >= 1;
|
||||
tasks.push({
|
||||
id: 'create_theme',
|
||||
name: 'Create Theme',
|
||||
description: 'Create a custom theme for your profile',
|
||||
current: hasTheme ? 1 : 0,
|
||||
required: 1,
|
||||
completed: hasTheme,
|
||||
type: 'persistent',
|
||||
action: 'navigate',
|
||||
actionTarget: '/themes',
|
||||
actionLabel: 'Create Theme',
|
||||
});
|
||||
|
||||
// 2. Color Moment (PERSISTENT)
|
||||
const hasColorMoment = (data?.colorMomentEvents?.length ?? 0) >= 1;
|
||||
tasks.push({
|
||||
id: 'color_moment',
|
||||
name: 'Color Moment',
|
||||
description: 'Share a color moment on espy',
|
||||
current: hasColorMoment ? 1 : 0,
|
||||
required: 1,
|
||||
completed: hasColorMoment,
|
||||
type: 'persistent',
|
||||
action: 'external_link',
|
||||
actionTarget: 'https://espy.you/',
|
||||
actionLabel: 'Open espy',
|
||||
});
|
||||
|
||||
// 3. Create Post (PERSISTENT)
|
||||
const blobbiName = companion?.name ?? '';
|
||||
const validPosts = data?.postEvents?.filter(e => isValidHatchPost(e, blobbiName)) ?? [];
|
||||
const hasValidPost = validPosts.length >= 1;
|
||||
tasks.push({
|
||||
id: 'create_post',
|
||||
name: 'Create Post',
|
||||
description: 'Share a post about hatching your Blobbi',
|
||||
current: hasValidPost ? 1 : 0,
|
||||
required: 1,
|
||||
completed: hasValidPost,
|
||||
type: 'persistent',
|
||||
action: 'open_modal',
|
||||
actionTarget: 'blobbi_post',
|
||||
actionLabel: 'Create Post',
|
||||
});
|
||||
|
||||
// 5. Interactions (PERSISTENT)
|
||||
const interactions = interactionCount ?? 0;
|
||||
const interactionsCompleted = interactions >= HATCH_REQUIRED_INTERACTIONS;
|
||||
tasks.push({
|
||||
id: 'interactions',
|
||||
name: 'Interact with Blobbi',
|
||||
description: `Care for your Blobbi ${HATCH_REQUIRED_INTERACTIONS} times`,
|
||||
current: Math.min(interactions, HATCH_REQUIRED_INTERACTIONS),
|
||||
required: HATCH_REQUIRED_INTERACTIONS,
|
||||
completed: interactionsCompleted,
|
||||
type: 'persistent',
|
||||
// No action - just interact with Blobbi
|
||||
});
|
||||
|
||||
// ─── Compute Completion States ───
|
||||
const persistentTasks = tasks.filter(t => t.type === 'persistent');
|
||||
const dynamicTasks = tasks.filter(t => t.type === 'dynamic');
|
||||
|
||||
const persistentTasksComplete = persistentTasks.every(t => t.completed);
|
||||
const dynamicTaskComplete = dynamicTasks.every(t => t.completed);
|
||||
const allCompleted = persistentTasksComplete && dynamicTaskComplete;
|
||||
|
||||
return {
|
||||
tasks,
|
||||
persistentTasksComplete,
|
||||
dynamicTaskComplete,
|
||||
allCompleted,
|
||||
isLoading,
|
||||
error: error as Error | null,
|
||||
refetch,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current interaction count from companion task cache.
|
||||
*/
|
||||
export function getInteractionCount(companion: BlobbiCompanion | null): number {
|
||||
if (!companion) return 0;
|
||||
const interactionTask = companion.tasks.find(t => t.name === 'interactions');
|
||||
return interactionTask?.value ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter tasks to only persistent tasks (for tag sync).
|
||||
* CRITICAL: Dynamic tasks must NEVER be synced to tags.
|
||||
*/
|
||||
export function filterPersistentTasks(tasks: HatchTask[]): HatchTask[] {
|
||||
return tasks.filter(t => t.type === 'persistent');
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* useItemCooldown — React hook for per-item cooldown state.
|
||||
*
|
||||
* Subscribes to the shared item-cooldown singleton so components
|
||||
* re-render when any item's cooldown starts or expires.
|
||||
*
|
||||
* Usage:
|
||||
* ```tsx
|
||||
* const { isOnCooldown } = useItemCooldown();
|
||||
* <Button disabled={isOnCooldown(item.id)}>Use</Button>
|
||||
* ```
|
||||
*/
|
||||
|
||||
import { useCallback, useSyncExternalStore } from 'react';
|
||||
|
||||
import { isItemOnCooldown, subscribeCooldowns } from '../lib/item-cooldown';
|
||||
|
||||
/** Monotonic version counter bumped by the subscription callback. */
|
||||
let snapshotVersion = 0;
|
||||
|
||||
function subscribe(onStoreChange: () => void): () => void {
|
||||
// subscribeCooldowns returns an unsubscribe function.
|
||||
// The callback bumps the version AND notifies React.
|
||||
return subscribeCooldowns(() => {
|
||||
snapshotVersion++;
|
||||
onStoreChange();
|
||||
});
|
||||
}
|
||||
|
||||
function getSnapshot(): number {
|
||||
return snapshotVersion;
|
||||
}
|
||||
|
||||
export function useItemCooldown() {
|
||||
useSyncExternalStore(subscribe, getSnapshot);
|
||||
|
||||
const isOnCooldown = useCallback((itemId: string): boolean => {
|
||||
return isItemOnCooldown(itemId);
|
||||
}, []);
|
||||
|
||||
return { isOnCooldown };
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* useRerollMission - Replace a daily mission with a new one from the pool
|
||||
*
|
||||
* Updates the in-memory session store.
|
||||
*/
|
||||
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { toast } from '@/hooks/useToast';
|
||||
|
||||
import type { BlobbiStage } from '../lib/daily-missions';
|
||||
import { rerollMission, getDefinition } from '../lib/daily-missions';
|
||||
import {
|
||||
readMissionsFromStorage,
|
||||
writeMissionsToStorage,
|
||||
} from '../lib/daily-mission-tracker';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface RerollMissionRequest {
|
||||
missionId: string;
|
||||
availableStages?: BlobbiStage[];
|
||||
}
|
||||
|
||||
export interface RerollMissionResult {
|
||||
oldMissionId: string;
|
||||
newMissionId: string;
|
||||
rerollsRemaining: number;
|
||||
}
|
||||
|
||||
// ─── Hook ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useRerollMission() {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ missionId, availableStages }: RerollMissionRequest): Promise<RerollMissionResult> => {
|
||||
if (!user?.pubkey) throw new Error('Must be logged in');
|
||||
|
||||
const current = readMissionsFromStorage(user.pubkey);
|
||||
if (!current) throw new Error('No missions state');
|
||||
|
||||
const updated = rerollMission(current, missionId, availableStages);
|
||||
if (!updated) throw new Error('Cannot reroll this mission');
|
||||
|
||||
writeMissionsToStorage(updated, user.pubkey);
|
||||
|
||||
// Notify React
|
||||
window.dispatchEvent(new CustomEvent('daily-missions-updated', {
|
||||
detail: { missionId, rerolled: true },
|
||||
}));
|
||||
|
||||
// Find the new mission ID at the same index
|
||||
const oldIdx = current.daily.findIndex((m) => m.id === missionId);
|
||||
const newMissionId = updated.daily[oldIdx]?.id ?? missionId;
|
||||
|
||||
return {
|
||||
oldMissionId: missionId,
|
||||
newMissionId,
|
||||
rerollsRemaining: updated.rerolls,
|
||||
};
|
||||
},
|
||||
onSuccess: ({ newMissionId, rerollsRemaining }) => {
|
||||
const def = getDefinition(newMissionId);
|
||||
const rerollText = rerollsRemaining === 0
|
||||
? 'No rerolls left'
|
||||
: `${rerollsRemaining} reroll${rerollsRemaining === 1 ? '' : 's'} left`;
|
||||
|
||||
toast({
|
||||
title: 'Mission Replaced',
|
||||
description: `New mission: ${def?.title ?? newMissionId}. ${rerollText}.`,
|
||||
});
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast({
|
||||
title: 'Failed to Reroll',
|
||||
description: error.message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
// src/blobbi/actions/index.ts
|
||||
|
||||
// Components
|
||||
export { BlobbiActionsModal } from './components/BlobbiActionsModal';
|
||||
export { BlobbiActionInventoryModal } from './components/BlobbiActionInventoryModal';
|
||||
export { PlayMusicModal } from './components/PlayMusicModal';
|
||||
export { SingModal } from './components/SingModal';
|
||||
export { InlineMusicPlayer } from './components/InlineMusicPlayer';
|
||||
export { InlineSingCard } from './components/InlineSingCard';
|
||||
export { HatchTasksPanel } from './components/HatchTasksPanel';
|
||||
export { TasksPanel } from './components/TasksPanel';
|
||||
export { BlobbiPostModal } from './components/BlobbiPostModal';
|
||||
export { StartIncubationDialog } from './components/StartIncubationDialog';
|
||||
export { StartEvolutionDialog } from './components/StartEvolutionDialog';
|
||||
export { BlobbiMissionsModal } from './components/BlobbiMissionsModal';
|
||||
|
||||
// Hooks
|
||||
export { useBlobbiUseInventoryItem } from './hooks/useBlobbiUseInventoryItem';
|
||||
export type { UseItemRequest, UseItemResult, UseBlobbiUseInventoryItemParams } from './hooks/useBlobbiUseInventoryItem';
|
||||
|
||||
export { useBlobbiHatch, useBlobbiEvolve } from './hooks/useBlobbiStageTransition';
|
||||
export type {
|
||||
UseBlobbiStageTransitionParams,
|
||||
StageTransitionResult,
|
||||
CanonicalActionResult,
|
||||
} from './hooks/useBlobbiStageTransition';
|
||||
|
||||
export {
|
||||
useStartIncubation,
|
||||
useStopIncubation,
|
||||
useStartEvolution,
|
||||
useStopEvolution,
|
||||
useSyncTaskCompletions,
|
||||
} from './hooks/useBlobbiIncubation';
|
||||
export type {
|
||||
StartIncubationMode,
|
||||
StartIncubationRequest,
|
||||
UseStartIncubationParams,
|
||||
StartIncubationResult,
|
||||
UseStopIncubationParams,
|
||||
StopIncubationResult,
|
||||
UseStartEvolutionParams,
|
||||
StartEvolutionResult,
|
||||
UseStopEvolutionParams,
|
||||
StopEvolutionResult,
|
||||
UseSyncTaskCompletionsParams,
|
||||
TaskCompletionToSync,
|
||||
} from './hooks/useBlobbiIncubation';
|
||||
|
||||
export { useActiveTaskProcess, filterPersistentTasks as filterPersistentTasksFromProcess, filterDynamicTasks } from './hooks/useActiveTaskProcess';
|
||||
export type { TaskProcessType, TaskProcessConfig, ActiveTaskProcessResult } from './hooks/useActiveTaskProcess';
|
||||
|
||||
export {
|
||||
useHatchTasks,
|
||||
getInteractionCount,
|
||||
filterPersistentTasks,
|
||||
sanitizeToHashtag,
|
||||
KIND_THEME_DEFINITION,
|
||||
KIND_COLOR_MOMENT,
|
||||
HATCH_REQUIRED_INTERACTIONS,
|
||||
REQUIRED_INTERACTIONS, // Legacy export
|
||||
BLOBBI_POST_PREFIX,
|
||||
BLOBBI_POST_REQUIRED_HASHTAGS,
|
||||
} from './hooks/useHatchTasks';
|
||||
export type { HatchTask, HatchTasksResult, TaskType } from './hooks/useHatchTasks';
|
||||
|
||||
export {
|
||||
useEvolveTasks,
|
||||
getEvolveInteractionCount,
|
||||
isValidEvolvePost,
|
||||
KIND_PROFILE_TABS,
|
||||
EVOLVE_REQUIRED_THEMES,
|
||||
EVOLVE_REQUIRED_COLOR_MOMENTS,
|
||||
EVOLVE_REQUIRED_POSTS,
|
||||
EVOLVE_REQUIRED_INTERACTIONS,
|
||||
EVOLVE_STAT_THRESHOLD,
|
||||
BLOBBI_EVOLVE_POST_PREFIX,
|
||||
} from './hooks/useEvolveTasks';
|
||||
export type { EvolveTasksResult } from './hooks/useEvolveTasks';
|
||||
|
||||
export { useBlobbiDirectAction, DIRECT_ACTION_HAPPINESS_EFFECTS } from './hooks/useBlobbiDirectAction';
|
||||
export type { DirectActionRequest, DirectActionResult, UseBlobbiDirectActionParams } from './hooks/useBlobbiDirectAction';
|
||||
|
||||
export { useAudioPlayback } from './hooks/useAudioPlayback';
|
||||
export type { PlaybackState, PlaybackError, UseAudioPlaybackOptions, UseAudioPlaybackReturn } from './hooks/useAudioPlayback';
|
||||
|
||||
// Track catalog
|
||||
export {
|
||||
BLOBBI_TRACK_CATALOG,
|
||||
getAllTracks,
|
||||
getTrackById,
|
||||
formatTrackDuration,
|
||||
type BlobbiTrack,
|
||||
} from './lib/blobbi-track-catalog';
|
||||
|
||||
// Activity state
|
||||
export {
|
||||
createMusicActivity,
|
||||
createSingActivity,
|
||||
createNoActivity,
|
||||
type InlineActivityType,
|
||||
type InlineActivityState,
|
||||
type MusicActivityState,
|
||||
type SingActivityState,
|
||||
type NoActivityState,
|
||||
type BlobbiReactionState,
|
||||
type SelectedTrack,
|
||||
} from './lib/blobbi-activity-state';
|
||||
|
||||
// Re-export stat bounds from canonical source
|
||||
export { STAT_MIN, STAT_MAX } from '@/blobbi/core/lib/blobbi';
|
||||
|
||||
// Utilities
|
||||
export {
|
||||
// Types
|
||||
type InventoryAction,
|
||||
type DirectAction,
|
||||
type BlobbiAction,
|
||||
type ResolvedInventoryItem,
|
||||
type EggStatPreview,
|
||||
type ItemUsabilityResult,
|
||||
type IncrementInteractionResult,
|
||||
// Constants
|
||||
ACTION_TO_ITEM_TYPE,
|
||||
ACTION_METADATA,
|
||||
DIRECT_ACTION_METADATA,
|
||||
ALL_ACTION_METADATA,
|
||||
GENERAL_ITEM_USABLE_STAGES,
|
||||
EGG_ALLOWED_ACTIONS,
|
||||
EGG_ALLOWED_INVENTORY_ACTIONS,
|
||||
EGG_ALLOWED_DIRECT_ACTIONS,
|
||||
EGG_VISIBLE_INVENTORY_ACTIONS,
|
||||
EGG_VISIBLE_ACTIONS,
|
||||
SHELL_REPAIR_KIT_ID,
|
||||
// Functions
|
||||
clampStat,
|
||||
applyStat,
|
||||
applyItemEffects,
|
||||
filterInventoryByAction,
|
||||
decrementStorageItem,
|
||||
canUseAction,
|
||||
canUseDirectAction,
|
||||
isActionVisibleForStage,
|
||||
canUseInventoryItems,
|
||||
getStageRestrictionMessage,
|
||||
previewStatChanges,
|
||||
previewMedicineForEgg,
|
||||
previewCleanForEgg,
|
||||
hasMedicineEffectForEgg,
|
||||
hasHygieneEffectForEgg,
|
||||
canUseItemForStage,
|
||||
getActionForItem,
|
||||
incrementInteractionTaskTags,
|
||||
} from './lib/blobbi-action-utils';
|
||||
|
||||
// Daily Missions
|
||||
export { useDailyMissions } from './hooks/useDailyMissions';
|
||||
export type { DailyMissionView, UseDailyMissionsResult } from './hooks/useDailyMissions';
|
||||
export { useAwardDailyXp, useClaimMissionReward } from './hooks/useClaimMissionReward';
|
||||
export type { AwardDailyXpRequest, AwardDailyXpResult, ClaimMissionRequest, ClaimMissionResult } from './hooks/useClaimMissionReward';
|
||||
export { useRerollMission } from './hooks/useRerollMission';
|
||||
export type { RerollMissionRequest, RerollMissionResult } from './hooks/useRerollMission';
|
||||
export {
|
||||
trackDailyMissionProgress,
|
||||
trackDailyMissionEvent,
|
||||
trackMultipleDailyMissionActions,
|
||||
} from './lib/daily-mission-tracker';
|
||||
export type {
|
||||
DailyMissionAction,
|
||||
DailyMissionDefinition,
|
||||
Mission,
|
||||
TallyMission,
|
||||
EventMission,
|
||||
MissionsContent,
|
||||
} from './lib/daily-missions';
|
||||
|
||||
// Progression
|
||||
export {
|
||||
xpToLevel,
|
||||
levelToXp,
|
||||
xpProgress,
|
||||
xpToNextLevel,
|
||||
getUnlocks,
|
||||
buildXpTagUpdates,
|
||||
MAX_LEVEL,
|
||||
} from '@/blobbi/core/lib/progression';
|
||||
export type { Unlocks } from '@/blobbi/core/lib/progression';
|
||||
|
||||
// Missions content model
|
||||
export {
|
||||
parseProfileContent,
|
||||
serializeProfileContent,
|
||||
isMissionComplete,
|
||||
isTallyMission,
|
||||
isEventMission,
|
||||
missionProgress,
|
||||
} from '@/blobbi/core/lib/missions';
|
||||
export type { ProfileContent } from '@/blobbi/core/lib/missions';
|
||||
|
||||
// Item cooldown
|
||||
export { isItemOnCooldown, setItemCooldown, subscribeCooldowns } from './lib/item-cooldown';
|
||||
export { ITEM_COOLDOWN_SUCCESS_MS, ITEM_COOLDOWN_FAILURE_MS } from './lib/item-cooldown';
|
||||
export { useItemCooldown } from './hooks/useItemCooldown';
|
||||
|
||||
// Action XP
|
||||
export {
|
||||
ACTION_XP,
|
||||
INVENTORY_ACTION_XP,
|
||||
DIRECT_ACTION_XP,
|
||||
POOP_CLEANUP_XP,
|
||||
calculateActionXP,
|
||||
calculateInventoryActionXP,
|
||||
applyXPGain,
|
||||
formatXPGain,
|
||||
} from './lib/blobbi-xp';
|
||||
|
||||
// Streak tracking
|
||||
export {
|
||||
calculateStreakUpdate,
|
||||
getStreakTagUpdates,
|
||||
needsStreakUpdate,
|
||||
getStreakStatus,
|
||||
} from './lib/blobbi-streak';
|
||||
export type {
|
||||
StreakUpdateResult,
|
||||
StreakTagUpdates,
|
||||
} from './lib/blobbi-streak';
|
||||
|
||||
export { useBlobbiCareActivity } from './hooks/useBlobbiCareActivity';
|
||||
export type {
|
||||
UseBlobbiCareActivityParams,
|
||||
CareActivityResult,
|
||||
} from './hooks/useBlobbiCareActivity';
|
||||
@@ -0,0 +1,632 @@
|
||||
// src/blobbi/actions/lib/blobbi-action-utils.ts
|
||||
|
||||
import { STAT_MIN, STAT_MAX, type BlobbiCompanion, type BlobbiStats, type StorageItem } from '@/blobbi/core/lib/blobbi';
|
||||
import type { ItemEffect, ShopItemCategory } from '@/blobbi/shop/types/shop.types';
|
||||
import { getShopItemById, getLiveShopItems } from '@/blobbi/shop/lib/blobbi-shop-items';
|
||||
|
||||
// ─── Action Types ─────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Item-based care actions (use a shop catalog item on the companion)
|
||||
*/
|
||||
export type InventoryAction = 'feed' | 'play' | 'clean' | 'medicine';
|
||||
|
||||
/**
|
||||
* Direct actions that don't use items.
|
||||
* These actions affect stats directly without selecting a shop item.
|
||||
*/
|
||||
export type DirectAction = 'play_music' | 'sing';
|
||||
|
||||
/**
|
||||
* All Blobbi actions (item-based + direct)
|
||||
*/
|
||||
export type BlobbiAction = InventoryAction | DirectAction;
|
||||
|
||||
/**
|
||||
* Mapping from action type to allowed item categories
|
||||
*/
|
||||
export const ACTION_TO_ITEM_TYPE: Record<InventoryAction, ShopItemCategory> = {
|
||||
feed: 'food',
|
||||
play: 'toy',
|
||||
clean: 'hygiene',
|
||||
medicine: 'medicine',
|
||||
};
|
||||
|
||||
/**
|
||||
* Action metadata for UI display (item-based care actions)
|
||||
*/
|
||||
export const ACTION_METADATA: Record<InventoryAction, { label: string; description: string; icon: string }> = {
|
||||
feed: {
|
||||
label: 'Feed',
|
||||
description: 'Feed your Blobbi',
|
||||
icon: '🍎',
|
||||
},
|
||||
play: {
|
||||
label: 'Play',
|
||||
description: 'Play with your Blobbi',
|
||||
icon: '⚽',
|
||||
},
|
||||
clean: {
|
||||
label: 'Clean',
|
||||
description: 'Clean your Blobbi',
|
||||
icon: '🧼',
|
||||
},
|
||||
medicine: {
|
||||
label: 'Medicine',
|
||||
description: 'Heal your Blobbi',
|
||||
icon: '💊',
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Action metadata for direct actions (no item required)
|
||||
*/
|
||||
export const DIRECT_ACTION_METADATA: Record<DirectAction, { label: string; description: string; icon: string }> = {
|
||||
play_music: {
|
||||
label: 'Play Music',
|
||||
description: 'Play music for your Blobbi',
|
||||
icon: '🎵',
|
||||
},
|
||||
sing: {
|
||||
label: 'Sing',
|
||||
description: 'Sing to your Blobbi',
|
||||
icon: '🎤',
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Combined action metadata for all action types
|
||||
*/
|
||||
export const ALL_ACTION_METADATA: Record<BlobbiAction, { label: string; description: string; icon: string }> = {
|
||||
...ACTION_METADATA,
|
||||
...DIRECT_ACTION_METADATA,
|
||||
};
|
||||
|
||||
// ─── Stat Helpers ─────────────────────────────────────────────────────────────
|
||||
// STAT_MIN and STAT_MAX are imported from @/lib/blobbi (single source of truth)
|
||||
|
||||
/**
|
||||
* Clamp a stat value between STAT_MIN (1) and STAT_MAX (100).
|
||||
* Safe for undefined values (returns STAT_MIN).
|
||||
*
|
||||
* The minimum of 1 (instead of 0) ensures:
|
||||
* - Blobbi is never in an unrecoverable state
|
||||
* - Visual feedback shows critical state without being "dead"
|
||||
* - Recovery is always possible with any healing item
|
||||
*/
|
||||
export function clampStat(value: number | undefined): number {
|
||||
if (value === undefined) return STAT_MIN;
|
||||
return Math.max(STAT_MIN, Math.min(STAT_MAX, Math.round(value)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a delta to a stat, clamping the result to STAT_MIN-STAT_MAX.
|
||||
*/
|
||||
export function applyStat(current: number | undefined, delta: number): number {
|
||||
const currentValue = current ?? STAT_MIN;
|
||||
return clampStat(currentValue + delta);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply item effects to current stats.
|
||||
* Returns a new partial stats object with all affected stats clamped.
|
||||
* Only modifies stats that have corresponding effects.
|
||||
*/
|
||||
export function applyItemEffects(
|
||||
currentStats: Partial<BlobbiStats>,
|
||||
effects: ItemEffect
|
||||
): Partial<BlobbiStats> {
|
||||
const newStats: Partial<BlobbiStats> = { ...currentStats };
|
||||
|
||||
if (effects.hunger !== undefined) {
|
||||
newStats.hunger = applyStat(currentStats.hunger, effects.hunger);
|
||||
}
|
||||
if (effects.happiness !== undefined) {
|
||||
newStats.happiness = applyStat(currentStats.happiness, effects.happiness);
|
||||
}
|
||||
if (effects.energy !== undefined) {
|
||||
newStats.energy = applyStat(currentStats.energy, effects.energy);
|
||||
}
|
||||
if (effects.hygiene !== undefined) {
|
||||
newStats.hygiene = applyStat(currentStats.hygiene, effects.hygiene);
|
||||
}
|
||||
if (effects.health !== undefined) {
|
||||
newStats.health = applyStat(currentStats.health, effects.health);
|
||||
}
|
||||
|
||||
return newStats;
|
||||
}
|
||||
|
||||
// ─── Egg-Specific Item Helpers ────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The Shell Repair Kit is a special medicine item only usable by eggs.
|
||||
*/
|
||||
export const SHELL_REPAIR_KIT_ID = 'med_shell_repair';
|
||||
|
||||
/**
|
||||
* Result of checking if an item can be used by a specific Blobbi stage.
|
||||
*/
|
||||
export interface ItemUsabilityResult {
|
||||
canUse: boolean;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a specific item can be used by a companion at the given stage.
|
||||
*
|
||||
* This is the centralized item usability logic:
|
||||
* - Shell Repair Kit: Only usable by eggs
|
||||
* - Food items: Only usable by baby/adult (not eggs)
|
||||
* - Toy items: Only usable by baby/adult (not eggs)
|
||||
* - Medicine items (except Shell Repair Kit): Usable by all stages with health effect
|
||||
* - Hygiene items: Usable by all stages
|
||||
*
|
||||
* @param itemId - The shop item ID
|
||||
* @param stage - The companion's life stage
|
||||
* @returns Object with canUse boolean and optional reason string
|
||||
*/
|
||||
export function canUseItemForStage(
|
||||
itemId: string,
|
||||
stage: 'egg' | 'baby' | 'adult'
|
||||
): ItemUsabilityResult {
|
||||
const shopItem = getShopItemById(itemId);
|
||||
if (!shopItem) {
|
||||
return { canUse: false, reason: 'Item not found' };
|
||||
}
|
||||
|
||||
const isEgg = stage === 'egg';
|
||||
|
||||
// Shell Repair Kit special case: only for eggs
|
||||
if (itemId === SHELL_REPAIR_KIT_ID) {
|
||||
if (!isEgg) {
|
||||
return { canUse: false, reason: 'Only usable for eggs' };
|
||||
}
|
||||
return { canUse: true };
|
||||
}
|
||||
|
||||
// Food items: not usable by eggs
|
||||
if (shopItem.type === 'food') {
|
||||
if (isEgg) {
|
||||
return { canUse: false, reason: 'Eggs cannot eat food' };
|
||||
}
|
||||
return { canUse: true };
|
||||
}
|
||||
|
||||
// Toy items: not usable by eggs
|
||||
if (shopItem.type === 'toy') {
|
||||
if (isEgg) {
|
||||
return { canUse: false, reason: 'Eggs cannot use toys' };
|
||||
}
|
||||
return { canUse: true };
|
||||
}
|
||||
|
||||
// Medicine items (except Shell Repair Kit): check for health effect
|
||||
if (shopItem.type === 'medicine') {
|
||||
if (!hasMedicineEffectForEgg(shopItem.effect)) {
|
||||
return { canUse: false, reason: 'This medicine has no effect' };
|
||||
}
|
||||
return { canUse: true };
|
||||
}
|
||||
|
||||
// Hygiene items: all stages can use
|
||||
if (shopItem.type === 'hygiene') {
|
||||
if (!hasHygieneEffectForEgg(shopItem.effect) && !hasHappinessEffectForEgg(shopItem.effect)) {
|
||||
return { canUse: false, reason: 'This item has no cleaning effect' };
|
||||
}
|
||||
return { canUse: true };
|
||||
}
|
||||
|
||||
return { canUse: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the action type for a given item.
|
||||
*/
|
||||
export function getActionForItem(itemId: string): InventoryAction | null {
|
||||
const shopItem = getShopItemById(itemId);
|
||||
if (!shopItem) return null;
|
||||
|
||||
const typeToAction: Record<string, InventoryAction> = {
|
||||
food: 'feed',
|
||||
toy: 'play',
|
||||
hygiene: 'clean',
|
||||
medicine: 'medicine',
|
||||
};
|
||||
|
||||
return typeToAction[shopItem.type] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a medicine item has any effect on an egg.
|
||||
*
|
||||
* Eggs use the standard 3-stat model:
|
||||
* - health
|
||||
* - hygiene
|
||||
* - happiness
|
||||
*
|
||||
* Medicine with a health effect will directly affect the egg's health stat.
|
||||
*/
|
||||
export function hasMedicineEffectForEgg(effects: ItemEffect | undefined): boolean {
|
||||
if (!effects) return false;
|
||||
return effects.health !== undefined && effects.health !== 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a hygiene item has any effect on an egg.
|
||||
* Hygiene items with a hygiene effect will directly affect the egg's hygiene stat.
|
||||
*/
|
||||
export function hasHygieneEffectForEgg(effects: ItemEffect | undefined): boolean {
|
||||
if (!effects) return false;
|
||||
return effects.hygiene !== undefined && effects.hygiene !== 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an item has a happiness effect for an egg.
|
||||
* Some items (like bubble bath) give happiness bonus in addition to primary effects.
|
||||
*/
|
||||
export function hasHappinessEffectForEgg(effects: ItemEffect | undefined): boolean {
|
||||
if (!effects) return false;
|
||||
return effects.happiness !== undefined && effects.happiness !== 0;
|
||||
}
|
||||
|
||||
// ─── Item Helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Resolved catalog item with shop metadata
|
||||
*/
|
||||
export interface ResolvedInventoryItem {
|
||||
itemId: string;
|
||||
quantity: number;
|
||||
name: string;
|
||||
icon: string;
|
||||
type: ShopItemCategory;
|
||||
effect?: ItemEffect;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for filtering catalog items by action
|
||||
*/
|
||||
export interface FilterInventoryOptions {
|
||||
/** Companion stage - used to filter items by egg-compatible effects */
|
||||
stage?: 'egg' | 'baby' | 'adult';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all available items for an action type from the shop catalog.
|
||||
* Items are abilities/tools — no inventory ownership is required.
|
||||
*
|
||||
* Filtering rules:
|
||||
* - Only items matching the action's item type are included
|
||||
* - Shell Repair Kit only appears in medicine modal for eggs
|
||||
* - For eggs: only items with egg-compatible effects are returned
|
||||
* - medicine action: only items with health effect
|
||||
* - clean action: only items with hygiene or happiness effect
|
||||
*/
|
||||
export function filterInventoryByAction(
|
||||
_storage: StorageItem[],
|
||||
action: InventoryAction,
|
||||
options: FilterInventoryOptions = {}
|
||||
): ResolvedInventoryItem[] {
|
||||
const allowedType = ACTION_TO_ITEM_TYPE[action];
|
||||
const result: ResolvedInventoryItem[] = [];
|
||||
const isEgg = options.stage === 'egg';
|
||||
const allItems = getLiveShopItems();
|
||||
|
||||
for (const shopItem of allItems) {
|
||||
if (shopItem.type !== allowedType) continue;
|
||||
|
||||
// Shell Repair Kit: only show for eggs in medicine modal
|
||||
if (shopItem.id === SHELL_REPAIR_KIT_ID && !isEgg) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// For eggs, filter items by egg-compatible effects
|
||||
if (isEgg) {
|
||||
if (action === 'medicine' && !hasMedicineEffectForEgg(shopItem.effect)) {
|
||||
continue; // Skip medicine without health effect
|
||||
}
|
||||
if (action === 'clean' && !hasHygieneEffectForEgg(shopItem.effect) && !hasHappinessEffectForEgg(shopItem.effect)) {
|
||||
continue; // Skip hygiene items without hygiene or happiness effect
|
||||
}
|
||||
}
|
||||
|
||||
result.push({
|
||||
itemId: shopItem.id,
|
||||
quantity: Infinity,
|
||||
name: shopItem.name,
|
||||
icon: shopItem.icon,
|
||||
type: shopItem.type,
|
||||
effect: shopItem.effect,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrement item quantity in storage array.
|
||||
* If quantity becomes 0, removes the item entirely.
|
||||
* Returns a new storage array (immutable).
|
||||
*/
|
||||
export function decrementStorageItem(
|
||||
storage: StorageItem[],
|
||||
itemId: string,
|
||||
amount = 1
|
||||
): StorageItem[] {
|
||||
const result: StorageItem[] = [];
|
||||
|
||||
for (const item of storage) {
|
||||
if (item.itemId !== itemId) {
|
||||
result.push(item);
|
||||
continue;
|
||||
}
|
||||
const newQuantity = item.quantity - amount;
|
||||
if (newQuantity > 0) {
|
||||
result.push({ ...item, quantity: newQuantity });
|
||||
}
|
||||
// If newQuantity <= 0, we don't add it (remove item)
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── Stage Restriction Helpers ────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Stages that can use general items (food, toys, hygiene)
|
||||
*/
|
||||
export const GENERAL_ITEM_USABLE_STAGES = ['baby', 'adult'] as const;
|
||||
|
||||
/**
|
||||
* Inventory actions that are allowed for eggs.
|
||||
* Eggs can use: medicine (health), clean (hygiene)
|
||||
*/
|
||||
export const EGG_ALLOWED_INVENTORY_ACTIONS: InventoryAction[] = ['medicine', 'clean'];
|
||||
|
||||
/**
|
||||
* Direct actions that are allowed for eggs.
|
||||
* All direct actions work on eggs.
|
||||
*/
|
||||
export const EGG_ALLOWED_DIRECT_ACTIONS: DirectAction[] = ['play_music', 'sing'];
|
||||
|
||||
/**
|
||||
* Inventory actions visible in the egg UI.
|
||||
* Note: feed, play, sleep are hidden in the UI for eggs but not hard-blocked.
|
||||
*/
|
||||
export const EGG_VISIBLE_INVENTORY_ACTIONS: InventoryAction[] = ['clean', 'medicine'];
|
||||
|
||||
/**
|
||||
* All actions visible in the egg UI.
|
||||
*/
|
||||
export const EGG_VISIBLE_ACTIONS: BlobbiAction[] = ['clean', 'medicine', 'play_music', 'sing'];
|
||||
|
||||
/**
|
||||
* @deprecated Use EGG_ALLOWED_INVENTORY_ACTIONS instead
|
||||
*/
|
||||
export const EGG_ALLOWED_ACTIONS = EGG_ALLOWED_INVENTORY_ACTIONS;
|
||||
|
||||
/**
|
||||
* Check if a companion can use a specific item action.
|
||||
*
|
||||
* Note: This function no longer hard-blocks egg actions at the domain layer.
|
||||
* UI visibility is handled separately by `isActionVisibleForStage()`.
|
||||
* The domain layer allows all actions - UI chooses what to show.
|
||||
*/
|
||||
export function canUseAction(_companion: BlobbiCompanion, _action: InventoryAction): boolean {
|
||||
// All stages can technically use all item actions at the domain layer.
|
||||
// UI filtering determines what actions are shown to users.
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a companion can use a specific direct action.
|
||||
* Direct actions (play_music, sing) are available for all stages.
|
||||
*/
|
||||
export function canUseDirectAction(_companion: BlobbiCompanion, _action: DirectAction): boolean {
|
||||
// All stages can use direct actions
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an action should be visible in the UI for a given stage.
|
||||
* This is for UI filtering only - some actions are hidden but not blocked.
|
||||
*/
|
||||
export function isActionVisibleForStage(stage: 'egg' | 'baby' | 'adult', action: BlobbiAction): boolean {
|
||||
if (stage === 'egg') {
|
||||
return EGG_VISIBLE_ACTIONS.includes(action);
|
||||
}
|
||||
return true; // baby and adult see all actions
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a companion can use general items (feed, play, clean).
|
||||
* Eggs cannot use food, toys, or hygiene items.
|
||||
* @deprecated Use canUseAction(companion, action) for action-specific checks
|
||||
*/
|
||||
export function canUseInventoryItems(companion: BlobbiCompanion): boolean {
|
||||
return GENERAL_ITEM_USABLE_STAGES.includes(companion.stage as typeof GENERAL_ITEM_USABLE_STAGES[number]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a user-friendly message explaining why an action can't be used.
|
||||
*/
|
||||
export function getStageRestrictionMessage(companion: BlobbiCompanion, action?: InventoryAction): string | null {
|
||||
if (companion.stage === 'egg') {
|
||||
if (action && EGG_ALLOWED_INVENTORY_ACTIONS.includes(action)) {
|
||||
return null; // Medicine and clean are allowed for eggs
|
||||
}
|
||||
return 'Eggs cannot use this item. Wait for your Blobbi to hatch!';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ─── Stats Preview ────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Preview stats after applying an item's effects.
|
||||
* Useful for showing the user what will happen before confirming.
|
||||
*/
|
||||
export function previewStatChanges(
|
||||
currentStats: Partial<BlobbiStats>,
|
||||
effects: ItemEffect | undefined
|
||||
): Array<{ stat: keyof BlobbiStats; current: number; after: number; delta: number }> {
|
||||
if (!effects) return [];
|
||||
|
||||
const changes: Array<{ stat: keyof BlobbiStats; current: number; after: number; delta: number }> = [];
|
||||
const statKeys: (keyof BlobbiStats)[] = ['hunger', 'happiness', 'energy', 'hygiene', 'health'];
|
||||
|
||||
for (const stat of statKeys) {
|
||||
const delta = effects[stat];
|
||||
if (delta !== undefined && delta !== 0) {
|
||||
const current = currentStats[stat] ?? 0;
|
||||
const after = clampStat(current + delta);
|
||||
changes.push({ stat, current, after, delta });
|
||||
}
|
||||
}
|
||||
|
||||
return changes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Preview stat change for an egg.
|
||||
* Eggs use the 3-stat model: health, hygiene, happiness.
|
||||
*/
|
||||
export type EggStatPreview = { stat: 'health' | 'hygiene' | 'happiness'; current: number; after: number; delta: number };
|
||||
|
||||
/**
|
||||
* Preview medicine effects for an egg.
|
||||
* Medicine directly affects the egg's health stat.
|
||||
*/
|
||||
export function previewMedicineForEgg(
|
||||
currentHealth: number | undefined,
|
||||
effects: ItemEffect | undefined
|
||||
): EggStatPreview[] {
|
||||
if (!effects || effects.health === undefined || effects.health === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const current = currentHealth ?? 100;
|
||||
const delta = effects.health;
|
||||
const after = clampStat(current + delta);
|
||||
|
||||
return [{ stat: 'health', current, after, delta }];
|
||||
}
|
||||
|
||||
/**
|
||||
* Preview clean (hygiene) effects for an egg.
|
||||
* Hygiene items directly affect the egg's hygiene stat.
|
||||
* May also include happiness bonus if the item has one.
|
||||
*/
|
||||
export function previewCleanForEgg(
|
||||
currentStats: { hygiene?: number; happiness?: number },
|
||||
effects: ItemEffect | undefined
|
||||
): EggStatPreview[] {
|
||||
if (!effects) return [];
|
||||
|
||||
const results: EggStatPreview[] = [];
|
||||
|
||||
// Hygiene effect
|
||||
if (effects.hygiene !== undefined && effects.hygiene !== 0) {
|
||||
const current = currentStats.hygiene ?? 100;
|
||||
const delta = effects.hygiene;
|
||||
const after = clampStat(current + delta);
|
||||
results.push({ stat: 'hygiene', current, after, delta });
|
||||
}
|
||||
|
||||
// Happiness bonus (some hygiene items like bubble bath give happiness)
|
||||
if (effects.happiness !== undefined && effects.happiness !== 0) {
|
||||
const current = currentStats.happiness ?? 100;
|
||||
const delta = effects.happiness;
|
||||
const after = clampStat(current + delta);
|
||||
results.push({ stat: 'happiness', current, after, delta });
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
// ─── Interaction Task Helpers ─────────────────────────────────────────────────
|
||||
|
||||
/** Enable debug logging in development only */
|
||||
const DEBUG_INTERACTION_TASK = import.meta.env.DEV;
|
||||
|
||||
/**
|
||||
* Result of incrementing interaction task tags
|
||||
*/
|
||||
export interface IncrementInteractionResult {
|
||||
/** Updated tags array */
|
||||
updatedTags: string[][];
|
||||
/** New interaction count after increment */
|
||||
newCount: number;
|
||||
/** Whether the task is now complete */
|
||||
isCompleted: boolean;
|
||||
/** Previous count before increment */
|
||||
previousCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment the interaction task counter in the tags array.
|
||||
*
|
||||
* This is used by both useBlobbiDirectAction and useBlobbiUseInventoryItem
|
||||
* to track progress on interaction tasks for both hatch and evolve.
|
||||
*
|
||||
* CRITICAL: This function is called during actual user actions (not retroactive sync).
|
||||
* It always increments by 1 because each call represents a real interaction.
|
||||
*
|
||||
* Tag format:
|
||||
* - Progress: ["task", "interactions:N"]
|
||||
* - Completion: ["task_completed", "interactions"]
|
||||
*
|
||||
* Idempotency notes:
|
||||
* - This is NOT idempotent by design - each call = one interaction
|
||||
* - Duplicate task_completed tags are prevented by filtering before add
|
||||
* - Multiple task:interactions tags are prevented by filtering before add
|
||||
*
|
||||
* @param currentTags - Current tags array from the Blobbi state
|
||||
* @param requiredInteractions - Threshold for completion (7 for hatch, 21 for evolve)
|
||||
* @returns Updated tags array with incremented interaction count
|
||||
*/
|
||||
export function incrementInteractionTaskTags(
|
||||
currentTags: string[][],
|
||||
requiredInteractions: number
|
||||
): IncrementInteractionResult {
|
||||
// Get current interaction count from task tags
|
||||
const interactionTag = currentTags.find(tag =>
|
||||
tag[0] === 'task' && tag[1]?.startsWith('interactions:')
|
||||
);
|
||||
const previousCount = interactionTag
|
||||
? parseInt(interactionTag[1].split(':')[1] || '0', 10)
|
||||
: 0;
|
||||
const newCount = previousCount + 1;
|
||||
|
||||
// Check if already completed (task_completed tag exists)
|
||||
const alreadyCompleted = currentTags.some(tag =>
|
||||
tag[0] === 'task_completed' && tag[1] === 'interactions'
|
||||
);
|
||||
|
||||
// Remove old interaction task tag (prevent duplicates) and add new one
|
||||
let updatedTags = currentTags.filter(tag =>
|
||||
!(tag[0] === 'task' && tag[1]?.startsWith('interactions:'))
|
||||
);
|
||||
updatedTags = [...updatedTags, ['task', `interactions:${newCount}`]];
|
||||
|
||||
// Mark as completed if reached required count AND not already marked
|
||||
const isCompleted = newCount >= requiredInteractions;
|
||||
if (isCompleted && !alreadyCompleted) {
|
||||
// Only add if not already present (handled by filter, but double-check)
|
||||
updatedTags = [...updatedTags, ['task_completed', 'interactions']];
|
||||
}
|
||||
|
||||
if (DEBUG_INTERACTION_TASK) {
|
||||
console.log('[InteractionTask] Increment:', {
|
||||
previousCount,
|
||||
newCount,
|
||||
requiredInteractions,
|
||||
isCompleted,
|
||||
alreadyCompleted,
|
||||
addedCompletionTag: isCompleted && !alreadyCompleted,
|
||||
});
|
||||
}
|
||||
|
||||
return { updatedTags, newCount, isCompleted, previousCount };
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// src/blobbi/actions/lib/blobbi-activity-state.ts
|
||||
|
||||
import type { SelectedTrack } from '../components/PlayMusicModal';
|
||||
|
||||
/**
|
||||
* Types of inline activities that can be displayed in BlobbiPage
|
||||
*/
|
||||
export type InlineActivityType = 'none' | 'music' | 'sing';
|
||||
|
||||
// Re-export for convenience
|
||||
export type { SelectedTrack } from '../components/PlayMusicModal';
|
||||
|
||||
/**
|
||||
* State for the music inline activity
|
||||
*/
|
||||
export interface MusicActivityState {
|
||||
type: 'music';
|
||||
selection: SelectedTrack;
|
||||
isPublished: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* State for the sing inline activity
|
||||
*/
|
||||
export interface SingActivityState {
|
||||
type: 'sing';
|
||||
}
|
||||
|
||||
/**
|
||||
* No active inline activity
|
||||
*/
|
||||
export interface NoActivityState {
|
||||
type: 'none';
|
||||
}
|
||||
|
||||
/**
|
||||
* Union type for all inline activity states
|
||||
*/
|
||||
export type InlineActivityState =
|
||||
| NoActivityState
|
||||
| MusicActivityState
|
||||
| SingActivityState;
|
||||
|
||||
/**
|
||||
* Blobbi reaction state - indicates how Blobbi should visually react
|
||||
*/
|
||||
export type BlobbiReactionState =
|
||||
| 'idle' // No special reaction
|
||||
| 'listening' // Music is playing, Blobbi is listening
|
||||
| 'swaying' // Blobbi is swaying to music
|
||||
| 'singing' // User is singing, Blobbi is engaged
|
||||
| 'happy'; // General happy reaction
|
||||
|
||||
/**
|
||||
* Helper to create a music activity state
|
||||
*/
|
||||
export function createMusicActivity(selection: SelectedTrack): MusicActivityState {
|
||||
return {
|
||||
type: 'music',
|
||||
selection,
|
||||
isPublished: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to create a sing activity state
|
||||
*/
|
||||
export function createSingActivity(): SingActivityState {
|
||||
return {
|
||||
type: 'sing',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to create no activity state
|
||||
*/
|
||||
export function createNoActivity(): NoActivityState {
|
||||
return {
|
||||
type: 'none',
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// src/blobbi/actions/lib/blobbi-random-lyrics.ts
|
||||
|
||||
/**
|
||||
* Random lyrics for the Sing action.
|
||||
* These are fun, simple lyrics that users can sing to their Blobbi.
|
||||
*/
|
||||
|
||||
export interface LyricsEntry {
|
||||
id: string;
|
||||
title: string;
|
||||
lines: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Collection of placeholder lyrics for singing to a Blobbi.
|
||||
* Simple, fun, and appropriate for all ages.
|
||||
*/
|
||||
export const BLOBBI_LYRICS: LyricsEntry[] = [
|
||||
{
|
||||
id: 'lullaby-1',
|
||||
title: 'Blobbi Lullaby',
|
||||
lines: [
|
||||
'Little Blobbi, close your eyes,',
|
||||
'Dream of stars up in the skies.',
|
||||
'Safe and warm, you drift away,',
|
||||
"We'll play again another day.",
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'happy-song-1',
|
||||
title: 'Happy Blobbi Song',
|
||||
lines: [
|
||||
'Blobbi, Blobbi, jump around!',
|
||||
"You're the happiest friend I've found!",
|
||||
'Dancing, playing, full of cheer,',
|
||||
"I'm so glad that you are here!",
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'adventure-1',
|
||||
title: 'Adventure Time',
|
||||
lines: [
|
||||
"Let's go on an adventure today,",
|
||||
'Through the clouds and far away!',
|
||||
'Mountains high and valleys deep,',
|
||||
'Memories to always keep.',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'breakfast-song',
|
||||
title: 'Breakfast Song',
|
||||
lines: [
|
||||
'Wake up, wake up, sleepy head,',
|
||||
"Time to get out of your bed!",
|
||||
"Breakfast's waiting, fresh and yummy,",
|
||||
'Food to fill your happy tummy!',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'rainy-day',
|
||||
title: 'Rainy Day',
|
||||
lines: [
|
||||
'Pitter patter on the roof,',
|
||||
'Rainy days can be so nice.',
|
||||
"We'll stay cozy, me and you,",
|
||||
'Watching raindrops, one by two.',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'sunshine-song',
|
||||
title: 'Sunshine Song',
|
||||
lines: [
|
||||
'Good morning, sunshine, bright and warm,',
|
||||
'A brand new day is being born!',
|
||||
'Blue sky smiling down on me,',
|
||||
'Happy as can be, so free!',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'bedtime-1',
|
||||
title: 'Bedtime Blues',
|
||||
lines: [
|
||||
'The moon is up, the stars are bright,',
|
||||
'Time to say a soft goodnight.',
|
||||
'Snuggle up and close your eyes,',
|
||||
'Sweet dreams under starry skies.',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'play-time',
|
||||
title: 'Play Time',
|
||||
lines: [
|
||||
"Bounce and jump and run around,",
|
||||
"Spin and twirl without a sound!",
|
||||
"Playing games is so much fun,",
|
||||
"Laughing underneath the sun!",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Get a random lyrics entry.
|
||||
*/
|
||||
export function getRandomLyrics(): LyricsEntry {
|
||||
const index = Math.floor(Math.random() * BLOBBI_LYRICS.length);
|
||||
return BLOBBI_LYRICS[index];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all available lyrics entries.
|
||||
*/
|
||||
export function getAllLyrics(): LyricsEntry[] {
|
||||
return BLOBBI_LYRICS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format lyrics for display (joined with newlines).
|
||||
*/
|
||||
export function formatLyrics(lyrics: LyricsEntry): string {
|
||||
return lyrics.lines.join('\n');
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* Blobbi Care Streak Management
|
||||
*
|
||||
* This module provides centralized logic for tracking care streaks on Blobbi companions.
|
||||
* A streak represents consecutive days of care activity (opening Blobbi page, performing
|
||||
* care actions, etc.).
|
||||
*
|
||||
* Streak Rules:
|
||||
* - Starts at 1 on first activity
|
||||
* - Increments when activity happens on the NEXT local calendar day
|
||||
* - Same-day activity does not increment (at most once per day)
|
||||
* - Missing 2+ days resets streak to 1
|
||||
*
|
||||
* Tags managed:
|
||||
* - care_streak: The current streak count (positive integer)
|
||||
* - care_streak_last_at: Unix timestamp (seconds) of last streak update
|
||||
* - care_streak_last_day: Local calendar day string (YYYY-MM-DD) of last update
|
||||
*/
|
||||
|
||||
import {
|
||||
getLocalDayString,
|
||||
getDaysDifference,
|
||||
type BlobbiCompanion,
|
||||
} from '@/blobbi/core/lib/blobbi';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Result of calculating a streak update.
|
||||
*/
|
||||
export interface StreakUpdateResult {
|
||||
/** Whether the streak was updated (incremented or reset) */
|
||||
wasUpdated: boolean;
|
||||
/** The new streak value */
|
||||
newStreak: number;
|
||||
/** The new timestamp for care_streak_last_at */
|
||||
newLastAt: number;
|
||||
/** The new day string for care_streak_last_day */
|
||||
newLastDay: string;
|
||||
/** Description of what happened (for debugging/logging) */
|
||||
action: 'initialized' | 'incremented' | 'reset' | 'same_day';
|
||||
}
|
||||
|
||||
/**
|
||||
* Tag updates to apply to the Blobbi event.
|
||||
* Only present if wasUpdated is true.
|
||||
* Uses index signature for compatibility with updateBlobbiTags.
|
||||
*/
|
||||
export interface StreakTagUpdates {
|
||||
care_streak: string;
|
||||
care_streak_last_at: string;
|
||||
care_streak_last_day: string;
|
||||
[key: string]: string;
|
||||
}
|
||||
|
||||
// ─── Core Logic ───────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Calculate what the streak should be updated to based on current state and activity.
|
||||
*
|
||||
* This is a pure function that calculates the new streak state without side effects.
|
||||
* Use this to determine if/how the streak should be updated.
|
||||
*
|
||||
* @param currentStreak - Current streak value (0 or undefined means no streak yet)
|
||||
* @param lastDay - The last day string (YYYY-MM-DD) when streak was updated, or undefined
|
||||
* @param now - Current timestamp (defaults to now)
|
||||
* @returns StreakUpdateResult describing the update
|
||||
*/
|
||||
export function calculateStreakUpdate(
|
||||
currentStreak: number | undefined,
|
||||
lastDay: string | undefined,
|
||||
now: Date = new Date()
|
||||
): StreakUpdateResult {
|
||||
const nowTimestamp = Math.floor(now.getTime() / 1000);
|
||||
const todayString = getLocalDayString(now);
|
||||
|
||||
// Case 1: No existing streak - initialize to 1
|
||||
if (currentStreak === undefined || currentStreak === 0 || !lastDay) {
|
||||
return {
|
||||
wasUpdated: true,
|
||||
newStreak: 1,
|
||||
newLastAt: nowTimestamp,
|
||||
newLastDay: todayString,
|
||||
action: 'initialized',
|
||||
};
|
||||
}
|
||||
|
||||
// Case 2: Activity on the same day - no update needed
|
||||
if (lastDay === todayString) {
|
||||
return {
|
||||
wasUpdated: false,
|
||||
newStreak: currentStreak,
|
||||
newLastAt: nowTimestamp,
|
||||
newLastDay: todayString,
|
||||
action: 'same_day',
|
||||
};
|
||||
}
|
||||
|
||||
// Calculate days since last activity
|
||||
const daysMissed = getDaysDifference(lastDay, todayString);
|
||||
|
||||
// Case 3: Next day (1 day difference) - increment streak
|
||||
if (daysMissed === 1) {
|
||||
return {
|
||||
wasUpdated: true,
|
||||
newStreak: currentStreak + 1,
|
||||
newLastAt: nowTimestamp,
|
||||
newLastDay: todayString,
|
||||
action: 'incremented',
|
||||
};
|
||||
}
|
||||
|
||||
// Case 4: Missed 2+ days - reset to 1
|
||||
return {
|
||||
wasUpdated: true,
|
||||
newStreak: 1,
|
||||
newLastAt: nowTimestamp,
|
||||
newLastDay: todayString,
|
||||
action: 'reset',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the tag updates to apply to a Blobbi event for a streak update.
|
||||
* Returns undefined if no update is needed (same day activity).
|
||||
*
|
||||
* @param companion - The current Blobbi companion state
|
||||
* @param now - Current timestamp (defaults to now)
|
||||
* @returns Tag updates to apply, or undefined if no update needed
|
||||
*/
|
||||
export function getStreakTagUpdates(
|
||||
companion: BlobbiCompanion,
|
||||
now: Date = new Date()
|
||||
): StreakTagUpdates | undefined {
|
||||
const result = calculateStreakUpdate(
|
||||
companion.careStreak,
|
||||
companion.careStreakLastDay,
|
||||
now
|
||||
);
|
||||
|
||||
if (!result.wasUpdated) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
care_streak: result.newStreak.toString(),
|
||||
care_streak_last_at: result.newLastAt.toString(),
|
||||
care_streak_last_day: result.newLastDay,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a streak update is needed for the companion.
|
||||
*
|
||||
* @param companion - The current Blobbi companion state
|
||||
* @param now - Current timestamp (defaults to now)
|
||||
* @returns true if the streak should be updated
|
||||
*/
|
||||
export function needsStreakUpdate(
|
||||
companion: BlobbiCompanion,
|
||||
now: Date = new Date()
|
||||
): boolean {
|
||||
const result = calculateStreakUpdate(
|
||||
companion.careStreak,
|
||||
companion.careStreakLastDay,
|
||||
now
|
||||
);
|
||||
return result.wasUpdated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current streak status for display purposes.
|
||||
*
|
||||
* @param companion - The current Blobbi companion state
|
||||
* @returns Object with streak info for UI display
|
||||
*/
|
||||
export function getStreakStatus(companion: BlobbiCompanion): {
|
||||
streak: number;
|
||||
lastDay: string | undefined;
|
||||
isActive: boolean;
|
||||
daysSinceLastActivity: number | undefined;
|
||||
} {
|
||||
const streak = companion.careStreak ?? 0;
|
||||
const lastDay = companion.careStreakLastDay;
|
||||
const today = getLocalDayString();
|
||||
|
||||
let daysSinceLastActivity: number | undefined;
|
||||
let isActive = false;
|
||||
|
||||
if (lastDay) {
|
||||
daysSinceLastActivity = getDaysDifference(lastDay, today);
|
||||
// Streak is "active" if we've had activity today or yesterday
|
||||
isActive = daysSinceLastActivity <= 1;
|
||||
}
|
||||
|
||||
return {
|
||||
streak,
|
||||
lastDay,
|
||||
isActive,
|
||||
daysSinceLastActivity,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// src/blobbi/actions/lib/blobbi-track-catalog.ts
|
||||
|
||||
/**
|
||||
* Blobbi Track Catalog
|
||||
*
|
||||
* Music tracks for the Blobbi "Play Music" action.
|
||||
* All tracks are hosted on remote Blossom servers and streamed on-demand.
|
||||
*
|
||||
* ## Adding New Tracks
|
||||
*
|
||||
* 1. Convert the audio file to M4A (AAC-LC):
|
||||
* `ffmpeg -i input.m4a -c:a aac -b:a 64k -ar 48000 output.m4a`
|
||||
* 2. Upload the M4A file to a Blossom server
|
||||
* 3. Add a new entry to `BLOBBI_TRACK_CATALOG` below
|
||||
* 4. Set `url` to the full Blossom URL
|
||||
* 5. Get the duration: `ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 <file>`
|
||||
*
|
||||
* ## Supported Formats
|
||||
*
|
||||
* M4A (AAC-LC) is required for iOS/Safari compatibility and small file size.
|
||||
*/
|
||||
|
||||
export interface BlobbiTrack {
|
||||
/** Unique identifier for the track (used in state/events) */
|
||||
id: string;
|
||||
/** Display title shown in the UI */
|
||||
title: string;
|
||||
/** Artist or source attribution */
|
||||
artist: string;
|
||||
/** Full URL to the remote audio file (Blossom server) */
|
||||
url: string;
|
||||
/** Duration in seconds (for display, get via ffprobe) */
|
||||
durationSeconds: number;
|
||||
/** Optional cover art URL */
|
||||
coverArt?: string;
|
||||
/** Optional tags for categorization/filtering */
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Blobbi track catalog.
|
||||
*
|
||||
* All tracks are royalty-free/Creative Commons licensed.
|
||||
* Audio files hosted on remote Blossom servers.
|
||||
*/
|
||||
export const BLOBBI_TRACK_CATALOG: BlobbiTrack[] = [
|
||||
{
|
||||
id: 'nap_in_the_meadow',
|
||||
title: 'Nap in the Meadow',
|
||||
artist: 'Chilltape FM',
|
||||
url: 'https://blossom.ditto.pub/6be1c95e879187f83af2a661ccac2bd96196f7bc334af44529ede6270b2811fc.m4a',
|
||||
durationSeconds: 240, // 4:00
|
||||
tags: ['relaxing', 'nature'],
|
||||
},
|
||||
{
|
||||
id: 'happy_kids',
|
||||
title: 'Happy Kids',
|
||||
artist: 'Dmitrii Kolesnikov',
|
||||
url: 'https://blossom.ditto.pub/94d49abd178aa8afb14737a55e0a7143f6b337f618d74858d011232bb2db845d.m4a',
|
||||
durationSeconds: 129, // 2:09
|
||||
tags: ['upbeat', 'fun'],
|
||||
},
|
||||
{
|
||||
id: 'soft_piano',
|
||||
title: 'Soft Piano',
|
||||
artist: 'Dmitrii Kolesnikov',
|
||||
url: 'https://blossom.ditto.pub/5367242d3dc555c77f5c637fd153df1166708a24c5a4c222bb4dcaeabf740743.m4a',
|
||||
durationSeconds: 124, // 2:04
|
||||
tags: ['calming', 'sleep'],
|
||||
},
|
||||
{
|
||||
id: 'epic_sacred_light',
|
||||
title: 'Epic Sacred Light',
|
||||
artist: 'Ura Megis',
|
||||
url: 'https://blossom.dreamith.to/c22953791d686605958165fd44a84cd7d9fd3d4423ebf786e47891ed3a82c6db.m4a',
|
||||
durationSeconds: 223, // 3:43
|
||||
tags: ['energetic', 'adventure'],
|
||||
},
|
||||
{
|
||||
id: 'split_memories',
|
||||
title: 'Split Memories',
|
||||
artist: 'ido berg',
|
||||
url: 'https://blossom.ditto.pub/57ba2e2122a732449880ae531d4bfac9a580bc19693c7dda735afbfa336b35fe.m4a',
|
||||
durationSeconds: 153, // 2:33
|
||||
tags: ['ambient', 'relaxing'],
|
||||
},
|
||||
{
|
||||
id: 'minhas_mensagens',
|
||||
title: 'Minhas Mensagens',
|
||||
artist: 'PReis',
|
||||
url: 'https://blossom.ditto.pub/0945064dc8f946f3392be23629b166e72090cafca7cca865a20b5395dd83ff46.m4a',
|
||||
durationSeconds: 248, // 4:08
|
||||
tags: ['ambient', 'relaxing'],
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Get a track by ID from the catalog
|
||||
*/
|
||||
export function getTrackById(id: string): BlobbiTrack | undefined {
|
||||
return BLOBBI_TRACK_CATALOG.find(track => track.id === id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all tracks from the catalog
|
||||
*/
|
||||
export function getAllTracks(): BlobbiTrack[] {
|
||||
return BLOBBI_TRACK_CATALOG;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format duration in seconds to MM:SS string
|
||||
*/
|
||||
export function formatTrackDuration(seconds: number): string {
|
||||
const mins = Math.floor(seconds / 60);
|
||||
const secs = Math.floor(seconds % 60);
|
||||
return `${mins}:${secs.toString().padStart(2, '0')}`;
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
|
||||
import {
|
||||
calculateActionXP,
|
||||
calculateInventoryActionXP,
|
||||
applyXPGain,
|
||||
getXPGainSummary,
|
||||
formatXPGain,
|
||||
getXPGainMessage,
|
||||
ACTION_XP,
|
||||
INVENTORY_ACTION_XP,
|
||||
DIRECT_ACTION_XP,
|
||||
} from './blobbi-xp';
|
||||
|
||||
describe('calculateActionXP', () => {
|
||||
it('returns the correct XP for each inventory action', () => {
|
||||
expect(calculateActionXP('feed')).toBe(5);
|
||||
expect(calculateActionXP('play')).toBe(8);
|
||||
expect(calculateActionXP('clean')).toBe(6);
|
||||
expect(calculateActionXP('medicine')).toBe(10);
|
||||
});
|
||||
|
||||
it('returns the correct XP for each direct action', () => {
|
||||
expect(calculateActionXP('play_music')).toBe(7);
|
||||
expect(calculateActionXP('sing')).toBe(9);
|
||||
});
|
||||
|
||||
it('returns 0 for an unknown action', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect(calculateActionXP('unknown' as any)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('calculateInventoryActionXP', () => {
|
||||
it('returns base XP for quantity 1', () => {
|
||||
expect(calculateInventoryActionXP('feed', 1)).toBe(5);
|
||||
expect(calculateInventoryActionXP('medicine', 1)).toBe(10);
|
||||
});
|
||||
|
||||
it('multiplies XP by quantity', () => {
|
||||
expect(calculateInventoryActionXP('feed', 3)).toBe(15);
|
||||
expect(calculateInventoryActionXP('play', 5)).toBe(40);
|
||||
});
|
||||
|
||||
it('defaults to quantity 1 when not specified', () => {
|
||||
expect(calculateInventoryActionXP('clean')).toBe(6);
|
||||
});
|
||||
|
||||
it('returns 0 for quantity less than 1', () => {
|
||||
expect(calculateInventoryActionXP('feed', 0)).toBe(0);
|
||||
expect(calculateInventoryActionXP('feed', -1)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('applyXPGain', () => {
|
||||
it('adds XP to a current value', () => {
|
||||
expect(applyXPGain(100, 25)).toBe(125);
|
||||
});
|
||||
|
||||
it('treats undefined current XP as 0', () => {
|
||||
expect(applyXPGain(undefined, 10)).toBe(10);
|
||||
});
|
||||
|
||||
it('never returns a negative value', () => {
|
||||
expect(applyXPGain(5, -20)).toBe(0);
|
||||
expect(applyXPGain(0, -1)).toBe(0);
|
||||
});
|
||||
|
||||
it('handles zero XP gain', () => {
|
||||
expect(applyXPGain(50, 0)).toBe(50);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getXPGainSummary', () => {
|
||||
it('returns the correct xpGained and quantity', () => {
|
||||
const result = getXPGainSummary('feed', 3);
|
||||
expect(result).toEqual({ xpGained: 15, quantity: 3 });
|
||||
});
|
||||
|
||||
it('defaults quantity to 1', () => {
|
||||
const result = getXPGainSummary('sing');
|
||||
expect(result).toEqual({ xpGained: 9, quantity: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatXPGain', () => {
|
||||
it('formats positive XP as "+N XP"', () => {
|
||||
expect(formatXPGain(15)).toBe('+15 XP');
|
||||
expect(formatXPGain(1)).toBe('+1 XP');
|
||||
});
|
||||
|
||||
it('returns empty string for zero or negative XP', () => {
|
||||
expect(formatXPGain(0)).toBe('');
|
||||
expect(formatXPGain(-5)).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getXPGainMessage', () => {
|
||||
it('formats a message with action and XP earned', () => {
|
||||
expect(getXPGainMessage('feed', 5)).toBe('+5 XP earned!');
|
||||
});
|
||||
|
||||
it('includes total when provided', () => {
|
||||
expect(getXPGainMessage('feed', 5, 105)).toBe('+5 XP earned! Total: 105 XP');
|
||||
});
|
||||
|
||||
it('returns empty string for zero or negative XP', () => {
|
||||
expect(getXPGainMessage('feed', 0)).toBe('');
|
||||
expect(getXPGainMessage('feed', -1)).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('XP constants', () => {
|
||||
it('ACTION_XP contains all inventory and direct actions', () => {
|
||||
for (const action of Object.keys(INVENTORY_ACTION_XP)) {
|
||||
expect(ACTION_XP).toHaveProperty(action);
|
||||
expect(ACTION_XP[action as keyof typeof ACTION_XP]).toBe(
|
||||
INVENTORY_ACTION_XP[action as keyof typeof INVENTORY_ACTION_XP],
|
||||
);
|
||||
}
|
||||
for (const action of Object.keys(DIRECT_ACTION_XP)) {
|
||||
expect(ACTION_XP).toHaveProperty(action);
|
||||
expect(ACTION_XP[action as keyof typeof ACTION_XP]).toBe(
|
||||
DIRECT_ACTION_XP[action as keyof typeof DIRECT_ACTION_XP],
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('all XP values are positive integers', () => {
|
||||
for (const xp of Object.values(ACTION_XP)) {
|
||||
expect(xp).toBeGreaterThan(0);
|
||||
expect(Number.isInteger(xp)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* Blobbi XP (Experience Points) System
|
||||
*
|
||||
* This module defines XP values for all Blobbi care actions and provides
|
||||
* utilities for calculating and applying XP gains.
|
||||
*
|
||||
* Design Philosophy:
|
||||
* - Different actions award different XP to reflect their complexity/value
|
||||
* - XP values are balanced to encourage variety in care activities
|
||||
* - Item actions (feed, play, clean, medicine) give varied XP per action type
|
||||
* - Direct actions (sing, play_music) give moderate XP
|
||||
* - XP accumulates across all life stages and never resets
|
||||
*/
|
||||
|
||||
import type { BlobbiAction, InventoryAction, DirectAction } from './blobbi-action-utils';
|
||||
|
||||
// ─── XP Values by Action ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Base XP values for item-based care actions (feed, play, clean, medicine).
|
||||
*/
|
||||
export const INVENTORY_ACTION_XP: Record<InventoryAction, number> = {
|
||||
feed: 5, // Feeding is common and essential - moderate XP
|
||||
play: 8, // Playing toys provides good interaction - higher XP
|
||||
clean: 6, // Hygiene maintenance is important - moderate-high XP
|
||||
medicine: 10, // Medicine is critical - highest item XP
|
||||
};
|
||||
|
||||
/**
|
||||
* Base XP values for direct actions (play_music, sing).
|
||||
* These actions don't require selecting an item.
|
||||
*/
|
||||
export const DIRECT_ACTION_XP: Record<DirectAction, number> = {
|
||||
play_music: 7, // Playing music is engaging - good XP
|
||||
sing: 9, // Singing requires more user effort - higher XP
|
||||
};
|
||||
|
||||
/**
|
||||
* Combined XP lookup for all action types.
|
||||
* Use this for a unified XP calculation interface.
|
||||
*/
|
||||
export const ACTION_XP: Record<BlobbiAction, number> = {
|
||||
...INVENTORY_ACTION_XP,
|
||||
...DIRECT_ACTION_XP,
|
||||
};
|
||||
|
||||
/**
|
||||
* XP awarded for cleaning up poop.
|
||||
*/
|
||||
export const POOP_CLEANUP_XP = 5;
|
||||
|
||||
// ─── XP Calculation Utilities ─────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Calculate XP gain for a single action.
|
||||
*
|
||||
* @param action - The action performed
|
||||
* @returns XP points earned
|
||||
*/
|
||||
export function calculateActionXP(action: BlobbiAction): number {
|
||||
return ACTION_XP[action] ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate XP gain for an item-based care action.
|
||||
*
|
||||
* @param action - The action performed
|
||||
* @param quantity - Number of times performed (always 1 in current usage)
|
||||
* @returns Total XP points earned
|
||||
*/
|
||||
export function calculateInventoryActionXP(action: InventoryAction, quantity: number = 1): number {
|
||||
if (quantity < 1) return 0;
|
||||
const baseXP = INVENTORY_ACTION_XP[action] ?? 0;
|
||||
return baseXP * quantity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply XP gain to current experience value.
|
||||
*
|
||||
* @param currentXP - Current experience points (undefined = 0)
|
||||
* @param xpGain - XP points to add
|
||||
* @returns New total XP (never negative)
|
||||
*/
|
||||
export function applyXPGain(currentXP: number | undefined, xpGain: number): number {
|
||||
const current = currentXP ?? 0;
|
||||
const newXP = current + xpGain;
|
||||
return Math.max(0, newXP);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get XP gain summary for displaying to the user.
|
||||
*
|
||||
* @param action - The action performed
|
||||
* @param quantity - Number of times the action was performed (always 1 in current usage)
|
||||
* @returns Object with xpGained and quantity
|
||||
*/
|
||||
export function getXPGainSummary(
|
||||
action: BlobbiAction,
|
||||
quantity: number = 1
|
||||
): { xpGained: number; quantity: number } {
|
||||
const baseXP = ACTION_XP[action] ?? 0;
|
||||
const xpGained = baseXP * quantity;
|
||||
return { xpGained, quantity };
|
||||
}
|
||||
|
||||
// ─── XP Display Utilities ─────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Format XP gain for display in toasts/notifications.
|
||||
*
|
||||
* @param xpGained - Amount of XP gained
|
||||
* @returns Formatted string like "+15 XP"
|
||||
*/
|
||||
export function formatXPGain(xpGained: number): string {
|
||||
if (xpGained <= 0) return '';
|
||||
return `+${xpGained} XP`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a descriptive message about XP gain.
|
||||
*
|
||||
* @param action - The action that earned XP
|
||||
* @param xpGained - Amount of XP gained
|
||||
* @param newTotal - New total XP (optional, for "You now have X XP" message)
|
||||
* @returns Formatted message for user feedback
|
||||
*/
|
||||
export function getXPGainMessage(
|
||||
action: BlobbiAction,
|
||||
xpGained: number,
|
||||
newTotal?: number
|
||||
): string {
|
||||
if (xpGained <= 0) return '';
|
||||
|
||||
const xpText = formatXPGain(xpGained);
|
||||
|
||||
if (newTotal !== undefined) {
|
||||
return `${xpText} earned! Total: ${newTotal} XP`;
|
||||
}
|
||||
|
||||
return `${xpText} earned!`;
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* Daily Mission Tracker - Standalone progress tracking utility
|
||||
*
|
||||
* Provides a way to record daily mission progress from anywhere
|
||||
* (hooks, event handlers, etc.) without requiring React context.
|
||||
*
|
||||
* Uses a pubkey-scoped in-memory Map. Kind 11125 content JSON is the
|
||||
* persistent source of truth. Completed missions are persisted by
|
||||
* `useAwardDailyXp`; intermediate progress resets on page refresh.
|
||||
*
|
||||
* Dispatches 'daily-missions-updated' CustomEvent so React hooks re-render.
|
||||
*/
|
||||
|
||||
import type { MissionsContent } from '@/blobbi/core/lib/missions';
|
||||
import type { DailyMissionAction } from './daily-missions';
|
||||
import {
|
||||
getTodayDateString,
|
||||
needsDailyReset,
|
||||
createDailyMissionsContent,
|
||||
trackTally,
|
||||
trackEvent,
|
||||
} from './daily-missions';
|
||||
|
||||
// ─── In-Memory Session Store ──────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Pubkey-scoped session cache. Each logged-in user gets their own entry.
|
||||
* Cleared on page refresh (intentional — kind 11125 is the persistent store).
|
||||
*/
|
||||
const sessionStore = new Map<string, MissionsContent>();
|
||||
|
||||
function key(pubkey: string | undefined): string {
|
||||
return pubkey ?? '';
|
||||
}
|
||||
|
||||
function ensureCurrent(pubkey?: string): MissionsContent {
|
||||
const current = sessionStore.get(key(pubkey));
|
||||
if (!needsDailyReset(current)) return current!;
|
||||
const fresh = createDailyMissionsContent(
|
||||
getTodayDateString(),
|
||||
current?.evolution ?? [],
|
||||
pubkey,
|
||||
);
|
||||
sessionStore.set(key(pubkey), fresh);
|
||||
return fresh;
|
||||
}
|
||||
|
||||
function notify(detail?: Record<string, unknown>): void {
|
||||
window.dispatchEvent(new CustomEvent('daily-missions-updated', { detail }));
|
||||
}
|
||||
|
||||
// ─── Public API ───────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Record a tally-based action (feed, clean, interact, etc.).
|
||||
*/
|
||||
export function trackDailyMissionProgress(
|
||||
action: DailyMissionAction,
|
||||
count: number = 1,
|
||||
pubkey?: string,
|
||||
): void {
|
||||
const current = ensureCurrent(pubkey);
|
||||
const updated = trackTally(current, action, count);
|
||||
sessionStore.set(key(pubkey), updated);
|
||||
notify({ action, count });
|
||||
}
|
||||
|
||||
/**
|
||||
* Record an event-based action (take_photo, etc.) with its Nostr event ID.
|
||||
*/
|
||||
export function trackDailyMissionEvent(
|
||||
action: DailyMissionAction,
|
||||
eventId: string,
|
||||
pubkey?: string,
|
||||
): void {
|
||||
const current = ensureCurrent(pubkey);
|
||||
const updated = trackEvent(current, action, eventId);
|
||||
sessionStore.set(key(pubkey), updated);
|
||||
notify({ action, eventId });
|
||||
}
|
||||
|
||||
/**
|
||||
* Track multiple tally actions at once.
|
||||
*/
|
||||
export function trackMultipleDailyMissionActions(
|
||||
actions: DailyMissionAction[],
|
||||
pubkey?: string,
|
||||
): void {
|
||||
let current = ensureCurrent(pubkey);
|
||||
for (const action of actions) {
|
||||
current = trackTally(current, action, 1);
|
||||
}
|
||||
sessionStore.set(key(pubkey), current);
|
||||
notify({ actions });
|
||||
}
|
||||
|
||||
/** Read current session state for a pubkey. */
|
||||
export function readMissionsFromStorage(pubkey?: string): MissionsContent | undefined {
|
||||
return sessionStore.get(key(pubkey));
|
||||
}
|
||||
|
||||
/** Write state to session store for a pubkey. */
|
||||
export function writeMissionsToStorage(missions: MissionsContent, pubkey?: string): void {
|
||||
sessionStore.set(key(pubkey), missions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hydrate the session store from kind 11125 persisted data.
|
||||
* Called once on mount / account switch when the session store is empty.
|
||||
* No-op if the store already has data for this pubkey.
|
||||
*/
|
||||
export function hydrateFromPersisted(missions: MissionsContent, pubkey: string): void {
|
||||
if (sessionStore.has(pubkey)) return;
|
||||
sessionStore.set(pubkey, missions);
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
/**
|
||||
* Daily Missions System for Blobbi
|
||||
*
|
||||
* Defines the daily mission pool, selection logic, and state management.
|
||||
* Missions use the tally/event model from missions.ts:
|
||||
* - Tally missions: { id, target, count }
|
||||
* - Event missions: { id, target, events }
|
||||
* Completion is derived: count >= target or events.length >= target.
|
||||
* No explicit completed/claimed flags.
|
||||
*/
|
||||
|
||||
import type { Mission, TallyMission, EventMission, MissionsContent } from '@/blobbi/core/lib/missions';
|
||||
import { isTallyMission, isEventMission, isMissionComplete } from '@/blobbi/core/lib/missions';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Actions that can trigger daily mission progress.
|
||||
* Tally actions increment a counter. Event actions append an event ID.
|
||||
*/
|
||||
export type DailyMissionAction =
|
||||
| 'interact' // Any care interaction (tally)
|
||||
| 'feed' // Feeding action (tally)
|
||||
| 'clean' // Cleaning action (tally)
|
||||
| 'sing' // Sing direct action (tally)
|
||||
| 'play_music' // Play music direct action (tally)
|
||||
| 'sleep' // Put Blobbi to sleep (tally)
|
||||
| 'take_photo' // Take a photo (event)
|
||||
| 'medicine'; // Give medicine (tally)
|
||||
|
||||
/** Whether a mission action tracks events or tallies */
|
||||
export type MissionTrackingType = 'tally' | 'event';
|
||||
|
||||
/** Blobbi stage type for filtering missions */
|
||||
export type BlobbiStage = 'egg' | 'baby' | 'adult';
|
||||
|
||||
/**
|
||||
* Definition of a daily mission in the pool.
|
||||
* This is the static template -- not the runtime state.
|
||||
*/
|
||||
export interface DailyMissionDefinition {
|
||||
/** Unique identifier */
|
||||
id: string;
|
||||
/** Display title */
|
||||
title: string;
|
||||
/** Description of what to do */
|
||||
description: string;
|
||||
/** Action that triggers progress */
|
||||
action: DailyMissionAction;
|
||||
/** Number of times the action must be performed */
|
||||
target: number;
|
||||
/** Whether this mission tracks events or tallies */
|
||||
tracking: MissionTrackingType;
|
||||
/** XP reward for completing this mission */
|
||||
xp: number;
|
||||
/** Selection weight (higher = more likely) */
|
||||
weight: number;
|
||||
/** Required stages to show this mission */
|
||||
requiredStages?: BlobbiStage[];
|
||||
}
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Maximum number of mission rerolls allowed per day */
|
||||
export const MAX_DAILY_REROLLS = 3;
|
||||
|
||||
/** Number of daily missions selected each day */
|
||||
export const DAILY_MISSION_COUNT = 3;
|
||||
|
||||
/** XP bonus for completing all daily missions */
|
||||
export const DAILY_BONUS_XP = 50;
|
||||
|
||||
// ─── Mission Pool ─────────────────────────────────────────────────────────────
|
||||
|
||||
export const DAILY_MISSION_POOL: DailyMissionDefinition[] = [
|
||||
// ── Baby/Adult only ──────────────────────────────────────────────────────
|
||||
{
|
||||
id: 'interact_3', title: 'Quick Care',
|
||||
description: 'Interact with your Blobbi 3 times',
|
||||
action: 'interact', target: 3, tracking: 'tally', xp: 15, weight: 10,
|
||||
requiredStages: ['baby', 'adult'],
|
||||
},
|
||||
{
|
||||
id: 'interact_6', title: 'Attentive Caretaker',
|
||||
description: 'Interact with your Blobbi 6 times',
|
||||
action: 'interact', target: 6, tracking: 'tally', xp: 30, weight: 8,
|
||||
requiredStages: ['baby', 'adult'],
|
||||
},
|
||||
{
|
||||
id: 'feed_1', title: 'Snack Time',
|
||||
description: 'Feed your Blobbi once',
|
||||
action: 'feed', target: 1, tracking: 'tally', xp: 10, weight: 10,
|
||||
requiredStages: ['baby', 'adult'],
|
||||
},
|
||||
{
|
||||
id: 'feed_2', title: 'Hungry Blobbi',
|
||||
description: 'Feed your Blobbi 2 times',
|
||||
action: 'feed', target: 2, tracking: 'tally', xp: 20, weight: 8,
|
||||
requiredStages: ['baby', 'adult'],
|
||||
},
|
||||
{
|
||||
id: 'feed_3', title: 'Feast Day',
|
||||
description: 'Feed your Blobbi 3 times',
|
||||
action: 'feed', target: 3, tracking: 'tally', xp: 35, weight: 5,
|
||||
requiredStages: ['baby', 'adult'],
|
||||
},
|
||||
{
|
||||
id: 'sleep_1', title: 'Nap Time',
|
||||
description: 'Put your Blobbi to sleep',
|
||||
action: 'sleep', target: 1, tracking: 'tally', xp: 15, weight: 6,
|
||||
requiredStages: ['baby', 'adult'],
|
||||
},
|
||||
{
|
||||
id: 'take_photo_1', title: 'Snapshot',
|
||||
description: 'Take a photo of your Blobbi',
|
||||
action: 'take_photo', target: 1, tracking: 'event', xp: 25, weight: 4,
|
||||
requiredStages: ['baby', 'adult'],
|
||||
},
|
||||
{
|
||||
id: 'take_photo_2', title: 'Photo Album',
|
||||
description: 'Take 2 photos of your Blobbi',
|
||||
action: 'take_photo', target: 2, tracking: 'event', xp: 40, weight: 2,
|
||||
requiredStages: ['baby', 'adult'],
|
||||
},
|
||||
|
||||
// ── All stages ───────────────────────────────────────────────────────────
|
||||
{
|
||||
id: 'clean_1', title: 'Quick Cleanup',
|
||||
description: 'Clean your Blobbi once',
|
||||
action: 'clean', target: 1, tracking: 'tally', xp: 10, weight: 10,
|
||||
requiredStages: ['egg', 'baby', 'adult'],
|
||||
},
|
||||
{
|
||||
id: 'clean_2', title: 'Squeaky Clean',
|
||||
description: 'Clean your Blobbi 2 times',
|
||||
action: 'clean', target: 2, tracking: 'tally', xp: 20, weight: 6,
|
||||
requiredStages: ['egg', 'baby', 'adult'],
|
||||
},
|
||||
{
|
||||
id: 'sing_1', title: 'Sing Along',
|
||||
description: 'Sing a song to your Blobbi',
|
||||
action: 'sing', target: 1, tracking: 'tally', xp: 15, weight: 6,
|
||||
requiredStages: ['egg', 'baby', 'adult'],
|
||||
},
|
||||
{
|
||||
id: 'sing_2', title: 'Karaoke Session',
|
||||
description: 'Sing 2 songs to your Blobbi',
|
||||
action: 'sing', target: 2, tracking: 'tally', xp: 25, weight: 3,
|
||||
requiredStages: ['egg', 'baby', 'adult'],
|
||||
},
|
||||
{
|
||||
id: 'play_music_1', title: 'DJ Time',
|
||||
description: 'Play a song for your Blobbi',
|
||||
action: 'play_music', target: 1, tracking: 'tally', xp: 15, weight: 6,
|
||||
requiredStages: ['egg', 'baby', 'adult'],
|
||||
},
|
||||
{
|
||||
id: 'play_music_2', title: 'Music Marathon',
|
||||
description: 'Play 2 songs for your Blobbi',
|
||||
action: 'play_music', target: 2, tracking: 'tally', xp: 25, weight: 3,
|
||||
requiredStages: ['egg', 'baby', 'adult'],
|
||||
},
|
||||
{
|
||||
id: 'medicine_1', title: 'Health Check',
|
||||
description: 'Give medicine to your Blobbi',
|
||||
action: 'medicine', target: 1, tracking: 'tally', xp: 20, weight: 5,
|
||||
requiredStages: ['egg', 'baby', 'adult'],
|
||||
},
|
||||
{
|
||||
id: 'medicine_2', title: 'Doctor Visit',
|
||||
description: 'Give medicine to your Blobbi 2 times',
|
||||
action: 'medicine', target: 2, tracking: 'tally', xp: 35, weight: 3,
|
||||
requiredStages: ['egg', 'baby', 'adult'],
|
||||
},
|
||||
];
|
||||
|
||||
// ─── Lookup ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const POOL_BY_ID = new Map(DAILY_MISSION_POOL.map((d) => [d.id, d]));
|
||||
|
||||
/** Look up a mission definition by ID */
|
||||
export function getDefinition(id: string): DailyMissionDefinition | undefined {
|
||||
return POOL_BY_ID.get(id);
|
||||
}
|
||||
|
||||
// ─── Date Utilities ──────────────────────────────────────────────────────────
|
||||
|
||||
/** YYYY-MM-DD in local timezone */
|
||||
export function getTodayDateString(): string {
|
||||
const now = new Date();
|
||||
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** Whether the missions content needs a daily reset */
|
||||
export function needsDailyReset(missions: MissionsContent | undefined): boolean {
|
||||
if (!missions) return true;
|
||||
return missions.date !== getTodayDateString();
|
||||
}
|
||||
|
||||
// ─── Selection ───────────────────────────────────────────────────────────────
|
||||
|
||||
/** Seeded PRNG (Mulberry32) */
|
||||
function seededRandom(seed: number): () => number {
|
||||
return function () {
|
||||
let t = seed += 0x6D2B79F5;
|
||||
t = Math.imul(t ^ t >>> 15, t | 1);
|
||||
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
|
||||
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
function generateDailySeed(dateString: string, pubkey?: string): number {
|
||||
const input = pubkey ? `${dateString}:${pubkey}` : dateString;
|
||||
let hash = 0;
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
hash = ((hash << 5) - hash) + input.charCodeAt(i);
|
||||
hash = hash & hash;
|
||||
}
|
||||
return Math.abs(hash);
|
||||
}
|
||||
|
||||
function isMissionAvailableForStages(def: DailyMissionDefinition, stages: BlobbiStage[]): boolean {
|
||||
const required = def.requiredStages ?? ['baby', 'adult'];
|
||||
return required.some((s) => stages.includes(s));
|
||||
}
|
||||
|
||||
/**
|
||||
* Select N missions deterministically from the pool.
|
||||
* Seeded by date + pubkey so the same user gets the same missions for a given day.
|
||||
*/
|
||||
export function selectDailyMissions(
|
||||
count: number,
|
||||
dateString: string,
|
||||
pubkey?: string,
|
||||
availableStages?: BlobbiStage[],
|
||||
): DailyMissionDefinition[] {
|
||||
const stages = availableStages ?? ['baby', 'adult'];
|
||||
const eligible = DAILY_MISSION_POOL.filter((m) => isMissionAvailableForStages(m, stages));
|
||||
if (eligible.length === 0) return [];
|
||||
|
||||
const random = seededRandom(generateDailySeed(dateString, pubkey));
|
||||
const available = [...eligible];
|
||||
const selected: DailyMissionDefinition[] = [];
|
||||
|
||||
while (selected.length < count && available.length > 0) {
|
||||
const totalWeight = available.reduce((sum, m) => sum + m.weight, 0);
|
||||
let pick = random() * totalWeight;
|
||||
let idx = 0;
|
||||
for (let i = 0; i < available.length; i++) {
|
||||
pick -= available[i].weight;
|
||||
if (pick <= 0) { idx = i; break; }
|
||||
}
|
||||
selected.push(available[idx]);
|
||||
available.splice(idx, 1);
|
||||
}
|
||||
|
||||
return selected;
|
||||
}
|
||||
|
||||
// ─── Mission Instantiation ───────────────────────────────────────────────────
|
||||
|
||||
/** Create a fresh Mission from a definition */
|
||||
export function createMission(def: DailyMissionDefinition): Mission {
|
||||
if (def.tracking === 'event') {
|
||||
return { id: def.id, target: def.target, events: [] } satisfies EventMission;
|
||||
}
|
||||
return { id: def.id, target: def.target, count: 0 } satisfies TallyMission;
|
||||
}
|
||||
|
||||
/** Create a fresh MissionsContent for a new day, preserving evolution missions */
|
||||
export function createDailyMissionsContent(
|
||||
dateString: string,
|
||||
existingEvolution: Mission[],
|
||||
pubkey?: string,
|
||||
availableStages?: BlobbiStage[],
|
||||
): MissionsContent {
|
||||
const defs = selectDailyMissions(DAILY_MISSION_COUNT, dateString, pubkey, availableStages);
|
||||
return {
|
||||
date: dateString,
|
||||
daily: defs.map(createMission),
|
||||
evolution: existingEvolution,
|
||||
rerolls: MAX_DAILY_REROLLS,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Progress Tracking ───────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Increment tally for all daily missions matching the given action.
|
||||
* Returns a new missions content (immutable).
|
||||
*/
|
||||
export function trackTally(
|
||||
missions: MissionsContent,
|
||||
action: DailyMissionAction,
|
||||
incrementBy: number = 1,
|
||||
): MissionsContent {
|
||||
const updated = missions.daily.map((m) => {
|
||||
const def = POOL_BY_ID.get(m.id);
|
||||
if (!def || def.action !== action) return m;
|
||||
if (!isTallyMission(m)) return m;
|
||||
if (m.count >= m.target) return m; // already complete
|
||||
return { ...m, count: Math.min(m.count + incrementBy, m.target) };
|
||||
});
|
||||
return { ...missions, daily: updated };
|
||||
}
|
||||
|
||||
/**
|
||||
* Append an event ID to a daily mission.
|
||||
* Deduplicates by event ID. Returns new missions content.
|
||||
*/
|
||||
export function trackEvent(
|
||||
missions: MissionsContent,
|
||||
action: DailyMissionAction,
|
||||
eventId: string,
|
||||
): MissionsContent {
|
||||
const updated = missions.daily.map((m) => {
|
||||
const def = POOL_BY_ID.get(m.id);
|
||||
if (!def || def.action !== action) return m;
|
||||
if (!isEventMission(m)) return m;
|
||||
if (m.events.length >= m.target) return m; // already complete
|
||||
if (m.events.includes(eventId)) return m; // dedup
|
||||
return { ...m, events: [...m.events, eventId] };
|
||||
});
|
||||
return { ...missions, daily: updated };
|
||||
}
|
||||
|
||||
/**
|
||||
* Track progress for an evolution mission by tally.
|
||||
*/
|
||||
export function trackEvolutionTally(
|
||||
missions: MissionsContent,
|
||||
missionId: string,
|
||||
incrementBy: number = 1,
|
||||
): MissionsContent {
|
||||
const updated = missions.evolution.map((m) => {
|
||||
if (m.id !== missionId) return m;
|
||||
if (!isTallyMission(m)) return m;
|
||||
if (m.count >= m.target) return m;
|
||||
return { ...m, count: Math.min(m.count + incrementBy, m.target) };
|
||||
});
|
||||
return { ...missions, evolution: updated };
|
||||
}
|
||||
|
||||
/**
|
||||
* Append an event ID to an evolution mission.
|
||||
*/
|
||||
export function trackEvolutionEvent(
|
||||
missions: MissionsContent,
|
||||
missionId: string,
|
||||
eventId: string,
|
||||
): MissionsContent {
|
||||
const updated = missions.evolution.map((m) => {
|
||||
if (m.id !== missionId) return m;
|
||||
if (!isEventMission(m)) return m;
|
||||
if (m.events.length >= m.target) return m;
|
||||
if (m.events.includes(eventId)) return m;
|
||||
return { ...m, events: [...m.events, eventId] };
|
||||
});
|
||||
return { ...missions, evolution: updated };
|
||||
}
|
||||
|
||||
// ─── Completion Queries ──────────────────────────────────────────────────────
|
||||
|
||||
/** Whether all daily missions are complete */
|
||||
export function areAllDailyComplete(missions: MissionsContent): boolean {
|
||||
return missions.daily.length > 0 && missions.daily.every(isMissionComplete);
|
||||
}
|
||||
|
||||
/** Whether all evolution missions are complete */
|
||||
export function areAllEvolutionComplete(missions: MissionsContent): boolean {
|
||||
return missions.evolution.length > 0 && missions.evolution.every(isMissionComplete);
|
||||
}
|
||||
|
||||
/** Total XP available from today's daily missions (including bonus if all complete) */
|
||||
export function totalDailyXp(missions: MissionsContent): number {
|
||||
const base = missions.daily.reduce((sum, m) => {
|
||||
const def = POOL_BY_ID.get(m.id);
|
||||
return sum + (def && isMissionComplete(m) ? def.xp : 0);
|
||||
}, 0);
|
||||
const bonus = areAllDailyComplete(missions) ? DAILY_BONUS_XP : 0;
|
||||
return base + bonus;
|
||||
}
|
||||
|
||||
/** XP earned by a specific daily mission (0 if incomplete or unknown) */
|
||||
export function missionXp(missionId: string, mission: Mission): number {
|
||||
const def = POOL_BY_ID.get(missionId);
|
||||
if (!def || !isMissionComplete(mission)) return 0;
|
||||
return def.xp;
|
||||
}
|
||||
|
||||
// ─── Reroll ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Select a replacement mission not already in the current set.
|
||||
* Uses Math.random (rerolls should feel random, not deterministic).
|
||||
*/
|
||||
export function selectReplacementMission(
|
||||
currentMissions: Mission[],
|
||||
missionToReplaceId: string,
|
||||
availableStages?: BlobbiStage[],
|
||||
): DailyMissionDefinition | null {
|
||||
const stages = availableStages ?? ['baby', 'adult'];
|
||||
const excludedIds = new Set(currentMissions.map((m) => m.id));
|
||||
|
||||
const eligible = DAILY_MISSION_POOL.filter((m) =>
|
||||
m.id !== missionToReplaceId &&
|
||||
!excludedIds.has(m.id) &&
|
||||
isMissionAvailableForStages(m, stages),
|
||||
);
|
||||
|
||||
if (eligible.length === 0) return null;
|
||||
|
||||
const totalWeight = eligible.reduce((sum, m) => sum + m.weight, 0);
|
||||
let pick = Math.random() * totalWeight;
|
||||
for (const def of eligible) {
|
||||
pick -= def.weight;
|
||||
if (pick <= 0) return def;
|
||||
}
|
||||
return eligible[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Reroll a daily mission. Returns updated missions content or null if not possible.
|
||||
*/
|
||||
export function rerollMission(
|
||||
missions: MissionsContent,
|
||||
missionId: string,
|
||||
availableStages?: BlobbiStage[],
|
||||
): MissionsContent | null {
|
||||
if (missions.rerolls <= 0) return null;
|
||||
|
||||
const idx = missions.daily.findIndex((m) => m.id === missionId);
|
||||
if (idx === -1) return null;
|
||||
|
||||
const existing = missions.daily[idx];
|
||||
if (isMissionComplete(existing)) return null; // can't reroll completed
|
||||
|
||||
const replacement = selectReplacementMission(missions.daily, missionId, availableStages);
|
||||
if (!replacement) return null;
|
||||
|
||||
const updatedDaily = [...missions.daily];
|
||||
updatedDaily[idx] = createMission(replacement);
|
||||
|
||||
return {
|
||||
...missions,
|
||||
daily: updatedDaily,
|
||||
rerolls: missions.rerolls - 1,
|
||||
};
|
||||
}
|
||||
|
||||
// Re-export mission utilities for convenience
|
||||
export { isTallyMission, isEventMission, isMissionComplete, missionProgress } from '@/blobbi/core/lib/missions';
|
||||
export type { Mission, TallyMission, EventMission, MissionsContent } from '@/blobbi/core/lib/missions';
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* Centralized item-use cooldown tracking.
|
||||
*
|
||||
* Module-level singleton shared by every item-use path
|
||||
* (dashboard, companion layer, shop modal, falling items).
|
||||
*
|
||||
* Keyed by item type ID (e.g. "food_apple"), not instance IDs.
|
||||
* Separate durations for success (short) and failure (longer).
|
||||
* Built-in subscriber system for React via useSyncExternalStore.
|
||||
*/
|
||||
|
||||
// ─── Configuration ────────────────────────────────────────────────────────────
|
||||
|
||||
/** Cooldown after a successful item use (ms). */
|
||||
export const ITEM_COOLDOWN_SUCCESS_MS = 400;
|
||||
|
||||
/** Cooldown after a failed item use (ms). */
|
||||
export const ITEM_COOLDOWN_FAILURE_MS = 2000;
|
||||
|
||||
// ─── Singleton State ──────────────────────────────────────────────────────────
|
||||
|
||||
interface CooldownEntry {
|
||||
expiresAt: number;
|
||||
timerId: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
const cooldowns = new Map<string, CooldownEntry>();
|
||||
const subscribers = new Set<() => void>();
|
||||
|
||||
function notify(): void {
|
||||
subscribers.forEach((cb) => cb());
|
||||
}
|
||||
|
||||
// ─── Public API ───────────────────────────────────────────────────────────────
|
||||
|
||||
/** Check whether an item is currently on cooldown. */
|
||||
export function isItemOnCooldown(itemId: string): boolean {
|
||||
const entry = cooldowns.get(itemId);
|
||||
if (!entry) return false;
|
||||
if (Date.now() >= entry.expiresAt) {
|
||||
clearTimeout(entry.timerId);
|
||||
cooldowns.delete(itemId);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Put an item on cooldown. Notifies subscribers on start and expiry. */
|
||||
export function setItemCooldown(itemId: string, success: boolean): void {
|
||||
const prev = cooldowns.get(itemId);
|
||||
if (prev) clearTimeout(prev.timerId);
|
||||
|
||||
const ms = success ? ITEM_COOLDOWN_SUCCESS_MS : ITEM_COOLDOWN_FAILURE_MS;
|
||||
|
||||
const timerId = setTimeout(() => {
|
||||
cooldowns.delete(itemId);
|
||||
notify();
|
||||
}, ms);
|
||||
|
||||
cooldowns.set(itemId, { expiresAt: Date.now() + ms, timerId });
|
||||
notify();
|
||||
}
|
||||
|
||||
/** Subscribe to cooldown state changes. Returns unsubscribe function. */
|
||||
export function subscribeCooldowns(callback: () => void): () => void {
|
||||
subscribers.add(callback);
|
||||
return () => { subscribers.delete(callback); };
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
<!-- Grupo das pétalas com rotação -->
|
||||
<g transform="rotate(0 100 110)">
|
||||
<animateTransform
|
||||
attributeName="transform"
|
||||
type="rotate"
|
||||
from="0 100 110"
|
||||
to="360 100 110"
|
||||
dur="10s"
|
||||
repeatCount="indefinite" />
|
||||
<circle cx="100" cy="70" r="25" fill="url(#bloomiPetal1)" />
|
||||
<circle cx="130" cy="90" r="25" fill="url(#bloomiPetal2)" />
|
||||
<circle cx="130" cy="130" r="25" fill="url(#bloomiPetal3)" />
|
||||
<circle cx="100" cy="150" r="25" fill="url(#bloomiPetal4)" />
|
||||
<circle cx="70" cy="130" r="25" fill="url(#bloomiPetal5)" />
|
||||
<circle cx="70" cy="90" r="25" fill="url(#bloomiPetal6)" />
|
||||
</g>
|
||||
|
||||
<!-- Grupo das partículas giratórias -->
|
||||
<g transform="rotate(0 100 110)">
|
||||
<animateTransform
|
||||
attributeName="transform"
|
||||
type="rotate"
|
||||
from="0 100 110"
|
||||
to="-360 100 110"
|
||||
dur="20s"
|
||||
repeatCount="indefinite" />
|
||||
<circle cx="60" cy="80" r="2" fill="url(#bloomiPollen)" opacity="0.8" />
|
||||
<circle cx="140" cy="85" r="1.5" fill="url(#bloomiPollen)" opacity="0.6" />
|
||||
<circle cx="55" cy="140" r="1" fill="url(#bloomiPollen)" opacity="0.7" />
|
||||
<circle cx="145" cy="135" r="2" fill="url(#bloomiPollen)" opacity="0.5" />
|
||||
<circle cx="75" cy="60" r="1.5" fill="url(#bloomiPollen)" opacity="0.9" />
|
||||
</g>
|
||||
|
||||
<!-- Centro da flor -->
|
||||
<circle cx="100" cy="110" r="35" fill="url(#bloomiCenter)" />
|
||||
<circle cx="100" cy="110" r="28" fill="url(#bloomiCenterHighlight)" opacity="0.6" />
|
||||
|
||||
<!-- Eyes (white/base eye shapes) -->
|
||||
<circle cx="88" cy="105" r="8" fill="white" />
|
||||
<circle cx="112" cy="105" r="8" fill="white" />
|
||||
|
||||
<!-- Pupils (pupil + highlights) -->
|
||||
<circle cx="88" cy="105" r="5" fill="#1f2937" />
|
||||
<circle cx="112" cy="105" r="5" fill="#1f2937" />
|
||||
<circle cx="90" cy="103" r="2" fill="white" />
|
||||
<circle cx="114" cy="103" r="2" fill="white" />
|
||||
|
||||
<!-- Mouth -->
|
||||
<path d="M 90 120 Q 100 128 110 120" stroke="#1f2937" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Bochechas -->
|
||||
<circle cx="70" cy="115" r="8" fill="url(#bloomiBlush)" opacity="0.6" />
|
||||
<circle cx="130" cy="115" r="8" fill="url(#bloomiBlush)" opacity="0.6" />
|
||||
|
||||
<!-- Gradientes -->
|
||||
<defs>
|
||||
<radialGradient id="bloomiPetal1" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#fef3c7" />
|
||||
<stop offset="100%" stop-color="#fbbf24" />
|
||||
</radialGradient>
|
||||
<radialGradient id="bloomiPetal2" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#fed7d7" />
|
||||
<stop offset="100%" stop-color="#f87171" />
|
||||
</radialGradient>
|
||||
<radialGradient id="bloomiPetal3" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#fce7f3" />
|
||||
<stop offset="100%" stop-color="#f472b6" />
|
||||
</radialGradient>
|
||||
<radialGradient id="bloomiPetal4" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#e0e7ff" />
|
||||
<stop offset="100%" stop-color="#8b5cf6" />
|
||||
</radialGradient>
|
||||
<radialGradient id="bloomiPetal5" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#dcfce7" />
|
||||
<stop offset="100%" stop-color="#22c55e" />
|
||||
</radialGradient>
|
||||
<radialGradient id="bloomiPetal6" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#dbeafe" />
|
||||
<stop offset="100%" stop-color="#3b82f6" />
|
||||
</radialGradient>
|
||||
<radialGradient id="bloomiCenter" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#fef3c7" />
|
||||
<stop offset="50%" stop-color="#fbbf24" />
|
||||
<stop offset="100%" stop-color="#f59e0b" />
|
||||
</radialGradient>
|
||||
<radialGradient id="bloomiCenterHighlight" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" stop-color="#ffffff" />
|
||||
<stop offset="100%" stop-color="rgba(255,255,255,0.3)" />
|
||||
</radialGradient>
|
||||
<radialGradient id="bloomiBlush" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#fce7f3" />
|
||||
<stop offset="100%" stop-color="#f472b6" />
|
||||
</radialGradient>
|
||||
<radialGradient id="bloomiPollen" cx="0.5" cy="0.5">
|
||||
<stop offset="0%" stop-color="#fef3c7" />
|
||||
<stop offset="100%" stop-color="#fbbf24" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
@@ -0,0 +1,99 @@
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
<!-- Grupo das pétalas com rotação mais lenta (ou pode ser removido completamente) -->
|
||||
<g transform="rotate(0 100 110)">
|
||||
<animateTransform
|
||||
attributeName="transform"
|
||||
type="rotate"
|
||||
from="0 100 110"
|
||||
to="360 100 110"
|
||||
dur="20s"
|
||||
repeatCount="indefinite" />
|
||||
<circle cx="100" cy="70" r="25" fill="url(#bloomiPetal1)" />
|
||||
<circle cx="130" cy="90" r="25" fill="url(#bloomiPetal2)" />
|
||||
<circle cx="130" cy="130" r="25" fill="url(#bloomiPetal3)" />
|
||||
<circle cx="100" cy="150" r="25" fill="url(#bloomiPetal4)" />
|
||||
<circle cx="70" cy="130" r="25" fill="url(#bloomiPetal5)" />
|
||||
<circle cx="70" cy="90" r="25" fill="url(#bloomiPetal6)" />
|
||||
</g>
|
||||
|
||||
<!-- Grupo das partículas giratórias -->
|
||||
<g transform="rotate(0 100 110)">
|
||||
<animateTransform
|
||||
attributeName="transform"
|
||||
type="rotate"
|
||||
from="0 100 110"
|
||||
to="-360 100 110"
|
||||
dur="30s"
|
||||
repeatCount="indefinite" />
|
||||
<circle cx="60" cy="80" r="2" fill="url(#bloomiPollen)" opacity="0.4" />
|
||||
<circle cx="140" cy="85" r="1.5" fill="url(#bloomiPollen)" opacity="0.3" />
|
||||
<circle cx="55" cy="140" r="1" fill="url(#bloomiPollen)" opacity="0.3" />
|
||||
<circle cx="145" cy="135" r="2" fill="url(#bloomiPollen)" opacity="0.2" />
|
||||
<circle cx="75" cy="60" r="1.5" fill="url(#bloomiPollen)" opacity="0.4" />
|
||||
</g>
|
||||
|
||||
<!-- Centro da flor -->
|
||||
<circle cx="100" cy="110" r="35" fill="url(#bloomiCenter)" />
|
||||
<circle cx="100" cy="110" r="28" fill="url(#bloomiCenterHighlight)" opacity="0.6" />
|
||||
|
||||
<!-- Olhos dormindo -->
|
||||
<path d="M 80 105 Q 88 108 96 105" stroke="#1f2937" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
<path d="M 104 105 Q 112 108 120 105" stroke="#1f2937" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Boca calma -->
|
||||
<circle cx="100" cy="120" r="2" fill="#1f2937" />
|
||||
|
||||
<!-- Bochechas -->
|
||||
<circle cx="70" cy="115" r="8" fill="url(#bloomiBlush)" opacity="0.6" />
|
||||
<circle cx="130" cy="115" r="8" fill="url(#bloomiBlush)" opacity="0.6" />
|
||||
|
||||
<!-- "Zzz" dormindo -->
|
||||
<text x="150" y="60" font-size="10" fill="#666" opacity="0.8">Z</text>
|
||||
<text x="157" y="55" font-size="8" fill="#666" opacity="0.6">z</text>
|
||||
<text x="162" y="51" font-size="6" fill="#666" opacity="0.4">z</text>
|
||||
|
||||
<!-- Gradientes -->
|
||||
<defs>
|
||||
<radialGradient id="bloomiPetal1" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#fef3c7" />
|
||||
<stop offset="100%" stop-color="#fbbf24" />
|
||||
</radialGradient>
|
||||
<radialGradient id="bloomiPetal2" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#fed7d7" />
|
||||
<stop offset="100%" stop-color="#f87171" />
|
||||
</radialGradient>
|
||||
<radialGradient id="bloomiPetal3" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#fce7f3" />
|
||||
<stop offset="100%" stop-color="#f472b6" />
|
||||
</radialGradient>
|
||||
<radialGradient id="bloomiPetal4" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#e0e7ff" />
|
||||
<stop offset="100%" stop-color="#8b5cf6" />
|
||||
</radialGradient>
|
||||
<radialGradient id="bloomiPetal5" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#dcfce7" />
|
||||
<stop offset="100%" stop-color="#22c55e" />
|
||||
</radialGradient>
|
||||
<radialGradient id="bloomiPetal6" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#dbeafe" />
|
||||
<stop offset="100%" stop-color="#3b82f6" />
|
||||
</radialGradient>
|
||||
<radialGradient id="bloomiCenter" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#fef3c7" />
|
||||
<stop offset="50%" stop-color="#fbbf24" />
|
||||
<stop offset="100%" stop-color="#f59e0b" />
|
||||
</radialGradient>
|
||||
<radialGradient id="bloomiCenterHighlight" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" stop-color="#ffffff" />
|
||||
<stop offset="100%" stop-color="rgba(255,255,255,0.3)" />
|
||||
</radialGradient>
|
||||
<radialGradient id="bloomiBlush" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#fce7f3" />
|
||||
<stop offset="100%" stop-color="#f472b6" />
|
||||
</radialGradient>
|
||||
<radialGradient id="bloomiPollen" cx="0.5" cy="0.5">
|
||||
<stop offset="0%" stop-color="#fef3c7" />
|
||||
<stop offset="100%" stop-color="#fbbf24" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.1 KiB |
@@ -0,0 +1,100 @@
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
<!-- Main leaf body - classic leaf shape -->
|
||||
<path d="M 100 40 Q 70 60 60 90 Q 55 120 70 140 Q 85 155 100 160 Q 115 155 130 140 Q 145 120 140 90 Q 130 60 100 40"
|
||||
fill="url(#breezyBody)" />
|
||||
|
||||
<!-- Leaf veins - central vein -->
|
||||
<path d="M 100 45 L 100 155" stroke="url(#breezyVein)" stroke-width="3" opacity="0.6" />
|
||||
|
||||
<!-- Side veins -->
|
||||
<path d="M 100 70 L 80 85" stroke="url(#breezyVein)" stroke-width="2" opacity="0.5" />
|
||||
<path d="M 100 70 L 120 85" stroke="url(#breezyVein)" stroke-width="2" opacity="0.5" />
|
||||
<path d="M 100 100 L 75 115" stroke="url(#breezyVein)" stroke-width="2" opacity="0.5" />
|
||||
<path d="M 100 100 L 125 115" stroke="url(#breezyVein)" stroke-width="2" opacity="0.5" />
|
||||
<path d="M 100 130 L 85 140" stroke="url(#breezyVein)" stroke-width="2" opacity="0.5" />
|
||||
<path d="M 100 130 L 115 140" stroke="url(#breezyVein)" stroke-width="2" opacity="0.5" />
|
||||
|
||||
<!-- Inner leaf highlight -->
|
||||
<path d="M 100 50 Q 75 65 68 85 Q 65 105 75 120 Q 85 130 100 135 Q 115 130 125 120 Q 135 105 132 85 Q 125 65 100 50"
|
||||
fill="url(#breezyInner)" opacity="0.6" />
|
||||
|
||||
<!-- Eyes (white base) -->
|
||||
<circle cx="85" cy="90" r="10" fill="white" />
|
||||
<circle cx="115" cy="90" r="10" fill="white" />
|
||||
|
||||
<!-- Pupils (dark circles + highlights) -->
|
||||
<circle cx="85" cy="90" r="6" fill="#1f2937" />
|
||||
<circle cx="115" cy="90" r="6" fill="#1f2937" />
|
||||
<circle cx="87" cy="88" r="3" fill="white" />
|
||||
<circle cx="117" cy="88" r="3" fill="white" />
|
||||
|
||||
<!-- Mouth -->
|
||||
<path d="M 85 110 Q 100 120 115 110" stroke="#1f2937" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Little arms -->
|
||||
<path d="M 65 100 Q 55 95 50 105 Q 55 115 65 110" fill="url(#breezyArm)" />
|
||||
<path d="M 135 100 Q 145 95 150 105 Q 145 115 135 110" fill="url(#breezyArm)" />
|
||||
|
||||
<!-- Little legs -->
|
||||
<ellipse cx="90" cy="155" rx="10" ry="8" fill="url(#breezyLeg)" />
|
||||
<ellipse cx="110" cy="155" rx="10" ry="8" fill="url(#breezyLeg)" />
|
||||
|
||||
<!-- Floating leaves with rotation groups -->
|
||||
<g transform="translate(100 100)">
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate" from="0" to="360" dur="8s" repeatCount="indefinite" />
|
||||
<path d="M -50 -30 Q -55 -25 -50 -20 Q -45 -25 -50 -30" fill="url(#breezyFloating)" opacity="0.8" />
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<g transform="translate(100 100)">
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate" from="0" to="-360" dur="9s" repeatCount="indefinite" />
|
||||
<path d="M 50 -25 Q 45 -20 50 -15 Q 55 -20 50 -25" fill="url(#breezyFloating)" opacity="0.6" />
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<g transform="translate(100 100)">
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate" from="0" to="360" dur="7s" repeatCount="indefinite" />
|
||||
<path d="M -55 30 Q -60 35 -55 40 Q -50 35 -55 30" fill="url(#breezyFloating)" opacity="0.7" />
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<g transform="translate(100 100)">
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate" from="0" to="-360" dur="10s" repeatCount="indefinite" />
|
||||
<path d="M 55 25 Q 50 30 55 35 Q 60 30 55 25" fill="url(#breezyFloating)" opacity="0.5" />
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<defs>
|
||||
<radialGradient id="breezyBody" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#86efac" />
|
||||
<stop offset="30%" stop-color="#4ade80" />
|
||||
<stop offset="70%" stop-color="#22c55e" />
|
||||
<stop offset="100%" stop-color="#16a34a" />
|
||||
</radialGradient>
|
||||
<radialGradient id="breezyInner" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" stop-color="#bbf7d0" />
|
||||
<stop offset="100%" stop-color="#86efac" />
|
||||
</radialGradient>
|
||||
<linearGradient id="breezyVein" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0%" stop-color="#15803d" />
|
||||
<stop offset="50%" stop-color="#16a34a" />
|
||||
<stop offset="100%" stop-color="#15803d" />
|
||||
</linearGradient>
|
||||
<radialGradient id="breezyArm" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#4ade80" />
|
||||
<stop offset="100%" stop-color="#16a34a" />
|
||||
</radialGradient>
|
||||
<radialGradient id="breezyLeg" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#22c55e" />
|
||||
<stop offset="100%" stop-color="#15803d" />
|
||||
</radialGradient>
|
||||
<radialGradient id="breezyFloating" cx="0.5" cy="0.5">
|
||||
<stop offset="0%" stop-color="#86efac" />
|
||||
<stop offset="100%" stop-color="#22c55e" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.4 KiB |
@@ -0,0 +1,95 @@
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
<!-- Main leaf body -->
|
||||
<path d="M 100 40 Q 70 60 60 90 Q 55 120 70 140 Q 85 155 100 160 Q 115 155 130 140 Q 145 120 140 90 Q 130 60 100 40"
|
||||
fill="url(#breezyBody)" />
|
||||
|
||||
<!-- Leaf veins -->
|
||||
<path d="M 100 45 L 100 155" stroke="url(#breezyVein)" stroke-width="3" opacity="0.6" />
|
||||
<path d="M 100 70 L 80 85" stroke="url(#breezyVein)" stroke-width="2" opacity="0.5" />
|
||||
<path d="M 100 70 L 120 85" stroke="url(#breezyVein)" stroke-width="2" opacity="0.5" />
|
||||
<path d="M 100 100 L 75 115" stroke="url(#breezyVein)" stroke-width="2" opacity="0.5" />
|
||||
<path d="M 100 100 L 125 115" stroke="url(#breezyVein)" stroke-width="2" opacity="0.5" />
|
||||
<path d="M 100 130 L 85 140" stroke="url(#breezyVein)" stroke-width="2" opacity="0.5" />
|
||||
<path d="M 100 130 L 115 140" stroke="url(#breezyVein)" stroke-width="2" opacity="0.5" />
|
||||
|
||||
<!-- Inner leaf highlight -->
|
||||
<path d="M 100 50 Q 75 65 68 85 Q 65 105 75 120 Q 85 130 100 135 Q 115 130 125 120 Q 135 105 132 85 Q 125 65 100 50"
|
||||
fill="url(#breezyInner)" opacity="0.6" />
|
||||
|
||||
<!-- Olhos dormindo -->
|
||||
<path d="M 75 90 Q 85 93 95 90" stroke="#1f2937" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
<path d="M 105 90 Q 115 93 125 90" stroke="#1f2937" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Boca tranquila -->
|
||||
<circle cx="100" cy="110" r="2" fill="#1f2937" />
|
||||
|
||||
<!-- Little arms -->
|
||||
<path d="M 65 100 Q 55 95 50 105 Q 55 115 65 110" fill="url(#breezyArm)" />
|
||||
<path d="M 135 100 Q 145 95 150 105 Q 145 115 135 110" fill="url(#breezyArm)" />
|
||||
|
||||
<!-- Little legs -->
|
||||
<ellipse cx="90" cy="155" rx="10" ry="8" fill="url(#breezyLeg)" />
|
||||
<ellipse cx="110" cy="155" rx="10" ry="8" fill="url(#breezyLeg)" />
|
||||
|
||||
<!-- Floating leaves -->
|
||||
<g transform="translate(100 100)">
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate" from="0" to="360" dur="8s" repeatCount="indefinite" />
|
||||
<path d="M -50 -30 Q -55 -25 -50 -20 Q -45 -25 -50 -30" fill="url(#breezyFloating)" opacity="0.6" />
|
||||
</g>
|
||||
</g>
|
||||
<g transform="translate(100 100)">
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate" from="0" to="-360" dur="9s" repeatCount="indefinite" />
|
||||
<path d="M 50 -25 Q 45 -20 50 -15 Q 55 -20 50 -25" fill="url(#breezyFloating)" opacity="0.5" />
|
||||
</g>
|
||||
</g>
|
||||
<g transform="translate(100 100)">
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate" from="0" to="360" dur="7s" repeatCount="indefinite" />
|
||||
<path d="M -55 30 Q -60 35 -55 40 Q -50 35 -55 30" fill="url(#breezyFloating)" opacity="0.5" />
|
||||
</g>
|
||||
</g>
|
||||
<g transform="translate(100 100)">
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate" from="0" to="-360" dur="10s" repeatCount="indefinite" />
|
||||
<path d="M 55 25 Q 50 30 55 35 Q 60 30 55 25" fill="url(#breezyFloating)" opacity="0.4" />
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<!-- "Zzz" dormindo -->
|
||||
<text x="150" y="60" font-size="10" fill="#666" opacity="0.8">Z</text>
|
||||
<text x="157" y="55" font-size="8" fill="#666" opacity="0.6">z</text>
|
||||
<text x="162" y="51" font-size="6" fill="#666" opacity="0.4">z</text>
|
||||
|
||||
<!-- Gradientes -->
|
||||
<defs>
|
||||
<radialGradient id="breezyBody" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#86efac" />
|
||||
<stop offset="30%" stop-color="#4ade80" />
|
||||
<stop offset="70%" stop-color="#22c55e" />
|
||||
<stop offset="100%" stop-color="#16a34a" />
|
||||
</radialGradient>
|
||||
<radialGradient id="breezyInner" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" stop-color="#bbf7d0" />
|
||||
<stop offset="100%" stop-color="#86efac" />
|
||||
</radialGradient>
|
||||
<linearGradient id="breezyVein" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0%" stop-color="#15803d" />
|
||||
<stop offset="50%" stop-color="#16a34a" />
|
||||
<stop offset="100%" stop-color="#15803d" />
|
||||
</linearGradient>
|
||||
<radialGradient id="breezyArm" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#4ade80" />
|
||||
<stop offset="100%" stop-color="#16a34a" />
|
||||
</radialGradient>
|
||||
<radialGradient id="breezyLeg" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#22c55e" />
|
||||
<stop offset="100%" stop-color="#15803d" />
|
||||
</radialGradient>
|
||||
<radialGradient id="breezyFloating" cx="0.5" cy="0.5">
|
||||
<stop offset="0%" stop-color="#86efac" />
|
||||
<stop offset="100%" stop-color="#22c55e" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.3 KiB |
@@ -0,0 +1,75 @@
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
|
||||
<!-- Main cactus body -->
|
||||
<rect x="85" y="80" width="30" height="80" rx="15" fill="url(#cactiBody)" />
|
||||
|
||||
<!-- Cactus arms -->
|
||||
<rect x="60" y="100" width="20" height="40" rx="10" fill="url(#cactiArm)" />
|
||||
<rect x="120" y="110" width="20" height="35" rx="10" fill="url(#cactiArm)" />
|
||||
|
||||
<!-- Cactus ridges -->
|
||||
<line x1="92" y1="85" x2="92" y2="155" stroke="#65a30d" stroke-width="2" opacity="0.5" />
|
||||
<line x1="100" y1="85" x2="100" y2="155" stroke="#65a30d" stroke-width="2" opacity="0.5" />
|
||||
<line x1="108" y1="85" x2="108" y2="155" stroke="#65a30d" stroke-width="2" opacity="0.5" />
|
||||
|
||||
<!-- Eyes (white base) -->
|
||||
<circle cx="90" cy="105" r="8" fill="white" />
|
||||
<circle cx="110" cy="105" r="8" fill="white" />
|
||||
|
||||
<!-- Pupils (dark circles + highlights) -->
|
||||
<circle cx="90" cy="105" r="5" fill="#1f2937" />
|
||||
<circle cx="110" cy="105" r="5" fill="#1f2937" />
|
||||
<circle cx="92" cy="103" r="2" fill="white" />
|
||||
<circle cx="112" cy="103" r="2" fill="white" />
|
||||
|
||||
<!-- Mouth -->
|
||||
<path d="M 92 120 Q 100 126 108 120" stroke="#1f2937" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Tiny spines -->
|
||||
<circle cx="88" cy="90" r="1" fill="#65a30d" />
|
||||
<circle cx="95" cy="95" r="1" fill="#65a30d" />
|
||||
<circle cx="105" cy="92" r="1" fill="#65a30d" />
|
||||
<circle cx="112" cy="88" r="1" fill="#65a30d" />
|
||||
<circle cx="65" cy="110" r="1" fill="#65a30d" />
|
||||
<circle cx="70" cy="120" r="1" fill="#65a30d" />
|
||||
<circle cx="125" cy="115" r="1" fill="#65a30d" />
|
||||
<circle cx="130" cy="125" r="1" fill="#65a30d" />
|
||||
|
||||
<!-- Little legs in pot -->
|
||||
<path d="M 75 160 L 80 175 L 120 175 L 125 160 Z" fill="url(#cactiPot)" />
|
||||
<rect x="75" y="160" width="50" height="5" fill="url(#cactiPotRim)" rx="2" />
|
||||
|
||||
<!-- Blooming flower -->
|
||||
<circle cx="100" cy="75" r="12" fill="url(#cactiFlower)" />
|
||||
<circle cx="100" cy="75" r="8" fill="url(#cactiFlowerCenter)" />
|
||||
<circle cx="100" cy="75" r="4" fill="#fbbf24" />
|
||||
|
||||
<defs>
|
||||
<radialGradient id="cactiBody" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#a3e635" />
|
||||
<stop offset="30%" stop-color="#84cc16" />
|
||||
<stop offset="70%" stop-color="#65a30d" />
|
||||
<stop offset="100%" stop-color="#4d7c0f" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cactiArm" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#84cc16" />
|
||||
<stop offset="100%" stop-color="#65a30d" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cactiPot" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#dc2626" />
|
||||
<stop offset="100%" stop-color="#991b1b" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cactiPotRim" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#ef4444" />
|
||||
<stop offset="100%" stop-color="#dc2626" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cactiFlower" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#fce7f3" />
|
||||
<stop offset="100%" stop-color="#f472b6" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cactiFlowerCenter" cx="0.5" cy="0.5">
|
||||
<stop offset="0%" stop-color="#fef3c7" />
|
||||
<stop offset="100%" stop-color="#fbbf24" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.1 KiB |
@@ -0,0 +1,74 @@
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
|
||||
<!-- Main cactus body -->
|
||||
<rect x="85" y="80" width="30" height="80" rx="15" fill="url(#cactiBody)" />
|
||||
|
||||
<!-- Cactus arms -->
|
||||
<rect x="60" y="100" width="20" height="40" rx="10" fill="url(#cactiArm)" />
|
||||
<rect x="120" y="110" width="20" height="35" rx="10" fill="url(#cactiArm)" />
|
||||
|
||||
<!-- Cactus ridges -->
|
||||
<line x1="92" y1="85" x2="92" y2="155" stroke="#65a30d" stroke-width="2" opacity="0.5" />
|
||||
<line x1="100" y1="85" x2="100" y2="155" stroke="#65a30d" stroke-width="2" opacity="0.5" />
|
||||
<line x1="108" y1="85" x2="108" y2="155" stroke="#65a30d" stroke-width="2" opacity="0.5" />
|
||||
|
||||
<!-- Sleeping eyes -->
|
||||
<path d="M 82 105 Q 90 108 98 105" stroke="#1f2937" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
<path d="M 102 105 Q 110 108 118 105" stroke="#1f2937" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Peaceful mouth -->
|
||||
<circle cx="100" cy="120" r="2" fill="#1f2937" />
|
||||
|
||||
<!-- Tiny spines -->
|
||||
<circle cx="88" cy="90" r="1" fill="#65a30d" />
|
||||
<circle cx="95" cy="95" r="1" fill="#65a30d" />
|
||||
<circle cx="105" cy="92" r="1" fill="#65a30d" />
|
||||
<circle cx="112" cy="88" r="1" fill="#65a30d" />
|
||||
<circle cx="65" cy="110" r="1" fill="#65a30d" />
|
||||
<circle cx="70" cy="120" r="1" fill="#65a30d" />
|
||||
<circle cx="125" cy="115" r="1" fill="#65a30d" />
|
||||
<circle cx="130" cy="125" r="1" fill="#65a30d" />
|
||||
|
||||
<!-- Little legs in pot -->
|
||||
<path d="M 75 160 L 80 175 L 120 175 L 125 160 Z" fill="url(#cactiPot)" />
|
||||
<rect x="75" y="160" width="50" height="5" fill="url(#cactiPotRim)" rx="2" />
|
||||
|
||||
<!-- Blooming flower -->
|
||||
<circle cx="100" cy="75" r="12" fill="url(#cactiFlower)" />
|
||||
<circle cx="100" cy="75" r="8" fill="url(#cactiFlowerCenter)" />
|
||||
<circle cx="100" cy="75" r="4" fill="#fbbf24" />
|
||||
|
||||
<!-- "Zzz" sleeping -->
|
||||
<text x="150" y="60" font-size="10" fill="#666" opacity="0.8">Z</text>
|
||||
<text x="157" y="55" font-size="8" fill="#666" opacity="0.6">z</text>
|
||||
<text x="162" y="51" font-size="6" fill="#666" opacity="0.4">z</text>
|
||||
|
||||
<defs>
|
||||
<radialGradient id="cactiBody" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#a3e635" />
|
||||
<stop offset="30%" stop-color="#84cc16" />
|
||||
<stop offset="70%" stop-color="#65a30d" />
|
||||
<stop offset="100%" stop-color="#4d7c0f" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cactiArm" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#84cc16" />
|
||||
<stop offset="100%" stop-color="#65a30d" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cactiPot" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#dc2626" />
|
||||
<stop offset="100%" stop-color="#991b1b" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cactiPotRim" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#ef4444" />
|
||||
<stop offset="100%" stop-color="#dc2626" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cactiFlower" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#fce7f3" />
|
||||
<stop offset="100%" stop-color="#f472b6" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cactiFlowerCenter" cx="0.5" cy="0.5">
|
||||
<stop offset="0%" stop-color="#fef3c7" />
|
||||
<stop offset="100%" stop-color="#fbbf24" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.2 KiB |
@@ -0,0 +1,91 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<!-- Gradients for 3D effect -->
|
||||
<radialGradient id="cattiBody3D" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#fed7aa;stop-opacity:1" />
|
||||
<stop offset="40%" style="stop-color:#f97316;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#c2410c;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cattiEar3D" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#f97316;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#c2410c;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cattiEarInner" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#fbbf24;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#f59e0b;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cattiEyeWhite3D" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#ffffff;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#f3f4f6;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cattiPupil3D" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#374151;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#1f2937;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cattiNose3D" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#f472b6;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#be185d;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cattiNoseHighlight" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#fce7f3;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#f472b6;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cattiTail3D" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#fed7aa;stop-opacity:1" />
|
||||
<stop offset="50%" style="stop-color:#f97316;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#c2410c;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cattiTailHighlight" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#fef3c7;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#fed7aa;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<linearGradient id="cattiMouth3D" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0%" style="stop-color:#374151;stop-opacity:1" />
|
||||
<stop offset="50%" style="stop-color:#1f2937;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#374151;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<!-- Oval upright body -->
|
||||
<ellipse cx="100" cy="120" rx="45" ry="60" fill="url(#cattiBody3D)" />
|
||||
|
||||
<!-- Triangle ears -->
|
||||
<path d="M 68 72 L 58 48 L 82 62 Z" fill="url(#cattiEar3D)" />
|
||||
<path d="M 132 72 L 142 48 L 118 62 Z" fill="url(#cattiEar3D)" />
|
||||
<path d="M 70 62 L 64 52 L 76 58 Z" fill="url(#cattiEarInner)" />
|
||||
<path d="M 130 62 L 136 52 L 124 58 Z" fill="url(#cattiEarInner)" />
|
||||
|
||||
<!-- Eyes (white/base eye shapes) -->
|
||||
<ellipse cx="85" cy="100" rx="12" ry="16" fill="url(#cattiEyeWhite3D)" />
|
||||
<ellipse cx="115" cy="100" rx="12" ry="16" fill="url(#cattiEyeWhite3D)" />
|
||||
|
||||
<!-- Pupils (pupil + highlights) -->
|
||||
<ellipse cx="85" cy="100" rx="8" ry="12" fill="url(#cattiPupil3D)" />
|
||||
<ellipse cx="115" cy="100" rx="8" ry="12" fill="url(#cattiPupil3D)" />
|
||||
<ellipse cx="87" cy="97" rx="3" ry="4" fill="white" opacity="0.9" />
|
||||
<ellipse cx="117" cy="97" rx="3" ry="4" fill="white" opacity="0.9" />
|
||||
|
||||
<!-- Nose -->
|
||||
<path d="M 94 115 L 100 122 L 106 115 Z" fill="url(#cattiNose3D)" />
|
||||
<path d="M 96 116 L 100 120 L 104 116 Z" fill="url(#cattiNoseHighlight)" />
|
||||
|
||||
<!-- Mouth -->
|
||||
<path d="M 100 122 Q 88 128 82 122" stroke="url(#cattiMouth3D)" stroke-width="2.5" fill="none" stroke-linecap="round" />
|
||||
<path d="M 100 122 Q 112 128 118 122" stroke="url(#cattiMouth3D)" stroke-width="2.5" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Enhanced curved tail -->
|
||||
<path d="M 145 140 Q 165 115 158 95 Q 148 75 165 65" stroke="url(#cattiTail3D)" stroke-width="22" fill="none" stroke-linecap="round" />
|
||||
<path d="M 145 140 Q 163 117 156 97 Q 148 79 163 69" stroke="url(#cattiTailHighlight)" stroke-width="16" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Enhanced whiskers -->
|
||||
<path d="M 48 108 Q 58 110 72 108" stroke="#1e293b" stroke-width="1.8" fill="none" stroke-linecap="round" />
|
||||
<path d="M 48 118 Q 58 120 72 118" stroke="#1e293b" stroke-width="1.8" fill="none" stroke-linecap="round" />
|
||||
<path d="M 128 108 Q 138 110 152 108" stroke="#1e293b" stroke-width="1.8" fill="none" stroke-linecap="round" />
|
||||
<path d="M 128 118 Q 138 120 152 118" stroke="#1e293b" stroke-width="1.8" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Soft fur texture details -->
|
||||
<ellipse cx="75" cy="135" rx="3" ry="2" fill="rgba(255,255,255,0.2)" />
|
||||
<ellipse cx="125" cy="130" rx="2.5" ry="2" fill="rgba(255,255,255,0.2)" />
|
||||
<ellipse cx="90" cy="150" rx="2" ry="1.5" fill="rgba(255,255,255,0.15)" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,89 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<!-- Gradients for 3D effect -->
|
||||
<radialGradient id="cattiBody3D" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#fed7aa;stop-opacity:1" />
|
||||
<stop offset="40%" style="stop-color:#f97316;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#c2410c;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cattiEar3D" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#f97316;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#c2410c;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cattiEarInner" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#fbbf24;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#f59e0b;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cattiEyeWhite3D" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#ffffff;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#f3f4f6;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cattiPupil3D" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#374151;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#1f2937;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cattiNose3D" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#f472b6;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#be185d;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cattiNoseHighlight" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#fce7f3;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#f472b6;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cattiTail3D" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#fed7aa;stop-opacity:1" />
|
||||
<stop offset="50%" style="stop-color:#f97316;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#c2410c;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cattiTailHighlight" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#fef3c7;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#fed7aa;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<linearGradient id="cattiMouth3D" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0%" style="stop-color:#374151;stop-opacity:1" />
|
||||
<stop offset="50%" style="stop-color:#1f2937;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#374151;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<!-- Oval upright body -->
|
||||
<ellipse cx="100" cy="120" rx="45" ry="60" fill="url(#cattiBody3D)" />
|
||||
|
||||
<!-- Triangle ears -->
|
||||
<path d="M 68 72 L 58 48 L 82 62 Z" fill="url(#cattiEar3D)" />
|
||||
<path d="M 132 72 L 142 48 L 118 62 Z" fill="url(#cattiEar3D)" />
|
||||
<path d="M 70 62 L 64 52 L 76 58 Z" fill="url(#cattiEarInner)" />
|
||||
<path d="M 130 62 L 136 52 L 124 58 Z" fill="url(#cattiEarInner)" />
|
||||
|
||||
<!-- Sleeping eyes -->
|
||||
<path d="M 73 100 Q 85 103 97 100" stroke="#1f2937" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
<path d="M 103 100 Q 115 103 127 100" stroke="#1f2937" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Enhanced cat nose -->
|
||||
<path d="M 94 115 L 100 122 L 106 115 Z" fill="url(#cattiNose3D)" />
|
||||
<path d="M 96 116 L 100 120 L 104 116 Z" fill="url(#cattiNoseHighlight)" />
|
||||
|
||||
<!-- Peaceful mouth -->
|
||||
<circle cx="100" cy="125" r="2" fill="#1f2937" />
|
||||
|
||||
<!-- Enhanced curved tail -->
|
||||
<path d="M 145 140 Q 165 115 158 95 Q 148 75 165 65" stroke="url(#cattiTail3D)" stroke-width="22" fill="none" stroke-linecap="round" />
|
||||
<path d="M 145 140 Q 163 117 156 97 Q 148 79 163 69" stroke="url(#cattiTailHighlight)" stroke-width="16" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Enhanced whiskers -->
|
||||
<path d="M 48 108 Q 58 110 72 108" stroke="#1e293b" stroke-width="1.8" fill="none" stroke-linecap="round" />
|
||||
<path d="M 48 118 Q 58 120 72 118" stroke="#1e293b" stroke-width="1.8" fill="none" stroke-linecap="round" />
|
||||
<path d="M 128 108 Q 138 110 152 108" stroke="#1e293b" stroke-width="1.8" fill="none" stroke-linecap="round" />
|
||||
<path d="M 128 118 Q 138 120 152 118" stroke="#1e293b" stroke-width="1.8" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Soft fur texture details -->
|
||||
<ellipse cx="75" cy="135" rx="3" ry="2" fill="rgba(255,255,255,0.2)" />
|
||||
<ellipse cx="125" cy="130" rx="2.5" ry="2" fill="rgba(255,255,255,0.2)" />
|
||||
<ellipse cx="90" cy="150" rx="2" ry="1.5" fill="rgba(255,255,255,0.15)" />
|
||||
|
||||
<!-- "Zzz" sleeping -->
|
||||
<text x="150" y="60" font-size="10" fill="#666" opacity="0.8">Z</text>
|
||||
<text x="157" y="55" font-size="8" fill="#666" opacity="0.6">z</text>
|
||||
<text x="162" y="51" font-size="6" fill="#666" opacity="0.4">z</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.7 KiB |
@@ -0,0 +1,49 @@
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
<!-- Main cloud body - multiple overlapping circles -->
|
||||
<circle cx="100" cy="120" r="45" fill="url(#cloudiBody)" />
|
||||
<circle cx="75" cy="110" r="35" fill="url(#cloudiBody)" />
|
||||
<circle cx="125" cy="110" r="35" fill="url(#cloudiBody)" />
|
||||
<circle cx="85" cy="95" r="25" fill="url(#cloudiBody)" />
|
||||
<circle cx="115" cy="95" r="25" fill="url(#cloudiBody)" />
|
||||
<circle cx="100" cy="85" r="30" fill="url(#cloudiBody)" />
|
||||
|
||||
<!-- Fluffy highlights -->
|
||||
<circle cx="90" cy="100" r="20" fill="url(#cloudiHighlight)" opacity="0.6" />
|
||||
<circle cx="110" cy="105" r="18" fill="url(#cloudiHighlight)" opacity="0.5" />
|
||||
<circle cx="100" cy="90" r="15" fill="url(#cloudiHighlight)" opacity="0.7" />
|
||||
|
||||
<!-- Eyes (white/base eye shapes) -->
|
||||
<circle cx="88" cy="100" r="8" fill="white" />
|
||||
<circle cx="112" cy="100" r="8" fill="white" />
|
||||
|
||||
<!-- Pupils (pupil + highlights) -->
|
||||
<circle cx="88" cy="100" r="5" fill="#64748b" />
|
||||
<circle cx="112" cy="100" r="5" fill="#64748b" />
|
||||
<circle cx="90" cy="98" r="2" fill="white" />
|
||||
<circle cx="114" cy="98" r="2" fill="white" />
|
||||
|
||||
<!-- Mouth -->
|
||||
<path d="M 92 115 Q 100 122 108 115" stroke="#64748b" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Floating raindrops -->
|
||||
<circle cx="70" cy="140" r="3" fill="url(#cloudiRain)" opacity="0.8" />
|
||||
<circle cx="130" cy="145" r="2.5" fill="url(#cloudiRain)" opacity="0.6" />
|
||||
<circle cx="85" cy="155" r="2" fill="url(#cloudiRain)" opacity="0.7" />
|
||||
<circle cx="115" cy="150" r="2.5" fill="url(#cloudiRain)" opacity="0.5" />
|
||||
|
||||
<defs>
|
||||
<radialGradient id="cloudiBody" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#ffffff" />
|
||||
<stop offset="50%" stop-color="#f1f5f9" />
|
||||
<stop offset="100%" stop-color="#e2e8f0" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cloudiHighlight" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" stop-color="#ffffff" />
|
||||
<stop offset="100%" stop-color="rgba(255,255,255,0.5)" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cloudiRain" cx="0.5" cy="0.3">
|
||||
<stop offset="0%" stop-color="#60a5fa" />
|
||||
<stop offset="100%" stop-color="#3b82f6" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.2 KiB |
@@ -0,0 +1,51 @@
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
<!-- Main cloud body - multiple overlapping circles -->
|
||||
<circle cx="100" cy="120" r="45" fill="url(#cloudiBody)" />
|
||||
<circle cx="75" cy="110" r="35" fill="url(#cloudiBody)" />
|
||||
<circle cx="125" cy="110" r="35" fill="url(#cloudiBody)" />
|
||||
<circle cx="85" cy="95" r="25" fill="url(#cloudiBody)" />
|
||||
<circle cx="115" cy="95" r="25" fill="url(#cloudiBody)" />
|
||||
<circle cx="100" cy="85" r="30" fill="url(#cloudiBody)" />
|
||||
|
||||
<!-- Fluffy highlights -->
|
||||
<circle cx="90" cy="100" r="20" fill="url(#cloudiHighlight)" opacity="0.6" />
|
||||
<circle cx="110" cy="105" r="18" fill="url(#cloudiHighlight)" opacity="0.5" />
|
||||
<circle cx="100" cy="90" r="15" fill="url(#cloudiHighlight)" opacity="0.7" />
|
||||
|
||||
<!-- Sleeping eyes -->
|
||||
<path d="M 80 100 Q 88 103 96 100" stroke="#64748b" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
<path d="M 104 100 Q 112 103 120 100" stroke="#64748b" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Peaceful mouth -->
|
||||
<circle cx="100" cy="115" r="2" fill="#64748b" />
|
||||
|
||||
<!-- Floating raindrops with gentle animation -->
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="translate" values="0,0; 0,5; 0,0" dur="3s" repeatCount="indefinite" />
|
||||
<circle cx="70" cy="140" r="3" fill="url(#cloudiRain)" opacity="0.6" />
|
||||
<circle cx="130" cy="145" r="2.5" fill="url(#cloudiRain)" opacity="0.4" />
|
||||
<circle cx="85" cy="155" r="2" fill="url(#cloudiRain)" opacity="0.5" />
|
||||
<circle cx="115" cy="150" r="2.5" fill="url(#cloudiRain)" opacity="0.3" />
|
||||
</g>
|
||||
|
||||
<!-- "Zzz" sleeping -->
|
||||
<text x="150" y="60" font-size="10" fill="#666" opacity="0.8">Z</text>
|
||||
<text x="157" y="55" font-size="8" fill="#666" opacity="0.6">z</text>
|
||||
<text x="162" y="51" font-size="6" fill="#666" opacity="0.4">z</text>
|
||||
|
||||
<defs>
|
||||
<radialGradient id="cloudiBody" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#ffffff" />
|
||||
<stop offset="50%" stop-color="#f1f5f9" />
|
||||
<stop offset="100%" stop-color="#e2e8f0" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cloudiHighlight" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" stop-color="#ffffff" />
|
||||
<stop offset="100%" stop-color="rgba(255,255,255,0.5)" />
|
||||
</radialGradient>
|
||||
<radialGradient id="cloudiRain" cx="0.5" cy="0.3">
|
||||
<stop offset="0%" stop-color="#60a5fa" />
|
||||
<stop offset="100%" stop-color="#3b82f6" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.4 KiB |
@@ -0,0 +1,84 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<!-- Crystal gradients -->
|
||||
<radialGradient id="crystiBody" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#f3e8ff;stop-opacity:1" />
|
||||
<stop offset="30%" style="stop-color:#e9d5ff;stop-opacity:1" />
|
||||
<stop offset="70%" style="stop-color:#c084fc;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#8b5cf6;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="crystiInner" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#ffffff;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:rgba(255,255,255,0.3);stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<linearGradient id="crystiFacet1" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0%" style="stop-color:#fbbf24;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#f59e0b;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
<linearGradient id="crystiFacet2" x1="1" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" style="stop-color:#f472b6;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#ec4899;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
<linearGradient id="crystiFacet3" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0%" style="stop-color:#34d399;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#10b981;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
<linearGradient id="crystiFacet4" x1="0" y1="1" x2="1" y2="0">
|
||||
<stop offset="0%" style="stop-color:#06b6d4;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#0891b2;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
<linearGradient id="crystiFacet5" x1="1" y1="1" x2="0" y2="0">
|
||||
<stop offset="0%" style="stop-color:#a78bfa;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#7c3aed;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
<linearGradient id="crystiFacet6" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0%" style="stop-color:#fb7185;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#e11d48;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
<radialGradient id="crystiEye" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#ffffff;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#e9d5ff;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<linearGradient id="crystiSmile" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0%" style="stop-color:#8b5cf6;stop-opacity:1" />
|
||||
<stop offset="50%" style="stop-color:#c084fc;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#8b5cf6;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<!-- Main crystal body - rounded hexagon shape -->
|
||||
<path d="M 100 50 L 140 80 L 140 130 L 100 160 L 60 130 L 60 80 Z" fill="url(#crystiBody)" />
|
||||
<path d="M 100 55 L 135 82 L 135 128 L 100 155 L 65 128 L 65 82 Z" fill="url(#crystiInner)" opacity="0.7" />
|
||||
|
||||
<!-- Crystal segments with rounded edges -->
|
||||
<path d="M 100 50 L 125 70 L 100 105 L 75 70 Z" fill="url(#crystiFacet1)" opacity="0.8" />
|
||||
<path d="M 75 70 L 100 105 L 60 80 L 60 105 Z" fill="url(#crystiFacet2)" opacity="0.7" />
|
||||
<path d="M 125 70 L 140 80 L 140 105 L 100 105 Z" fill="url(#crystiFacet3)" opacity="0.7" />
|
||||
<path d="M 60 105 L 100 105 L 75 140 L 60 130 Z" fill="url(#crystiFacet4)" opacity="0.6" />
|
||||
<path d="M 100 105 L 140 105 L 125 140 L 100 105 Z" fill="url(#crystiFacet5)" opacity="0.6" />
|
||||
<path d="M 75 140 L 100 105 L 125 140 L 100 160 Z" fill="url(#crystiFacet6)" opacity="0.8" />
|
||||
|
||||
<!-- Eyes (white base) -->
|
||||
<circle cx="88" cy="95" r="10" fill="url(#crystiEye)" />
|
||||
<circle cx="112" cy="95" r="10" fill="url(#crystiEye)" />
|
||||
|
||||
<!-- Pupils (dark circles + highlights) -->
|
||||
<circle cx="88" cy="95" r="6" fill="#1e1b4b" />
|
||||
<circle cx="112" cy="95" r="6" fill="#1e1b4b" />
|
||||
<circle cx="90" cy="93" r="3" fill="white" />
|
||||
<circle cx="114" cy="93" r="3" fill="white" />
|
||||
|
||||
<!-- Mouth -->
|
||||
<path d="M 90 115 Q 100 123 110 115" stroke="url(#crystiSmile)" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Floating sparkles -->
|
||||
<circle cx="65" cy="65" r="2" fill="#fbbf24" opacity="0.9" />
|
||||
<circle cx="135" cy="70" r="1.5" fill="#f472b6" opacity="0.8" />
|
||||
<circle cx="70" cy="140" r="1" fill="#06b6d4" opacity="0.7" />
|
||||
<circle cx="130" cy="135" r="2" fill="#fbbf24" opacity="0.6" />
|
||||
<circle cx="50" cy="105" r="1.5" fill="#f472b6" opacity="0.8" />
|
||||
<circle cx="150" cy="110" r="1" fill="#06b6d4" opacity="0.9" />
|
||||
<circle cx="100" cy="40" r="1.5" fill="#fbbf24" opacity="0.7" />
|
||||
<circle cx="100" cy="170" r="1" fill="#f472b6" opacity="0.8" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.5 KiB |
@@ -0,0 +1,89 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<!-- Crystal gradients -->
|
||||
<radialGradient id="crystiBody" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#f3e8ff;stop-opacity:1" />
|
||||
<stop offset="30%" style="stop-color:#e9d5ff;stop-opacity:1" />
|
||||
<stop offset="70%" style="stop-color:#c084fc;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#8b5cf6;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="crystiInner" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#ffffff;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:rgba(255,255,255,0.3);stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<linearGradient id="crystiFacet1" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0%" style="stop-color:#fbbf24;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#f59e0b;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
<linearGradient id="crystiFacet2" x1="1" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" style="stop-color:#f472b6;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#ec4899;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
<linearGradient id="crystiFacet3" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0%" style="stop-color:#34d399;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#10b981;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
<linearGradient id="crystiFacet4" x1="0" y1="1" x2="1" y2="0">
|
||||
<stop offset="0%" style="stop-color:#06b6d4;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#0891b2;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
<linearGradient id="crystiFacet5" x1="1" y1="1" x2="0" y2="0">
|
||||
<stop offset="0%" style="stop-color:#a78bfa;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#7c3aed;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
<linearGradient id="crystiFacet6" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0%" style="stop-color:#fb7185;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#e11d48;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
<radialGradient id="crystiEye" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#ffffff;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#e9d5ff;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<linearGradient id="crystiSmile" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0%" style="stop-color:#8b5cf6;stop-opacity:1" />
|
||||
<stop offset="50%" style="stop-color:#c084fc;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#8b5cf6;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<!-- Main crystal body - rounded hexagon shape -->
|
||||
<path d="M 100 50 L 140 80 L 140 130 L 100 160 L 60 130 L 60 80 Z" fill="url(#crystiBody)" />
|
||||
<path d="M 100 55 L 135 82 L 135 128 L 100 155 L 65 128 L 65 82 Z" fill="url(#crystiInner)" opacity="0.7" />
|
||||
|
||||
<!-- Crystal segments with rounded edges -->
|
||||
<path d="M 100 50 L 125 70 L 100 105 L 75 70 Z" fill="url(#crystiFacet1)" opacity="0.6" />
|
||||
<path d="M 75 70 L 100 105 L 60 80 L 60 105 Z" fill="url(#crystiFacet2)" opacity="0.5" />
|
||||
<path d="M 125 70 L 140 80 L 140 105 L 100 105 Z" fill="url(#crystiFacet3)" opacity="0.5" />
|
||||
<path d="M 60 105 L 100 105 L 75 140 L 60 130 Z" fill="url(#crystiFacet4)" opacity="0.4" />
|
||||
<path d="M 100 105 L 140 105 L 125 140 L 100 105 Z" fill="url(#crystiFacet5)" opacity="0.4" />
|
||||
<path d="M 75 140 L 100 105 L 125 140 L 100 160 Z" fill="url(#crystiFacet6)" opacity="0.6" />
|
||||
|
||||
<!-- Sleeping eyes -->
|
||||
<path d="M 78 95 Q 88 98 98 95" stroke="#1e1b4b" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
<path d="M 102 95 Q 112 98 122 95" stroke="#1e1b4b" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Peaceful mouth -->
|
||||
<circle cx="100" cy="115" r="2" fill="#8b5cf6" />
|
||||
|
||||
<!-- Floating sparkles with gentle animation -->
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate" from="0 100 100" to="360 100 100" dur="15s" repeatCount="indefinite" />
|
||||
<circle cx="65" cy="65" r="2" fill="#fbbf24" opacity="0.6" />
|
||||
<circle cx="135" cy="70" r="1.5" fill="#f472b6" opacity="0.5" />
|
||||
<circle cx="70" cy="140" r="1" fill="#06b6d4" opacity="0.4" />
|
||||
<circle cx="130" cy="135" r="2" fill="#fbbf24" opacity="0.3" />
|
||||
</g>
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate" from="0 100 100" to="-360 100 100" dur="20s" repeatCount="indefinite" />
|
||||
<circle cx="50" cy="105" r="1.5" fill="#f472b6" opacity="0.5" />
|
||||
<circle cx="150" cy="110" r="1" fill="#06b6d4" opacity="0.6" />
|
||||
<circle cx="100" cy="40" r="1.5" fill="#fbbf24" opacity="0.4" />
|
||||
<circle cx="100" cy="170" r="1" fill="#f472b6" opacity="0.5" />
|
||||
</g>
|
||||
|
||||
<!-- "Zzz" sleeping -->
|
||||
<text x="150" y="60" font-size="10" fill="#666" opacity="0.8">Z</text>
|
||||
<text x="157" y="55" font-size="8" fill="#666" opacity="0.6">z</text>
|
||||
<text x="162" y="51" font-size="6" fill="#666" opacity="0.4">z</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,89 @@
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<!-- Water gradients -->
|
||||
<radialGradient id="droppiBody" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#67e8f9;stop-opacity:1" />
|
||||
<stop offset="30%" style="stop-color:#22d3ee;stop-opacity:1" />
|
||||
<stop offset="70%" style="stop-color:#06b6d4;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#0891b2;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="droppiInner" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#e0f2fe;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#7dd3fc;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="droppiHighlight" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#ffffff;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:rgba(255,255,255,0.3);stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="droppiArm" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#22d3ee;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#0891b2;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="droppiLeg" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#06b6d4;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#0284c7;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="droppiDroplet" cx="0.5" cy="0.5">
|
||||
<stop offset="0%" style="stop-color:#7dd3fc;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#06b6d4;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
|
||||
<!-- Main water drop body -->
|
||||
<path d="M 100 40 Q 100 30 100 40 Q 135 60 140 110 Q 140 150 100 165 Q 60 150 60 110 Q 65 60 100 40"
|
||||
fill="url(#droppiBody)" />
|
||||
|
||||
<!-- Inner water reflection -->
|
||||
<ellipse cx="100" cy="100" rx="35" ry="45" fill="url(#droppiInner)" opacity="0.6" />
|
||||
<ellipse cx="90" cy="80" rx="20" ry="25" fill="url(#droppiHighlight)" opacity="0.7" />
|
||||
|
||||
<!-- Eyes (white base) -->
|
||||
<circle cx="85" cy="95" r="12" fill="white" />
|
||||
<circle cx="115" cy="95" r="12" fill="white" />
|
||||
|
||||
<!-- Pupils (dark circles + highlights) -->
|
||||
<circle cx="85" cy="95" r="8" fill="#0891b2" />
|
||||
<circle cx="115" cy="95" r="8" fill="#0891b2" />
|
||||
<circle cx="88" cy="92" r="4" fill="white" />
|
||||
<circle cx="118" cy="92" r="4" fill="white" />
|
||||
|
||||
<!-- Mouth -->
|
||||
<path d="M 88 115 Q 100 123 112 115" stroke="#0891b2" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Little arms -->
|
||||
<ellipse cx="60" cy="110" rx="10" ry="18" fill="url(#droppiArm)" transform="rotate(-25 60 110)" />
|
||||
<ellipse cx="140" cy="110" rx="10" ry="18" fill="url(#droppiArm)" transform="rotate(25 140 110)" />
|
||||
|
||||
<!-- Little legs -->
|
||||
<ellipse cx="85" cy="160" rx="12" ry="10" fill="url(#droppiLeg)" />
|
||||
<ellipse cx="115" cy="160" rx="12" ry="10" fill="url(#droppiLeg)" />
|
||||
|
||||
<!-- Water droplets floating around - grouped with rotation -->
|
||||
<g transform="translate(100 110)">
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate" from="0" to="360" dur="8s" repeatCount="indefinite" />
|
||||
<circle cx="-45" cy="-35" r="3" fill="url(#droppiDroplet)" opacity="0.8" />
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<g transform="translate(100 110)">
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate" from="0" to="-360" dur="9s" repeatCount="indefinite" />
|
||||
<circle cx="45" cy="-30" r="2.5" fill="url(#droppiDroplet)" opacity="0.6" />
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<g transform="translate(100 110)">
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate" from="0" to="360" dur="7s" repeatCount="indefinite" />
|
||||
<circle cx="-50" cy="25" r="2" fill="url(#droppiDroplet)" opacity="0.7" />
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<g transform="translate(100 110)">
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate" from="0" to="-360" dur="10s" repeatCount="indefinite" />
|
||||
<circle cx="50" cy="20" r="2.5" fill="url(#droppiDroplet)" opacity="0.5" />
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.9 KiB |
@@ -0,0 +1,88 @@
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<!-- Water gradients -->
|
||||
<radialGradient id="droppiBody" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#67e8f9;stop-opacity:1" />
|
||||
<stop offset="30%" style="stop-color:#22d3ee;stop-opacity:1" />
|
||||
<stop offset="70%" style="stop-color:#06b6d4;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#0891b2;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="droppiInner" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#e0f2fe;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#7dd3fc;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="droppiHighlight" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#ffffff;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:rgba(255,255,255,0.3);stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="droppiArm" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#22d3ee;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#0891b2;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="droppiLeg" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#06b6d4;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#0284c7;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="droppiDroplet" cx="0.5" cy="0.5">
|
||||
<stop offset="0%" style="stop-color:#7dd3fc;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#06b6d4;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
|
||||
<!-- Main water drop body -->
|
||||
<path d="M 100 40 Q 100 30 100 40 Q 135 60 140 110 Q 140 150 100 165 Q 60 150 60 110 Q 65 60 100 40"
|
||||
fill="url(#droppiBody)" />
|
||||
|
||||
<!-- Inner water reflection -->
|
||||
<ellipse cx="100" cy="100" rx="35" ry="45" fill="url(#droppiInner)" opacity="0.6" />
|
||||
<ellipse cx="90" cy="80" rx="20" ry="25" fill="url(#droppiHighlight)" opacity="0.7" />
|
||||
|
||||
<!-- Sleeping eyes -->
|
||||
<path d="M 73 95 Q 85 98 97 95" stroke="#0891b2" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
<path d="M 103 95 Q 115 98 127 95" stroke="#0891b2" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Peaceful mouth -->
|
||||
<circle cx="100" cy="115" r="2" fill="#0891b2" />
|
||||
|
||||
<!-- Little arms -->
|
||||
<ellipse cx="60" cy="110" rx="10" ry="18" fill="url(#droppiArm)" transform="rotate(-25 60 110)" />
|
||||
<ellipse cx="140" cy="110" rx="10" ry="18" fill="url(#droppiArm)" transform="rotate(25 140 110)" />
|
||||
|
||||
<!-- Little legs -->
|
||||
<ellipse cx="85" cy="160" rx="12" ry="10" fill="url(#droppiLeg)" />
|
||||
<ellipse cx="115" cy="160" rx="12" ry="10" fill="url(#droppiLeg)" />
|
||||
|
||||
<!-- Water droplets floating around - grouped with slower rotation -->
|
||||
<g transform="translate(100 110)">
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate" from="0" to="360" dur="12s" repeatCount="indefinite" />
|
||||
<circle cx="-45" cy="-35" r="3" fill="url(#droppiDroplet)" opacity="0.5" />
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<g transform="translate(100 110)">
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate" from="0" to="-360" dur="15s" repeatCount="indefinite" />
|
||||
<circle cx="45" cy="-30" r="2.5" fill="url(#droppiDroplet)" opacity="0.4" />
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<g transform="translate(100 110)">
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate" from="0" to="360" dur="10s" repeatCount="indefinite" />
|
||||
<circle cx="-50" cy="25" r="2" fill="url(#droppiDroplet)" opacity="0.4" />
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<g transform="translate(100 110)">
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate" from="0" to="-360" dur="18s" repeatCount="indefinite" />
|
||||
<circle cx="50" cy="20" r="2.5" fill="url(#droppiDroplet)" opacity="0.3" />
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<!-- "Zzz" sleeping -->
|
||||
<text x="150" y="60" font-size="10" fill="#666" opacity="0.8">Z</text>
|
||||
<text x="157" y="55" font-size="8" fill="#666" opacity="0.6">z</text>
|
||||
<text x="162" y="51" font-size="6" fill="#666" opacity="0.4">z</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
@@ -0,0 +1,76 @@
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<defs>
|
||||
<!-- Flame gradients -->
|
||||
<radialGradient id="flammiBody" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#fbbf24" />
|
||||
<stop offset="30%" stop-color="#f97316" />
|
||||
<stop offset="70%" stop-color="#ef4444" />
|
||||
<stop offset="100%" stop-color="#dc2626" />
|
||||
</radialGradient>
|
||||
<radialGradient id="flammiInner" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" stop-color="#fde047" />
|
||||
<stop offset="50%" stop-color="#fbbf24" />
|
||||
<stop offset="100%" stop-color="#f97316" />
|
||||
</radialGradient>
|
||||
<radialGradient id="flammiCore" cx="0.5" cy="0.4">
|
||||
<stop offset="0%" stop-color="#fef3c7" />
|
||||
<stop offset="100%" stop-color="#fde047" />
|
||||
</radialGradient>
|
||||
<radialGradient id="flammiArm" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#f97316" />
|
||||
<stop offset="100%" stop-color="#dc2626" />
|
||||
</radialGradient>
|
||||
<radialGradient id="flammiLeg" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#ef4444" />
|
||||
<stop offset="100%" stop-color="#b91c1c" />
|
||||
</radialGradient>
|
||||
<radialGradient id="flammiEmber" cx="0.5" cy="0.5">
|
||||
<stop offset="0%" stop-color="#fde047" />
|
||||
<stop offset="100%" stop-color="#f97316" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
|
||||
<!-- Larger rotating flames -->
|
||||
<g transform="rotate(0 100 110)">
|
||||
<path d="M45 80 Q50 65 55 80 Q50 90 45 80 Z" fill="url(#flammiEmber)" opacity="0.8" />
|
||||
<animateTransform attributeName="transform" type="rotate" from="0 100 110" to="360 100 110" dur="4s" repeatCount="indefinite" />
|
||||
</g>
|
||||
<g transform="rotate(0 100 110)">
|
||||
<path d="M155 85 Q160 70 165 85 Q160 95 155 85 Z" fill="url(#flammiEmber)" opacity="0.6" />
|
||||
<animateTransform attributeName="transform" type="rotate" from="0 100 110" to="-360 100 110" dur="6s" repeatCount="indefinite" />
|
||||
</g>
|
||||
<g transform="rotate(0 100 110)">
|
||||
<path d="M40 130 Q45 115 50 130 Q45 140 40 130 Z" fill="url(#flammiEmber)" opacity="0.7" />
|
||||
<animateTransform attributeName="transform" type="rotate" from="0 100 110" to="360 100 110" dur="7s" repeatCount="indefinite" />
|
||||
</g>
|
||||
<g transform="rotate(0 100 110)">
|
||||
<path d="M160 125 Q165 110 170 125 Q165 135 160 125 Z" fill="url(#flammiEmber)" opacity="0.5" />
|
||||
<animateTransform attributeName="transform" type="rotate" from="0 100 110" to="-360 100 110" dur="5s" repeatCount="indefinite" />
|
||||
</g>
|
||||
|
||||
<!-- Flammy Body -->
|
||||
<path d="M 100 160 Q 60 140 50 110 Q 45 80 70 60 Q 80 40 100 25 Q 120 40 130 60 Q 155 80 150 110 Q 140 140 100 160 Z" fill="url(#flammiBody)" />
|
||||
<path d="M 100 155 Q 65 138 58 115 Q 55 90 75 70 Q 82 50 100 35 Q 118 50 125 70 Q 145 90 142 115 Q 135 138 100 155 Z" fill="url(#flammiInner)" opacity="0.8" />
|
||||
<path d="M 100 145 Q 70 130 65 110 Q 62 95 80 80 Q 85 65 100 55 Q 115 65 120 80 Q 138 95 135 110 Q 130 130 100 145 Z" fill="url(#flammiCore)" opacity="0.9" />
|
||||
|
||||
<!-- Eyes (white base) -->
|
||||
<circle cx="88" cy="100" r="10" fill="white" />
|
||||
<circle cx="112" cy="100" r="10" fill="white" />
|
||||
|
||||
<!-- Pupils (dark circles + highlights) -->
|
||||
<circle cx="88" cy="100" r="6" fill="#1f2937" />
|
||||
<circle cx="112" cy="100" r="6" fill="#1f2937" />
|
||||
<circle cx="90" cy="98" r="3" fill="white" />
|
||||
<circle cx="114" cy="98" r="3" fill="white" />
|
||||
|
||||
<!-- Mouth -->
|
||||
<path d="M 88 115 Q 100 125 112 115" stroke="#1f2937" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Arms -->
|
||||
<ellipse cx="55" cy="110" rx="8" ry="15" fill="url(#flammiArm)" transform="rotate(-30 55 110)" />
|
||||
<ellipse cx="145" cy="110" rx="8" ry="15" fill="url(#flammiArm)" transform="rotate(30 145 110)" />
|
||||
|
||||
<!-- Legs -->
|
||||
<ellipse cx="90" cy="155" rx="10" ry="8" fill="url(#flammiLeg)" />
|
||||
<ellipse cx="110" cy="155" rx="10" ry="8" fill="url(#flammiLeg)" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.8 KiB |
@@ -0,0 +1,75 @@
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<defs>
|
||||
<!-- Flame gradients -->
|
||||
<radialGradient id="flammiBody" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#fbbf24" />
|
||||
<stop offset="30%" stop-color="#f97316" />
|
||||
<stop offset="70%" stop-color="#ef4444" />
|
||||
<stop offset="100%" stop-color="#dc2626" />
|
||||
</radialGradient>
|
||||
<radialGradient id="flammiInner" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" stop-color="#fde047" />
|
||||
<stop offset="50%" stop-color="#fbbf24" />
|
||||
<stop offset="100%" stop-color="#f97316" />
|
||||
</radialGradient>
|
||||
<radialGradient id="flammiCore" cx="0.5" cy="0.4">
|
||||
<stop offset="0%" stop-color="#fef3c7" />
|
||||
<stop offset="100%" stop-color="#fde047" />
|
||||
</radialGradient>
|
||||
<radialGradient id="flammiArm" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#f97316" />
|
||||
<stop offset="100%" stop-color="#dc2626" />
|
||||
</radialGradient>
|
||||
<radialGradient id="flammiLeg" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#ef4444" />
|
||||
<stop offset="100%" stop-color="#b91c1c" />
|
||||
</radialGradient>
|
||||
<radialGradient id="flammiEmber" cx="0.5" cy="0.5">
|
||||
<stop offset="0%" stop-color="#fde047" />
|
||||
<stop offset="100%" stop-color="#f97316" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
|
||||
<!-- Slower rotating flames for sleeping state -->
|
||||
<g transform="rotate(0 100 110)">
|
||||
<path d="M45 80 Q50 65 55 80 Q50 90 45 80 Z" fill="url(#flammiEmber)" opacity="0.5" />
|
||||
<animateTransform attributeName="transform" type="rotate" from="0 100 110" to="360 100 110" dur="8s" repeatCount="indefinite" />
|
||||
</g>
|
||||
<g transform="rotate(0 100 110)">
|
||||
<path d="M155 85 Q160 70 165 85 Q160 95 155 85 Z" fill="url(#flammiEmber)" opacity="0.4" />
|
||||
<animateTransform attributeName="transform" type="rotate" from="0 100 110" to="-360 100 110" dur="12s" repeatCount="indefinite" />
|
||||
</g>
|
||||
<g transform="rotate(0 100 110)">
|
||||
<path d="M40 130 Q45 115 50 130 Q45 140 40 130 Z" fill="url(#flammiEmber)" opacity="0.4" />
|
||||
<animateTransform attributeName="transform" type="rotate" from="0 100 110" to="360 100 110" dur="14s" repeatCount="indefinite" />
|
||||
</g>
|
||||
<g transform="rotate(0 100 110)">
|
||||
<path d="M160 125 Q165 110 170 125 Q165 135 160 125 Z" fill="url(#flammiEmber)" opacity="0.3" />
|
||||
<animateTransform attributeName="transform" type="rotate" from="0 100 110" to="-360 100 110" dur="10s" repeatCount="indefinite" />
|
||||
</g>
|
||||
|
||||
<!-- Flammy Body -->
|
||||
<path d="M 100 160 Q 60 140 50 110 Q 45 80 70 60 Q 80 40 100 25 Q 120 40 130 60 Q 155 80 150 110 Q 140 140 100 160 Z" fill="url(#flammiBody)" />
|
||||
<path d="M 100 155 Q 65 138 58 115 Q 55 90 75 70 Q 82 50 100 35 Q 118 50 125 70 Q 145 90 142 115 Q 135 138 100 155 Z" fill="url(#flammiInner)" opacity="0.8" />
|
||||
<path d="M 100 145 Q 70 130 65 110 Q 62 95 80 80 Q 85 65 100 55 Q 115 65 120 80 Q 138 95 135 110 Q 130 130 100 145 Z" fill="url(#flammiCore)" opacity="0.9" />
|
||||
|
||||
<!-- Sleeping eyes -->
|
||||
<path d="M 78 100 Q 88 103 98 100" stroke="#1f2937" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
<path d="M 102 100 Q 112 103 122 100" stroke="#1f2937" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Peaceful mouth -->
|
||||
<circle cx="100" cy="115" r="2" fill="#1f2937" />
|
||||
|
||||
<!-- Arms -->
|
||||
<ellipse cx="55" cy="110" rx="8" ry="15" fill="url(#flammiArm)" transform="rotate(-30 55 110)" />
|
||||
<ellipse cx="145" cy="110" rx="8" ry="15" fill="url(#flammiArm)" transform="rotate(30 145 110)" />
|
||||
|
||||
<!-- Legs -->
|
||||
<ellipse cx="90" cy="155" rx="10" ry="8" fill="url(#flammiLeg)" />
|
||||
<ellipse cx="110" cy="155" rx="10" ry="8" fill="url(#flammiLeg)" />
|
||||
|
||||
<!-- "Zzz" sleeping -->
|
||||
<text x="150" y="60" font-size="10" fill="#666" opacity="0.8">Z</text>
|
||||
<text x="157" y="55" font-size="8" fill="#666" opacity="0.6">z</text>
|
||||
<text x="162" y="51" font-size="6" fill="#666" opacity="0.4">z</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.8 KiB |
@@ -0,0 +1,101 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<!-- Gradients for 3D effect -->
|
||||
<radialGradient id="froggiBody3D" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#86efac;stop-opacity:1" />
|
||||
<stop offset="40%" style="stop-color:#22c55e;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#15803d;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="froggiEyeBase3D" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#4ade80;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#16a34a;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="froggiEyeWhite3D" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#ffffff;stop-opacity:1" />
|
||||
<stop offset="70%" style="stop-color:#f5f5f4;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#e7e5e4;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="froggiPupil3D" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#374151;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#1e293b;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<linearGradient id="froggiMouth3D" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0%" style="stop-color:#374151;stop-opacity:1" />
|
||||
<stop offset="50%" style="stop-color:#1e293b;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#374151;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
<linearGradient id="froggiMouthHighlight" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0%" style="stop-color:rgba(255,255,255,0.3);stop-opacity:1" />
|
||||
<stop offset="50%" style="stop-color:rgba(255,255,255,0.1);stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:rgba(255,255,255,0.3);stop-opacity:1" />
|
||||
</linearGradient>
|
||||
<radialGradient id="froggiNostril3D" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#16a34a;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#14532d;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="froggiNostrilHighlight" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#4ade80;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#16a34a;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="froggiFeet3D" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#4ade80;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#16a34a;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="froggiFeetHighlight" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#86efac;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#4ade80;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<linearGradient id="froggiToe3D" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0%" style="stop-color:#16a34a;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#14532d;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<!-- Flattened oval body -->
|
||||
<ellipse cx="100" cy="120" rx="70" ry="50" fill="url(#froggiBody3D)" />
|
||||
|
||||
<!-- Big circular pop-out eyes -->
|
||||
<circle cx="70" cy="80" r="27" fill="url(#froggiEyeBase3D)" />
|
||||
<circle cx="130" cy="80" r="27" fill="url(#froggiEyeBase3D)" />
|
||||
|
||||
<!-- Eyes (white/base eye shapes) -->
|
||||
<circle cx="70" cy="80" r="22" fill="url(#froggiEyeWhite3D)" />
|
||||
<circle cx="130" cy="80" r="22" fill="url(#froggiEyeWhite3D)" />
|
||||
|
||||
<!-- Pupils (pupil + highlights) -->
|
||||
<circle cx="70" cy="80" r="16" fill="url(#froggiPupil3D)" />
|
||||
<circle cx="130" cy="80" r="16" fill="url(#froggiPupil3D)" />
|
||||
<circle cx="74" cy="76" r="6" fill="white" opacity="0.9" />
|
||||
<circle cx="134" cy="76" r="6" fill="white" opacity="0.9" />
|
||||
|
||||
<!-- Mouth -->
|
||||
<path d="M 45 120 Q 100 145 155 120" stroke="url(#froggiMouth3D)" stroke-width="5" fill="none" stroke-linecap="round" />
|
||||
<path d="M 50 122 Q 100 142 150 122" stroke="url(#froggiMouthHighlight)" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Enhanced nostrils -->
|
||||
<ellipse cx="90" cy="110" rx="4" ry="6" fill="url(#froggiNostril3D)" />
|
||||
<ellipse cx="110" cy="110" rx="4" ry="6" fill="url(#froggiNostril3D)" />
|
||||
<ellipse cx="90" cy="108" rx="2" ry="3" fill="url(#froggiNostrilHighlight)" />
|
||||
<ellipse cx="110" cy="108" rx="2" ry="3" fill="url(#froggiNostrilHighlight)" />
|
||||
|
||||
<!-- Enhanced webbed feet -->
|
||||
<ellipse cx="60" cy="160" rx="22" ry="12" fill="url(#froggiFeet3D)" />
|
||||
<ellipse cx="140" cy="160" rx="22" ry="12" fill="url(#froggiFeet3D)" />
|
||||
<ellipse cx="60" cy="158" rx="18" ry="8" fill="url(#froggiFeetHighlight)" />
|
||||
<ellipse cx="140" cy="158" rx="18" ry="8" fill="url(#froggiFeetHighlight)" />
|
||||
|
||||
<!-- Enhanced webbed toes -->
|
||||
<path d="M 43 160 Q 47 155 52 160" stroke="url(#froggiToe3D)" stroke-width="2.5" fill="none" stroke-linecap="round" />
|
||||
<path d="M 53 160 Q 57 155 62 160" stroke="url(#froggiToe3D)" stroke-width="2.5" fill="none" stroke-linecap="round" />
|
||||
<path d="M 63 160 Q 67 155 72 160" stroke="url(#froggiToe3D)" stroke-width="2.5" fill="none" stroke-linecap="round" />
|
||||
<path d="M 123 160 Q 127 155 132 160" stroke="url(#froggiToe3D)" stroke-width="2.5" fill="none" stroke-linecap="round" />
|
||||
<path d="M 133 160 Q 137 155 142 160" stroke="url(#froggiToe3D)" stroke-width="2.5" fill="none" stroke-linecap="round" />
|
||||
<path d="M 143 160 Q 147 155 152 160" stroke="url(#froggiToe3D)" stroke-width="2.5" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Soft skin texture details -->
|
||||
<ellipse cx="75" cy="135" rx="4" ry="3" fill="rgba(255,255,255,0.2)" />
|
||||
<ellipse cx="125" cy="130" rx="3.5" ry="2.5" fill="rgba(255,255,255,0.2)" />
|
||||
<ellipse cx="85" cy="145" rx="3" ry="2" fill="rgba(255,255,255,0.15)" />
|
||||
<ellipse cx="115" cy="140" rx="3.5" ry="2.5" fill="rgba(255,255,255,0.15)" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 5.7 KiB |
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<!-- Gradients for 3D effect -->
|
||||
<radialGradient id="froggiBody3D" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#86efac;stop-opacity:1" />
|
||||
<stop offset="40%" style="stop-color:#22c55e;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#15803d;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="froggiEyeBase3D" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#4ade80;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#16a34a;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="froggiEyeWhite3D" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#ffffff;stop-opacity:1" />
|
||||
<stop offset="70%" style="stop-color:#f5f5f4;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#e7e5e4;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="froggiPupil3D" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#374151;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#1e293b;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<linearGradient id="froggiMouth3D" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0%" style="stop-color:#374151;stop-opacity:1" />
|
||||
<stop offset="50%" style="stop-color:#1e293b;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#374151;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
<linearGradient id="froggiMouthHighlight" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0%" style="stop-color:rgba(255,255,255,0.3);stop-opacity:1" />
|
||||
<stop offset="50%" style="stop-color:rgba(255,255,255,0.1);stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:rgba(255,255,255,0.3);stop-opacity:1" />
|
||||
</linearGradient>
|
||||
<radialGradient id="froggiNostril3D" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#16a34a;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#14532d;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="froggiNostrilHighlight" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#4ade80;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#16a34a;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="froggiFeet3D" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" style="stop-color:#4ade80;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#16a34a;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<radialGradient id="froggiFeetHighlight" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" style="stop-color:#86efac;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#4ade80;stop-opacity:1" />
|
||||
</radialGradient>
|
||||
<linearGradient id="froggiToe3D" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0%" style="stop-color:#16a34a;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#14532d;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<!-- Flattened oval body -->
|
||||
<ellipse cx="100" cy="120" rx="70" ry="50" fill="url(#froggiBody3D)" />
|
||||
|
||||
<!-- Big circular pop-out eyes -->
|
||||
<circle cx="70" cy="80" r="27" fill="url(#froggiEyeBase3D)" />
|
||||
<circle cx="130" cy="80" r="27" fill="url(#froggiEyeBase3D)" />
|
||||
|
||||
<!-- Sleeping eyes -->
|
||||
<path d="M 54 80 Q 70 83 86 80" stroke="#1e293b" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
<path d="M 114 80 Q 130 83 146 80" stroke="#1e293b" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Peaceful mouth -->
|
||||
<circle cx="100" cy="125" r="2" fill="#1e293b" />
|
||||
|
||||
<!-- Enhanced nostrils -->
|
||||
<ellipse cx="90" cy="110" rx="4" ry="6" fill="url(#froggiNostril3D)" />
|
||||
<ellipse cx="110" cy="110" rx="4" ry="6" fill="url(#froggiNostril3D)" />
|
||||
<ellipse cx="90" cy="108" rx="2" ry="3" fill="url(#froggiNostrilHighlight)" />
|
||||
<ellipse cx="110" cy="108" rx="2" ry="3" fill="url(#froggiNostrilHighlight)" />
|
||||
|
||||
<!-- Enhanced webbed feet -->
|
||||
<ellipse cx="60" cy="160" rx="22" ry="12" fill="url(#froggiFeet3D)" />
|
||||
<ellipse cx="140" cy="160" rx="22" ry="12" fill="url(#froggiFeet3D)" />
|
||||
<ellipse cx="60" cy="158" rx="18" ry="8" fill="url(#froggiFeetHighlight)" />
|
||||
<ellipse cx="140" cy="158" rx="18" ry="8" fill="url(#froggiFeetHighlight)" />
|
||||
|
||||
<!-- Enhanced webbed toes -->
|
||||
<path d="M 43 160 Q 47 155 52 160" stroke="url(#froggiToe3D)" stroke-width="2.5" fill="none" stroke-linecap="round" />
|
||||
<path d="M 53 160 Q 57 155 62 160" stroke="url(#froggiToe3D)" stroke-width="2.5" fill="none" stroke-linecap="round" />
|
||||
<path d="M 63 160 Q 67 155 72 160" stroke="url(#froggiToe3D)" stroke-width="2.5" fill="none" stroke-linecap="round" />
|
||||
<path d="M 123 160 Q 127 155 132 160" stroke="url(#froggiToe3D)" stroke-width="2.5" fill="none" stroke-linecap="round" />
|
||||
<path d="M 133 160 Q 137 155 142 160" stroke="url(#froggiToe3D)" stroke-width="2.5" fill="none" stroke-linecap="round" />
|
||||
<path d="M 143 160 Q 147 155 152 160" stroke="url(#froggiToe3D)" stroke-width="2.5" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Soft skin texture details -->
|
||||
<ellipse cx="75" cy="135" rx="4" ry="3" fill="rgba(255,255,255,0.2)" />
|
||||
<ellipse cx="125" cy="130" rx="3.5" ry="2.5" fill="rgba(255,255,255,0.2)" />
|
||||
<ellipse cx="85" cy="145" rx="3" ry="2" fill="rgba(255,255,255,0.15)" />
|
||||
<ellipse cx="115" cy="140" rx="3.5" ry="2.5" fill="rgba(255,255,255,0.15)" />
|
||||
|
||||
<!-- "Zzz" sleeping -->
|
||||
<text x="150" y="60" font-size="10" fill="#666" opacity="0.8">Z</text>
|
||||
<text x="157" y="55" font-size="8" fill="#666" opacity="0.6">z</text>
|
||||
<text x="162" y="51" font-size="6" fill="#666" opacity="0.4">z</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 5.5 KiB |
@@ -0,0 +1,116 @@
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
<!-- Sunflower stem -->
|
||||
<rect x="96" y="120" width="8" height="55" fill="url(#leafyStem)" rx="4" />
|
||||
<rect x="98" y="125" width="4" height="50" fill="url(#leafyStemHighlight)" rx="2" opacity="0.6" />
|
||||
|
||||
<!-- Stem leaves -->
|
||||
<ellipse cx="85" cy="140" rx="15" ry="8" fill="url(#leafyStemLeaf)" transform="rotate(-30 85 140)" />
|
||||
<ellipse cx="115" cy="150" rx="15" ry="8" fill="url(#leafyStemLeaf)" transform="rotate(30 115 150)" />
|
||||
<ellipse cx="87" cy="140" rx="10" ry="5" fill="url(#leafyStemLeafHighlight)" transform="rotate(-30 87 140)" opacity="0.7" />
|
||||
<ellipse cx="113" cy="150" rx="10" ry="5" fill="url(#leafyStemLeafHighlight)" transform="rotate(30 113 150)" opacity="0.7" />
|
||||
|
||||
<!-- Sunflower petals - outer ring -->
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(0 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(22.5 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(45 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(67.5 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(90 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(112.5 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(135 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(157.5 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(180 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(202.5 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(225 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(247.5 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(270 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(292.5 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(315 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(337.5 100 85)" />
|
||||
|
||||
<!-- Sunflower center - outer ring -->
|
||||
<circle cx="100" cy="85" r="30" fill="url(#leafyCenter)" />
|
||||
<circle cx="100" cy="85" r="25" fill="url(#leafyCenterInner)" />
|
||||
|
||||
<!-- Eyes (white base) -->
|
||||
<circle cx="90" cy="82" r="8" fill="white" />
|
||||
<circle cx="110" cy="82" r="8" fill="white" />
|
||||
|
||||
<!-- Pupils (dark circles + highlights) -->
|
||||
<circle cx="90" cy="82" r="5" fill="#1f2937" />
|
||||
<circle cx="110" cy="82" r="5" fill="#1f2937" />
|
||||
<circle cx="92" cy="80" r="2" fill="white" />
|
||||
<circle cx="112" cy="80" r="2" fill="white" />
|
||||
|
||||
<!-- Mouth -->
|
||||
<path d="M 88 92 Q 100 100 112 92" stroke="#1f2937" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Floating pollen -->
|
||||
<circle cx="55" cy="60" r="2" fill="url(#leafyPollen)" opacity="0.8" />
|
||||
<circle cx="145" cy="65" r="1.5" fill="url(#leafyPollen)" opacity="0.6" />
|
||||
<circle cx="50" cy="110" r="1" fill="url(#leafyPollen)" opacity="0.7" />
|
||||
<circle cx="150" cy="105" r="2" fill="url(#leafyPollen)" opacity="0.5" />
|
||||
<circle cx="75" cy="45" r="1.5" fill="url(#leafyPollen)" opacity="0.9" />
|
||||
<circle cx="125" cy="50" r="1" fill="url(#leafyPollen)" opacity="0.8" />
|
||||
|
||||
<!-- Leavy pot -->
|
||||
<path d="M 75 160 L 80 175 L 120 175 L 125 160 Z" fill="url(#leafyPot)" />
|
||||
<rect x="75" y="160" width="50" height="5" fill="url(#leafyPotRim)" rx="2" />
|
||||
|
||||
<defs>
|
||||
<radialGradient id="leafyStem" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#22c55e" />
|
||||
<stop offset="100%" stop-color="#15803d" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyStemHighlight" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" stop-color="#4ade80" />
|
||||
<stop offset="100%" stop-color="#22c55e" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyStemLeaf" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#4ade80" />
|
||||
<stop offset="100%" stop-color="#16a34a" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyStemLeafHighlight" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" stop-color="#86efac" />
|
||||
<stop offset="100%" stop-color="#4ade80" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyPetal" cx="0.3" cy="0.3">
|
||||
<stop offset="100%" stop-color="#eab308" />
|
||||
<!-- <stop offset="70%" stop-color="#eab308" /> -->
|
||||
<stop offset="30%" stop-color="#fde047" />
|
||||
<stop offset="0%" stop-color="#ffce09" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyCenter" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#a16207" />
|
||||
<stop offset="50%" stop-color="#92400e" />
|
||||
<stop offset="100%" stop-color="#78350f" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyCenterInner" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" stop-color="#d97706" />
|
||||
<stop offset="100%" stop-color="#a16207" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafySeed" cx="0.5" cy="0.5">
|
||||
<stop offset="0%" stop-color="#451a03" />
|
||||
<stop offset="100%" stop-color="#292524" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyArm" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#4ade80" />
|
||||
<stop offset="100%" stop-color="#16a34a" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyRoot" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#a16207" />
|
||||
<stop offset="100%" stop-color="#78350f" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyPollen" cx="0.5" cy="0.5">
|
||||
<stop offset="0%" stop-color="#fef3c7" />
|
||||
<stop offset="100%" stop-color="#fde047" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyPot" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#dc2626" />
|
||||
<stop offset="100%" stop-color="#991b1b" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyPotRim" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#ef4444" />
|
||||
<stop offset="100%" stop-color="#dc2626" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 6.1 KiB |
@@ -0,0 +1,113 @@
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
<!-- Sunflower stem -->
|
||||
<rect x="96" y="120" width="8" height="55" fill="url(#leafyStem)" rx="4" />
|
||||
<rect x="98" y="125" width="4" height="50" fill="url(#leafyStemHighlight)" rx="2" opacity="0.6" />
|
||||
|
||||
<!-- Stem leaves -->
|
||||
<ellipse cx="85" cy="140" rx="15" ry="8" fill="url(#leafyStemLeaf)" transform="rotate(-30 85 140)" />
|
||||
<ellipse cx="115" cy="150" rx="15" ry="8" fill="url(#leafyStemLeaf)" transform="rotate(30 115 150)" />
|
||||
<ellipse cx="87" cy="140" rx="10" ry="5" fill="url(#leafyStemLeafHighlight)" transform="rotate(-30 87 140)" opacity="0.7" />
|
||||
<ellipse cx="113" cy="150" rx="10" ry="5" fill="url(#leafyStemLeafHighlight)" transform="rotate(30 113 150)" opacity="0.7" />
|
||||
|
||||
<!-- Sunflower petals - outer ring -->
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(0 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(22.5 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(45 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(67.5 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(90 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(112.5 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(135 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(157.5 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(180 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(202.5 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(225 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(247.5 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(270 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(292.5 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(315 100 85)" />
|
||||
<ellipse cx="100" cy="85" rx="45" ry="12" fill="url(#leafyPetal)" transform="rotate(337.5 100 85)" />
|
||||
|
||||
<!-- Sunflower center - outer ring -->
|
||||
<circle cx="100" cy="85" r="30" fill="url(#leafyCenter)" />
|
||||
<circle cx="100" cy="85" r="25" fill="url(#leafyCenterInner)" />
|
||||
|
||||
<!-- Sleeping eyes -->
|
||||
<path d="M 82 82 Q 90 85 98 82" stroke="#1f2937" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
<path d="M 102 82 Q 110 85 118 82" stroke="#1f2937" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Peaceful mouth -->
|
||||
<circle cx="100" cy="92" r="2" fill="#1f2937" />
|
||||
|
||||
<!-- Little arms - small leaves -->
|
||||
<ellipse cx="60" cy="85" rx="12" ry="6" fill="url(#leafyArm)" transform="rotate(-20 60 85)" />
|
||||
<ellipse cx="140" cy="85" rx="12" ry="6" fill="url(#leafyArm)" transform="rotate(20 140 85)" />
|
||||
|
||||
<!-- Base/roots -->
|
||||
<ellipse cx="95" cy="170" rx="8" ry="6" fill="url(#leafyRoot)" />
|
||||
<ellipse cx="105" cy="170" rx="8" ry="6" fill="url(#leafyRoot)" />
|
||||
|
||||
<!-- Floating pollen with gentle animation -->
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="translate" values="0,0; 2,3; 0,0" dur="4s" repeatCount="indefinite" />
|
||||
<circle cx="55" cy="60" r="2" fill="url(#leafyPollen)" opacity="0.5" />
|
||||
<circle cx="145" cy="65" r="1.5" fill="url(#leafyPollen)" opacity="0.4" />
|
||||
<circle cx="50" cy="110" r="1" fill="url(#leafyPollen)" opacity="0.4" />
|
||||
<circle cx="150" cy="105" r="2" fill="url(#leafyPollen)" opacity="0.3" />
|
||||
<circle cx="75" cy="45" r="1.5" fill="url(#leafyPollen)" opacity="0.6" />
|
||||
<circle cx="125" cy="50" r="1" fill="url(#leafyPollen)" opacity="0.5" />
|
||||
</g>
|
||||
|
||||
<!-- "Zzz" sleeping -->
|
||||
<text x="150" y="60" font-size="10" fill="#666" opacity="0.8">Z</text>
|
||||
<text x="157" y="55" font-size="8" fill="#666" opacity="0.6">z</text>
|
||||
<text x="162" y="51" font-size="6" fill="#666" opacity="0.4">z</text>
|
||||
|
||||
<defs>
|
||||
<radialGradient id="leafyStem" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#22c55e" />
|
||||
<stop offset="100%" stop-color="#15803d" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyStemHighlight" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" stop-color="#4ade80" />
|
||||
<stop offset="100%" stop-color="#22c55e" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyStemLeaf" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#4ade80" />
|
||||
<stop offset="100%" stop-color="#16a34a" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyStemLeafHighlight" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" stop-color="#86efac" />
|
||||
<stop offset="100%" stop-color="#4ade80" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyPetal" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#fef3c7" />
|
||||
<stop offset="30%" stop-color="#fde047" />
|
||||
<stop offset="100%" stop-color="#eab308" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyCenter" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#a16207" />
|
||||
<stop offset="50%" stop-color="#92400e" />
|
||||
<stop offset="100%" stop-color="#78350f" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyCenterInner" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" stop-color="#d97706" />
|
||||
<stop offset="100%" stop-color="#a16207" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafySeed" cx="0.5" cy="0.5">
|
||||
<stop offset="0%" stop-color="#451a03" />
|
||||
<stop offset="100%" stop-color="#292524" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyArm" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#4ade80" />
|
||||
<stop offset="100%" stop-color="#16a34a" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyRoot" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#a16207" />
|
||||
<stop offset="100%" stop-color="#78350f" />
|
||||
</radialGradient>
|
||||
<radialGradient id="leafyPollen" cx="0.5" cy="0.5">
|
||||
<stop offset="0%" stop-color="#fef3c7" />
|
||||
<stop offset="100%" stop-color="#fde047" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 6.2 KiB |
@@ -0,0 +1,72 @@
|
||||
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
|
||||
<!-- Mushroom stem -->
|
||||
<ellipse cx="100" cy="140" rx="25" ry="40" fill="url(#mushieStem)" />
|
||||
<ellipse cx="100" cy="135" rx="20" ry="35" fill="url(#mushieStemHighlight)" opacity="0.6" />
|
||||
|
||||
<!-- Mushroom cap -->
|
||||
<path d="M 50 110 Q 50 70 100 60 Q 150 70 150 110 Z" fill="url(#mushieCap)" />
|
||||
<path d="M 55 108 Q 55 75 100 65 Q 145 75 145 108 Z" fill="url(#mushieCapHighlight)" opacity="0.7" />
|
||||
|
||||
<!-- Cap spots -->
|
||||
<circle cx="80" cy="85" r="8" fill="white" opacity="0.8" />
|
||||
<circle cx="120" cy="80" r="10" fill="white" opacity="0.8" />
|
||||
<circle cx="100" cy="95" r="6" fill="white" opacity="0.7" />
|
||||
<circle cx="130" cy="100" r="5" fill="white" opacity="0.6" />
|
||||
<circle cx="70" cy="100" r="5" fill="white" opacity="0.6" />
|
||||
|
||||
<!-- Eyes (white base) -->
|
||||
<circle cx="88" cy="130" r="8" fill="white" />
|
||||
<circle cx="112" cy="130" r="8" fill="white" />
|
||||
|
||||
<!-- Pupils (dark circles + highlights) -->
|
||||
<circle cx="88" cy="130" r="5" fill="#1f2937" />
|
||||
<circle cx="112" cy="130" r="5" fill="#1f2937" />
|
||||
<circle cx="90" cy="128" r="2" fill="white" />
|
||||
<circle cx="114" cy="128" r="2" fill="white" />
|
||||
|
||||
<!-- Mouth -->
|
||||
<path d="M 88 145 Q 100 153 112 145" stroke="#1f2937" stroke-width="3" fill="none" stroke-linecap="round" />
|
||||
|
||||
<!-- Little arms -->
|
||||
<ellipse cx="70" cy="140" rx="8" ry="12" fill="url(#mushieArm)" transform="rotate(-20 70 140)" />
|
||||
<ellipse cx="130" cy="140" rx="8" ry="12" fill="url(#mushieArm)" transform="rotate(20 130 140)" />
|
||||
|
||||
<!-- Floating spores -->
|
||||
<circle cx="55" cy="120" r="2" fill="url(#mushieSpore)" opacity="0.8" />
|
||||
<circle cx="145" cy="115" r="1.5" fill="url(#mushieSpore)" opacity="0.6" />
|
||||
<circle cx="50" cy="90" r="1" fill="url(#mushieSpore)" opacity="0.7" />
|
||||
<circle cx="150" cy="95" r="2" fill="url(#mushieSpore)" opacity="0.5" />
|
||||
<circle cx="65" cy="70" r="1.5" fill="url(#mushieSpore)" opacity="0.6" />
|
||||
<circle cx="135" cy="65" r="1" fill="url(#mushieSpore)" opacity="0.8" />
|
||||
|
||||
<defs>
|
||||
<radialGradient id="mushieStem" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#fef3c7" />
|
||||
<stop offset="30%" stop-color="#fde68a" />
|
||||
<stop offset="70%" stop-color="#fbbf24" />
|
||||
<stop offset="100%" stop-color="#f59e0b" />
|
||||
</radialGradient>
|
||||
<radialGradient id="mushieStemHighlight" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" stop-color="#ffffff" />
|
||||
<stop offset="100%" stop-color="rgba(255,255,255,0.3)" />
|
||||
</radialGradient>
|
||||
<radialGradient id="mushieCap" cx="0.3" cy="0.2">
|
||||
<stop offset="0%" stop-color="#f87171" />
|
||||
<stop offset="30%" stop-color="#ef4444" />
|
||||
<stop offset="70%" stop-color="#dc2626" />
|
||||
<stop offset="100%" stop-color="#b91c1c" />
|
||||
</radialGradient>
|
||||
<radialGradient id="mushieCapHighlight" cx="0.4" cy="0.3">
|
||||
<stop offset="0%" stop-color="#fca5a5" />
|
||||
<stop offset="100%" stop-color="#f87171" />
|
||||
</radialGradient>
|
||||
<radialGradient id="mushieArm" cx="0.3" cy="0.3">
|
||||
<stop offset="0%" stop-color="#fde68a" />
|
||||
<stop offset="100%" stop-color="#f59e0b" />
|
||||
</radialGradient>
|
||||
<radialGradient id="mushieSpore" cx="0.5" cy="0.5">
|
||||
<stop offset="0%" stop-color="#c084fc" />
|
||||
<stop offset="100%" stop-color="#8b5cf6" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.3 KiB |