Compare commits
896 Commits
fix/popup-
...
f40c4b2a69
| Author | SHA1 | Date | |
|---|---|---|---|
| f40c4b2a69 | |||
| 2dae3adf66 | |||
| e079afc0a2 | |||
| 85b3e4db47 | |||
| 0197224c75 | |||
| 70f8fb867d | |||
| 86b87eeb9d | |||
| 297b545e55 | |||
| 3e2ae9b7ca | |||
| 2016b87b6e | |||
| a42ad4ebb3 | |||
| 158750b933 | |||
| 3abe65de2a | |||
| c0e432cc22 | |||
| f8115f47fd | |||
| 66b56387e6 | |||
| 3079cf4ba5 | |||
| aefb0c1550 | |||
| 235adb5ebd | |||
| 744981ed93 | |||
| ee20c214de | |||
| 8fd68033ed | |||
| 62b4b44f88 | |||
| 9d599d5f47 | |||
| 2b1f8a4fe2 | |||
| 7a81045290 | |||
| 67ce0f8b39 | |||
| 01df6c9116 | |||
| 480a109114 | |||
| 509fe203f7 | |||
| 0f9cc1087f | |||
| 0f24f47048 | |||
| a3d2ee562e | |||
| 1b1704f7c6 | |||
| 8b2670bf31 | |||
| e66c91acfc | |||
| 29699a66fd | |||
| 3b4051c775 | |||
| fffb5dae18 | |||
| 8cfc144ba9 | |||
| 065fba7cf8 | |||
| f2cb69cb06 | |||
| fe2d3dcfe2 | |||
| 78973c99a3 | |||
| 171190c1cd | |||
| 7952f5a722 | |||
| 3f29116345 | |||
| 3f99a1b9e4 | |||
| 7a5de9a44f | |||
| b4a8415a38 | |||
| e2573cbaef | |||
| ca772295ba | |||
| 0925d28eb0 | |||
| 782a26f446 | |||
| 278645230a | |||
| 21ee661cef | |||
| 3fffab81c8 | |||
| 6993582592 | |||
| 429487b1d1 | |||
| d15724dd2f | |||
| 4cb34bf28e | |||
| 2daaa258a0 | |||
| 3892fb517f | |||
| 659308e116 | |||
| bc127a45e8 | |||
| 596e7cdb03 | |||
| f09fffb7ad | |||
| a01587fc68 | |||
| 04cd90078b | |||
| 45015cc781 | |||
| fce62e988f | |||
| c5f91be93b | |||
| d0960da1d8 | |||
| 8443cadba9 | |||
| 9739eea32a | |||
| 90c77096aa | |||
| 1deb805d29 | |||
| b079442cfa | |||
| 88a0153f90 | |||
| 50cd3081e6 | |||
| f37633525f | |||
| 1893f6d884 | |||
| 661b33b6b6 | |||
| 1d8bcf7d73 | |||
| aaa4faeb57 | |||
| 2288746182 | |||
| 56d6d17b6a | |||
| 53e885164d | |||
| e82355cf9b | |||
| 16f2053927 | |||
| 0fbff1004c | |||
| 75690ba6cc | |||
| 0506e765a9 | |||
| acab1971ab | |||
| f8797b9529 | |||
| 11cc4f6319 | |||
| fc5c7e682c | |||
| b2211edeab | |||
| cd1ba1fbe2 | |||
| d2ad7b4108 | |||
| b4c47fcc26 | |||
| b31c133d8e | |||
| 2787e73126 | |||
| aafd888596 | |||
| ff3c2a0d9b | |||
| e7ad9a3cb5 | |||
| fc2b77135b | |||
| 33f54eb63c | |||
| a026adaec7 | |||
| 278d8c94f9 | |||
| f66b70c087 | |||
| c1407a84bb | |||
| 6ffbae0f33 | |||
| f6038575cc | |||
| 5cdafb6f7f | |||
| 7ebbdaf996 | |||
| ecb0789780 | |||
| e693e4273c | |||
| e3171ef7ad | |||
| 3ca1ca8cd7 | |||
| fcbbb05afe | |||
| dd94e53d81 | |||
| b8ff67aaa3 | |||
| 40a6f739d0 | |||
| 58a5a7d535 | |||
| 0e8db6f821 | |||
| e6a45f6b7d | |||
| 1b7cc4b679 | |||
| 876f639bb5 | |||
| 02c9fa602e | |||
| b5b27039ee | |||
| 8901e302e4 | |||
| 68bcd3ae7c | |||
| 9f89172829 | |||
| ddd1ec3056 | |||
| d305268cb8 | |||
| 1efb866e41 | |||
| b8182a0f97 | |||
| 37463a173c | |||
| 422ca8cdb5 | |||
| f92b1fb5b7 | |||
| a0043418c8 | |||
| 927f763d0a | |||
| 69ad814985 | |||
| 92599453c2 | |||
| 5d7facc94d | |||
| f6eb1fad11 | |||
| 83b253bced | |||
| 19cb332645 | |||
| e5406a27ba | |||
| ffa170ff13 | |||
| 3b81ecdf98 | |||
| c536fac4d2 | |||
| 475449f04e | |||
| e40b46a888 | |||
| 8a95b0310d | |||
| a81386d336 | |||
| b69eeba74b | |||
| f656be789d | |||
| 82139e616d | |||
| ed6d9f563d | |||
| 3a8ad7d871 | |||
| ec960a29c4 | |||
| 8312de5d09 | |||
| 5833a244de | |||
| 92fe95d131 | |||
| 07718235c3 | |||
| 183181a15d | |||
| a4f2c81528 | |||
| 30b66ad7b3 | |||
| 077fac40c2 | |||
| 10d45b1c3b | |||
| 60dc054383 | |||
| ef8c7568ac | |||
| 551d6c103d | |||
| 4a92d9bec2 | |||
| ff4340c3a9 | |||
| 4303a93278 | |||
| 12e4493a17 | |||
| c94e214d05 | |||
| afede79047 | |||
| ab727eef1d | |||
| ee050f5df9 | |||
| 855fbb2fe5 | |||
| b706e67e82 | |||
| 557addb76b | |||
| dacc25b281 | |||
| ec4fb3e688 | |||
| 75e40c752b | |||
| 24df6f0dd5 | |||
| a8ab093eae | |||
| 7f4b1d6d13 | |||
| 1420b7435e | |||
| 8b331e53d3 | |||
| 10fd785b4c | |||
| 2c0b8ed076 | |||
| ab8625ebaf | |||
| bbef0ecf55 | |||
| 671c350d95 | |||
| 2d19a653c9 | |||
| 5f60504c75 | |||
| 289e582ba1 | |||
| c26280a4d3 | |||
| 619ca3a236 | |||
| c35d0e2505 | |||
| a6e9176dbf | |||
| f4517be6c3 | |||
| 408c40fbe9 | |||
| b46dc248d5 | |||
| 1fb2b470da | |||
| 81ff205d2c | |||
| 1b3dd41a4b | |||
| 670d3f99fc | |||
| eb2839eeb8 | |||
| b0f7c7a15c | |||
| f1487e60bb | |||
| 74c24d084e | |||
| 5e8a1a48dd | |||
| 66deecdcf8 | |||
| 37d72381c7 | |||
| be40bb19b3 | |||
| 157a7b4e16 | |||
| 9d187bb8a4 | |||
| d4326bc827 | |||
| 24cb3a096d | |||
| 1610f3f75d | |||
| 837bfbfd77 | |||
| e24a6b25f2 | |||
| 318ed4028e | |||
| 1cda06573e | |||
| be1e175471 | |||
| 0598f97efe | |||
| cd91ff9d49 | |||
| e01ba29604 | |||
| ca60948fcd | |||
| beaa330651 | |||
| a891e4abf9 | |||
| de6a76e91b | |||
| eed766366d | |||
| ed944ee192 | |||
| 270f5f4eff | |||
| 0cb5c1a4df | |||
| 4f7f4f5117 | |||
| 51274b70ce | |||
| 9d8324bb44 | |||
| d1c58f2ec8 | |||
| 6f0d6a9f59 | |||
| 8ebd7918fb | |||
| 3dd059a6f6 | |||
| 414a0e4438 | |||
| df9d45fc1d | |||
| 3bbf8c9531 | |||
| f6cc866aa7 | |||
| d5d3c2b7be | |||
| c5134c1eb2 | |||
| 7c51841dba | |||
| a70a29eda1 | |||
| 4bd36db70f | |||
| eab5a97ba5 | |||
| 3d4941865e | |||
| 9da07f1566 | |||
| 8cef7b775b | |||
| 791d0bb623 | |||
| dbc6002248 | |||
| 6cf8261298 | |||
| 9eb42c4a0c | |||
| ed8a316bc0 | |||
| daab99fd88 | |||
| dac27ca43b | |||
| f5f893b445 | |||
| 45c0c2afb1 | |||
| f4a770e246 | |||
| 352c359326 | |||
| 1cc9fec69c | |||
| 2c89235f15 | |||
| 1d8d18922b | |||
| 18dad6c112 | |||
| 3debab7291 | |||
| a2449ddd91 | |||
| ff0d26908c | |||
| c4675deb1e | |||
| c99d808051 | |||
| acbac773db | |||
| b9cb6bf75b | |||
| 14e0fb9969 | |||
| 3d2a982718 | |||
| eefcc9fe57 | |||
| f51b601ecb | |||
| 70a01bfd2b | |||
| 94142268a0 | |||
| 4b0aa0ac40 | |||
| 6ee4de94a2 | |||
| 658396c9a3 | |||
| 0a6abd87ae | |||
| 25fc8311f8 | |||
| d4a249d744 | |||
| f7efbfd4b7 | |||
| e9b96df758 | |||
| 75f70138ed | |||
| c9aa4c75ae | |||
| a1db706072 | |||
| 276120162a | |||
| f523122889 | |||
| cea0e36d5d | |||
| 0169f25ca5 | |||
| 3939d15f2a | |||
| fd4edc177d | |||
| f96fee60d3 | |||
| d57b69d7cb | |||
| d875642d99 | |||
| 0bcb5e7f4a | |||
| 65013a35f0 | |||
| 31daebc83b | |||
| b8894ea2dc | |||
| ff130bbf15 | |||
| 3a88941828 | |||
| b8c813e43b | |||
| 73776841d8 | |||
| cd2705e5b9 | |||
| 02b8966a91 | |||
| 2adb574dd5 | |||
| 5b7351dcd2 | |||
| 63e2cb2ff7 | |||
| d65f27b256 | |||
| ce7cbc75df | |||
| a6091f6b68 | |||
| 9d6c3218fb | |||
| 71ea945743 | |||
| c8d92d8100 | |||
| 5831189e5e | |||
| 109cba6b6c | |||
| f01a1d7efc | |||
| ae5b878822 | |||
| 7d4ecb9731 | |||
| b5e9940934 | |||
| 018616dd0e | |||
| 74e53a9ca6 | |||
| fdc0b54fbd | |||
| 8e31b9e327 | |||
| 460dbcb447 | |||
| 81ecd45de4 | |||
| 059630ba2c | |||
| 1ac0fb2484 | |||
| d8816bbe42 | |||
| b410597d9c | |||
| 1143ef7b72 | |||
| 987e75c65a | |||
| ac8c461546 | |||
| f3032a6004 | |||
| a4d8023e1f | |||
| bb0adb0542 | |||
| a4c218fecc | |||
| 0d820b04f7 | |||
| 70c9c49b94 | |||
| 6d1bdb5d8b | |||
| 73b7b2a8df | |||
| b2063418fb | |||
| 21c342e389 | |||
| cbf91fa905 | |||
| 61495b5e90 | |||
| 185d4914a6 | |||
| e3bbb7c77a | |||
| 4044070867 | |||
| 41b0d15570 | |||
| aafb75bad3 | |||
| 6e19bc7aff | |||
| 94e852032b | |||
| 5ccbc5d4f4 | |||
| cf6d54e2bf | |||
| 19bcf64844 | |||
| a27ae6cba0 | |||
| 660ab27377 | |||
| d78a23602e | |||
| 7a6495fa33 | |||
| 61e7a0d859 | |||
| 4116bfcbb0 | |||
| 29e96a9357 | |||
| 88024cbd11 | |||
| 55a9ed5946 | |||
| 165edc38ee | |||
| b20ab5bf5d | |||
| 05d6ea1e96 | |||
| 4c58db0710 | |||
| d7bc1165f7 | |||
| a32cedad9e | |||
| 7f2e5d3934 | |||
| 616fac0312 | |||
| 2c1703acc5 | |||
| 82f1659649 | |||
| 1c88bcf99b | |||
| 793b988376 | |||
| 313c283d9b | |||
| b10bf472e3 | |||
| 1814fffc12 | |||
| 13da4f1c9f | |||
| c8fada4b9d | |||
| 6c3f90bf96 | |||
| 229c6aa969 | |||
| 00bf4bcfd6 | |||
| cb5878ad29 | |||
| d213c5a488 | |||
| 3ac8162d9c | |||
| 873e1efe73 | |||
| c1289cd6b1 | |||
| b7cfa61a34 | |||
| 52f952a6df | |||
| fa082f59c1 | |||
| d8785d9d41 | |||
| 0312d00642 | |||
| 39d4264389 | |||
| ef407d6008 | |||
| aac44de359 | |||
| 2708ac55d1 | |||
| 3d822ed641 | |||
| e88dc2b205 | |||
| 83fc02a279 | |||
| edc077eef7 | |||
| 30cda71749 | |||
| cb9234bdac | |||
| 10bc06f212 | |||
| c739d691a2 | |||
| 0ca64b7dcf | |||
| 88921e61d2 | |||
| 6b8b4acc96 | |||
| edea8c32de | |||
| 3f09dca054 | |||
| aa15518980 | |||
| 8597504b57 | |||
| a913961be5 | |||
| a2066285cd | |||
| 397589c4e6 | |||
| c3cb420bf5 | |||
| bec47d1860 | |||
| 117cbccbd7 | |||
| 7a76824fcf | |||
| 75bc8876b5 | |||
| 203c47e437 | |||
| 6eaebc7d75 | |||
| 575145eae9 | |||
| 81e85c804a | |||
| 6178f699ed | |||
| 2276291a4b | |||
| acbb89997b | |||
| e04f5aabc0 | |||
| 013eef46fb | |||
| d9c6e41ebe | |||
| e3e63899d8 | |||
| 9d2b76687c | |||
| 679c53c501 | |||
| a90245b201 | |||
| 897a8157e7 | |||
| e8db412595 | |||
| 08e4d866f5 | |||
| d4794a7be4 | |||
| d0a3976cda | |||
| 94be20d499 | |||
| a7dd0b302e | |||
| fd4fd61399 | |||
| 7808c63a79 | |||
| 82fd3839a9 | |||
| b60ea984e5 | |||
| 3713cd2cf6 | |||
| 83a5f358e2 | |||
| bd1a9a67e0 | |||
| 224b409455 | |||
| 1c5cc62368 | |||
| aa7d967422 | |||
| 9815f09c1f | |||
| fc61a02211 | |||
| aebe8b557f | |||
| dd90d60a14 | |||
| 960f4ebaaa | |||
| 9dabcc2135 | |||
| 337a9618ef | |||
| f48b8f0e41 | |||
| bb18dedc35 | |||
| 55c4d507db | |||
| 014f111cd1 | |||
| 181717a7ab | |||
| 112c9a2aa5 | |||
| 6617a0b36c | |||
| c9c062edcb | |||
| f37baad045 | |||
| ea504d8434 | |||
| eb46748ae0 | |||
| 2d7d7f731c | |||
| 783c10fc62 | |||
| 92e8823566 | |||
| a27e3518da | |||
| e4c9b7fd59 | |||
| 94f3631421 | |||
| 80d390886a | |||
| b93badedd4 | |||
| d1e6cc3122 | |||
| 2a2161c9d9 | |||
| 6470912498 | |||
| f628d7a0ef | |||
| b8387de6c6 | |||
| 2705038c36 | |||
| f05eebad43 | |||
| 1e0a06850a | |||
| a88ecb9529 | |||
| 34f8ae2322 | |||
| cf6b683ffc | |||
| 0cdb956065 | |||
| d3e8b62581 | |||
| e1ce2ae268 | |||
| c86e688e47 | |||
| 2014d27834 | |||
| 15a61fdc39 | |||
| c430c8971c | |||
| de52406be8 | |||
| e749209128 | |||
| fbf2dfdcee | |||
| 563ab9274f | |||
| 5cfee417be | |||
| 5ae4bbcbd3 | |||
| c0220492a2 | |||
| 24ae55867a | |||
| b2eb04ab98 | |||
| 7045a05a73 | |||
| 4adaa945a1 | |||
| eef59211d3 | |||
| 07c38c1b1b | |||
| de4314ec9b | |||
| 50a1c1c695 | |||
| 55a5a68517 | |||
| e6d47a3d78 | |||
| 32db276e68 | |||
| 04a1d3c287 | |||
| d124d58552 | |||
| c7810f16f7 | |||
| c3956f7bcd | |||
| 3ef3d05624 | |||
| 509b4d2238 | |||
| 053a279102 | |||
| 3cedbd7b6b | |||
| 7e4400267e | |||
| 1150dad0b5 | |||
| 16cfe039ba | |||
| c629562190 | |||
| 2e535b9d93 | |||
| 0b760e41a3 | |||
| f794a2ae27 | |||
| aee630b546 | |||
| 95194585d2 | |||
| 55c8e58f32 | |||
| 1bf8a4a9b2 | |||
| ea40123c76 | |||
| bf4fe97aa3 | |||
| 84f5cd4568 | |||
| 4ae21c5d7a | |||
| f7fb9f34f9 | |||
| 66a579d48c | |||
| 066ca61d97 | |||
| 2d8846c64c | |||
| ca4e7fd170 | |||
| 5d3663786c | |||
| cc7125361f | |||
| 8e218bb663 | |||
| 5f41febd70 | |||
| a74263016b | |||
| 1f1a642f99 | |||
| 2e85cfd78c | |||
| 638406567d | |||
| b0dad04b59 | |||
| f258987e0e | |||
| 750ed2dac7 | |||
| 6c7f7d4837 | |||
| 0858618e77 | |||
| 1143175990 | |||
| e9483e26e5 | |||
| b30ba914b9 | |||
| 4715f06b2f | |||
| 47098bddda | |||
| cb81aad784 | |||
| d8705398bb | |||
| 23426b168f | |||
| 26eac57dc2 | |||
| 47f21f391c | |||
| a2a637c320 | |||
| 5ca4509d5b | |||
| a7541d0598 | |||
| d6633b698a | |||
| 4d89454a17 | |||
| 4b5dda9c4c | |||
| 9f07967982 | |||
| 2337e3cacf | |||
| 46508c7d55 | |||
| c59abc9545 | |||
| fce936feee | |||
| cc39e06161 | |||
| 014046bc9e | |||
| 45830ebda4 | |||
| 062fb3be90 | |||
| 02644e1959 | |||
| 315bdc71ff | |||
| f3d9f397d7 | |||
| b799e67e54 | |||
| 06e3a4d796 | |||
| 17864427c1 | |||
| 851b5fe722 | |||
| c2b38476ea | |||
| e9ee61f509 | |||
| c01a026149 | |||
| 2e85e11e92 | |||
| efd7cdb8d7 | |||
| e51c03235f | |||
| 92700f9a21 | |||
| c0e64437f0 | |||
| 6fb0e264b8 | |||
| 64d3ac8f8a | |||
| 6c6822ca16 | |||
| b86e8e7fa6 | |||
| 7b83636c99 | |||
| d01b0d46e4 | |||
| db1d47f456 | |||
| de4b510c00 | |||
| 089da9181b | |||
| c1d4a68e26 | |||
| f7f1b1191e | |||
| f9d144159a | |||
| 3952517ac9 | |||
| 01e7c3e981 | |||
| ebe2963466 | |||
| 5847612a58 | |||
| 4a5bac7aa5 | |||
| e3c69e7e32 | |||
| 12a1422470 | |||
| 48235c18a5 | |||
| fe9cbcd21d | |||
| 87fbda698c | |||
| 39ab70510c | |||
| ea01bbd260 | |||
| b3dd1af674 | |||
| bbe3d75267 | |||
| f11146013e | |||
| 7c7e67df4a | |||
| f5badc550c | |||
| 25636f8133 | |||
| 08caa49b43 | |||
| 555443dc44 | |||
| fae1d77ba5 | |||
| 2f5f23d21a | |||
| 071db2d70c | |||
| fd6527aa38 | |||
| 605ca69238 | |||
| 8c32f78503 | |||
| 14ba88b645 | |||
| 4f44b4f574 | |||
| dcc261b0d0 | |||
| d6c994e8f0 | |||
| e604a41e14 | |||
| 51ae3b1308 | |||
| 2ec9aa990f | |||
| a23d57547b | |||
| dc2018ee17 | |||
| cbbb1e0327 | |||
| 1ab8a52c38 | |||
| 6027f0d6de | |||
| 048305eb23 | |||
| 8f1eb1f5fe | |||
| 70cb01cfc0 | |||
| 719d32b77b | |||
| fe6c000fc7 | |||
| d4c1e1d6a5 | |||
| e9c679e1aa | |||
| 65b49fe4d5 | |||
| 5a0c903346 | |||
| 6690788a17 | |||
| 9b5275b6f6 | |||
| 1abc53734b | |||
| 829444231c | |||
| ffd046fc0a | |||
| 0f9647e7c5 | |||
| 23b5e91d11 | |||
| b8112e20d6 | |||
| 31b22e7225 | |||
| e86c5d874e | |||
| 49479ea24e | |||
| 0e409247cd | |||
| 0b06ad56dc | |||
| a27925c24f | |||
| 1b2a8f83c2 | |||
| 81570dda30 | |||
| db941673fc | |||
| f58a6723de | |||
| 61243b8dd4 | |||
| b08d7a389b | |||
| a1fc8f5955 | |||
| d3c34c3698 | |||
| 6410257a25 | |||
| f836254381 | |||
| 21252dc2ad | |||
| cc2ca14133 | |||
| dc4b3df715 | |||
| 6745f2093e | |||
| 3781e54a32 | |||
| 1edda80d21 | |||
| a443121426 | |||
| 5e5e5cb1d5 | |||
| 2bd94a1e5a | |||
| 58883b02f3 | |||
| 92549b979e | |||
| a929cfedb4 | |||
| abd6c122d5 | |||
| f7b1552239 | |||
| b5077b6a33 | |||
| 9f40ebc09e | |||
| dfbcd0c9a5 | |||
| 800cdbc805 | |||
| 8d350b24e5 | |||
| a6189a5f9e | |||
| 00870e4554 | |||
| 233093bebb | |||
| d082baa06f | |||
| 5ac7f3cf95 | |||
| 7526143c7d | |||
| 4377ab919f | |||
| 7c703ace4f | |||
| 6837a5d934 | |||
| 474b3a1091 | |||
| e4c905d278 | |||
| fb133ced3c | |||
| da17911a9c | |||
| 988b36ebb4 | |||
| fe2c53b43e | |||
| 9ed2acb8ae | |||
| f36f9ce992 | |||
| bca90e959e | |||
| 1615f9aafe | |||
| 1f6e260711 | |||
| dba637af38 | |||
| 68ed022c95 | |||
| 22a89013d0 | |||
| 107b5dd71b | |||
| 63789124f4 | |||
| a2dd7eb6f1 | |||
| d0e74a0925 | |||
| ccbce61755 | |||
| b827aba722 | |||
| 836eeb080e | |||
| 31c6914880 | |||
| 1ee402b581 | |||
| b1491ad69e | |||
| a954f9cc49 | |||
| 3a310f0b98 | |||
| 70fbdce641 | |||
| 861c43a428 | |||
| 556ce9d132 | |||
| 5c56cfaaa7 | |||
| 6d704f7f5a | |||
| 7580d8b763 | |||
| 76afe5f433 | |||
| 0bc1b5e90c | |||
| 9fc34ef467 | |||
| 7a713e07e1 | |||
| bd778c0283 | |||
| fed3962965 | |||
| 6de74a3baf | |||
| a4f2823e75 | |||
| cd82ba2f27 | |||
| 698d419525 | |||
| a252d42b62 | |||
| 69466f410c | |||
| 39245dfcac | |||
| 80b18cee0f | |||
| b2688dc8a1 | |||
| d5ca77e2d8 | |||
| e789ab2ca3 | |||
| 5e83771193 | |||
| 0d18041037 | |||
| 875cf0b428 | |||
| e16402c9c1 | |||
| dee2887026 | |||
| 6033cc2fa0 | |||
| c1fbabe07b | |||
| 221ef7bb6d | |||
| 55c1e80ed7 | |||
| 79202c4542 | |||
| 3bff91e421 | |||
| 979384c2d6 | |||
| 504e5322fb | |||
| 25fc0a59a8 | |||
| 34e27d0621 | |||
| 913fc90176 | |||
| c1bac6d9e8 | |||
| 31382a2388 | |||
| d009077183 | |||
| 133eb29a71 | |||
| a2616c9757 | |||
| fb47da8095 | |||
| 37958cbe39 | |||
| 9f53f147ee | |||
| 2342a14f2e | |||
| 36b0c22e47 | |||
| 4a52b9c229 | |||
| 9ec90a906f | |||
| e125a5f39c | |||
| 8c0ec46dd8 | |||
| b65ec35d3c | |||
| d113d6125b | |||
| 2f24661cd9 | |||
| 50908a274b | |||
| 9e68562de5 | |||
| 8e5561c2a7 | |||
| 8d5c543a4f | |||
| cf411407dd | |||
| 86e4be302b | |||
| 2fd06796e1 | |||
| 60c51e551a | |||
| d0d3ac47c6 | |||
| af677f6565 | |||
| f889efeb16 | |||
| d026bb6180 | |||
| 82b856f5d9 | |||
| 7f33b6948a | |||
| 3489b89a0b | |||
| dc4f2769f9 | |||
| 5cf87e4d56 | |||
| c9ca63cff5 | |||
| a6072f4895 | |||
| 38947ddc62 | |||
| cfe83ada38 | |||
| 1e9e0ffea8 | |||
| 28acdfb621 | |||
| ad9f1c495b | |||
| 7c2a7468e7 | |||
| b2051dcf92 | |||
| e3c86de84a | |||
| 6e0eb5d4f3 | |||
| 9d186ff094 | |||
| 8611ec4dc3 | |||
| 89bfd94a07 | |||
| 5cf8b7b467 | |||
| 2cc0162435 | |||
| d8e75a0c9e | |||
| 8af3c0ccb9 | |||
| d8b78168a8 | |||
| 7675e8e04d | |||
| 88d05048a6 | |||
| 28a92c0635 | |||
| b5a47b8b4e | |||
| 4f99e8b5f2 | |||
| 87fc49146c | |||
| 826fcfb024 | |||
| 7174d87b79 | |||
| 4bc747cd9c | |||
| e046868665 | |||
| 19c3ec4f9f | |||
| ffbc15929d | |||
| 524280d816 | |||
| 6e736e0733 | |||
| 4891566793 | |||
| b02f5fbc21 | |||
| 4f5a300afa | |||
| aae6e76797 | |||
| 3162d6a9f2 | |||
| 8010ac45a6 | |||
| baebba4cef | |||
| 1be7155fe8 | |||
| 611c0b930b | |||
| ec1903519d | |||
| b1953a020d | |||
| 3ce26322e0 | |||
| 4e480d35df | |||
| bc6d243362 | |||
| a285706112 | |||
| 9c04c031ab | |||
| 0ce929f8a1 | |||
| 61ab9f11bd | |||
| 2747cb49ae | |||
| 9c8ebf8d74 | |||
| 588ec60948 | |||
| 962ea124fa | |||
| 0ca0fe3b0d | |||
| cef2b6e02e | |||
| e018f9a8b9 | |||
| def8a6cf6f | |||
| 857f295923 | |||
| 50ee885b74 | |||
| 410f248510 | |||
| ba5fcfaab1 | |||
| 5a46bb8d69 | |||
| e33ad16d10 | |||
| d8ba7ace0f | |||
| 875072bb68 | |||
| 0912b9b031 | |||
| 7ffe4acc0f | |||
| 4bcf0cbd2d | |||
| fdf85dfec7 | |||
| 1d62b37060 | |||
| b23c21d05b | |||
| 65a24f25bb | |||
| 2a0935b581 | |||
| b31197a8b4 |
155
.claude/commands/opsx/apply.md
Normal file
155
.claude/commands/opsx/apply.md
Normal file
@@ -0,0 +1,155 @@
|
||||
---
|
||||
name: "OPSX: Apply"
|
||||
description: Implement tasks from an OpenSpec change (Experimental)
|
||||
category: Workflow
|
||||
tags: [workflow, artifacts, experimental]
|
||||
---
|
||||
|
||||
Implement tasks from an OpenSpec change.
|
||||
|
||||
**Input**: Optionally specify a change name (e.g., `/opsx:apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
|
||||
|
||||
2. **Check status to understand the schema**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used (e.g., "spec-driven")
|
||||
- `planningHome`, `changeRoot`, and `actionContext`: planning scope and edit constraints
|
||||
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
|
||||
|
||||
3. **Get apply instructions**
|
||||
|
||||
```bash
|
||||
openspec instructions apply --change "<name>" --json
|
||||
```
|
||||
|
||||
This returns:
|
||||
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema)
|
||||
- Progress (total, complete, remaining)
|
||||
- Task list with status
|
||||
- Dynamic instruction based on current state
|
||||
|
||||
**Handle states:**
|
||||
- If `state: "blocked"` (missing artifacts): show message, suggest using `/opsx:continue`
|
||||
- If `state: "all_done"`: congratulate, suggest archive
|
||||
- Otherwise: proceed to implementation
|
||||
|
||||
**Workspace guard:** If status JSON reports `actionContext.mode: "workspace-planning"` and `allowedEditRoots` is empty, explain that full workspace apply is not supported in this slice. Treat linked repos and folders as read-only context, ask the user to select an affected area through an explicit implementation workflow, and STOP before editing files.
|
||||
|
||||
4. **Read context files**
|
||||
|
||||
Read every file path listed under `contextFiles` from the apply instructions output.
|
||||
The files depend on the schema being used:
|
||||
- **spec-driven**: proposal, specs, design, tasks
|
||||
- Other schemas: follow the contextFiles from CLI output
|
||||
|
||||
5. **Show current progress**
|
||||
|
||||
Display:
|
||||
- Schema being used
|
||||
- Progress: "N/M tasks complete"
|
||||
- Remaining tasks overview
|
||||
- Dynamic instruction from CLI
|
||||
|
||||
6. **Implement tasks (loop until done or blocked)**
|
||||
|
||||
For each pending task:
|
||||
- Show which task is being worked on
|
||||
- Make the code changes required
|
||||
- Keep changes minimal and focused
|
||||
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
|
||||
- Continue to next task
|
||||
|
||||
**Pause if:**
|
||||
- Task is unclear → ask for clarification
|
||||
- Implementation reveals a design issue → suggest updating artifacts
|
||||
- Error or blocker encountered → report and wait for guidance
|
||||
- User interrupts
|
||||
|
||||
7. **On completion or pause, show status**
|
||||
|
||||
Display:
|
||||
- Tasks completed this session
|
||||
- Overall progress: "N/M tasks complete"
|
||||
- If all done: suggest archive
|
||||
- If paused: explain why and wait for guidance
|
||||
|
||||
**Output During Implementation**
|
||||
|
||||
```
|
||||
## Implementing: <change-name> (schema: <schema-name>)
|
||||
|
||||
Working on task 3/7: <task description>
|
||||
[...implementation happening...]
|
||||
✓ Task complete
|
||||
|
||||
Working on task 4/7: <task description>
|
||||
[...implementation happening...]
|
||||
✓ Task complete
|
||||
```
|
||||
|
||||
**Output On Completion**
|
||||
|
||||
```
|
||||
## Implementation Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 7/7 tasks complete ✓
|
||||
|
||||
### Completed This Session
|
||||
- [x] Task 1
|
||||
- [x] Task 2
|
||||
...
|
||||
|
||||
All tasks complete! You can archive this change with `/opsx:archive`.
|
||||
```
|
||||
|
||||
**Output On Pause (Issue Encountered)**
|
||||
|
||||
```
|
||||
## Implementation Paused
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 4/7 tasks complete
|
||||
|
||||
### Issue Encountered
|
||||
<description of the issue>
|
||||
|
||||
**Options:**
|
||||
1. <option 1>
|
||||
2. <option 2>
|
||||
3. Other approach
|
||||
|
||||
What would you like to do?
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Keep going through tasks until done or blocked
|
||||
- Always read context files before starting (from the apply instructions output)
|
||||
- If task is ambiguous, pause and ask before implementing
|
||||
- If implementation reveals issues, pause and suggest artifact updates
|
||||
- Keep code changes minimal and scoped to each task
|
||||
- Update task checkbox immediately after completing each task
|
||||
- Pause on errors, blockers, or unclear requirements - don't guess
|
||||
- Use contextFiles from CLI output, don't assume specific file names
|
||||
|
||||
**Fluid Workflow Integration**
|
||||
|
||||
This skill supports the "actions on a change" model:
|
||||
|
||||
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
|
||||
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
|
||||
160
.claude/commands/opsx/archive.md
Normal file
160
.claude/commands/opsx/archive.md
Normal file
@@ -0,0 +1,160 @@
|
||||
---
|
||||
name: "OPSX: Archive"
|
||||
description: Archive a completed change in the experimental workflow
|
||||
category: Workflow
|
||||
tags: [workflow, archive, experimental]
|
||||
---
|
||||
|
||||
Archive a completed change in the experimental workflow.
|
||||
|
||||
**Input**: Optionally specify a change name after `/opsx:archive` (e.g., `/opsx:archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no change name provided, prompt for selection**
|
||||
|
||||
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
|
||||
|
||||
Show only active changes (not already archived).
|
||||
Include the schema used for each change if available.
|
||||
|
||||
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||
|
||||
2. **Check artifact completion status**
|
||||
|
||||
Run `openspec status --change "<name>" --json` to check artifact completion.
|
||||
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used
|
||||
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context
|
||||
- `artifacts`: List of artifacts with their status (`done` or other)
|
||||
|
||||
If status reports `actionContext.mode: "workspace-planning"`, explain that workspace archive is not supported in this slice and STOP. Do not move workspace changes into repo-local archives or edit linked repos.
|
||||
|
||||
**If any artifacts are not `done`:**
|
||||
- Display warning listing incomplete artifacts
|
||||
- Prompt user for confirmation to continue
|
||||
- Proceed if user confirms
|
||||
|
||||
3. **Check task completion status**
|
||||
|
||||
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
|
||||
|
||||
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
|
||||
|
||||
**If incomplete tasks found:**
|
||||
- Display warning showing count of incomplete tasks
|
||||
- Prompt user for confirmation to continue
|
||||
- Proceed if user confirms
|
||||
|
||||
**If no tasks file exists:** Proceed without task-related warning.
|
||||
|
||||
4. **Assess delta spec sync state**
|
||||
|
||||
Use `artifactPaths.specs.existingOutputPaths` from status JSON to check for delta specs. If none exist, proceed without sync prompt.
|
||||
|
||||
**If delta specs exist:**
|
||||
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
|
||||
- Determine what changes would be applied (adds, modifications, removals, renames)
|
||||
- Show a combined summary before prompting
|
||||
|
||||
**Prompt options:**
|
||||
- If changes needed: "Sync now (recommended)", "Archive without syncing"
|
||||
- If already synced: "Archive now", "Sync anyway", "Cancel"
|
||||
|
||||
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
|
||||
|
||||
5. **Perform the archive**
|
||||
|
||||
Create an `archive` directory under `planningHome.changesDir` if it doesn't exist:
|
||||
```bash
|
||||
mkdir -p "<planningHome.changesDir>/archive"
|
||||
```
|
||||
|
||||
Generate target name using current date: `YYYY-MM-DD-<change-name>`
|
||||
|
||||
**Check if target already exists:**
|
||||
- If yes: Fail with error, suggest renaming existing archive or using different date
|
||||
- If no: Move `changeRoot` to the archive directory
|
||||
|
||||
```bash
|
||||
mv "<changeRoot>" "<planningHome.changesDir>/archive/YYYY-MM-DD-<name>"
|
||||
```
|
||||
|
||||
6. **Display summary**
|
||||
|
||||
Show archive completion summary including:
|
||||
- Change name
|
||||
- Schema that was used
|
||||
- Archive location
|
||||
- Spec sync status (synced / sync skipped / no delta specs)
|
||||
- Note about any warnings (incomplete artifacts/tasks)
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** the archive path derived from `planningHome.changesDir`/YYYY-MM-DD-<name>/
|
||||
**Specs:** ✓ Synced to main specs
|
||||
|
||||
All artifacts complete. All tasks complete.
|
||||
```
|
||||
|
||||
**Output On Success (No Delta Specs)**
|
||||
|
||||
```
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** the archive path derived from `planningHome.changesDir`/YYYY-MM-DD-<name>/
|
||||
**Specs:** No delta specs
|
||||
|
||||
All artifacts complete. All tasks complete.
|
||||
```
|
||||
|
||||
**Output On Success With Warnings**
|
||||
|
||||
```
|
||||
## Archive Complete (with warnings)
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** the archive path derived from `planningHome.changesDir`/YYYY-MM-DD-<name>/
|
||||
**Specs:** Sync skipped (user chose to skip)
|
||||
|
||||
**Warnings:**
|
||||
- Archived with 2 incomplete artifacts
|
||||
- Archived with 3 incomplete tasks
|
||||
- Delta spec sync was skipped (user chose to skip)
|
||||
|
||||
Review the archive if this was not intentional.
|
||||
```
|
||||
|
||||
**Output On Error (Archive Exists)**
|
||||
|
||||
```
|
||||
## Archive Failed
|
||||
|
||||
**Change:** <change-name>
|
||||
**Target:** the archive path derived from `planningHome.changesDir`/YYYY-MM-DD-<name>/
|
||||
|
||||
Target archive directory already exists.
|
||||
|
||||
**Options:**
|
||||
1. Rename the existing archive
|
||||
2. Delete the existing archive if it's a duplicate
|
||||
3. Wait until a different date to archive
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Always prompt for change selection if not provided
|
||||
- Use artifact graph (openspec status --json) for completion checking
|
||||
- Don't block archive on warnings - just inform and confirm
|
||||
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
|
||||
- Show clear summary of what happened
|
||||
- If sync is requested, use the Skill tool to invoke `openspec-sync-specs` (agent-driven)
|
||||
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
|
||||
172
.claude/commands/opsx/explore.md
Normal file
172
.claude/commands/opsx/explore.md
Normal file
@@ -0,0 +1,172 @@
|
||||
---
|
||||
name: "OPSX: Explore"
|
||||
description: "Enter explore mode - think through ideas, investigate problems, clarify requirements"
|
||||
category: Workflow
|
||||
tags: [workflow, explore, experimental, thinking]
|
||||
---
|
||||
|
||||
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
|
||||
|
||||
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
|
||||
|
||||
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
|
||||
|
||||
**Input**: The argument after `/opsx:explore` is whatever the user wants to think about. Could be:
|
||||
- A vague idea: "real-time collaboration"
|
||||
- A specific problem: "the auth system is getting unwieldy"
|
||||
- A change name: "add-dark-mode" (to explore in context of that change)
|
||||
- A comparison: "postgres vs sqlite for this"
|
||||
- Nothing (just enter explore mode)
|
||||
|
||||
---
|
||||
|
||||
## The Stance
|
||||
|
||||
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
|
||||
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
|
||||
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
|
||||
- **Adaptive** - Follow interesting threads, pivot when new information emerges
|
||||
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
|
||||
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
|
||||
|
||||
---
|
||||
|
||||
## What You Might Do
|
||||
|
||||
Depending on what the user brings, you might:
|
||||
|
||||
**Explore the problem space**
|
||||
- Ask clarifying questions that emerge from what they said
|
||||
- Challenge assumptions
|
||||
- Reframe the problem
|
||||
- Find analogies
|
||||
|
||||
**Investigate the codebase**
|
||||
- Map existing architecture relevant to the discussion
|
||||
- Find integration points
|
||||
- Identify patterns already in use
|
||||
- Surface hidden complexity
|
||||
|
||||
**Compare options**
|
||||
- Brainstorm multiple approaches
|
||||
- Build comparison tables
|
||||
- Sketch tradeoffs
|
||||
- Recommend a path (if asked)
|
||||
|
||||
**Visualize**
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ Use ASCII diagrams liberally │
|
||||
├─────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌────────┐ ┌────────┐ │
|
||||
│ │ State │────────▶│ State │ │
|
||||
│ │ A │ │ B │ │
|
||||
│ └────────┘ └────────┘ │
|
||||
│ │
|
||||
│ System diagrams, state machines, │
|
||||
│ data flows, architecture sketches, │
|
||||
│ dependency graphs, comparison tables │
|
||||
│ │
|
||||
└─────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Surface risks and unknowns**
|
||||
- Identify what could go wrong
|
||||
- Find gaps in understanding
|
||||
- Suggest spikes or investigations
|
||||
|
||||
---
|
||||
|
||||
## OpenSpec Awareness
|
||||
|
||||
You have full context of the OpenSpec system. Use it naturally, don't force it.
|
||||
|
||||
### Check for context
|
||||
|
||||
At the start, quickly check what exists:
|
||||
```bash
|
||||
openspec list --json
|
||||
```
|
||||
|
||||
This tells you:
|
||||
- If there are active changes
|
||||
- Their names, schemas, and status
|
||||
- What the user might be working on
|
||||
|
||||
If the user mentioned a specific change name, read its artifacts for context.
|
||||
|
||||
### When no change exists
|
||||
|
||||
Think freely. When insights crystallize, you might offer:
|
||||
|
||||
- "This feels solid enough to start a change. Want me to create a proposal?"
|
||||
- Or keep exploring - no pressure to formalize
|
||||
|
||||
### When a change exists
|
||||
|
||||
If the user mentions a change or you detect one is relevant:
|
||||
|
||||
1. **Resolve and read existing artifacts for context**
|
||||
- Run `openspec status --change "<name>" --json`.
|
||||
- Use `changeRoot`, `artifactPaths`, and `actionContext` from the status JSON.
|
||||
- Read existing files from `artifactPaths.<artifact>.existingOutputPaths`.
|
||||
|
||||
2. **Reference them naturally in conversation**
|
||||
- "Your design mentions using Redis, but we just realized SQLite fits better..."
|
||||
- "The proposal scopes this to premium users, but we're now thinking everyone..."
|
||||
|
||||
3. **Offer to capture when decisions are made**
|
||||
|
||||
| Insight Type | Where to Capture |
|
||||
|----------------------------|--------------------------------|
|
||||
| New requirement discovered | `specs/<capability>/spec.md` |
|
||||
| Requirement changed | `specs/<capability>/spec.md` |
|
||||
| Design decision made | `design.md` |
|
||||
| Scope changed | `proposal.md` |
|
||||
| New work identified | `tasks.md` |
|
||||
| Assumption invalidated | Relevant artifact |
|
||||
|
||||
Example offers:
|
||||
- "That's a design decision. Capture it in design.md?"
|
||||
- "This is a new requirement. Add it to specs?"
|
||||
- "This changes scope. Update the proposal?"
|
||||
|
||||
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
|
||||
|
||||
---
|
||||
|
||||
## What You Don't Have To Do
|
||||
|
||||
- Follow a script
|
||||
- Ask the same questions every time
|
||||
- Produce a specific artifact
|
||||
- Reach a conclusion
|
||||
- Stay on topic if a tangent is valuable
|
||||
- Be brief (this is thinking time)
|
||||
|
||||
---
|
||||
|
||||
## Ending Discovery
|
||||
|
||||
There's no required ending. Discovery might:
|
||||
|
||||
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
|
||||
- **Result in artifact updates**: "Updated design.md with these decisions"
|
||||
- **Just provide clarity**: User has what they need, moves on
|
||||
- **Continue later**: "We can pick this up anytime"
|
||||
|
||||
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
|
||||
|
||||
---
|
||||
|
||||
## Guardrails
|
||||
|
||||
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
|
||||
- **Don't fake understanding** - If something is unclear, dig deeper
|
||||
- **Don't rush** - Discovery is thinking time, not task time
|
||||
- **Don't force structure** - Let patterns emerge naturally
|
||||
- **Don't auto-capture** - Offer to save insights, don't just do it
|
||||
- **Do visualize** - A good diagram is worth many paragraphs
|
||||
- **Do explore the codebase** - Ground discussions in reality
|
||||
- **Do question assumptions** - Including the user's and your own
|
||||
107
.claude/commands/opsx/propose.md
Normal file
107
.claude/commands/opsx/propose.md
Normal file
@@ -0,0 +1,107 @@
|
||||
---
|
||||
name: "OPSX: Propose"
|
||||
description: Propose a new change - create it and generate all artifacts in one step
|
||||
category: Workflow
|
||||
tags: [workflow, artifacts, experimental]
|
||||
---
|
||||
|
||||
Propose a new change - create the change and generate all artifacts in one step.
|
||||
|
||||
I'll create a change with artifacts:
|
||||
- proposal.md (what & why)
|
||||
- design.md (how)
|
||||
- tasks.md (implementation steps)
|
||||
|
||||
When ready to implement, run /opsx:apply
|
||||
|
||||
---
|
||||
|
||||
**Input**: The argument after `/opsx:propose` is the change name (kebab-case), OR a description of what the user wants to build.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no input provided, ask what they want to build**
|
||||
|
||||
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
|
||||
> "What change do you want to work on? Describe what you want to build or fix."
|
||||
|
||||
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
|
||||
|
||||
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||
|
||||
2. **Create the change directory**
|
||||
```bash
|
||||
openspec new change "<name>"
|
||||
```
|
||||
This creates a scaffolded change in the planning home resolved by the CLI with `.openspec.yaml`.
|
||||
|
||||
3. **Get the artifact build order**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to get:
|
||||
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
|
||||
- `artifacts`: list of all artifacts with their status and dependencies
|
||||
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
|
||||
|
||||
4. **Create artifacts in sequence until apply-ready**
|
||||
|
||||
Use the **TodoWrite tool** to track progress through the artifacts.
|
||||
|
||||
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
|
||||
|
||||
a. **For each artifact that is `ready` (dependencies satisfied)**:
|
||||
- Get instructions:
|
||||
```bash
|
||||
openspec instructions <artifact-id> --change "<name>" --json
|
||||
```
|
||||
- The instructions JSON includes:
|
||||
- `context`: Project background (constraints for you - do NOT include in output)
|
||||
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
|
||||
- `template`: The structure to use for your output file
|
||||
- `instruction`: Schema-specific guidance for this artifact type
|
||||
- `resolvedOutputPath`: Resolved path or pattern to write the artifact
|
||||
- `dependencies`: Completed artifacts to read for context
|
||||
- Read any completed dependency files for context
|
||||
- Create the artifact file using `template` as the structure and write it to `resolvedOutputPath`
|
||||
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
|
||||
- Show brief progress: "Created <artifact-id>"
|
||||
|
||||
b. **Continue until all `applyRequires` artifacts are complete**
|
||||
- After creating each artifact, re-run `openspec status --change "<name>" --json`
|
||||
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
|
||||
- Stop when all `applyRequires` artifacts are done
|
||||
|
||||
c. **If an artifact requires user input** (unclear context):
|
||||
- Use **AskUserQuestion tool** to clarify
|
||||
- Then continue with creation
|
||||
|
||||
5. **Show final status**
|
||||
```bash
|
||||
openspec status --change "<name>"
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
After completing all artifacts, summarize:
|
||||
- Change name and location
|
||||
- List of artifacts created with brief descriptions
|
||||
- What's ready: "All artifacts created! Ready for implementation."
|
||||
- Prompt: "Run `/opsx:apply` to start implementing."
|
||||
|
||||
**Artifact Creation Guidelines**
|
||||
|
||||
- Follow the `instruction` field from `openspec instructions` for each artifact type
|
||||
- The schema defines what each artifact should contain - follow it
|
||||
- Read dependency artifacts for context before creating new ones
|
||||
- Use `template` as the structure for your output file - fill in its sections
|
||||
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
|
||||
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
|
||||
- These guide what you write, but should never appear in the output
|
||||
|
||||
**Guardrails**
|
||||
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
|
||||
- Always read dependency artifacts before creating a new one
|
||||
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
|
||||
- If a change with that name already exists, ask if user wants to continue it or create a new one
|
||||
- Verify each artifact file exists after writing before proceeding to next
|
||||
143
.claude/commands/opsx/sync.md
Normal file
143
.claude/commands/opsx/sync.md
Normal file
@@ -0,0 +1,143 @@
|
||||
---
|
||||
name: "OPSX: Sync"
|
||||
description: Sync delta specs from a change to main specs
|
||||
category: Workflow
|
||||
tags: [workflow, specs, experimental]
|
||||
---
|
||||
|
||||
Sync delta specs from a change to main specs.
|
||||
|
||||
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
|
||||
|
||||
**Input**: Optionally specify a change name after `/opsx:sync` (e.g., `/opsx:sync add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no change name provided, prompt for selection**
|
||||
|
||||
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
|
||||
|
||||
Show changes that have delta specs (under `specs/` directory).
|
||||
|
||||
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||
|
||||
2. **Resolve change context**
|
||||
|
||||
Run:
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
|
||||
If status reports `actionContext.mode: "workspace-planning"`, explain that workspace spec sync is not supported in this slice and STOP. Do not fall back to repo-local paths or edit linked repos.
|
||||
|
||||
3. **Find delta specs**
|
||||
|
||||
Use `artifactPaths.specs.existingOutputPaths` from the status JSON as the list of delta spec files.
|
||||
|
||||
Each delta spec file contains sections like:
|
||||
- `## ADDED Requirements` - New requirements to add
|
||||
- `## MODIFIED Requirements` - Changes to existing requirements
|
||||
- `## REMOVED Requirements` - Requirements to remove
|
||||
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
|
||||
|
||||
If no delta specs found, inform user and stop.
|
||||
|
||||
4. **For each delta spec, apply changes to main specs**
|
||||
|
||||
For each repo-local capability delta spec path returned by the CLI:
|
||||
|
||||
a. **Read the delta spec** to understand the intended changes
|
||||
|
||||
b. **Read the main spec** at `openspec/specs/<capability>/spec.md` (may not exist yet)
|
||||
|
||||
c. **Apply changes intelligently**:
|
||||
|
||||
**ADDED Requirements:**
|
||||
- If requirement doesn't exist in main spec → add it
|
||||
- If requirement already exists → update it to match (treat as implicit MODIFIED)
|
||||
|
||||
**MODIFIED Requirements:**
|
||||
- Find the requirement in main spec
|
||||
- Apply the changes - this can be:
|
||||
- Adding new scenarios (don't need to copy existing ones)
|
||||
- Modifying existing scenarios
|
||||
- Changing the requirement description
|
||||
- Preserve scenarios/content not mentioned in the delta
|
||||
|
||||
**REMOVED Requirements:**
|
||||
- Remove the entire requirement block from main spec
|
||||
|
||||
**RENAMED Requirements:**
|
||||
- Find the FROM requirement, rename to TO
|
||||
|
||||
d. **Create new main spec** if capability doesn't exist yet:
|
||||
- Create `openspec/specs/<capability>/spec.md`
|
||||
- Add Purpose section (can be brief, mark as TBD)
|
||||
- Add Requirements section with the ADDED requirements
|
||||
|
||||
5. **Show summary**
|
||||
|
||||
After applying all changes, summarize:
|
||||
- Which capabilities were updated
|
||||
- What changes were made (requirements added/modified/removed/renamed)
|
||||
|
||||
**Delta Spec Format Reference**
|
||||
|
||||
```markdown
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: New Feature
|
||||
The system SHALL do something new.
|
||||
|
||||
#### Scenario: Basic case
|
||||
- **WHEN** user does X
|
||||
- **THEN** system does Y
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Existing Feature
|
||||
#### Scenario: New scenario to add
|
||||
- **WHEN** user does A
|
||||
- **THEN** system does B
|
||||
|
||||
## REMOVED Requirements
|
||||
|
||||
### Requirement: Deprecated Feature
|
||||
|
||||
## RENAMED Requirements
|
||||
|
||||
- FROM: `### Requirement: Old Name`
|
||||
- TO: `### Requirement: New Name`
|
||||
```
|
||||
|
||||
**Key Principle: Intelligent Merging**
|
||||
|
||||
Unlike programmatic merging, you can apply **partial updates**:
|
||||
- To add a scenario, just include that scenario under MODIFIED - don't copy existing scenarios
|
||||
- The delta represents *intent*, not a wholesale replacement
|
||||
- Use your judgment to merge changes sensibly
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```
|
||||
## Specs Synced: <change-name>
|
||||
|
||||
Updated main specs:
|
||||
|
||||
**<capability-1>**:
|
||||
- Added requirement: "New Feature"
|
||||
- Modified requirement: "Existing Feature" (added 1 scenario)
|
||||
|
||||
**<capability-2>**:
|
||||
- Created new spec file
|
||||
- Added requirement: "Another Feature"
|
||||
|
||||
Main specs are now updated. The change remains active - archive when implementation is complete.
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Read both delta and main specs before making changes
|
||||
- Preserve existing content not mentioned in delta
|
||||
- If something is unclear, ask for clarification
|
||||
- Show what you're changing as you go
|
||||
- The operation should be idempotent - running twice should give same result
|
||||
159
.claude/skills/openspec-apply-change/SKILL.md
Normal file
159
.claude/skills/openspec-apply-change/SKILL.md
Normal file
@@ -0,0 +1,159 @@
|
||||
---
|
||||
name: openspec-apply-change
|
||||
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.4.1"
|
||||
---
|
||||
|
||||
Implement tasks from an OpenSpec change.
|
||||
|
||||
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
|
||||
|
||||
2. **Check status to understand the schema**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used (e.g., "spec-driven")
|
||||
- `planningHome`, `changeRoot`, and `actionContext`: planning scope and edit constraints
|
||||
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
|
||||
|
||||
3. **Get apply instructions**
|
||||
|
||||
```bash
|
||||
openspec instructions apply --change "<name>" --json
|
||||
```
|
||||
|
||||
This returns:
|
||||
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
|
||||
- Progress (total, complete, remaining)
|
||||
- Task list with status
|
||||
- Dynamic instruction based on current state
|
||||
|
||||
**Handle states:**
|
||||
- If `state: "blocked"` (missing artifacts): show message, suggest using openspec-continue-change
|
||||
- If `state: "all_done"`: congratulate, suggest archive
|
||||
- Otherwise: proceed to implementation
|
||||
|
||||
**Workspace guard:** If status JSON reports `actionContext.mode: "workspace-planning"` and `allowedEditRoots` is empty, explain that full workspace apply is not supported in this slice. Treat linked repos and folders as read-only context, ask the user to select an affected area through an explicit implementation workflow, and STOP before editing files.
|
||||
|
||||
4. **Read context files**
|
||||
|
||||
Read every file path listed under `contextFiles` from the apply instructions output.
|
||||
The files depend on the schema being used:
|
||||
- **spec-driven**: proposal, specs, design, tasks
|
||||
- Other schemas: follow the contextFiles from CLI output
|
||||
|
||||
5. **Show current progress**
|
||||
|
||||
Display:
|
||||
- Schema being used
|
||||
- Progress: "N/M tasks complete"
|
||||
- Remaining tasks overview
|
||||
- Dynamic instruction from CLI
|
||||
|
||||
6. **Implement tasks (loop until done or blocked)**
|
||||
|
||||
For each pending task:
|
||||
- Show which task is being worked on
|
||||
- Make the code changes required
|
||||
- Keep changes minimal and focused
|
||||
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
|
||||
- Continue to next task
|
||||
|
||||
**Pause if:**
|
||||
- Task is unclear → ask for clarification
|
||||
- Implementation reveals a design issue → suggest updating artifacts
|
||||
- Error or blocker encountered → report and wait for guidance
|
||||
- User interrupts
|
||||
|
||||
7. **On completion or pause, show status**
|
||||
|
||||
Display:
|
||||
- Tasks completed this session
|
||||
- Overall progress: "N/M tasks complete"
|
||||
- If all done: suggest archive
|
||||
- If paused: explain why and wait for guidance
|
||||
|
||||
**Output During Implementation**
|
||||
|
||||
```
|
||||
## Implementing: <change-name> (schema: <schema-name>)
|
||||
|
||||
Working on task 3/7: <task description>
|
||||
[...implementation happening...]
|
||||
✓ Task complete
|
||||
|
||||
Working on task 4/7: <task description>
|
||||
[...implementation happening...]
|
||||
✓ Task complete
|
||||
```
|
||||
|
||||
**Output On Completion**
|
||||
|
||||
```
|
||||
## Implementation Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 7/7 tasks complete ✓
|
||||
|
||||
### Completed This Session
|
||||
- [x] Task 1
|
||||
- [x] Task 2
|
||||
...
|
||||
|
||||
All tasks complete! Ready to archive this change.
|
||||
```
|
||||
|
||||
**Output On Pause (Issue Encountered)**
|
||||
|
||||
```
|
||||
## Implementation Paused
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 4/7 tasks complete
|
||||
|
||||
### Issue Encountered
|
||||
<description of the issue>
|
||||
|
||||
**Options:**
|
||||
1. <option 1>
|
||||
2. <option 2>
|
||||
3. Other approach
|
||||
|
||||
What would you like to do?
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Keep going through tasks until done or blocked
|
||||
- Always read context files before starting (from the apply instructions output)
|
||||
- If task is ambiguous, pause and ask before implementing
|
||||
- If implementation reveals issues, pause and suggest artifact updates
|
||||
- Keep code changes minimal and scoped to each task
|
||||
- Update task checkbox immediately after completing each task
|
||||
- Pause on errors, blockers, or unclear requirements - don't guess
|
||||
- Use contextFiles from CLI output, don't assume specific file names
|
||||
|
||||
**Fluid Workflow Integration**
|
||||
|
||||
This skill supports the "actions on a change" model:
|
||||
|
||||
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
|
||||
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
|
||||
117
.claude/skills/openspec-archive-change/SKILL.md
Normal file
117
.claude/skills/openspec-archive-change/SKILL.md
Normal file
@@ -0,0 +1,117 @@
|
||||
---
|
||||
name: openspec-archive-change
|
||||
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.4.1"
|
||||
---
|
||||
|
||||
Archive a completed change in the experimental workflow.
|
||||
|
||||
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no change name provided, prompt for selection**
|
||||
|
||||
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
|
||||
|
||||
Show only active changes (not already archived).
|
||||
Include the schema used for each change if available.
|
||||
|
||||
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||
|
||||
2. **Check artifact completion status**
|
||||
|
||||
Run `openspec status --change "<name>" --json` to check artifact completion.
|
||||
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used
|
||||
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context
|
||||
- `artifacts`: List of artifacts with their status (`done` or other)
|
||||
|
||||
If status reports `actionContext.mode: "workspace-planning"`, explain that workspace archive is not supported in this slice and STOP. Do not move workspace changes into repo-local archives or edit linked repos.
|
||||
|
||||
**If any artifacts are not `done`:**
|
||||
- Display warning listing incomplete artifacts
|
||||
- Use **AskUserQuestion tool** to confirm user wants to proceed
|
||||
- Proceed if user confirms
|
||||
|
||||
3. **Check task completion status**
|
||||
|
||||
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
|
||||
|
||||
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
|
||||
|
||||
**If incomplete tasks found:**
|
||||
- Display warning showing count of incomplete tasks
|
||||
- Use **AskUserQuestion tool** to confirm user wants to proceed
|
||||
- Proceed if user confirms
|
||||
|
||||
**If no tasks file exists:** Proceed without task-related warning.
|
||||
|
||||
4. **Assess delta spec sync state**
|
||||
|
||||
Use `artifactPaths.specs.existingOutputPaths` from status JSON to check for delta specs. If none exist, proceed without sync prompt.
|
||||
|
||||
**If delta specs exist:**
|
||||
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
|
||||
- Determine what changes would be applied (adds, modifications, removals, renames)
|
||||
- Show a combined summary before prompting
|
||||
|
||||
**Prompt options:**
|
||||
- If changes needed: "Sync now (recommended)", "Archive without syncing"
|
||||
- If already synced: "Archive now", "Sync anyway", "Cancel"
|
||||
|
||||
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
|
||||
|
||||
5. **Perform the archive**
|
||||
|
||||
Create an `archive` directory under `planningHome.changesDir` if it doesn't exist:
|
||||
```bash
|
||||
mkdir -p "<planningHome.changesDir>/archive"
|
||||
```
|
||||
|
||||
Generate target name using current date: `YYYY-MM-DD-<change-name>`
|
||||
|
||||
**Check if target already exists:**
|
||||
- If yes: Fail with error, suggest renaming existing archive or using different date
|
||||
- If no: Move `changeRoot` to the archive directory
|
||||
|
||||
```bash
|
||||
mv "<changeRoot>" "<planningHome.changesDir>/archive/YYYY-MM-DD-<name>"
|
||||
```
|
||||
|
||||
6. **Display summary**
|
||||
|
||||
Show archive completion summary including:
|
||||
- Change name
|
||||
- Schema that was used
|
||||
- Archive location
|
||||
- Whether specs were synced (if applicable)
|
||||
- Note about any warnings (incomplete artifacts/tasks)
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** the archive path derived from `planningHome.changesDir`/YYYY-MM-DD-<name>/
|
||||
**Specs:** ✓ Synced to main specs (or "No delta specs" or "Sync skipped")
|
||||
|
||||
All artifacts complete. All tasks complete.
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Always prompt for change selection if not provided
|
||||
- Use artifact graph (openspec status --json) for completion checking
|
||||
- Don't block archive on warnings - just inform and confirm
|
||||
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
|
||||
- Show clear summary of what happened
|
||||
- If sync is requested, use openspec-sync-specs approach (agent-driven)
|
||||
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
|
||||
287
.claude/skills/openspec-explore/SKILL.md
Normal file
287
.claude/skills/openspec-explore/SKILL.md
Normal file
@@ -0,0 +1,287 @@
|
||||
---
|
||||
name: openspec-explore
|
||||
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.4.1"
|
||||
---
|
||||
|
||||
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
|
||||
|
||||
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
|
||||
|
||||
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
|
||||
|
||||
---
|
||||
|
||||
## The Stance
|
||||
|
||||
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
|
||||
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
|
||||
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
|
||||
- **Adaptive** - Follow interesting threads, pivot when new information emerges
|
||||
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
|
||||
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
|
||||
|
||||
---
|
||||
|
||||
## What You Might Do
|
||||
|
||||
Depending on what the user brings, you might:
|
||||
|
||||
**Explore the problem space**
|
||||
- Ask clarifying questions that emerge from what they said
|
||||
- Challenge assumptions
|
||||
- Reframe the problem
|
||||
- Find analogies
|
||||
|
||||
**Investigate the codebase**
|
||||
- Map existing architecture relevant to the discussion
|
||||
- Find integration points
|
||||
- Identify patterns already in use
|
||||
- Surface hidden complexity
|
||||
|
||||
**Compare options**
|
||||
- Brainstorm multiple approaches
|
||||
- Build comparison tables
|
||||
- Sketch tradeoffs
|
||||
- Recommend a path (if asked)
|
||||
|
||||
**Visualize**
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ Use ASCII diagrams liberally │
|
||||
├─────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌────────┐ ┌────────┐ │
|
||||
│ │ State │────────▶│ State │ │
|
||||
│ │ A │ │ B │ │
|
||||
│ └────────┘ └────────┘ │
|
||||
│ │
|
||||
│ System diagrams, state machines, │
|
||||
│ data flows, architecture sketches, │
|
||||
│ dependency graphs, comparison tables │
|
||||
│ │
|
||||
└─────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Surface risks and unknowns**
|
||||
- Identify what could go wrong
|
||||
- Find gaps in understanding
|
||||
- Suggest spikes or investigations
|
||||
|
||||
---
|
||||
|
||||
## OpenSpec Awareness
|
||||
|
||||
You have full context of the OpenSpec system. Use it naturally, don't force it.
|
||||
|
||||
### Check for context
|
||||
|
||||
At the start, quickly check what exists:
|
||||
```bash
|
||||
openspec list --json
|
||||
```
|
||||
|
||||
This tells you:
|
||||
- If there are active changes
|
||||
- Their names, schemas, and status
|
||||
- What the user might be working on
|
||||
|
||||
### When no change exists
|
||||
|
||||
Think freely. When insights crystallize, you might offer:
|
||||
|
||||
- "This feels solid enough to start a change. Want me to create a proposal?"
|
||||
- Or keep exploring - no pressure to formalize
|
||||
|
||||
### When a change exists
|
||||
|
||||
If the user mentions a change or you detect one is relevant:
|
||||
|
||||
1. **Resolve and read existing artifacts for context**
|
||||
- Run `openspec status --change "<name>" --json`.
|
||||
- Use `changeRoot`, `artifactPaths`, and `actionContext` from the status JSON.
|
||||
- Read existing files from `artifactPaths.<artifact>.existingOutputPaths`.
|
||||
|
||||
2. **Reference them naturally in conversation**
|
||||
- "Your design mentions using Redis, but we just realized SQLite fits better..."
|
||||
- "The proposal scopes this to premium users, but we're now thinking everyone..."
|
||||
|
||||
3. **Offer to capture when decisions are made**
|
||||
|
||||
| Insight Type | Where to Capture |
|
||||
|----------------------------|--------------------------------|
|
||||
| New requirement discovered | `specs/<capability>/spec.md` |
|
||||
| Requirement changed | `specs/<capability>/spec.md` |
|
||||
| Design decision made | `design.md` |
|
||||
| Scope changed | `proposal.md` |
|
||||
| New work identified | `tasks.md` |
|
||||
| Assumption invalidated | Relevant artifact |
|
||||
|
||||
Example offers:
|
||||
- "That's a design decision. Capture it in design.md?"
|
||||
- "This is a new requirement. Add it to specs?"
|
||||
- "This changes scope. Update the proposal?"
|
||||
|
||||
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
|
||||
|
||||
---
|
||||
|
||||
## What You Don't Have To Do
|
||||
|
||||
- Follow a script
|
||||
- Ask the same questions every time
|
||||
- Produce a specific artifact
|
||||
- Reach a conclusion
|
||||
- Stay on topic if a tangent is valuable
|
||||
- Be brief (this is thinking time)
|
||||
|
||||
---
|
||||
|
||||
## Handling Different Entry Points
|
||||
|
||||
**User brings a vague idea:**
|
||||
```
|
||||
User: I'm thinking about adding real-time collaboration
|
||||
|
||||
You: Real-time collab is a big space. Let me think about this...
|
||||
|
||||
COLLABORATION SPECTRUM
|
||||
════════════════════════════════════════════
|
||||
|
||||
Awareness Coordination Sync
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
┌────────┐ ┌────────┐ ┌────────┐
|
||||
│Presence│ │Cursors │ │ CRDT │
|
||||
│ "3 │ │ Multi │ │Conflict│
|
||||
│online" │ │ select │ │ free │
|
||||
└────────┘ └────────┘ └────────┘
|
||||
│ │ │
|
||||
trivial moderate complex
|
||||
|
||||
Where's your head at?
|
||||
```
|
||||
|
||||
**User brings a specific problem:**
|
||||
```
|
||||
User: The auth system is a mess
|
||||
|
||||
You: [reads codebase]
|
||||
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ CURRENT AUTH FLOW │
|
||||
└─────────────────────────────────────────────┘
|
||||
│
|
||||
┌─────────────┼─────────────┐
|
||||
▼ ▼ ▼
|
||||
┌─────────┐ ┌─────────┐ ┌─────────┐
|
||||
│ Google │ │ GitHub │ │ Email │
|
||||
│ OAuth │ │ OAuth │ │ Magic │
|
||||
└────┬────┘ └────┬────┘ └────┬────┘
|
||||
│ │ │
|
||||
└─────────────┼─────────────┘
|
||||
▼
|
||||
┌───────────┐
|
||||
│ Session │
|
||||
└─────┬─────┘
|
||||
│
|
||||
▼
|
||||
┌───────────┐
|
||||
│ Perms │
|
||||
└───────────┘
|
||||
|
||||
I see three tangles. Which one's burning?
|
||||
```
|
||||
|
||||
**User is stuck mid-implementation:**
|
||||
```
|
||||
User: /opsx:explore add-auth-system
|
||||
The OAuth integration is more complex than expected
|
||||
|
||||
You: [reads change artifacts]
|
||||
|
||||
You're on task 4: "Implement OAuth flow"
|
||||
|
||||
Let me trace what's involved...
|
||||
|
||||
[draws diagram, explores options, suggests paths]
|
||||
|
||||
Want to update the design to reflect this?
|
||||
Or add a spike task to investigate?
|
||||
```
|
||||
|
||||
**User wants to compare options:**
|
||||
```
|
||||
User: Should we use Postgres or SQLite?
|
||||
|
||||
You: Generic answer is boring. What's the context?
|
||||
|
||||
User: A CLI tool that tracks local dev environments
|
||||
|
||||
You: That changes everything.
|
||||
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ CLI TOOL DATA STORAGE │
|
||||
└─────────────────────────────────────────────────┘
|
||||
|
||||
Key constraints:
|
||||
• No daemon running
|
||||
• Must work offline
|
||||
• Single user
|
||||
|
||||
SQLite Postgres
|
||||
Deployment embedded ✓ needs server ✗
|
||||
Offline yes ✓ no ✗
|
||||
Single file yes ✓ no ✗
|
||||
|
||||
SQLite. Not even close.
|
||||
|
||||
Unless... is there a sync component?
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Ending Discovery
|
||||
|
||||
There's no required ending. Discovery might:
|
||||
|
||||
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
|
||||
- **Result in artifact updates**: "Updated design.md with these decisions"
|
||||
- **Just provide clarity**: User has what they need, moves on
|
||||
- **Continue later**: "We can pick this up anytime"
|
||||
|
||||
When it feels like things are crystallizing, you might summarize:
|
||||
|
||||
```
|
||||
## What We Figured Out
|
||||
|
||||
**The problem**: [crystallized understanding]
|
||||
|
||||
**The approach**: [if one emerged]
|
||||
|
||||
**Open questions**: [if any remain]
|
||||
|
||||
**Next steps** (if ready):
|
||||
- Create a change proposal
|
||||
- Keep exploring: just keep talking
|
||||
```
|
||||
|
||||
But this summary is optional. Sometimes the thinking IS the value.
|
||||
|
||||
---
|
||||
|
||||
## Guardrails
|
||||
|
||||
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
|
||||
- **Don't fake understanding** - If something is unclear, dig deeper
|
||||
- **Don't rush** - Discovery is thinking time, not task time
|
||||
- **Don't force structure** - Let patterns emerge naturally
|
||||
- **Don't auto-capture** - Offer to save insights, don't just do it
|
||||
- **Do visualize** - A good diagram is worth many paragraphs
|
||||
- **Do explore the codebase** - Ground discussions in reality
|
||||
- **Do question assumptions** - Including the user's and your own
|
||||
111
.claude/skills/openspec-propose/SKILL.md
Normal file
111
.claude/skills/openspec-propose/SKILL.md
Normal file
@@ -0,0 +1,111 @@
|
||||
---
|
||||
name: openspec-propose
|
||||
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.4.1"
|
||||
---
|
||||
|
||||
Propose a new change - create the change and generate all artifacts in one step.
|
||||
|
||||
I'll create a change with artifacts:
|
||||
- proposal.md (what & why)
|
||||
- design.md (how)
|
||||
- tasks.md (implementation steps)
|
||||
|
||||
When ready to implement, run /opsx:apply
|
||||
|
||||
---
|
||||
|
||||
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no clear input provided, ask what they want to build**
|
||||
|
||||
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
|
||||
> "What change do you want to work on? Describe what you want to build or fix."
|
||||
|
||||
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
|
||||
|
||||
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||
|
||||
2. **Create the change directory**
|
||||
```bash
|
||||
openspec new change "<name>"
|
||||
```
|
||||
This creates a scaffolded change in the planning home resolved by the CLI with `.openspec.yaml`.
|
||||
|
||||
3. **Get the artifact build order**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to get:
|
||||
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
|
||||
- `artifacts`: list of all artifacts with their status and dependencies
|
||||
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
|
||||
|
||||
4. **Create artifacts in sequence until apply-ready**
|
||||
|
||||
Use the **TodoWrite tool** to track progress through the artifacts.
|
||||
|
||||
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
|
||||
|
||||
a. **For each artifact that is `ready` (dependencies satisfied)**:
|
||||
- Get instructions:
|
||||
```bash
|
||||
openspec instructions <artifact-id> --change "<name>" --json
|
||||
```
|
||||
- The instructions JSON includes:
|
||||
- `context`: Project background (constraints for you - do NOT include in output)
|
||||
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
|
||||
- `template`: The structure to use for your output file
|
||||
- `instruction`: Schema-specific guidance for this artifact type
|
||||
- `resolvedOutputPath`: Resolved path or pattern to write the artifact
|
||||
- `dependencies`: Completed artifacts to read for context
|
||||
- Read any completed dependency files for context
|
||||
- Create the artifact file using `template` as the structure and write it to `resolvedOutputPath`
|
||||
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
|
||||
- Show brief progress: "Created <artifact-id>"
|
||||
|
||||
b. **Continue until all `applyRequires` artifacts are complete**
|
||||
- After creating each artifact, re-run `openspec status --change "<name>" --json`
|
||||
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
|
||||
- Stop when all `applyRequires` artifacts are done
|
||||
|
||||
c. **If an artifact requires user input** (unclear context):
|
||||
- Use **AskUserQuestion tool** to clarify
|
||||
- Then continue with creation
|
||||
|
||||
5. **Show final status**
|
||||
```bash
|
||||
openspec status --change "<name>"
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
After completing all artifacts, summarize:
|
||||
- Change name and location
|
||||
- List of artifacts created with brief descriptions
|
||||
- What's ready: "All artifacts created! Ready for implementation."
|
||||
- Prompt: "Run `/opsx:apply` or ask me to implement to start working on the tasks."
|
||||
|
||||
**Artifact Creation Guidelines**
|
||||
|
||||
- Follow the `instruction` field from `openspec instructions` for each artifact type
|
||||
- The schema defines what each artifact should contain - follow it
|
||||
- Read dependency artifacts for context before creating new ones
|
||||
- Use `template` as the structure for your output file - fill in its sections
|
||||
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
|
||||
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
|
||||
- These guide what you write, but should never appear in the output
|
||||
|
||||
**Guardrails**
|
||||
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
|
||||
- Always read dependency artifacts before creating a new one
|
||||
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
|
||||
- If a change with that name already exists, ask if user wants to continue it or create a new one
|
||||
- Verify each artifact file exists after writing before proceeding to next
|
||||
147
.claude/skills/openspec-sync-specs/SKILL.md
Normal file
147
.claude/skills/openspec-sync-specs/SKILL.md
Normal file
@@ -0,0 +1,147 @@
|
||||
---
|
||||
name: openspec-sync-specs
|
||||
description: Sync delta specs from a change to main specs. Use when the user wants to update main specs with changes from a delta spec, without archiving the change.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.4.1"
|
||||
---
|
||||
|
||||
Sync delta specs from a change to main specs.
|
||||
|
||||
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
|
||||
|
||||
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no change name provided, prompt for selection**
|
||||
|
||||
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
|
||||
|
||||
Show changes that have delta specs (under `specs/` directory).
|
||||
|
||||
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||
|
||||
2. **Resolve change context**
|
||||
|
||||
Run:
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
|
||||
If status reports `actionContext.mode: "workspace-planning"`, explain that workspace spec sync is not supported in this slice and STOP. Do not fall back to repo-local paths or edit linked repos.
|
||||
|
||||
3. **Find delta specs**
|
||||
|
||||
Use `artifactPaths.specs.existingOutputPaths` from the status JSON as the list of delta spec files.
|
||||
|
||||
Each delta spec file contains sections like:
|
||||
- `## ADDED Requirements` - New requirements to add
|
||||
- `## MODIFIED Requirements` - Changes to existing requirements
|
||||
- `## REMOVED Requirements` - Requirements to remove
|
||||
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
|
||||
|
||||
If no delta specs found, inform user and stop.
|
||||
|
||||
4. **For each delta spec, apply changes to main specs**
|
||||
|
||||
For each repo-local capability delta spec path returned by the CLI:
|
||||
|
||||
a. **Read the delta spec** to understand the intended changes
|
||||
|
||||
b. **Read the main spec** at `openspec/specs/<capability>/spec.md` (may not exist yet)
|
||||
|
||||
c. **Apply changes intelligently**:
|
||||
|
||||
**ADDED Requirements:**
|
||||
- If requirement doesn't exist in main spec → add it
|
||||
- If requirement already exists → update it to match (treat as implicit MODIFIED)
|
||||
|
||||
**MODIFIED Requirements:**
|
||||
- Find the requirement in main spec
|
||||
- Apply the changes - this can be:
|
||||
- Adding new scenarios (don't need to copy existing ones)
|
||||
- Modifying existing scenarios
|
||||
- Changing the requirement description
|
||||
- Preserve scenarios/content not mentioned in the delta
|
||||
|
||||
**REMOVED Requirements:**
|
||||
- Remove the entire requirement block from main spec
|
||||
|
||||
**RENAMED Requirements:**
|
||||
- Find the FROM requirement, rename to TO
|
||||
|
||||
d. **Create new main spec** if capability doesn't exist yet:
|
||||
- Create `openspec/specs/<capability>/spec.md`
|
||||
- Add Purpose section (can be brief, mark as TBD)
|
||||
- Add Requirements section with the ADDED requirements
|
||||
|
||||
5. **Show summary**
|
||||
|
||||
After applying all changes, summarize:
|
||||
- Which capabilities were updated
|
||||
- What changes were made (requirements added/modified/removed/renamed)
|
||||
|
||||
**Delta Spec Format Reference**
|
||||
|
||||
```markdown
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: New Feature
|
||||
The system SHALL do something new.
|
||||
|
||||
#### Scenario: Basic case
|
||||
- **WHEN** user does X
|
||||
- **THEN** system does Y
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Existing Feature
|
||||
#### Scenario: New scenario to add
|
||||
- **WHEN** user does A
|
||||
- **THEN** system does B
|
||||
|
||||
## REMOVED Requirements
|
||||
|
||||
### Requirement: Deprecated Feature
|
||||
|
||||
## RENAMED Requirements
|
||||
|
||||
- FROM: `### Requirement: Old Name`
|
||||
- TO: `### Requirement: New Name`
|
||||
```
|
||||
|
||||
**Key Principle: Intelligent Merging**
|
||||
|
||||
Unlike programmatic merging, you can apply **partial updates**:
|
||||
- To add a scenario, just include that scenario under MODIFIED - don't copy existing scenarios
|
||||
- The delta represents *intent*, not a wholesale replacement
|
||||
- Use your judgment to merge changes sensibly
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```
|
||||
## Specs Synced: <change-name>
|
||||
|
||||
Updated main specs:
|
||||
|
||||
**<capability-1>**:
|
||||
- Added requirement: "New Feature"
|
||||
- Modified requirement: "Existing Feature" (added 1 scenario)
|
||||
|
||||
**<capability-2>**:
|
||||
- Created new spec file
|
||||
- Added requirement: "Another Feature"
|
||||
|
||||
Main specs are now updated. The change remains active - archive when implementation is complete.
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Read both delta and main specs before making changes
|
||||
- Preserve existing content not mentioned in delta
|
||||
- If something is unclear, ask for clarification
|
||||
- Show what you're changing as you go
|
||||
- The operation should be idempotent - running twice should give same result
|
||||
33
.github/workflows/i18n-audit.yml
vendored
Normal file
33
.github/workflows/i18n-audit.yml
vendored
Normal file
@@ -0,0 +1,33 @@
|
||||
# GitHub Actions 示例:i18n audit on PR
|
||||
name: i18n-audit
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'lang/**'
|
||||
- 'lang-bundle.json'
|
||||
- '**/*.vue'
|
||||
- '**/*.js'
|
||||
- 'scripts/i18n_audit.py'
|
||||
- 'scripts/audit_lang_bundle_v2.py'
|
||||
|
||||
jobs:
|
||||
audit:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.11'
|
||||
- name: Run i18n audit
|
||||
run: |
|
||||
python scripts/i18n_audit.py --strict
|
||||
- name: Upload audit report
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: i18n-audit-report
|
||||
path: scripts/lang_audit_report_v2.json
|
||||
83
.gitignore
vendored
83
.gitignore
vendored
@@ -1,5 +1,86 @@
|
||||
/unpackage
|
||||
/.hbuilderx
|
||||
/.idea
|
||||
/.logs
|
||||
/node_modules
|
||||
/iconfont-preview.html
|
||||
|
||||
.codebuddy
|
||||
.vscode
|
||||
.trae
|
||||
# 本地调试配置 (含 uniacid / 域名, 每人不同, 不应入仓)
|
||||
# 注意: 如果 .local.config.js 已经被之前的 commit 入仓,
|
||||
# 需要手动 `git rm --cached .local.config.js` 并用 filter-branch
|
||||
# 清理历史 (仅限团队协商后操作)
|
||||
.local.config.js
|
||||
|
||||
# 鸿蒙元服务构建产物 (被 .gitignore 的只是产物, HAR 元数据需要 git 管理)
|
||||
# 重要: ascf_build 根目录的元数据 (oh-package.json5 / Index.ets / build-profile.json5 / ...)
|
||||
# 必须被 git 管理, 否则无法追踪 "module.name 被清空" 等回归。
|
||||
# 这些元数据通过下方的 ! 取反规则显式纳入 git。
|
||||
stub-app-projects/mp-harmony/ascf/ascf_src
|
||||
stub-app-projects/mp-harmony/entry/src/main/resources/rawfile
|
||||
|
||||
# ascf_build/<pkg>/ 是 HAR 包定义
|
||||
# 区分两类内容:
|
||||
# 1. 必须入 git (元数据 / 构建配置 / HAR 入口):
|
||||
# - oh-package.json5, build-profile.json5, hvigorfile.ts
|
||||
# - obfuscation-rules.txt, src/main/module.json5
|
||||
# - src/main/resources/base/element/string.json (HAR i18n)
|
||||
# 2. 每次构建覆盖 (不应入 git):
|
||||
# - src/main/resources/rawfile/** : 鸿蒙端从 ascf_src 同步的编译产物
|
||||
# - Index.ets : 空壳文件, 无内容
|
||||
# - build/, oh_modules/, .preview/, .cxx/, .test/, node_modules/
|
||||
|
||||
# rawfile/ 整体 ignore (鸿蒙端每次 Build 重新生成)
|
||||
stub-app-projects/mp-harmony/ascf/ascf_build/**/rawfile/**
|
||||
|
||||
# Index.ets 是空壳 (每个包都是 0 字节), 不入 git
|
||||
stub-app-projects/mp-harmony/ascf/ascf_build/**/Index.ets
|
||||
|
||||
# 其他产物目录
|
||||
stub-app-projects/mp-harmony/ascf/ascf_build/**/build
|
||||
stub-app-projects/mp-harmony/ascf/ascf_build/**/oh_modules
|
||||
stub-app-projects/mp-harmony/ascf/ascf_build/**/.preview
|
||||
stub-app-projects/mp-harmony/ascf/ascf_build/**/.cxx
|
||||
stub-app-projects/mp-harmony/ascf/ascf_build/**/.test
|
||||
stub-app-projects/mp-harmony/ascf/ascf_build/**/node_modules
|
||||
|
||||
# entry 下的产物
|
||||
stub-app-projects/mp-harmony/entry/build
|
||||
stub-app-projects/mp-harmony/entry/oh_modules
|
||||
stub-app-projects/mp-harmony/entry/.preview
|
||||
stub-app-projects/mp-harmony/entry/.cxx
|
||||
stub-app-projects/mp-harmony/entry/.test
|
||||
stub-app-projects/mp-harmony/entry/node_modules
|
||||
# 鸿蒙工程顶层产物 (.hvigor / hvigor / .idea 已在根 .gitignore 范围或更精准的鸿蒙子 .gitignore)
|
||||
stub-app-projects/mp-harmony/oh_modules
|
||||
stub-app-projects/mp-harmony/.hvigor
|
||||
stub-app-projects/mp-harmony/.idea
|
||||
# 鸿蒙 hvigor 自身依赖
|
||||
stub-app-projects/mp-harmony/hvigor
|
||||
# Trae/IDE 临时文件
|
||||
.hvigor/outputs
|
||||
.trae_permission_check_*
|
||||
|
||||
# 本地测试脚本与产物归档(不入 git, 留本地复用)
|
||||
# 内容: Playwright 截图 / 测试脚本 / 对比图 / 临时提交草稿
|
||||
# 复用方式: cd _test_archive && python xxx.py
|
||||
_test_archive/
|
||||
|
||||
# 兜底:防止任何临时测试文件被遗漏在根目录
|
||||
# 名称以 _test_/_compare_/_auth_ 开头, 或 check_button.py 等
|
||||
_test_*.png
|
||||
_test_*.html
|
||||
_compare*.png
|
||||
_compare*.py
|
||||
_auth_*.json
|
||||
_commit_msg.txt
|
||||
/check_button.py
|
||||
# 鸿蒙签名材料 (敏感, 绝不能提交到公共 git)
|
||||
# 仓库有 origin (github.com/Zajd/jsysq-uniapp) 是公开仓库, 签名材料必须 gitignore
|
||||
stub-app-projects/mp-harmony/**/cert-profile
|
||||
stub-app-projects/mp-harmony/**/.p12
|
||||
stub-app-projects/mp-harmony/**/.p7b
|
||||
stub-app-projects/mp-harmony/**/.cer
|
||||
stub-app-projects/mp-harmony/**/.csr
|
||||
stub-app-projects/mp-harmony/**/material
|
||||
13
.hbuilderx/launch.json
Normal file
13
.hbuilderx/launch.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"version" : "1.0",
|
||||
"configurations" : [
|
||||
{
|
||||
"openVueDevtools" : true,
|
||||
"type" : "uni-app:h5"
|
||||
},
|
||||
{
|
||||
"playground" : "standard",
|
||||
"type" : "uni-app:app-android"
|
||||
}
|
||||
]
|
||||
}
|
||||
43
.husky/pre-commit
Normal file
43
.husky/pre-commit
Normal file
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env sh
|
||||
#
|
||||
# 自动 hook:i18n 完整性。
|
||||
# 在 commit 前,如果改动触及 lang/、使用 $lang() 的 .vue/.js,或 lang-bundle.json,
|
||||
# 就跑一次审计,真问题会拦下 commit。
|
||||
#
|
||||
# 启用方法:
|
||||
# 1) 项目根已有 .husky/pre-commit(本脚本)
|
||||
# 2) 把这个 commit-msg / pre-commit 加入 husky 钩子(本仓库用 simple-git-hooks
|
||||
# 或 husky 都行,本脚本不依赖特定框架)
|
||||
#
|
||||
# 也可以在 CI 跑:
|
||||
# python scripts/i18n_audit.py --strict
|
||||
|
||||
set -e
|
||||
|
||||
# 检测本次 diff 是否触动相关文件
|
||||
changed=$(git diff --cached --name-only HEAD)
|
||||
|
||||
relevant=$(echo "$changed" | grep -E '(lang/|lang-bundle\.json|\.vue$|\.js$)' | grep -v 'scripts/i18n_audit\|scripts/audit\|scripts/I18N_AUDIT' || true)
|
||||
|
||||
if [ -z "$relevant" ]; then
|
||||
echo "[pre-commit] No lang-touching files; skip i18n audit."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "[pre-commit] Running i18n audit on changed files:"
|
||||
echo "$relevant" | sed 's/^/ /'
|
||||
|
||||
cd "$(git rev-parse --show-toplevel)"
|
||||
|
||||
if command -v python >/dev/null 2>&1; then
|
||||
if python scripts/i18n_audit.py --strict; then
|
||||
echo "[pre-commit] i18n OK"
|
||||
exit 0
|
||||
else
|
||||
echo "[pre-commit] i18n FAILED — 修复方法见 scripts/I18N_AUDIT.md"
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
echo "[pre-commit] python not available; skipping"
|
||||
exit 0
|
||||
fi
|
||||
229
.local.config.js
229
.local.config.js
@@ -9,7 +9,7 @@ const localDevConfig = ({
|
||||
'576-xcx30.5g': { // 活性石灰装备
|
||||
uniacid: 576,
|
||||
domain: 'https://xcx30.5g-quickapp.com/',
|
||||
},
|
||||
},
|
||||
'2285': { // 数码喷墨墨水
|
||||
uniacid: 2285,
|
||||
domain: 'https://xcx.aigc-quickapp.com/',
|
||||
@@ -17,19 +17,23 @@ const localDevConfig = ({
|
||||
'2811': { // POCT检测分析平台
|
||||
uniacid: 2811,
|
||||
domain: 'https://xcx6.aigc-quickapp.com/',
|
||||
},
|
||||
},
|
||||
'2881': { // 防爆电器
|
||||
uniacid: 2881,
|
||||
domain: 'https://xcx6.aigc-quickapp.com/',
|
||||
},
|
||||
'2724': { // 生物菌肥
|
||||
uniacid: 2724,
|
||||
domain: 'https://xcx.aigc-quickapp.com/',
|
||||
},
|
||||
},
|
||||
'2505': { // 煤矿钻机
|
||||
uniacid: 2505,
|
||||
domain: 'https://xcx.aigc-quickapp.com/',
|
||||
},
|
||||
},
|
||||
'2777': { // 养老服务
|
||||
uniacid: 2777,
|
||||
domain: 'https://xcx.aigc-quickapp.com/',
|
||||
},
|
||||
},
|
||||
'1': { // 开发平台
|
||||
uniacid: 1,
|
||||
domain: 'https://dev.aigc-quickapp.com',
|
||||
@@ -38,18 +42,211 @@ const localDevConfig = ({
|
||||
uniacid: 1,
|
||||
domain: 'https://test.aigc-quickapp.com',
|
||||
},
|
||||
'11-test': { // 测试平台
|
||||
uniacid: 11,
|
||||
domain: 'https://test.aigc-quickapp.com',
|
||||
},
|
||||
'18-test': { // 测试平台
|
||||
uniacid: 18,
|
||||
domain: 'https://test.aigc-quickapp.com',
|
||||
},
|
||||
'local-2': { // 测试平台
|
||||
uniacid: 2,
|
||||
domain: 'http://localhost:8050/',
|
||||
},
|
||||
'47': { // 修改弹窗
|
||||
uniacid: 47,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'2075': { //
|
||||
uniacid: 2075,
|
||||
domain: 'https://xcx.aigc-quickapp.com/',
|
||||
},
|
||||
})['47']; // 选择要使用的环境配置
|
||||
|
||||
},
|
||||
'local-1': { // 测试平台
|
||||
uniacid: 1,
|
||||
domain: 'http://192.168.197.1:8050/',
|
||||
// domain: 'http://localhost:8050/',
|
||||
},
|
||||
'192.168.8.118-1': { // 测试平台
|
||||
uniacid: 1,
|
||||
domain: 'http://192.168.8.118:8050/',
|
||||
// domain: 'http://localhost:8050/',
|
||||
},
|
||||
'local-11': { // 测试平台
|
||||
uniacid: 11,
|
||||
domain: 'http://localhost:8050/',
|
||||
},
|
||||
'100': {// 口译教学
|
||||
uniacid: 100,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'1': {
|
||||
uniacid: 1,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'115': {// 低压断路器
|
||||
uniacid: 115,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'5g-11': {// 铝箔袋包装
|
||||
uniacid: 11,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'5g-206': {// 气体探测
|
||||
uniacid: 206,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'5g-165': { // 鸡肉调理品, 优惠卷显示不全,及逻辑错误
|
||||
uniacid: 165,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'47': { // 免疫细胞干细胞外泌体 ,修改弹窗
|
||||
uniacid: 47,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'145': { //昆山昆创净化科技有限公司 , 表单链接转义问题
|
||||
uniacid: 145,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'5g-213': { // 碱性康养水天然泡茶水 , 单图组点击链接无法跳转
|
||||
uniacid: 213,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'5g-4': { // 高端硅钢制造装备 , 公告点击链接无法跳转
|
||||
uniacid: 4,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'5g-97': { // 大宗商品贸易,支持自定义字体大小、颜色
|
||||
uniacid: 97,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'5g-50': { // 燃气安全产品机器人,购物车无反应
|
||||
uniacid: 50,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'5g-237': { //高活性氧化镁 商品分类,没有立即咨询文字
|
||||
uniacid: 237,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'2847': { // 家居装饰品
|
||||
uniacid: 2847,
|
||||
domain: 'https://xcx.aigc-quickapp.com/',
|
||||
},
|
||||
'2482': { // 低空经济
|
||||
uniacid: 2482,
|
||||
domain: 'https://xcx6.aigc-quickapp.com/',
|
||||
},
|
||||
'2485': { // 智能物流仓储 , 验证电子表单前后端数据一致性
|
||||
uniacid: 2485,
|
||||
domain: 'https://xcx6.aigc-quickapp.com/',
|
||||
},
|
||||
'2821': { // 离型纸硅油纸
|
||||
uniacid: 2821,
|
||||
domain: 'https://xcx.aigc-quickapp.com/',
|
||||
},
|
||||
'18': { // 测试平台
|
||||
uniacid: 18,
|
||||
domain: 'https://test.aigc-quickapp.com',
|
||||
},
|
||||
'2': { // 测试平台
|
||||
uniacid: 2,
|
||||
domain: 'https://test.aigc-quickapp.com',
|
||||
},
|
||||
'48': { // 测试平台
|
||||
uniacid: 48,
|
||||
domain: 'https://test.aigc-quickapp.com',
|
||||
},
|
||||
'test-12': { // 户外鞋,测试优惠券
|
||||
uniacid: 12,
|
||||
domain: 'https://test.aigc-quickapp.com',
|
||||
},
|
||||
'248': { // 工业称重系统垃圾吊电子秤,支持自定义字体大小、颜色
|
||||
uniacid: 248,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'228': { // 反渗透阻垢剂RO装置 商品分类,没有立即咨询文字
|
||||
uniacid: 228,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'2797': { //气雾栽培机,视频组件安卓ios播放正常
|
||||
uniacid: 2797,
|
||||
domain: 'https://xcx.aigc-quickapp.com/',
|
||||
},
|
||||
'5g-95': { // 加热器 ,商品分类,没有立即咨询文字
|
||||
uniacid: 95,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'5g-160': { // 过瘤胃瘤胃保护,商品详情视频
|
||||
uniacid: 160,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'5g-268': { // 合成孔径雷达,一级分类背景字体颜色
|
||||
uniacid: 268,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'225-test': { // 测试平台
|
||||
uniacid: 225,
|
||||
domain: 'https://test.aigc-quickapp.com',
|
||||
},
|
||||
'192.168.8.118-321': { // 测试平台
|
||||
uniacid: 321,
|
||||
domain: 'http://192.168.8.118:8050/',
|
||||
// domain: 'http://localhost:8050/',
|
||||
},
|
||||
'5g-59': { // 脱模剂粘合剂乐瑞固Lorechem
|
||||
uniacid: 59,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'5g-204': { // 热固性塑料,公告不跳转
|
||||
uniacid: 204,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'5g-351': { // 洗车机,商品详情的销量,购物车,库存隐藏
|
||||
uniacid: 351,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'2709': { // 中央厨房
|
||||
uniacid: 2709,
|
||||
domain: 'https://xcx.aigc-quickapp.com/',
|
||||
},
|
||||
'192.168.8.118-325': { // 测试平台
|
||||
uniacid: 325,
|
||||
domain: 'http://192.168.8.118:8050/',
|
||||
// domain: 'http://localhost:8050/',
|
||||
},
|
||||
'2505': { // 煤矿钻机
|
||||
uniacid: 2505,
|
||||
domain: 'https://xcx.aigc-quickapp.com/',
|
||||
},
|
||||
'3007': { // 钎焊材料
|
||||
uniacid: 3007,
|
||||
domain: 'https://xcx.aigc-quickapp.com/',
|
||||
},
|
||||
'5g-317': { // 电磁兼容,模板显示不全商品
|
||||
uniacid: 317,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
'5g-312': { // 天然植物功效活性物
|
||||
uniacid: 312,
|
||||
domain: 'https://5g.aigc-quickapp.com/',
|
||||
},
|
||||
// })['5g-237']; // 商品分类,没有立即咨询文字
|
||||
// })['5g-97']; // 大宗商品贸易,支持自定义字体大小、颜色
|
||||
// })['5g-50']; // 燃气安全产品机器人,购物车无反应
|
||||
// })['2821']; // 离型纸硅油纸
|
||||
// })['2482']; // 低空经济
|
||||
// })['48']; // 离型纸硅油纸
|
||||
// })['2485']; // 验证电子表单前后端数据一致性
|
||||
// })['5g-11']; // 数码
|
||||
// })['5g-213']; // 选择要使用的环境配置
|
||||
// })['2881']; // 鸡肉调理品, 优惠卷显示不全,及逻辑错误
|
||||
// })['2724']; // 生物菌肥
|
||||
// })['2811']; // 选择要使用的环境配置
|
||||
// })['5g-351']; //洗车机
|
||||
// })['5g-204']; //热固性塑料
|
||||
// })['5g-59']; //合成孔径雷达
|
||||
// })['2709']; //中央厨房
|
||||
// })['3007']; //钎焊材料
|
||||
// })['2505']; //煤矿钻机
|
||||
// })['local-11']; // 选择要使用的环境配置
|
||||
// })['2811']; // 本地
|
||||
// })['5g-317']; // 电磁兼容
|
||||
// })['5g-351']; //
|
||||
})['1']; // 本地
|
||||
// })['local-2']; // 本地
|
||||
// })['local-11']; // 本地
|
||||
// })['1-test']; // test
|
||||
// })['test-12']; // test
|
||||
export default localDevConfig;
|
||||
435
App.vue
435
App.vue
@@ -1,42 +1,389 @@
|
||||
<script>
|
||||
import auth from 'common/js/auth.js';
|
||||
import configExternal from 'common/js/config-external.js'
|
||||
|
||||
import configExternal, { themeConfig, privacyConfig } from 'common/js/config-external.js'
|
||||
import Lang from 'common/js/lang.js';
|
||||
import ThemeOverride from 'common/js/theme-override.js';
|
||||
import PrivacyManager from 'common/js/privacy.js';
|
||||
import splashState from 'common/js/splash-state.js';
|
||||
// PR-MULTI-TURN-KEY-BINDING (2026-09-18): AI 客服会话 key 切换
|
||||
// 登录态恢复后通知 aiService 清旧 user key,避免串会话
|
||||
import aiService from 'common/js/ai-service.js';
|
||||
|
||||
import {
|
||||
Weixin
|
||||
} from 'common/js/wx-jssdk.js';
|
||||
|
||||
// ============================================================
|
||||
// 隐私弹窗 URL/路由规则 (H5 + 微信小程序 + 鸿蒙元服务)
|
||||
//
|
||||
// 配置来源 (沿用 config-external.js 同构模式):
|
||||
// 1. 本地兜底: privacyConfig.urlRulesBase (与 langConfig/themeConfig 同构)
|
||||
// 2. 远程 patch: /api/config/init data.privacy_url_rules (由 store/init 融合)
|
||||
// 融合策略 (同上一轮):
|
||||
// - mode: 远程有值则覆盖, 否则用本地
|
||||
// - patterns: 按 patch.merge 字段决定 (replace 默认 / union / intersect)
|
||||
// 匹配: 子串匹配
|
||||
// H5: pathname + search + hash
|
||||
// 小程序/鸿蒙: 当前页面 route + query
|
||||
// 命中白名单后, 仍会走 storage / 平台级隐私检查, 已同意则不再弹
|
||||
// ============================================================
|
||||
const PRIVACY_URL_RULES_BASE = privacyConfig.urlRulesBase
|
||||
|
||||
// 启动期配置注入: 把 privacyConfig 的 bootTimeout / waitChannels / signSecret 灌进 PrivacyManager
|
||||
// 这样 PrivacyManager.show() 即便被业务侧独立调用, 也能感知启动期资源就绪状态
|
||||
// 签名密钥注入: 远程 patch 必须通过 verifyRemotePatch() 才允许 applyWithMerge
|
||||
PrivacyManager.setExternalBootTimeout(configExternal.getPrivacyBootTimeout())
|
||||
PrivacyManager.setWaitChannels(privacyConfig.waitChannels || {})
|
||||
PrivacyManager.setSignSecret(privacyConfig.signSecret || '')
|
||||
|
||||
// 登记本地 base 规则, 供后续远程 patch 融合时读取
|
||||
// 必须在 setStorageKey / loadPersistedRules 之前完成, 因为 store/init action
|
||||
// 会通过 PrivacyManager.__getBaseRules() 读取这个 base
|
||||
PrivacyManager.setBaseRules(PRIVACY_URL_RULES_BASE)
|
||||
|
||||
// uniacid 隔离的持久化 key
|
||||
// 关键: 持久化必须基于 uniacid 隔离, 否则多租户切换会读到对方租户的规则
|
||||
// 无 uniacid 时降级到 _anon (使用 localStorage 之外的隔离, 避免与任何具体租户冲突)
|
||||
const _uniacid = uni.getStorageSync('uniacid')
|
||||
const _persistKey = _uniacid
|
||||
? ('privacy_url_rules_' + _uniacid)
|
||||
: 'privacy_url_rules__anon'
|
||||
PrivacyManager.setStorageKey(_persistKey)
|
||||
|
||||
// 1) 先尝试恢复上次的"已融合规则" (跨冷启动)
|
||||
// 无持久化值 → 退化为 base
|
||||
const _persisted = PrivacyManager.loadPersistedRules()
|
||||
if (_persisted && _persisted.mode && Array.isArray(_persisted.patterns)) {
|
||||
PrivacyManager.setUrlRules(_persisted)
|
||||
} else {
|
||||
// 2) 用本地 base 兜底
|
||||
PrivacyManager.setUrlRules(PRIVACY_URL_RULES_BASE)
|
||||
}
|
||||
|
||||
// 业务侧可监听: 远程下发完成后, 会触发 'privacy:rules-updated'
|
||||
uni.$on && uni.$on('privacy:rules-updated', (info) => {
|
||||
// 只在远程下发时打印, 避免被本地 base 加载/持久化恢复时的 emit 噪音淹没
|
||||
if (info && info.source === 'remote' && console && console.log) {
|
||||
console.log('[privacy] rules updated by remote, mode=' + info.mode + ', patterns=' + info.patterns.length)
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* 取 onLaunch options 作为首次启动的兜底路径
|
||||
* H5: options.path/query 不一定存在, 此时用 window.location
|
||||
* 小程序/鸿蒙: options.path 是启动路径, options.query 是启动参数
|
||||
* @param {Object} launchOptions onLaunch 的 options
|
||||
* @returns {Object} urlFallback
|
||||
*/
|
||||
function _buildPrivacyUrlFallback(launchOptions) {
|
||||
const fallback = { pathname: '', search: '', hash: '', route: '', query: null }
|
||||
// #ifdef H5
|
||||
if (typeof window !== 'undefined' && window.location) {
|
||||
fallback.pathname = window.location.pathname || ''
|
||||
fallback.search = window.location.search || ''
|
||||
fallback.hash = window.location.hash || ''
|
||||
}
|
||||
// #endif
|
||||
// #ifndef H5
|
||||
if (launchOptions && launchOptions.path) {
|
||||
fallback.route = launchOptions.path
|
||||
fallback.query = launchOptions.query || null
|
||||
}
|
||||
// #endif
|
||||
return fallback
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 主题/语言启动
|
||||
// ============================================================
|
||||
export default {
|
||||
mixins: [auth],
|
||||
data() {
|
||||
return {
|
||||
// remote-only 模式下,业务可通过 await getApp().$langReady 等待语言包就绪
|
||||
$langReady: Promise.resolve({ ok: true, source: 'local' })
|
||||
};
|
||||
},
|
||||
// 同步钩子:在 page mounted 之前同步设置隐私弹窗的 skip 状态
|
||||
// 必须在 onLaunch (async) 之前跑,否则 onLaunch 第一个 await 让出事件循环时
|
||||
// privacy-popup.vue 已经挂载,会走 consumePendingShow 兜底分支把弹窗弹出来
|
||||
created() {
|
||||
if (!PrivacyManager.shouldShowByUrlRule()) {
|
||||
PrivacyManager.markSkipped()
|
||||
}
|
||||
},
|
||||
onLaunch: async function(options) {
|
||||
// 方式:支持快应用,从url中query部分获取uniacid,或useragent中获取uniacid
|
||||
if(options.query.uniacid){
|
||||
// ============================================================
|
||||
// 主题提前加载(关键):让首屏渲染前 CSS 变量已挂上,避免闪一下
|
||||
// ============================================================
|
||||
|
||||
// ---- 0) 同步预热: 立即读 storage 拿 preset,触发 require(不 await)
|
||||
// 目的: 让 loadTheme 的 require 提前进入 microtask,后续 await 几乎瞬时
|
||||
const cached = uni.getStorageSync('themeStyle');
|
||||
let presetName = themeConfig.defaultTheme;
|
||||
if (cached) {
|
||||
presetName = (typeof cached === 'object') ? cached.name : cached;
|
||||
}
|
||||
// 触发 preset require(不 await,缓存 promise 到 configExternal.loadedConfigs)
|
||||
configExternal.loadTheme(presetName);
|
||||
|
||||
// ---- 1) uniacid 立即写入(后续所有 HTTP 都要用到)
|
||||
const uniacidChanged = options.query && options.query.uniacid && String(uni.getStorageSync('uniacid') || '') !== String(options.query.uniacid);
|
||||
if (options.query && options.query.uniacid) {
|
||||
uni.setStorageSync('uniacid', options.query.uniacid);
|
||||
}
|
||||
// 关键: 即便 uniacid 未变化 (首次启动 options.query 没传 uniacid),
|
||||
// 也要尝试从 storage 拿真实 uniacid 并设置 PrivacyManager 的 persist key
|
||||
// 否则 App.vue 顶层用 _anon 占位, 后续 persistRules 写到 _anon key 下,
|
||||
// 下次冷启动 (有 uniacid) 切到 uniacid key 时读不到上次结果
|
||||
try {
|
||||
const _nowUniacid = uni.getStorageSync('uniacid')
|
||||
const _newPersistKey = _nowUniacid
|
||||
? ('privacy_url_rules_' + _nowUniacid)
|
||||
: 'privacy_url_rules__anon'
|
||||
if (_newPersistKey !== _persistKey) {
|
||||
PrivacyManager.setStorageKey(_newPersistKey)
|
||||
const _newPersisted = PrivacyManager.loadPersistedRules()
|
||||
if (_newPersisted && _newPersisted.mode && Array.isArray(_newPersisted.patterns)) {
|
||||
PrivacyManager.setUrlRules(_newPersisted)
|
||||
} else {
|
||||
PrivacyManager.setUrlRules(PRIVACY_URL_RULES_BASE)
|
||||
}
|
||||
}
|
||||
} catch (e) {}
|
||||
if (uniacidChanged) {
|
||||
try { Lang.onUniacidChange(); } catch (e) {}
|
||||
try { ThemeOverride.onUniacidChange(); } catch (e) {}
|
||||
// 切租户: 切换 PrivacyManager 持久化 key 并重新应用本地 base
|
||||
// (远程 patch 由后续 /api/config/init 重新下发并融合)
|
||||
try {
|
||||
const newUniacid = String(options.query.uniacid)
|
||||
const newPersistKey = newUniacid
|
||||
? ('privacy_url_rules_' + newUniacid)
|
||||
: 'privacy_url_rules__anon'
|
||||
PrivacyManager.setStorageKey(newPersistKey)
|
||||
PrivacyManager.setBaseRules(PRIVACY_URL_RULES_BASE)
|
||||
// 切租户: 重新加载该租户上次持久化的规则
|
||||
// 无持久化值则退化为 base
|
||||
const _newPersisted = PrivacyManager.loadPersistedRules()
|
||||
if (_newPersisted && _newPersisted.mode && Array.isArray(_newPersisted.patterns)) {
|
||||
PrivacyManager.setUrlRules(_newPersisted)
|
||||
} else {
|
||||
PrivacyManager.setUrlRules(PRIVACY_URL_RULES_BASE)
|
||||
}
|
||||
} catch (e) {}
|
||||
try { uni.$emit && uni.$emit('uniacid:changed'); } catch (e) {}
|
||||
}
|
||||
|
||||
// remote-only 模式:
|
||||
// H5: main.js 已 await boot 完成, 这里秒回 (splash 也由 main.js 全权负责)
|
||||
// 小程序/鸿蒙: main.js 同步 $mount() 之前已经调用 splashState.show(),
|
||||
// 这里不需要重复调用
|
||||
const langBoot = Lang.boot();
|
||||
this.$langReady = langBoot;
|
||||
|
||||
// ---- 2) 启动期关键资源就绪 (并行 + 显式 await)
|
||||
// 隐私弹窗的诉求: 必须在 i18n + theme + remote-config 三态都就绪后才弹
|
||||
// 这里把三个通道收敛为一个 await 链, 不再用 fire-and-forget
|
||||
// 任何通道自身有超时保护 (Lang.bootTimeout=langConfig.remote.bootTimeout=5000,
|
||||
// ThemeOverride.bootTimeout=themeConfig.overrideRemote.bootTimeout=5000)
|
||||
// 总超时熔断走 configExternal.getPrivacyBootTimeout() (默认取两者最大值+1000ms)
|
||||
// 业务侧想"宁愿晚一点也要全资源就绪" → 调大 privacyConfig.bootTimeout
|
||||
// 业务侧想"快速失败" → 调小或关闭 privacyConfig.waitChannels
|
||||
|
||||
const _i18nDone = langBoot.then((res) => {
|
||||
// 进度上报: i18n 完成 → 30%
|
||||
try { splashState.reportProgress('lang', { source: 'channel' }); } catch (e) {}
|
||||
// i18n fallback toast (原逻辑保留)
|
||||
if (res && res.status === 'fail' && res.reason && res.reason !== 'unknown') {
|
||||
if (globalThis.__i18nFallbackToastShown) return res;
|
||||
globalThis.__i18nFallbackToastShown = true;
|
||||
setTimeout(() => {
|
||||
try {
|
||||
uni.showToast({
|
||||
title: `Failed to load i18n. ${res.reason} Please check your network and try again.`,
|
||||
icon: 'none',
|
||||
duration: 10000,
|
||||
});
|
||||
} catch (e) {}
|
||||
}, 3000);
|
||||
}
|
||||
return res;
|
||||
}, (e) => {
|
||||
console.warn('[i18n] boot fail', e);
|
||||
try { splashState.reportProgress('lang', { source: 'error' }); } catch (e) {}
|
||||
return { ok: false, source: 'remote-failed', status: 'fail', reason: 'exception', lang: '' };
|
||||
})
|
||||
|
||||
const _themeFirstApply = this.$store.dispatch('applyThemeWithRemote', presetName)
|
||||
.then(() => {
|
||||
try { splashState.reportProgress('theme', { source: 'channel' }); } catch (e) {}
|
||||
})
|
||||
.catch(e => {
|
||||
console.warn('[theme] pre-apply fail', e);
|
||||
try { splashState.reportProgress('theme', { source: 'error' }); } catch (e) {}
|
||||
return null
|
||||
})
|
||||
|
||||
const _themeOverride = ThemeOverride.boot()
|
||||
.then(() => {
|
||||
try { splashState.reportProgress('override', { source: 'channel' }); } catch (e) {}
|
||||
})
|
||||
.catch(e => {
|
||||
console.warn('[theme] boot fail', e);
|
||||
try { splashState.reportProgress('override', { source: 'error' }); } catch (e) {}
|
||||
return null
|
||||
})
|
||||
|
||||
// /api/config/init 走 fire-and-forget:
|
||||
// - race 不再等它, popup 可以更早弹出
|
||||
// - 远程 patch (privacy_url_rules 等) 后续异步到达时通过 applyWithMerge 触发双阶段弹窗
|
||||
// - 失败也不阻塞 boot 链路
|
||||
//
|
||||
// 进度上报单独走 (展示效果, 不依赖 _remoteConfig resolve)
|
||||
this.$store.dispatch('init').then(() => {
|
||||
try { splashState.reportProgress('config', { source: 'channel' }); } catch (e) {}
|
||||
}).catch(e => {
|
||||
console.warn('[config] init fail', e);
|
||||
try { splashState.reportProgress('config', { source: 'error' }); } catch (e) {}
|
||||
})
|
||||
const _remoteConfig = Promise.resolve(null) // 占位 promise, race 不再等 init
|
||||
|
||||
// 注入启动期等待通道 → ConfigExternal 持有
|
||||
// PrivacyManager.show() 时通过 getPrivacyReadyGuard(waitChannels) 自动拼成 readyGuard
|
||||
configExternal.setReadyWaiters({
|
||||
lang: _i18nDone,
|
||||
theme: _themeFirstApply,
|
||||
themeOverride: _themeOverride,
|
||||
remoteConfig: _remoteConfig,
|
||||
})
|
||||
|
||||
const _privacyBootTimeout = configExternal.getPrivacyBootTimeout()
|
||||
const _bootRaceResult = await Promise.race([
|
||||
Promise.all([_i18nDone, _themeFirstApply, _themeOverride, _remoteConfig]),
|
||||
new Promise(resolve => setTimeout(() => resolve('timeout'), _privacyBootTimeout))
|
||||
])
|
||||
if (_bootRaceResult === 'timeout') {
|
||||
// race 超时上报 (source: 'timeout', 不允许 percent 后退, 已有最大值为准)
|
||||
try { splashState.reportProgress('config', { percent: 80, source: 'timeout' }); } catch (e) {}
|
||||
}
|
||||
|
||||
// privacy 阶段开始上报
|
||||
try { splashState.reportProgress('privacy', { source: 'channel' }); } catch (e) {}
|
||||
|
||||
// 隐私协议弹窗: 启动期关键资源 (i18n/theme/remote-config) 就绪后触发
|
||||
// 通过 PrivacyManager → uni.$emit('privacy:show') 通知当前页面的 privacy-popup 组件
|
||||
// 只弹一次: 同意后写 storage,后续不再弹
|
||||
// 异步查询平台隐私状态(微信/快应用), H5 同步返回
|
||||
// H5 直访特定 URL(子串匹配)时跳过本次弹窗,不写 storage,下次正常访问其他页面还会弹
|
||||
// urlFallback: 首次启动 onLaunch 时 getCurrentPages 还没页面, 用 onLaunch options 兜底
|
||||
// readyGuard: 双保险 — 若调用方没传, PrivacyManager 内部从 _externalReadyGuard 取
|
||||
// (= ConfigExternal.getPrivacyReadyGuard(privacyConfig.waitChannels))
|
||||
// 二次 await 仍保留: race 后还有可能某个通道没真完成, 二次 await 兜底
|
||||
//
|
||||
// 鸿蒙元服务(双轨制):
|
||||
// 已接入平台隐私托管, 鸿蒙系统自动弹出系统级隐私弹窗.
|
||||
// 应用层不调 PrivacyManager.show() (会和系统弹窗叠加被驳回).
|
||||
// #ifdef MP-HARMONY
|
||||
// 鸿蒙: 走平台隐私托管, markSkipped 写 storage
|
||||
try {
|
||||
await Promise.all([_i18nDone, _themeFirstApply, _themeOverride, _remoteConfig])
|
||||
PrivacyManager.markSkipped()
|
||||
} catch (e) { console.warn('[privacy] MP-HARMONY markSkipped fail', e); }
|
||||
// #endif
|
||||
// #ifndef MP-HARMONY
|
||||
try {
|
||||
await PrivacyManager.show({
|
||||
urlFallback: _buildPrivacyUrlFallback(options),
|
||||
readyGuard: Promise.all([_i18nDone, _themeFirstApply, _themeOverride, _remoteConfig]),
|
||||
})
|
||||
} catch (e) { console.warn('[privacy] show fail', e); }
|
||||
// #endif
|
||||
|
||||
// splash 必须在隐私弹窗决策后再 hide (否则 splash 关掉瞬间弹窗还没渲染, 视觉闪一下)
|
||||
// mode='fast': 隐私弹窗即将出现, splash 用 80ms 短动画, 让 modal 更快接管视觉
|
||||
// 避免 splash 和弹窗同时显示造成的"双遮罩"感, 减少约 400ms 启动时间
|
||||
// 只有 remote-only 模式才用了 splash (其他场景 src 模式不需要等远端)
|
||||
//
|
||||
// 关键 (鸿蒙 + 其他平台): 这里只发"软隐藏"信号, splash 实际关闭要等
|
||||
// splashState._softHide() 看到 _hasMounted && _pageReady 才真关。
|
||||
// _pageReady 由首页 diy-group 渲染完时调 notifyPageReady() 触发。
|
||||
// 这样保证 splash **一直显示**, 直到首页 diy 内容真的渲染好,
|
||||
// 避免 splash 关闭后到 diy 内容出现之间出现白屏。
|
||||
//
|
||||
// 鸿蒙端 (mode='strict'):
|
||||
// 鸿蒙系统弹窗是用户视觉锚点, 应用层 splash 必须**真等到**diy 渲染好
|
||||
// 才能关, 不走 MOUNT_GRACE_MS/PAGE_READY_GRACE_MS 软隐藏兜底
|
||||
// (软隐藏兜底 1+2=3s 经常不够用, 会导致 splash 提前 hide → 白屏)
|
||||
// strict 模式只受 DEFAULT_TIMEOUT=12s 总超时兜底, 实际由 notifyPageReady() 触发
|
||||
// #ifndef H5
|
||||
const _needSplash = typeof Lang !== 'undefined' && Lang.isRemoteOnly && Lang.isRemoteOnly();
|
||||
if (_needSplash) {
|
||||
// 所有平台都用 strict 模式: 不走 1+2s 软隐藏兜底
|
||||
// splash 真等到 notifyPageReady (diy 渲染好) 或 notifyDiyLoadError (diy 错误) 才关
|
||||
// DEFAULT_TIMEOUT=12s 总超时仍然兜底
|
||||
// 避免 splash 提前关导致白屏
|
||||
splashState.hide({ reason: 'boot-complete', mode: 'strict' });
|
||||
}
|
||||
// #endif
|
||||
|
||||
// ---- 3) 远端就绪后,主题再 apply 一次(preset + remote 合并 )
|
||||
// 这一次 setThemeStyle + themeColorSet 是同步路径(preset 已在 cache,remote 也在 cache)
|
||||
// 如果跟 step 2 的 apply 值相同,Vuex 会重复 commit 但页面无视觉变化
|
||||
await this.$store.dispatch('applyThemeWithRemote', presetName);
|
||||
|
||||
// ============================================================
|
||||
// 后续: 监听器 / 平台条件 / 其它 storage commit(全部同步/轻量)
|
||||
// ============================================================
|
||||
|
||||
// 监听远端翻译更新事件(管理后台改了词条后由后端推送 / 主动 reload)
|
||||
// 注意:lang.js 内 emitUpdated 已经 commit 了 setComponentRefresh,这里
|
||||
// 只做副作用(navigation title 等),不重复 forceUpdate
|
||||
uni.$on && uni.$on('lang:updated', (info) => {
|
||||
if (info && info.lang) {
|
||||
Lang.refresh(true); // true = 显式推送 emitUpdated(虽然 loadOverrides 内部已发,这里保险起见)
|
||||
}
|
||||
});
|
||||
// 监听远端主题覆写更新(管理后台改了 token 后,本地 Vuex 重新合并并应用)
|
||||
// 关键: 走 applyThemeWithRemote action,保留原 setThemeStyle/themeColorSet 链路不动
|
||||
uni.$on && uni.$on('theme:updated', () => {
|
||||
// 重新从 storage 读 preset(可能用户在管理页切了预设)
|
||||
const cur = uni.getStorageSync('themeStyle');
|
||||
const curName = (cur && typeof cur === 'object') ? cur.name : (cur || 'default');
|
||||
this.$store.dispatch('applyThemeWithRemote', curName);
|
||||
});
|
||||
// 监听 uniacid 切换: 通知主题运行时清旧租户缓存,下次 refresh 拿到新值
|
||||
uni.$on && uni.$on('uniacid:changed', () => {
|
||||
try { ThemeOverride.onUniacidChange(); } catch (e) {}
|
||||
});
|
||||
// i18n 远端拉取失败的 toast 提示已迁移到上方 boot() 完成的 then() 中,
|
||||
// 直接根据 boot 返回值判断,不再依赖 lang:fallback 事件
|
||||
uni.hideTabBar();
|
||||
|
||||
// #ifdef MP
|
||||
const updateManager = uni.getUpdateManager();
|
||||
updateManager.onCheckForUpdate(function(res) {
|
||||
// 请求完新版本信息的回调
|
||||
});
|
||||
|
||||
updateManager.onUpdateReady(function(res) {
|
||||
uni.showModal({
|
||||
title: '更新提示',
|
||||
content: '新版本已经准备好,是否重启应用?',
|
||||
success(res) {
|
||||
if (res.confirm) {
|
||||
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
|
||||
updateManager.applyUpdate();
|
||||
}
|
||||
}
|
||||
if (uni.getUpdateManager) {
|
||||
const updateManager = uni.getUpdateManager();
|
||||
updateManager.onCheckForUpdate(function(res) {
|
||||
// 请求完新版本信息的回调
|
||||
});
|
||||
});
|
||||
|
||||
updateManager.onUpdateFailed(function(res) {
|
||||
// 新的版本下载失败
|
||||
});
|
||||
updateManager.onUpdateReady(function(res) {
|
||||
uni.showModal({
|
||||
title: Lang.lang('common.updateTip'),
|
||||
content: Lang.lang('common.updateReady'),
|
||||
success(res) {
|
||||
if (res.confirm) {
|
||||
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
|
||||
updateManager.applyUpdate();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
updateManager.onUpdateFailed(function(res) {
|
||||
// 新的版本下载失败
|
||||
});
|
||||
}
|
||||
// #endif
|
||||
|
||||
// #ifdef H5
|
||||
@@ -45,27 +392,22 @@
|
||||
}
|
||||
// #endif
|
||||
|
||||
uni.onNetworkStatusChange(function(res) {
|
||||
if (!res.isConnected) {
|
||||
uni.showModal({
|
||||
title: '网络失去链接',
|
||||
content: '请检查网络链接',
|
||||
showCancel: false
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
this.$store.dispatch('init');
|
||||
|
||||
// 存储到store中
|
||||
|
||||
// 主题风格
|
||||
if (uni.getStorageSync('themeStyle')) {
|
||||
const themeData = await configExternal.loadTheme(uni.getStorageSync('themeStyle'));
|
||||
this.$store.commit('setThemeStyle', themeData);
|
||||
this.$store.dispatch('themeColorSet');
|
||||
if (uni.onNetworkStatusChange) {
|
||||
uni.onNetworkStatusChange(function(res) {
|
||||
if (!res.isConnected) {
|
||||
uni.showModal({
|
||||
title: Lang.lang('common.networkLost'),
|
||||
content: Lang.lang('common.networkCheck'),
|
||||
showCancel: false
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// /api/config/init 已在 step 2.5 await 过 (含 800ms 超时), 此处不再重复触发
|
||||
// 原 fire-and-forget 注释: 不阻塞后续同步 commit
|
||||
// 现在 init 已被升级为 "首次配置等待通道", 这里留空以避免重复 dispatch
|
||||
|
||||
// 插件是否存在
|
||||
if (uni.getStorageSync('addonIsExist')) {
|
||||
this.$store.commit('setAddonIsExist', uni.getStorageSync('addonIsExist'));
|
||||
@@ -124,6 +466,14 @@
|
||||
if (uni.getStorageSync('memberInfo')) {
|
||||
this.$store.commit('setMemberInfo', uni.getStorageSync('memberInfo'));
|
||||
|
||||
// PR-MULTI-TURN-KEY-BINDING (2026-09-18): 登录态恢复后清旧 user key
|
||||
// 避免"A 退出 → B 登录 → 直接复用 A 的会话 ID" 串会话
|
||||
try {
|
||||
if (aiService && typeof aiService.onUserChange === 'function') {
|
||||
aiService.onUserChange();
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
|
||||
// 查询购物车信息
|
||||
this.$store.dispatch('getCartNumber');
|
||||
}
|
||||
@@ -266,7 +616,6 @@
|
||||
imgUrl: this.$util.img(share_data.imgUrl)
|
||||
},
|
||||
res => {
|
||||
console.log(res);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ image {
|
||||
/* #ifdef H5 */
|
||||
height: calc(100vh - 88rpx);
|
||||
/* #endif */
|
||||
/* #ifdef MP-WEIXIN */
|
||||
/* #ifdef MP */
|
||||
height: 100vh;
|
||||
/* #endif */
|
||||
}
|
||||
|
||||
@@ -118,6 +118,8 @@
|
||||
.goods-video video {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
object-position: center;
|
||||
}
|
||||
|
||||
.goods-video .uni-video-cover {
|
||||
@@ -1223,6 +1225,7 @@
|
||||
}
|
||||
|
||||
.popup-layer {
|
||||
position: relative;
|
||||
background: #fff;
|
||||
.head-wrap {
|
||||
font-size: $font-size-toolbar;
|
||||
|
||||
@@ -5705,9 +5705,9 @@
|
||||
|
||||
@font-face {
|
||||
font-family: "iconj"; /* Project id 1752049 */
|
||||
src: url('//at.alicdn.com/t/c/font_1752049_n0jw9cvfunm.woff2?t=1727498649486') format('woff2'),
|
||||
url('//at.alicdn.com/t/c/font_1752049_n0jw9cvfunm.woff?t=1727498649486') format('woff'),
|
||||
url('//at.alicdn.com/t/c/font_1752049_n0jw9cvfunm.ttf?t=1727498649486') format('truetype');
|
||||
src: url('https://at.alicdn.com/t/c/font_1752049_n0jw9cvfunm.woff2?t=1727498649486') format('woff2'),
|
||||
url('https://at.alicdn.com/t/c/font_1752049_n0jw9cvfunm.woff?t=1727498649486') format('woff'),
|
||||
url('https://at.alicdn.com/t/c/font_1752049_n0jw9cvfunm.ttf?t=1727498649486') format('truetype');
|
||||
}
|
||||
|
||||
.iconj {
|
||||
|
||||
@@ -23,6 +23,22 @@ page {
|
||||
$base-color: #ff4544;
|
||||
$base-help-color: #ffb644; //辅助颜色
|
||||
--tab-bar-height: 112rpx;
|
||||
|
||||
/* ============================================================
|
||||
* 浮动按钮 / 回到顶部按钮 的全局尺寸变量
|
||||
* ------------------------------------------------------------
|
||||
* to-top.vue 和 hover-nav.vue 共同使用这些变量,
|
||||
* 保证两者的位置关系(垂直中心对齐、上下间距)始终一致。
|
||||
*
|
||||
* 注意:这些是"权威源",如果改了这里,JS 计算的 containerRight
|
||||
* / containerBottom 在 H5 下会自动跟随变化(JS 读取 :root 变量)。
|
||||
* 小程序环境没有 document,JS 端用 fallback 默认值 46/72/100/272,
|
||||
* 改这里的同时也需要同步更新 hover-nav.vue 的 data 默认值。
|
||||
* ============================================================ */
|
||||
--top-btn-right: 46rpx; // 回到顶部按钮距屏幕右边
|
||||
--top-btn-bottom: 272rpx; // 回到顶部按钮距屏幕底部
|
||||
--top-btn-size: 72rpx; // 回到顶部按钮边长(正方形)
|
||||
--floating-btn-width: 100rpx; // hover-nav 浮动容器宽度
|
||||
}
|
||||
|
||||
.uni-input-input:-webkit-autofill {
|
||||
|
||||
@@ -25,7 +25,7 @@ view {
|
||||
background-size: 100% 260rpx;
|
||||
background-repeat: no-repeat;
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
// #ifdef MP
|
||||
background-size: 100% 380rpx;
|
||||
// #endif
|
||||
|
||||
@@ -52,7 +52,7 @@ view {
|
||||
background: linear-gradient(180deg, $base-color 10%, $color-bg 100%);
|
||||
background-size: 100% 260rpx;
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
// #ifdef MP
|
||||
background-size: 100% 380rpx;
|
||||
// #endif
|
||||
|
||||
@@ -462,7 +462,10 @@ view {
|
||||
background: #f6f6cb;
|
||||
text-align: left;
|
||||
padding: 10rpx 20rpx;
|
||||
color: #FF0000;
|
||||
// P0: 角标红 → var(--goods-cart-num-corner)
|
||||
// 注: black preset 值是 #FF0000, default 是 #FC5227 — var() 兼顾
|
||||
// 兼容: 微信小程序 / 鸿蒙元服务 — color 接受 var() 无问题
|
||||
color: var(--goods-cart-num-corner, #FF0000);
|
||||
}
|
||||
.order-submit {
|
||||
position: fixed;
|
||||
@@ -1286,9 +1289,13 @@ view {
|
||||
margin-right: 10rpx;
|
||||
line-height: 1;
|
||||
font-size: 36rpx;
|
||||
background-image:linear-gradient(156deg, #814635 0%, #3A221B 100%);
|
||||
-webkit-background-clip:text;
|
||||
-webkit-text-fill-color:transparent;
|
||||
// P0: 会员图标渐变 → var(--member-icon-grad-start/end)
|
||||
// 注: 暂用 placeholder 命名,后续如需主题化可加到 style_color.js
|
||||
// 兼容: 微信小程序 / 鸿蒙元服务 — linear-gradient 嵌套 var() 现代 runtime 支持
|
||||
background: #814635; // 兜底
|
||||
background-image: linear-gradient(156deg, var(--member-icon-grad-start, #814635) 0%, var(--member-icon-grad-end, #3A221B) 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
}
|
||||
|
||||
.info{
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -8,9 +8,11 @@ export default {
|
||||
/**
|
||||
* 获取用户登录凭证code
|
||||
*/
|
||||
getCode(callback) {
|
||||
getCode(callback, fallbackFunc) {
|
||||
console.log(`-----> auth.js getCode`)
|
||||
// 微信小程序
|
||||
// #ifdef MP-WEIXIN
|
||||
console.log(`微信小程序登录`)
|
||||
uni.login({
|
||||
provider: 'weixin',
|
||||
timeout: 3000,
|
||||
@@ -29,12 +31,15 @@ export default {
|
||||
.unionid;
|
||||
typeof callback == 'function' && callback(this.authInfo);
|
||||
} else {
|
||||
fallbackFunc && fallbackFunc(res);
|
||||
this.$util.showToast({
|
||||
title: res.message ? res.message : '小程序配置错误'
|
||||
});
|
||||
title: res.message ? res.message : this.$lang('auth.miniProgramConfigError')
|
||||
});
|
||||
}
|
||||
}
|
||||
})
|
||||
} else {
|
||||
fallbackFunc && fallbackFunc(res);
|
||||
}
|
||||
},
|
||||
fail: (res) => {
|
||||
@@ -46,6 +51,7 @@ export default {
|
||||
});
|
||||
}
|
||||
// #endif
|
||||
fallbackFunc && fallbackFunc(res);
|
||||
}
|
||||
})
|
||||
// #endif
|
||||
@@ -66,9 +72,10 @@ export default {
|
||||
.user_id;
|
||||
typeof callback == 'function' && callback(this.authInfo);
|
||||
} else {
|
||||
fallbackFunc && fallbackFunc(res);
|
||||
this.$util.showToast({
|
||||
title: res.message ? res.message : '小程序配置错误'
|
||||
});
|
||||
title: res.message ? res.message : this.$lang('auth.miniProgramConfigError')
|
||||
});
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -94,6 +101,9 @@ export default {
|
||||
if (res.code >= 0) {
|
||||
location.href = res.data;
|
||||
}
|
||||
},
|
||||
fail: err => {
|
||||
fallbackFunc && fallbackFunc(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3,20 +3,83 @@
|
||||
|
||||
// 语言包配置
|
||||
export const langConfig = {
|
||||
// 语言列表
|
||||
// 语言列表 — 与后端 Lang.php::overrides() 白名单对齐
|
||||
// 增删需要后端同步改 LangOverrideModel::normalizeAppType 旁的 $allow_lang
|
||||
langList: ['zh-cn', 'en-us'],
|
||||
// 默认语言
|
||||
defaultLang: 'zh-cn',
|
||||
// 语言包加载方式:'lazy'(按需加载)或 'preload'(预加载)
|
||||
loadMode: 'lazy'
|
||||
loadMode: 'lazy',
|
||||
// 数据源开关
|
||||
// 数据源开关
|
||||
// local : 纯本地包,忽略 remote
|
||||
// remote : 本地兜底 + 后端 KV 覆写(首屏强依赖,见 bootTimeout)
|
||||
// hybrid : 同 remote,后端不可用时用本地
|
||||
// remote-only : 完全依赖后端 /api/lang/bundle,本地 lang/ 目录可删除
|
||||
source: 'remote-only',
|
||||
// 远端覆写相关
|
||||
remote: {
|
||||
overridesUrl: '/api/lang/overrides',
|
||||
// bundle 接口(remote-only 模式下使用)
|
||||
bundleUrl: '/api/lang/bundle',
|
||||
// diff 接口(预留)
|
||||
diffUrl: '/api/lang/diff',
|
||||
// 首屏强依赖远端翻译(多租户文案强隔离),阻塞启动
|
||||
// 但必须有上限避免白屏
|
||||
// 2026-07-02: 从 2000 改为 5000 — 慢启动场景下,给首屏渲染更多时间
|
||||
bootTimeout: 5000,
|
||||
// 单次请求超时(ms)
|
||||
// 2026-07-02: 从 4000 改为 60000 — 远端首次冷启动可能慢(CDN 边缘冷缓存/跨网段回源/MySQL JOIN)
|
||||
// 配合 loadBundleTree 的"迟到数据补救"机制,即便超时也能拿到远端最终返回的数据
|
||||
requestTimeout: 60000,
|
||||
// 缓存有效期(秒),与后端 Cache::set 600s 对齐;过期后后台刷新
|
||||
cacheTtl: 600,
|
||||
// 本地缓存 key 前缀: <prefix><uniacid>_<appType>_<lang>
|
||||
// 三维隔离,与 lang.js::getOverrideStorageKey / getOverrideMemKey 保持一致
|
||||
storagePrefix: 'LANG_OVR_',
|
||||
// 切租户/uniacid 时强制重拉
|
||||
refreshOnUniacidChange: true,
|
||||
// 签名校验密钥,留空不校验(需与后端 LANG_SIGN_SECRET 一致)
|
||||
signSecret: '',
|
||||
}
|
||||
};
|
||||
|
||||
// 主题配置
|
||||
export const themeConfig = {
|
||||
// 主题列表
|
||||
themeList: ['default', 'red', 'green', 'blue', 'pink', 'gold', 'purple', 'yellow', 'black'],
|
||||
// 默认主题
|
||||
defaultTheme: 'default'
|
||||
// 主题列表 — 与 style_color.js 顶层的 preset 名严格一致(8 个)
|
||||
// 关键: 这里列出的名字必须能在 style_color.js (或后端 style_color.php 镜像) 中找到对应 preset
|
||||
// 历史上曾包含 'red' 但 style_color.js 从未定义 'red' preset, 切到 'red' 主题时
|
||||
// loadTheme() 会返回 undefined → 走 stub default 兜底样式, 远端也无法补齐
|
||||
// 2026-07-07 移除 'red' 以保持一致性
|
||||
themeList: ['default', 'green', 'blue', 'pink', 'gold', 'purple', 'yellow', 'black'],
|
||||
// 默认主题
|
||||
defaultTheme: 'default',
|
||||
// 远端 token 覆写相关(与 langConfig 同构)
|
||||
// source : 'local' | 'remote' | 'hybrid' | 'remote-only'
|
||||
// remote.* : 首屏拉取 + 缓存 + 三态机 + 多租户多端隔离
|
||||
overrideRemote: {
|
||||
overridesUrl: '/api/theme/overrides',
|
||||
// 全量 preset 拉取(remote-only 模式下使用)
|
||||
// 返回 8 个 preset 完整 token,替代本地 style_color.js
|
||||
presetsUrl: '/api/theme/presets',
|
||||
bootTimeout: 5000,
|
||||
requestTimeout: 60000,
|
||||
// 远端全量 preset 缓存 key 前缀
|
||||
storagePresetsPrefix: 'THEME_PRESETS_',
|
||||
storagePrefix: 'THEME_OVR_',
|
||||
refreshOnUniacidChange: true,
|
||||
// source: 'remote-only' 时,webpack 会用 NormalModuleReplacementPlugin
|
||||
// 把 style_color.js 替换为 empty-style-stub.js(只含 emergency fallback)
|
||||
// 节省主包 ~75KB(完整 8 preset × ~50 token = 80KB → stub 7KB)
|
||||
//
|
||||
// 与 lang/ 目录的 remote-only 模式完全同构:
|
||||
// - 构建期: webpack 替换为 stub
|
||||
// - 运行时: ThemeOverride.loadAllPresets() 异步拉 /api/theme/presets
|
||||
// - 首屏: 走 stub 的 default preset,不白屏
|
||||
// - 切换: 切到非 default preset 时,等远端拉完再应用(由 applyThemeWithRemote
|
||||
// 订阅 theme:presets-updated 事件驱动)
|
||||
source: 'remote-only',
|
||||
}
|
||||
};
|
||||
|
||||
// API配置
|
||||
@@ -31,11 +94,130 @@ export const apiConfig = {
|
||||
retryDelay: 1000
|
||||
};
|
||||
|
||||
// 隐私弹窗配置 (与 langConfig/themeConfig 同构)
|
||||
// 本地兜底 + 远程 patch (来自 /api/config/init data.privacy_url_rules) 融合
|
||||
// source: 'local' - 仅本地兜底, 忽略远程 patch
|
||||
// 'remote' - 本地兜底 + 远程 patch 覆盖 (默认)
|
||||
// 'hybrid' - 同 remote, 远程失败时退回本地
|
||||
// 'remote-only' - 完全依赖远程 patch, 本地兜底为空
|
||||
export const privacyConfig = {
|
||||
// 本地兜底规则 (mode: 'all'|'only'|'skip', patterns: string[])
|
||||
// 远程 patch 由 store/index.js 的 init action 通过 PrivacyManager.applyWithMerge() 融合
|
||||
// patterns 写法:
|
||||
// - 子串匹配 + 结尾匹配 (双通道), 业务侧可以写完整路径或相对路径
|
||||
// - subPackage 路由 (如 /pages_tool/member/index) 用短路径 'member/index' 即可命中
|
||||
urlRulesBase: {
|
||||
// 场景 2: 只有首页、商品详情、个人中心才弹, 其他页面都不弹
|
||||
mode: 'only',
|
||||
patterns: [
|
||||
// 首页 (含 subPackage 重定向后也是 pages/index/index)
|
||||
'pages/index/index',
|
||||
// 商品详情 (subPackage 内可能为 pages_goods/goods/detail/detail, 这里用末尾匹配)
|
||||
'goods/detail/detail',
|
||||
// 个人中心 (subPackage 内通常为 pages_tool/member/index)
|
||||
'member/index',
|
||||
],
|
||||
},
|
||||
// dataSource: 与 langConfig.source 同构
|
||||
// 'local' 纯本地, 忽略 /api/config/init 的 privacy_url_rules
|
||||
// 'remote' 本地 + 远程 patch (远程失败时仍用本地)
|
||||
// 'hybrid' 同 remote, 语义别名
|
||||
// 'remote-only' 必须有远程 patch, 本地空 patterns → 一律不弹
|
||||
source: 'remote',
|
||||
// 启动期等待通道 (弹窗必须等这些 promise 才弹)
|
||||
// waitLang: Lang.boot() - i18n 数据就绪
|
||||
// waitTheme: applyThemeWithRemote() - 本地 preset 应用
|
||||
// waitThemeOverride: ThemeOverride.boot() - brand/light/dark 三桶 token
|
||||
// waitRemoteConfig: /api/config/init (含 privacy_url_rules 远程 patch)
|
||||
waitChannels: {
|
||||
lang: true,
|
||||
theme: true,
|
||||
themeOverride: true,
|
||||
remoteConfig: true,
|
||||
},
|
||||
// 总超时熔断 (ms): 所有等待通道超过这个时间强制放行, 不阻塞弹窗
|
||||
// 取 langConfig.remote.bootTimeout (5000) 和 themeConfig.overrideRemote.bootTimeout (5000) 的最大值
|
||||
// + 1000ms 余量 → 6000ms. 与原硬编码值一致, 但可通过修改此字段调整.
|
||||
// 业务侧想"宁愿晚一点也要全资源就绪" → 调大; 想"快速失败" → 调小.
|
||||
bootTimeout: 6000,
|
||||
// 远程 patch 签名密钥 (与 langConfig.remote.signSecret 同构)
|
||||
// 后端约定: hash_hmac('sha256', JSON.stringify(patch), secret)
|
||||
// secret='' → 跳过校验, 接受任意 patch (向后兼容老后端)
|
||||
// secret='xxx' → 校验 patch.sign, 不匹配则拒绝
|
||||
// 留空默认不校验. 前端实现是 btoa 弱校验, 仅防简单篡改, 强校验建议用 crypto-js.
|
||||
signSecret: '',
|
||||
// 单次 /api/config/init 请求超时 (ms)
|
||||
// 复用 apiConfig.timeout, 不单独配置
|
||||
// remote: {
|
||||
// // 远程 patch 字段名 (后端 /api/config/init 返回 data.privacy_url_rules)
|
||||
// fieldPath: 'privacy_url_rules',
|
||||
// // 切租户/uniacid 时强制重拉 (远端 patch 重新下发)
|
||||
// refreshOnUniacidChange: true,
|
||||
// // 本地缓存 key 前缀: <prefix><uniacid>
|
||||
// storagePrefix: 'privacy_url_rules_',
|
||||
// },
|
||||
};
|
||||
|
||||
// 配置外置管理类
|
||||
class ConfigExternal {
|
||||
constructor() {
|
||||
this.loadedConfigs = {};
|
||||
this.loadPromises = {};
|
||||
// 启动期各通道的 await promise (由 App.vue onLaunch 注入)
|
||||
// 隐私弹窗 show() 时通过 PrivacyManager.getReadyWaiters() 拿到 → 串成 readyGuard
|
||||
this.readyWaiters = {
|
||||
lang: null,
|
||||
theme: null,
|
||||
themeOverride: null,
|
||||
remoteConfig: null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置启动期各通道的 await promise
|
||||
* App.vue onLaunch 在 step 2 注入, PrivacyManager.show() 时读取
|
||||
* @param {Object} waiters { lang?, theme?, themeOverride?, remoteConfig? }
|
||||
*/
|
||||
setReadyWaiters(waiters) {
|
||||
if (!waiters || typeof waiters !== 'object') return
|
||||
for (const k of Object.keys(this.readyWaiters)) {
|
||||
if (waiters[k] && typeof waiters[k].then === 'function') {
|
||||
this.readyWaiters[k] = waiters[k]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取隐私弹窗 readyGuard (合并所有启用的等待通道)
|
||||
* 任意通道 disabled → 不等
|
||||
* 所有通道都 null → 返回 Promise.resolve() (不退化)
|
||||
* @param {Object} channels { lang?, theme?, themeOverride?, remoteConfig? }
|
||||
* @returns {Promise}
|
||||
*/
|
||||
getPrivacyReadyGuard(channels) {
|
||||
const cfg = (typeof channels === 'object' && channels) || (privacyConfig.waitChannels || {})
|
||||
const promises = []
|
||||
for (const k of ['lang', 'theme', 'themeOverride', 'remoteConfig']) {
|
||||
if (cfg[k] && this.readyWaiters[k]) {
|
||||
promises.push(this.readyWaiters[k])
|
||||
}
|
||||
}
|
||||
if (!promises.length) return Promise.resolve()
|
||||
return Promise.all(promises).catch(() => {})
|
||||
}
|
||||
|
||||
/**
|
||||
* 隐私弹窗总超时熔断 (ms)
|
||||
* 默认取 langConfig.remote.bootTimeout 与 themeConfig.overrideRemote.bootTimeout 的最大值 + 1000ms 余量
|
||||
* 业务侧可通过 privacyConfig.bootTimeout 覆盖
|
||||
*/
|
||||
getPrivacyBootTimeout() {
|
||||
if (privacyConfig && typeof privacyConfig.bootTimeout === 'number' && privacyConfig.bootTimeout > 0) {
|
||||
return privacyConfig.bootTimeout
|
||||
}
|
||||
const langT = (langConfig && langConfig.remote && langConfig.remote.bootTimeout) || 5000
|
||||
const themeT = (themeConfig && themeConfig.overrideRemote && themeConfig.overrideRemote.bootTimeout) || 5000
|
||||
return Math.max(langT, themeT) + 1000
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -59,7 +241,7 @@ class ConfigExternal {
|
||||
this.loadedConfigs[`lang_${lang}`] = langData;
|
||||
resolve(langData);
|
||||
} catch (error) {
|
||||
console.error(`加载语言包 ${lang} 失败:`, error);
|
||||
// console.error(`加载语言包 ${lang} 失败:`, error);
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
@@ -100,23 +282,40 @@ class ConfigExternal {
|
||||
|
||||
/**
|
||||
* 加载主题配置(异步方式)
|
||||
* 关键: 在 remote-only 模式下, style_color.js 已被 webpack 替换为 empty-style-stub.js,
|
||||
* 只含 1 个 default preset. 其它 7 个 preset 由 ThemeOverride.loadAllPresets()
|
||||
* 异步拉取并合并到本地缓存. 这里的 loadTheme 优先从缓存取,缓存未命中时回退到 stub.
|
||||
*
|
||||
* @param {string} theme - 主题名称
|
||||
* @returns {Promise} - 加载结果
|
||||
*/
|
||||
async loadTheme(theme = themeConfig.defaultTheme) {
|
||||
// 1) 先查已加载的内存缓存(包括远端拉取后写入的)
|
||||
if (this.loadedConfigs[`theme_${theme}`]) {
|
||||
return this.loadedConfigs[`theme_${theme}`];
|
||||
}
|
||||
|
||||
// 2) remote-only 模式下,从 ThemeOverride 内存缓存(由 loadAllPresets 写入)取
|
||||
try {
|
||||
const ThemeOverride = require('./theme-override.js').default;
|
||||
const remotePresets = ThemeOverride.getAllPresets();
|
||||
if (remotePresets && remotePresets[theme]) {
|
||||
this.loadedConfigs[`theme_${theme}`] = remotePresets[theme];
|
||||
return remotePresets[theme];
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore — ThemeOverride 不可用时继续走 require stub
|
||||
}
|
||||
|
||||
// 3) 兜底: require style_color.js (local 模式全量, remote-only 模式 stub)
|
||||
if (this.loadPromises[`theme_${theme}`]) {
|
||||
return this.loadPromises[`theme_${theme}`];
|
||||
}
|
||||
|
||||
this.loadPromises[`theme_${theme}`] = new Promise((resolve, reject) => {
|
||||
try {
|
||||
// 动态加载主题配置
|
||||
// 动态加载主题配置 (webpack 替换为 stub 时,只返回 1 个 default preset)
|
||||
const themeData = require(`@/common/js/style_color.js`)['default'][theme];
|
||||
// console.log('async themeData => ', themeData);
|
||||
this.loadedConfigs[`theme_${theme}`] = themeData;
|
||||
resolve(themeData);
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// 发行版本,配置说明
|
||||
let releaseCfg = undefined;
|
||||
|
||||
// #ifdef APP-PLUS || MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-QQ || MP-TOUTIAO
|
||||
// #ifdef APP-PLUS || MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-QQ || MP-TOUTIAO || MP-HARMONY
|
||||
try {
|
||||
if (site) { // 从site.js文件中获取配置, 针对微信小程序类
|
||||
releaseCfg = {
|
||||
@@ -11,29 +11,28 @@ try {
|
||||
uniacid: site.uniacid,
|
||||
}
|
||||
} else {
|
||||
console.warn('小程序发行环境下,必须配置site.js文件, 不然将使用默认配置,影响小程序定制分发!');
|
||||
// 惰性加载 Lang 避免循环依赖(lang.js 引用了 config.js)
|
||||
try {
|
||||
const Lang = require('@/common/js/lang.js').default;
|
||||
console.warn(Lang.lang('common.config.siteJsNotConfigured'));
|
||||
} catch (e) {
|
||||
console.warn('小程序发行环境下,必须配置site.js文件,不然将使用默认配置,影响小程序定制分发!');
|
||||
}
|
||||
}
|
||||
} catch (e) {}
|
||||
// #endif
|
||||
|
||||
// 线上版本部署域名, 注意: 必须以 '/' 结尾,适用于小程序/H5/快应用等场景
|
||||
// 默认域名, 自定义发行时可以修改
|
||||
let defaultDomain = '';
|
||||
let defaultDomain = '';
|
||||
|
||||
// #ifdef H5_XCX_5G_QUICKAPP_COM
|
||||
defaultDomain = 'https://xcx20.5g-quickapp.com';
|
||||
// #endif
|
||||
|
||||
// #ifdef H5_XCX_AIGC_QUICKAPP_COM
|
||||
defaultDomain = 'https://xcx.aigc-quickapp.com/';
|
||||
// #endif
|
||||
|
||||
// #ifdef H5_5G_AIGC_QUICKAPP_COM
|
||||
defaultDomain = 'https://5g.aigc-quickapp.com/';
|
||||
// #endif
|
||||
|
||||
// #ifdef H5_TEST_AIGC_QUICKAPP_COM
|
||||
defaultDomain = 'https://test.aigc-quickapp.com/';
|
||||
// #ifdef H5
|
||||
// 域名由 vue.config.js 中 DefinePlugin 注入的 process.env.UNI_APP_DOMAIN 传入
|
||||
try {
|
||||
if (process.env.UNI_APP_DOMAIN) {
|
||||
defaultDomain = process.env.UNI_APP_DOMAIN;
|
||||
}
|
||||
} catch (e) {}
|
||||
// #endif
|
||||
|
||||
// 确保域名以 '/' 结尾
|
||||
@@ -59,13 +58,12 @@ if (process?.env?.NODE_ENV === 'development') {
|
||||
// 如果本地配置文件不存在或加载失败,保持使用默认配置
|
||||
// 只在开发模式下输出提示信息
|
||||
// #ifdef WEB
|
||||
console.log('本地配置文件 .local.config.js 不存在,使用默认配置');
|
||||
// #endif
|
||||
}
|
||||
}
|
||||
// #endif
|
||||
|
||||
const { uniacid = 0, domain = defaultDomain } = localDevConfig ?? { uniacid: 0, domain: defaultDomain }
|
||||
const { uniacid = 0, domain = defaultDomain, aikefuConfigUuid = '' } = localDevConfig ?? { uniacid: 0, domain: defaultDomain }
|
||||
|
||||
export default {
|
||||
/**
|
||||
@@ -82,6 +80,10 @@ export default {
|
||||
//api请求地址
|
||||
baseUrl: domain,
|
||||
|
||||
// aikefu 智能客服配置 uuid (媒体上传必填; 后端 /api/kefu/info 目前不返回该值,
|
||||
// 需在 .local.config.js 对应环境配置里手动填写 aikefuConfigUuid: 'xxx')
|
||||
aikefuConfigUuid: aikefuConfigUuid,
|
||||
|
||||
// 图片域名
|
||||
imgDomain: domain,
|
||||
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
* 客服统一处理服务
|
||||
* 整合各种客服方式,提供统一的调用接口
|
||||
*/
|
||||
import IMAGE_CONFIG from './image-config.js';
|
||||
import Platform from './platform.js';
|
||||
import PAGE_KEY_MAP from './util.js';
|
||||
|
||||
export class CustomerService {
|
||||
constructor(vueInstance, externalConfig = null) {
|
||||
this.vm = vueInstance;
|
||||
@@ -28,29 +32,25 @@ export class CustomerService {
|
||||
return this.latestPlatformConfig;
|
||||
}
|
||||
|
||||
// 优先级:外部传入 > vuex store > 空对象
|
||||
const servicerConfig = this.externalConfig || this.vm.$store.state.servicerConfig || {};
|
||||
console.log(`【实时客服配置】`, servicerConfig);
|
||||
const platformMap = {
|
||||
h5: 'h5',
|
||||
weapp: 'weapp',
|
||||
alipay: 'aliapp',
|
||||
baidu: 'baidu',
|
||||
toutiao: 'toutiao',
|
||||
qq: 'qq',
|
||||
kuaishou: 'kuaishou',
|
||||
jd: 'jd',
|
||||
'360': '360',
|
||||
xhs: 'xhs',
|
||||
app: 'app',
|
||||
pc: 'pc'
|
||||
};
|
||||
|
||||
let platformConfig = null;
|
||||
const platformKey = platformMap[Platform.detect()] || Platform.detect();
|
||||
let platformConfig = servicerConfig[platformKey] && typeof servicerConfig[platformKey] === 'object' ? servicerConfig[platformKey] : null;
|
||||
|
||||
// #ifdef H5
|
||||
platformConfig = servicerConfig.h5 && typeof servicerConfig.h5 === 'object' ? servicerConfig.h5 : null;
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
platformConfig = servicerConfig.weapp && typeof servicerConfig.weapp === 'object' ? servicerConfig.weapp : null;
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-ALIPAY
|
||||
platformConfig = servicerConfig.aliapp && typeof servicerConfig.aliapp === 'object' ? servicerConfig.aliapp : null;
|
||||
// #endif
|
||||
|
||||
// #ifdef PC
|
||||
platformConfig = servicerConfig.pc && typeof servicerConfig.pc === 'object' ? servicerConfig.pc : null;
|
||||
// #endif
|
||||
|
||||
// 防止空数组被当作有效配置
|
||||
if (Array.isArray(platformConfig)) {
|
||||
platformConfig = null;
|
||||
}
|
||||
@@ -101,7 +101,7 @@ export class CustomerService {
|
||||
|
||||
if (!config || !config.type) {
|
||||
result.isValid = false;
|
||||
result.errors.push('客服类型未配置');
|
||||
result.errors.push(this.vm.$lang('customerService.serviceTypeNotConfigured'));
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -118,9 +118,19 @@ export class CustomerService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 跳转到 AI 客服页面(Dify)
|
||||
* 跳转到 AI智能客服页面(AiChat)
|
||||
*
|
||||
* 注意:不在此处注入 __dyu=FloatBtn。
|
||||
* 该标记原本是 diy-float-btn.vue 用来告诉 ai-chat "我是从浮动按钮来的,请隐藏底部 tabBar"。
|
||||
* 此方法是 customer-service.js 的**通用 AI 客服入口**,被多处复用:
|
||||
* - hover-nav(悬浮客服按钮)
|
||||
* - 商品详情页 / 会员中心 / 个人中心 等的"联系客服"按钮
|
||||
* - DIY 浮动按钮(diy-float-btn 内部已自行注入 __dyu=FloatBtn,这里再注入会重复)
|
||||
* 若在此处统一注入,会让所有 AI 客服入口都隐藏底部 tabBar,语义错误且侵入性过强。
|
||||
* hover-nav 需要隐藏 tabBar 的场景,由 hover-nav.vue#handleUnifiedKefuClick
|
||||
* 自行注入 __dyu=FloatBtn(与 diy-float-btn.vue#onFloatBtnClick 一致)。
|
||||
*/
|
||||
openDifyService() {
|
||||
openAiChatService() {
|
||||
try {
|
||||
// 清除未读数(如果存在)
|
||||
if (typeof this.vm.setAiUnreadCount === 'function') {
|
||||
@@ -128,23 +138,23 @@ export class CustomerService {
|
||||
}
|
||||
|
||||
// ✅ 修正路径:必须与 pages.json 中注册的路径一致
|
||||
const aiChatUrl = '/pages_tool/ai-chat/index';
|
||||
const aiChatUrl = PAGE_KEY_MAP.AI_CHAT_PAGE_URL;
|
||||
|
||||
// ✅ 使用 navigateTo 保留返回栈(体验更好)
|
||||
uni.navigateTo({
|
||||
url: aiChatUrl,
|
||||
fail: (err) => {
|
||||
console.error('跳转 AI 客服失败:', err);
|
||||
console.error('跳转 AI智能客服失败:', err);
|
||||
// H5 兜底
|
||||
// #ifdef H5
|
||||
window.location.href = aiChatUrl;
|
||||
// #endif
|
||||
uni.showToast({ title: '打开客服失败', icon: 'none' });
|
||||
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' });
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('跳转 AI 客服异常:', e);
|
||||
uni.showToast({ title: '打开客服失败', icon: 'none' });
|
||||
console.error('跳转 AI智能客服异常:', e);
|
||||
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,8 +175,6 @@ export class CustomerService {
|
||||
}
|
||||
|
||||
const config = this.getPlatformConfig();
|
||||
console.log('【当前客服配置】', config);
|
||||
console.log('【客服类型】', config.type);
|
||||
|
||||
const { niushop = {}, sendMessageTitle = '', sendMessagePath = '', sendMessageImg = '' } = options;
|
||||
|
||||
@@ -178,31 +186,24 @@ export class CustomerService {
|
||||
// 核心路由:根据 type 决定行为
|
||||
switch (config.type) {
|
||||
case 'aikefu':
|
||||
console.log('【跳转 AI 客服】目标路径: /pages_tool/ai-chat/index');
|
||||
this.openDifyService();
|
||||
this.openAiChatService();
|
||||
break;
|
||||
case 'wxwork':
|
||||
console.log('【跳转企业微信客服】');
|
||||
this.openWxworkService(false, config, options);
|
||||
break;
|
||||
case 'third':
|
||||
console.log('【跳转第三方客服】');
|
||||
this.openThirdService(config);
|
||||
break;
|
||||
case 'miniprogram':
|
||||
console.log('【跳转第三方小程序客服】');
|
||||
this.openThirdService(config);
|
||||
break;
|
||||
case 'niushop':
|
||||
console.log('【跳转牛商客服】');
|
||||
this.openNiushopService(niushop);
|
||||
break;
|
||||
case 'weapp':
|
||||
console.log('【跳转微信官方客服】');
|
||||
this.openWeappService(config, options);
|
||||
break;
|
||||
case 'aliapp':
|
||||
console.log('【跳转支付宝客服】');
|
||||
this.openAliappService(config);
|
||||
break;
|
||||
default:
|
||||
@@ -223,7 +224,7 @@ export class CustomerService {
|
||||
wx.navigateToMiniProgram({
|
||||
appId: 'wxeb490c6f9b154ef9',
|
||||
path: `pages/contacts/externalContactDetail?url=${encodeURIComponent(wxworkConfig.contact_url)}`,
|
||||
success: () => console.log('跳转企业微信成功'),
|
||||
success: () => {},
|
||||
fail: (err) => {
|
||||
console.error('跳转企业微信失败:', err);
|
||||
this.fallbackToOriginalService();
|
||||
@@ -233,7 +234,7 @@ export class CustomerService {
|
||||
// 检查是否有企业微信配置
|
||||
if (!config.wxwork_url && !config.corpid) {
|
||||
console.error('企业微信配置不完整,缺少 wxwork_url 或 corpid');
|
||||
uni.showToast({ title: '企业微信配置不完整', icon: 'none' });
|
||||
uni.showToast({ title: this.vm.$lang('customerService.wxworkConfigIncomplete'), icon: 'none' });
|
||||
this.fallbackToPhoneCall();
|
||||
return;
|
||||
}
|
||||
@@ -260,48 +261,43 @@ export class CustomerService {
|
||||
}
|
||||
|
||||
openThirdService(config) {
|
||||
console.log('【第三方客服配置】', config);
|
||||
console.log('【配置字段】', Object.keys(config));
|
||||
|
||||
// 支持多种可能的字段名
|
||||
const miniAppId = config.mini_app_id || config.miniAppId || config.appid || config.appId || config.app_id;
|
||||
const miniAppPath = config.mini_app_path || config.miniAppPath || config.path || config.page_path || '';
|
||||
|
||||
console.log('【解析后的小程序配置】AppID:', miniAppId, 'Path:', miniAppPath);
|
||||
|
||||
|
||||
// 优先处理第三方微信小程序客服
|
||||
if (miniAppId) {
|
||||
console.log('【跳转第三方小程序】AppID:', miniAppId, 'Path:', miniAppPath);
|
||||
// #ifdef MP-WEIXIN
|
||||
wx.navigateToMiniProgram({
|
||||
appId: miniAppId,
|
||||
path: miniAppPath,
|
||||
success: () => {
|
||||
console.log('【跳转第三方小程序成功】');
|
||||
},
|
||||
fail: (err) => {
|
||||
console.error('【跳转第三方小程序失败】', err);
|
||||
uni.showToast({ title: '跳转失败,请稍后重试', icon: 'none' });
|
||||
uni.showToast({ title: this.vm.$lang('customerService.jumpFailed'), icon: 'none' });
|
||||
}
|
||||
});
|
||||
// #endif
|
||||
// #ifdef H5
|
||||
uni.showToast({ title: '第三方小程序客服仅在微信小程序中可用', icon: 'none' });
|
||||
uni.showToast({ title: this.vm.$lang('customerService.miniProgramOnly'), icon: 'none' });
|
||||
// #endif
|
||||
return;
|
||||
}
|
||||
|
||||
// 处理第三方链接客服
|
||||
if (config.third_url) {
|
||||
console.log('【跳转第三方链接】', config.third_url);
|
||||
// #ifdef H5
|
||||
window.location.href = config.third_url;
|
||||
// #endif
|
||||
// #ifdef MP-WEIXIN
|
||||
// #ifdef MP
|
||||
uni.setClipboardData({
|
||||
data: config.third_url,
|
||||
success: () => {
|
||||
uni.showToast({ title: '链接已复制,请在浏览器打开', icon: 'none' });
|
||||
uni.showToast({ title: this.vm.$lang('customerService.linkCopied'), icon: 'none' });
|
||||
}
|
||||
});
|
||||
// #endif
|
||||
@@ -324,7 +320,7 @@ export class CustomerService {
|
||||
// 此方法仅用于自定义跳转(如 useOfficial: false)
|
||||
if (config.useOfficial !== false) {
|
||||
// 不做任何事,应由 <button open-type="contact"> 触发
|
||||
console.log('使用微信官方客服,请确保按钮为 <button open-type="contact">');
|
||||
|
||||
return;
|
||||
}
|
||||
this.handleCustomWeappService(config, options);
|
||||
@@ -365,9 +361,9 @@ export class CustomerService {
|
||||
// #ifdef H5
|
||||
window.open(serviceUrl, '_blank');
|
||||
// #endif
|
||||
// #ifdef MP-WEIXIN
|
||||
// #ifdef MP
|
||||
uni.setClipboardData({ data: serviceUrl });
|
||||
uni.showToast({ title: '客服链接已复制', icon: 'none' });
|
||||
uni.showToast({ title: this.vm.$lang('customerService.customerLinkCopied'), icon: 'none' });
|
||||
// #endif
|
||||
return;
|
||||
}
|
||||
@@ -377,12 +373,12 @@ export class CustomerService {
|
||||
|
||||
openAliappService(config) {
|
||||
if (config.type === 'aikefu') {
|
||||
this.openDifyService();
|
||||
this.openAiChatService();
|
||||
} else if (config.type === 'third') {
|
||||
this.openThirdService(config);
|
||||
} else {
|
||||
// 支付宝原生客服由 button open-type="contact" 触发,此处不处理
|
||||
console.log('使用支付宝官方客服');
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -395,11 +391,11 @@ export class CustomerService {
|
||||
if (res.code === 0 && res.data?.mobile) {
|
||||
uni.makePhoneCall({ phoneNumber: res.data.mobile });
|
||||
} else {
|
||||
uni.showToast({ title: '暂无客服电话', icon: 'none' });
|
||||
uni.showToast({ title: this.vm.$lang('customerService.noServicePhone'), icon: 'none' });
|
||||
}
|
||||
},
|
||||
fail: () => {
|
||||
uni.showToast({ title: '获取客服电话失败', icon: 'none' });
|
||||
uni.showToast({ title: this.vm.$lang('customerService.getPhoneFailed'), icon: 'none' });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -407,23 +403,23 @@ export class CustomerService {
|
||||
showNoServicePopup() {
|
||||
const siteInfo = this.vm.$store.state.siteInfo || {};
|
||||
const message = siteInfo?.site_tel
|
||||
? `请联系客服,客服电话是 ${siteInfo.site_tel}`
|
||||
: '抱歉,商家暂无客服,请线下联系';
|
||||
uni.showModal({ title: '联系客服', content: message, showCancel: false });
|
||||
? this.vm.$lang('customerService.callServiceTip', { phone: siteInfo.site_tel })
|
||||
: this.vm.$lang('customerService.noServiceOffline');
|
||||
uni.showModal({ title: this.vm.$lang('customerService.contactCustomerService'), content: message, showCancel: false });
|
||||
}
|
||||
|
||||
showConfigErrorPopup(errors) {
|
||||
uni.showModal({
|
||||
title: '客服配置错误',
|
||||
content: `配置有误:\n${errors.join('\n')}`,
|
||||
title: this.vm.$lang('customerService.configError'),
|
||||
content: this.vm.$lang('customerService.configErrorDetail', { errors: errors.join('\n') }),
|
||||
showCancel: false
|
||||
});
|
||||
}
|
||||
|
||||
fallbackToOriginalService() {
|
||||
uni.showModal({
|
||||
title: '提示',
|
||||
content: '无法直接添加企业微信,是否使用其他方式联系客服?',
|
||||
title: this.vm.$lang('customerService.tip'),
|
||||
content: this.vm.$lang('customerService.cannotAddWxwork'),
|
||||
success: (res) => {
|
||||
if (res.confirm) {
|
||||
this.openWxworkService(true);
|
||||
@@ -434,8 +430,8 @@ export class CustomerService {
|
||||
|
||||
fallbackToPhoneCall() {
|
||||
uni.showModal({
|
||||
title: '提示',
|
||||
content: '在线客服不可用,是否拨打电话联系客服?',
|
||||
title: this.vm.$lang('customerService.tip'),
|
||||
content: this.vm.$lang('customerService.onlineUnavailable'),
|
||||
success: (res) => {
|
||||
if (res.confirm) this.makePhoneCall();
|
||||
}
|
||||
@@ -471,13 +467,11 @@ export class CustomerService {
|
||||
const shopInfo = this.vm.shopInfo || {};
|
||||
const config = this.getPlatformConfig();
|
||||
|
||||
if (config?.type === 'aikefu') {
|
||||
return shopInfo.aiAgentimg || '';
|
||||
} else if (config?.type === 'wxwork' || config?.type === 'qyweixin') {
|
||||
return shopInfo.aiAgentimg || '';
|
||||
} else if (config?.type === 'third') {
|
||||
return '';
|
||||
// 优先使用指定的智能客服头像
|
||||
if (config?.type === 'aikefu' || config?.type === 'wxwork' || config?.type === 'qyweixin') {
|
||||
return this.vm.$util.img(IMAGE_CONFIG.aiAvatar);
|
||||
}
|
||||
|
||||
return shopInfo.kefuimg || this.vm.$util?.getDefaultImage()?.kefu || '';
|
||||
}
|
||||
|
||||
@@ -568,6 +562,9 @@ export class CustomerService {
|
||||
|
||||
/**
|
||||
* 打开 AI 智能助手
|
||||
*
|
||||
* 注意:不在此处注入 __dyu=FloatBtn,理由同 openAiChatService()。
|
||||
* 由调用方(hover-nav.vue 等)按需注入。
|
||||
*/
|
||||
openAIChat() {
|
||||
try {
|
||||
@@ -575,21 +572,21 @@ export class CustomerService {
|
||||
this.vm.setAiUnreadCount(0);
|
||||
}
|
||||
|
||||
const aiChatUrl = '/pages_tool/ai-chat/index';
|
||||
const aiChatUrl = PAGE_KEY_MAP.AI_CHAT_PAGE_URL;
|
||||
|
||||
uni.navigateTo({
|
||||
url: aiChatUrl,
|
||||
fail: (err) => {
|
||||
console.error('跳转 AI 客服失败:', err);
|
||||
console.error('跳转 AI智能客服失败:', err);
|
||||
// #ifdef H5
|
||||
window.location.href = aiChatUrl;
|
||||
// #endif
|
||||
uni.showToast({ title: '打开客服失败', icon: 'none' });
|
||||
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' });
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('跳转 AI 客服异常:', e);
|
||||
uni.showToast({ title: '打开客服失败', icon: 'none' });
|
||||
console.error('跳转 AI智能客服异常:', e);
|
||||
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -597,7 +594,7 @@ export class CustomerService {
|
||||
* 打开客服选择对话框(预留方法)
|
||||
*/
|
||||
openCustomerSelectPopupDialog() {
|
||||
uni.showToast({ title: '客服选择功能开发中', icon: 'none' });
|
||||
uni.showToast({ title: this.vm.$lang('customerService.developing'), icon: 'none' });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -627,7 +624,7 @@ export class CustomerService {
|
||||
if (qyweixinUrl) {
|
||||
window.location.href = qyweixinUrl;
|
||||
} else {
|
||||
uni.showToast({ title: '企业微信客服未配置', icon: 'none' });
|
||||
uni.showToast({ title: this.vm.$lang('customerService.wxworkNotConfigured'), icon: 'none' });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -644,11 +641,9 @@ export class CustomerService {
|
||||
handleUnifiedKefuClick(options = {}) {
|
||||
const validation = this.validateConfig();
|
||||
|
||||
console.log('【客服配置验证】', validation);
|
||||
|
||||
if (!validation.isValid) {
|
||||
console.error('客服配置无效:', validation.errors);
|
||||
uni.showToast({ title: '客服暂不可用', icon: 'none' });
|
||||
uni.showToast({ title: this.vm.$lang('customerService.serviceUnavailable'), icon: 'none' });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -657,24 +652,22 @@ export class CustomerService {
|
||||
}
|
||||
|
||||
const platformConfig = this.getPlatformConfig();
|
||||
console.log('【当前客服配置】', platformConfig);
|
||||
|
||||
// 检查企业微信配置
|
||||
if (platformConfig.type === 'wxwork') {
|
||||
const wxworkConfig = this.getWxworkConfig();
|
||||
console.log('【企业微信配置】', wxworkConfig);
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
if (!wxworkConfig?.enable || !wxworkConfig?.contact_url) {
|
||||
console.warn('企业微信配置不完整,使用原生客服');
|
||||
uni.showToast({ title: '企业微信配置不完整', icon: 'none' });
|
||||
uni.showToast({ title: this.vm.$lang('customerService.wxworkConfigIncomplete'), icon: 'none' });
|
||||
}
|
||||
// #endif
|
||||
|
||||
// #ifdef H5
|
||||
if (!wxworkConfig?.contact_url && !platformConfig.wxwork_url) {
|
||||
console.error('企业微信链接未配置');
|
||||
uni.showToast({ title: '企业微信链接未配置', icon: 'none' });
|
||||
uni.showToast({ title: this.vm.$lang('customerService.wxworkLinkNotConfigured'), icon: 'none' });
|
||||
return;
|
||||
}
|
||||
// #endif
|
||||
@@ -683,12 +676,12 @@ export class CustomerService {
|
||||
// 直接调用统一处理方法,由 CustomerService 内部根据配置路由
|
||||
try {
|
||||
this.handleCustomerClick({
|
||||
sendMessageTitle: options.sendMessageTitle || '来自悬浮按钮的咨询',
|
||||
sendMessageTitle: options.sendMessageTitle || this.vm.$lang('customerService.fromFloatButton'),
|
||||
sendMessagePath: options.sendMessagePath || '/pages/index/index'
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('客服处理失败:', error);
|
||||
uni.showToast({ title: '打开客服失败', icon: 'none' });
|
||||
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
220
common/js/diy.js
220
common/js/diy.js
@@ -1,6 +1,7 @@
|
||||
import WxMap from 'common/js/map-wx-jssdk.js';
|
||||
import Config from '@/common/js/config.js';
|
||||
import util from '@/common/js/util.js';
|
||||
import { classifyHttpError, httpErrorKey } from '@/common/js/http-error.js';
|
||||
|
||||
let systemInfo = util.getDeviceInfo();
|
||||
|
||||
@@ -45,10 +46,21 @@ export default {
|
||||
diyRoute: '', // 页面路由
|
||||
openBottomNav: false,
|
||||
isShowCopyRight: false,
|
||||
|
||||
|
||||
// getDiyInfo 节流
|
||||
diyInfoLoading: false, // 是否正在请求
|
||||
lastDiyInfoTime: 0, // 上次成功加载的时间戳
|
||||
lastDiyInfoLang: '', // 上次加载时的语言,语言切换时强制刷新
|
||||
diyInfoTtl: 3 * 60 * 1000, // 3分钟内不重复请求
|
||||
|
||||
// diy 数据网络加载失败时的页面内错误提示(比 showModal 在各端更可靠)
|
||||
diyLoadError: false,
|
||||
diyLoadErrorMsg: '',
|
||||
diyLoadErrorUrl: '', // 出错的网络请求地址
|
||||
|
||||
//启动广告
|
||||
adv:{},
|
||||
|
||||
adv: {},
|
||||
|
||||
};
|
||||
},
|
||||
onLoad(option) {
|
||||
@@ -111,10 +123,10 @@ export default {
|
||||
// 关闭定位
|
||||
this.enterDefaultStore();
|
||||
}
|
||||
|
||||
|
||||
},
|
||||
onShow() {
|
||||
|
||||
|
||||
this.init();
|
||||
},
|
||||
onHide() {
|
||||
@@ -199,13 +211,12 @@ export default {
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
play(){
|
||||
console.log(123)
|
||||
play() {
|
||||
},
|
||||
async init() {
|
||||
|
||||
// 定位信息过期后,重新获取定位
|
||||
if(this.mapConfig.wap_is_open == 1 && this.locationStorage && this.locationStorage.is_expired) {
|
||||
if (this.mapConfig.wap_is_open == 1 && this.locationStorage && this.locationStorage.is_expired) {
|
||||
this.$util.getLocation({
|
||||
fail: (res) => {
|
||||
// 拒绝定位,进入默认总店
|
||||
@@ -221,6 +232,7 @@ export default {
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[DIY][init] calling getDiyInfo, storeToken=', !!this.storeToken);
|
||||
await this.getDiyInfo();
|
||||
//获取启动广告
|
||||
await this.getDiyAdv();
|
||||
@@ -278,7 +290,7 @@ export default {
|
||||
}, 50);
|
||||
// #endif
|
||||
},
|
||||
async getDiyAdv(){
|
||||
async getDiyAdv() {
|
||||
//启动广告
|
||||
let res = await this.$api.sendRequest({
|
||||
url: '/api/diyview/getstartadv',
|
||||
@@ -287,13 +299,13 @@ export default {
|
||||
});
|
||||
this.adv = res.value
|
||||
// 弹框形式,首次弹出 1,每次弹出 0
|
||||
if(this.adv.advshow == 1){
|
||||
if (this.adv.advshow == 1) {
|
||||
setTimeout(() => {
|
||||
if (res.value.advtype == 1) {
|
||||
var popwindow_count = uni.getStorageSync(this.id + this.name + '_popwindow_count');
|
||||
if ((this.$refs.uniPopupWindow && popwindow_count == '') || (
|
||||
this.$refs.uniPopupWindow && popwindow_count == 1)) {
|
||||
|
||||
|
||||
this.$refs.uniPopupWindow.open();
|
||||
uni.setStorageSync(this.id + this.name + '_popwindow_count', 1);
|
||||
}
|
||||
@@ -303,62 +315,165 @@ export default {
|
||||
}
|
||||
}, 500);
|
||||
}
|
||||
|
||||
|
||||
},
|
||||
async getDiyInfo() {
|
||||
let res = await this.$api.sendRequest({
|
||||
url: '/api/diyview/info',
|
||||
data: {
|
||||
id: this.id,
|
||||
name: this.name,
|
||||
en_type:uni.getStorageSync("lang"),//获取语言底部
|
||||
},
|
||||
async: false
|
||||
});
|
||||
if (res.code != 0 || !res.data) {
|
||||
// 无法从网络获取 diy 数据时:在页面内渲染错误横幅(各端可靠、一定可见)
|
||||
// 同时通过 uni.$emit 通知 splash-state 关闭启动屏 (否则 strict 模式永远不关)
|
||||
// @param {Object|string} [err] 网络异常对象 {errMsg, statusCode} / 服务端消息字符串
|
||||
// @param {string} [url] 出错的请求地址(完整 URL),用于横幅展示
|
||||
// @param {string} [errorType] 错误类型: 'network' | 'no-response' | 'business'
|
||||
_showDiyLoadError(err, url, errorType) {
|
||||
this.diyLoadErrorMsg = this._buildDiyErrorMsg(err);
|
||||
this.diyLoadErrorUrl = url || '';
|
||||
this.diyLoadError = true;
|
||||
// 通知 splash: diy 加载失败, 启动屏应该让位给错误横幅
|
||||
// 用 uni.$emit 而非直接 import splash-state, 避免循环依赖
|
||||
// reason 拼成 'diy-{errorType}-error' 方便业务方区分 (splash:diy-error 事件)
|
||||
const reason = errorType ? `diy-${errorType}-error` : 'diy-load-error'
|
||||
try { uni.$emit && uni.$emit('diy:load-error', { reason, errorType, err, url }); } catch (e) { }
|
||||
},
|
||||
// 根据错误信息组织更详细的提示文案
|
||||
// 说明:remote-only 模式下 $lang 可能返回空串,故统一用 `|| 中文兜底` 保证非空
|
||||
_buildDiyErrorMsg(err) {
|
||||
const info = classifyHttpError(err);
|
||||
|
||||
// 服务端明确返回的业务消息(字符串):直接透传
|
||||
if (info.type === 'business') return info.raw;
|
||||
|
||||
const key = httpErrorKey(info.type);
|
||||
let reason = this.$lang(key);
|
||||
|
||||
// HTTP 状态码类错误:把 statusCode 拼到 reason 后面
|
||||
if (info.statusCode) reason += '(' + info.statusCode + ')';
|
||||
|
||||
// empty / unknown 不走模板,直接返回通用网络异常
|
||||
if (info.type === 'empty' || info.type === 'unknown') return reason;
|
||||
|
||||
const tpl = this.$lang('diy.loadFailTpl', { reason });
|
||||
return tpl;
|
||||
},
|
||||
// 错误横幅「重试」入口
|
||||
retryDiyInfo() {
|
||||
this.diyLoadError = false;
|
||||
this.diyLoadErrorMsg = '';
|
||||
this.diyLoadErrorUrl = '';
|
||||
this.getDiyInfo(true);
|
||||
},
|
||||
async getDiyInfo(force = false) {
|
||||
// 节流:正在请求 / N 秒内已加载过 / 语言未变 -> 跳过
|
||||
const now = Date.now();
|
||||
const currentLang = uni.getStorageSync("lang") || '';
|
||||
console.log('[DIY][getDiyInfo] start', 'force=', force, 'id=', this.id, 'name=', this.name, 'lang=', currentLang, 'loading=', this.diyInfoLoading, 'lastAt=', this.lastDiyInfoTime, 'lastLang=', this.lastDiyInfoLang);
|
||||
if (!force) {
|
||||
if (this.diyInfoLoading) {
|
||||
console.log('[DIY][getDiyInfo] skip: already loading');
|
||||
return;
|
||||
}
|
||||
if (this.lastDiyInfoTime && (now - this.lastDiyInfoTime) < this.diyInfoTtl
|
||||
&& this.lastDiyInfoLang === currentLang) {
|
||||
console.log('[DIY][getDiyInfo] skip: throttled by ttl');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
this.diyInfoLoading = true;
|
||||
let res;
|
||||
// 出错时用于展示的完整请求地址(Request URL),与 http.js 拼接/归一化方式保持一致
|
||||
const diyInfoUrl = '/api/diyview/info';
|
||||
const diyInfoFullUrl = ((Config.baseUrl || '') + diyInfoUrl).replace(/(?<!:)\/+/g, '/');
|
||||
try {
|
||||
res = await this.$api.sendRequest({
|
||||
url: diyInfoUrl,
|
||||
data: {
|
||||
id: this.id,
|
||||
name: this.name,
|
||||
en_type: currentLang,
|
||||
},
|
||||
async: false
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('[DIY][getDiyInfo] request failed', e);
|
||||
if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
|
||||
this.diyInfoLoading = false;
|
||||
// 无法从网络获取数据时,页面内显示错误横幅并提供重试(带详细原因 + 请求地址)
|
||||
// errorType='network': 网络异常 (uni.request catch)
|
||||
this._showDiyLoadError(e, diyInfoFullUrl, 'network');
|
||||
return;
|
||||
}
|
||||
this.diyInfoLoading = false;
|
||||
console.log('[DIY][getDiyInfo] got response', 'code=', res && res.code, 'hasData=', !!(res && res.data), 'valueType=', res && res.data && typeof res.data.value, 'valueLen=', res && res.data && (typeof res.data.value === 'string' ? res.data.value.length : (res.data.value ? res.data.value.length : null)));
|
||||
|
||||
if (!res || res.code != 0 || !res.data) {
|
||||
console.warn('[DIY][getDiyInfo] invalid response', JSON.stringify(res));
|
||||
if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
|
||||
|
||||
if (res.code == -3) {
|
||||
this.$util.showToast({
|
||||
title: res.message
|
||||
});
|
||||
this.diyData = {};
|
||||
// 完全没有拿到网络响应,视为无法从网络获取数据,页面内显示错误横幅
|
||||
if (!res) {
|
||||
// errorType='no-response': 完全没有 res 对象
|
||||
this._showDiyLoadError(null, diyInfoFullUrl, 'no-response');
|
||||
// 保持原有数据结构,仅清空 value,避免鸿蒙下重新布局
|
||||
this.diyData = { ...(this.diyData || {}), value: [] };
|
||||
return;
|
||||
}
|
||||
|
||||
this.$util.showToast({
|
||||
title: '未配置自定义页面数据'
|
||||
});
|
||||
this.diyData = {};
|
||||
if (res && res.code == -3) {
|
||||
this.$util.showToast({
|
||||
title: res.message
|
||||
});
|
||||
// 保持原有数据结构,仅清空 value,避免鸿蒙下重新布局
|
||||
this.diyData = { ...(this.diyData || {}), value: [] };
|
||||
return;
|
||||
}
|
||||
|
||||
// 拿到响应但业务失败 / 无数据(如接口 404 返回 200+错误码、code!=0)
|
||||
// 同样视为无法获取到 diy 数据,页面内显示错误横幅
|
||||
// errorType='business': 业务失败 (code!=0 / 消息提示)
|
||||
this._showDiyLoadError(res && res.message, diyInfoFullUrl, 'business');
|
||||
// 保持原有数据结构,仅清空 value,避免鸿蒙下重新布局
|
||||
this.diyData = { ...(this.diyData || {}), value: [] };
|
||||
return;
|
||||
}
|
||||
|
||||
this.lastDiyInfoTime = now;
|
||||
this.lastDiyInfoLang = currentLang;
|
||||
// 成功加载后清除错误提示
|
||||
this.diyLoadError = false;
|
||||
this.diyLoadErrorMsg = '';
|
||||
this.diyLoadErrorUrl = '';
|
||||
|
||||
let diyDataValue = res.data;
|
||||
if (diyDataValue.value) {
|
||||
this.diyData = JSON.parse(diyDataValue.value);
|
||||
try {
|
||||
this.diyData = JSON.parse(diyDataValue.value);
|
||||
} catch (parseErr) {
|
||||
console.error('[DIY][getDiyInfo] JSON.parse(value) failed', parseErr, 'value preview=', String(diyDataValue.value).slice(0, 200));
|
||||
throw parseErr;
|
||||
}
|
||||
console.log('[DIY][getDiyInfo] parsed diyData', 'globalKeys=', this.diyData && this.diyData.global ? Object.keys(this.diyData.global) : null, 'valueCount=', this.diyData && this.diyData.value && this.diyData.value.length, 'topIndexValue before=', this.topIndexValue);
|
||||
|
||||
// 导航栏标题要根据语言环境切换
|
||||
const title = this.isEnEnv ? this.diyData?.global?.en_title : this.diyData?.global?.title;
|
||||
// 优先使用 title_map 多语言 map,没有则回退到 title / en_title
|
||||
const title = this.$langConfig.getField(this.diyData?.global, 'title');
|
||||
if (title) this.$langConfig.title(title);
|
||||
|
||||
this.mpCollect = this.diyData.global.mpCollect;
|
||||
this.setPublicShare();
|
||||
/* if (this.diyData.global.popWindow && this.diyData.global.popWindow.imageUrl) {
|
||||
// 弹框形式,首次弹出 1,每次弹出 0
|
||||
setTimeout(() => {
|
||||
if (this.diyData.global.popWindow.count == 1) {
|
||||
var popwindow_count = uni.getStorageSync(this.id + this.name + '_popwindow_count');
|
||||
if ((this.$refs.uniPopupWindow && popwindow_count == '') || (
|
||||
this.$refs.uniPopupWindow && popwindow_count == 1)) {
|
||||
/* if (this.diyData.global.popWindow && this.diyData.global.popWindow.imageUrl) {
|
||||
// 弹框形式,首次弹出 1,每次弹出 0
|
||||
setTimeout(() => {
|
||||
if (this.diyData.global.popWindow.count == 1) {
|
||||
var popwindow_count = uni.getStorageSync(this.id + this.name + '_popwindow_count');
|
||||
if ((this.$refs.uniPopupWindow && popwindow_count == '') || (
|
||||
this.$refs.uniPopupWindow && popwindow_count == 1)) {
|
||||
this.$refs.uniPopupWindow.open();
|
||||
uni.setStorageSync(this.id + this.name + '_popwindow_count', 1);
|
||||
}
|
||||
} else if (this.diyData.global.popWindow.count == 0) {
|
||||
this.$refs.uniPopupWindow.open();
|
||||
uni.setStorageSync(this.id + this.name + '_popwindow_count', 1);
|
||||
uni.setStorageSync(this.id + this.name + '_popwindow_count', 0);
|
||||
}
|
||||
} else if (this.diyData.global.popWindow.count == 0) {
|
||||
this.$refs.uniPopupWindow.open();
|
||||
uni.setStorageSync(this.id + this.name + '_popwindow_count', 0);
|
||||
}
|
||||
}, 500);
|
||||
}*/
|
||||
}, 500);
|
||||
}*/
|
||||
|
||||
// 修改diy数据结构排序
|
||||
let searchIndex = -1;
|
||||
@@ -422,6 +537,9 @@ export default {
|
||||
this.openBottomNav = this.diyData.global.openBottomNav;
|
||||
}
|
||||
this.isShowCopyRight = true;
|
||||
console.log('[DIY][getDiyInfo] done', 'topIndexValue after=', this.topIndexValue && this.topIndexValue.componentName, 'valueCount=', this.diyData.value.length, 'openBottomNav=', this.openBottomNav, 'isShowCopyRight=', this.isShowCopyRight);
|
||||
} else {
|
||||
console.warn('[DIY][getDiyInfo] no value in res.data', JSON.stringify(diyDataValue).slice(0, 200));
|
||||
}
|
||||
},
|
||||
closePopupWindow() {
|
||||
@@ -561,7 +679,7 @@ export default {
|
||||
if (res.code == 0 && res.data) {
|
||||
this.currentPosition = res.data.formatted_addresses.recommend; // 结合知名地点形成的描述性地址,更具人性化特点
|
||||
} else {
|
||||
this.currentPosition = '未获取到定位';
|
||||
this.currentPosition = this.$lang('diy.locationNotAvailable');
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -573,7 +691,7 @@ export default {
|
||||
this.nearestStore = this.defaultStoreInfo;
|
||||
this.nearestStore.show_address = this.nearestStore.full_address.replace(/,/g, ' ') + ' ' + this.nearestStore.address;
|
||||
}
|
||||
if (this.currentPosition == '') this.currentPosition = '未获取到定位';
|
||||
if (this.currentPosition == '') this.currentPosition = this.$lang('diy.locationNotAvailable');
|
||||
this.openChooseStorePopup();
|
||||
}
|
||||
},
|
||||
@@ -583,7 +701,7 @@ export default {
|
||||
if (this.id) shareUrl += '?id=' + this.id;
|
||||
else if (this.name) shareUrl += '?name=' + this.name;
|
||||
this.$util.setPublicShare({
|
||||
title: this.diyData.global.title,
|
||||
title: this.$langConfig.getField(this.diyData.global, 'title'),
|
||||
desc: '',
|
||||
link: shareUrl,
|
||||
imgUrl: this.siteInfo ? this.$util.img(this.siteInfo.logo_square) : ''
|
||||
|
||||
15
common/js/empty-lang-stub.js
Normal file
15
common/js/empty-lang-stub.js
Normal file
@@ -0,0 +1,15 @@
|
||||
// ============================================================
|
||||
// 空 lang 包占位
|
||||
//
|
||||
// 在 source === 'remote-only' 模式下, lang/ 目录下的所有 .js 会被
|
||||
// webpack.NormalModuleReplacementPlugin 替换为这个 stub.
|
||||
//
|
||||
// 设计要点:
|
||||
// - 导出 default 对象, 结构与真实 lang 包一致: { lang: {...} }
|
||||
// - lang 字段是空对象, 让 lang() 函数 fallback 路径不报错
|
||||
// - 不导出 named export, 避免 tree-shaking 把整个 stub 干掉
|
||||
// ============================================================
|
||||
|
||||
export default {
|
||||
lang: {}
|
||||
};
|
||||
169
common/js/empty-style-stub.js
Normal file
169
common/js/empty-style-stub.js
Normal file
@@ -0,0 +1,169 @@
|
||||
// ============================================================
|
||||
// 空主题预设占位(stub)
|
||||
//
|
||||
// 在 themeConfig.overrideRemote.source === 'remote-only' 模式下,
|
||||
// style_color.js 会被 webpack.NormalModuleReplacementPlugin 替换为这个 stub.
|
||||
//
|
||||
// 目的: 主包不再包含 8 个完整 preset (~80KB), 只保留最小 emergency fallback
|
||||
// (~5KB, 仅 1 个 default preset 的核心 token).
|
||||
//
|
||||
// 设计要点:
|
||||
// 1) 导出 default 对象, 结构与 style_color.js 一致: { 'default': { ... } }
|
||||
// 2) 包含最关键的 token(main_color, aux_color, bg_color 等),
|
||||
// 保证 themeColorSet 能写入基础 CSS 变量,首屏不白屏
|
||||
// 3) 缺失的 token 由远端 /api/theme/presets 异步补齐,补齐前 var() 解析失败
|
||||
// 时浏览器会回退到 SCSS 的 fallback 值(uni-app H5 已做 rpx→px)
|
||||
// 4) 其他 7 个 preset 完全由远端提供,本地不打包
|
||||
// 5) 失败兜底: 远端不可用时, 切到非 default preset 会落到 default 的样式
|
||||
//
|
||||
// token 数量统计: 8 preset × ~50 token = ~400 token. 完整 80KB.
|
||||
// 1 preset × ~50 token = ~5KB. 节省 ~94%.
|
||||
// ============================================================
|
||||
|
||||
export default {
|
||||
'default': {
|
||||
name: 'default',
|
||||
main_color: '#F4391c',
|
||||
aux_color: '#F7B500',
|
||||
bg_color: '#FF4646',
|
||||
bg_color_shallow: '#FF4646',
|
||||
promotion_color: '#FF4646',
|
||||
promotion_aux_color: '#F7B500',
|
||||
main_color_shallow: '#FFF4F4',
|
||||
price_color: 'rgb(252,82,39)',
|
||||
btn_text_color: '#FFFFFF',
|
||||
|
||||
goods_price: 'rgb(252,82,39,1)',
|
||||
promotion_tag: '#FF4646',
|
||||
goods_card_bg: '#201A18',
|
||||
goods_card_bg_shallow: '#7C7878',
|
||||
goods_card_color: '#FFD792',
|
||||
goods_coupon: '#FC5227',
|
||||
goods_cart_num_corner: '#FC5227',
|
||||
goods_btn_color: '#FF4646',
|
||||
goods_btn_color_shallow: '#F7B500',
|
||||
|
||||
pintuan_label_bg: '#F7B500',
|
||||
pintuan_label_color: '#FFFFFF',
|
||||
pintuan_color: '#FA6400',
|
||||
pintuan_promotion_color: '#FA3A1D',
|
||||
pintuan_promotion_aux_color: '#FD9A01',
|
||||
|
||||
super_member_start_bg: '#7c7878',
|
||||
super_member_end_bg: '#201a18',
|
||||
super_member_start_text_color: '#FFDBA6',
|
||||
super_member_end_text_color: '#FFEBCA',
|
||||
|
||||
bargain_promotion_color: '#F0353E',
|
||||
bargain_promotion_aux_color: '#FD9A01',
|
||||
|
||||
seckill_promotion_color: '#F83530',
|
||||
seckill_promotion_aux_color: '#FD9A01',
|
||||
|
||||
giftcard_promotion_color: '#FF3369',
|
||||
giftcard_promotion_aux_color: '#F7B500',
|
||||
|
||||
groupby_promotion_color: '#E64136',
|
||||
groupby_promotion_aux_color: '#F7B500',
|
||||
|
||||
hover_nav_bg_color: '#FFFC',
|
||||
hover_nav_text_color: '#000',
|
||||
|
||||
// ===== DIY 分类页字号 token =====
|
||||
diy_category_tree_select_size: '28rpx',
|
||||
diy_category_tree_normal_size: '20rpx',
|
||||
diy_category_item_title_size: '26rpx',
|
||||
diy_category_item_goods_title_size:'28rpx',
|
||||
diy_category_item_name_size: '24rpx',
|
||||
diy_category_item_goods_name_size:'28rpx',
|
||||
diy_category_item_goods_tag_size: '22rpx',
|
||||
diy_category_item_consult_now_size:'26rpx',
|
||||
diy_category_item_consult_now_bg: '#FF4646',
|
||||
diy_category_item_consult_now_text: '#FFFFFF',
|
||||
diy_category_item_consult_now_padding: '12rpx 30rpx',
|
||||
diy_category_item_consult_now_radius: '40rpx',
|
||||
diy_category_item_consult_now_weight: '500',
|
||||
diy_category_item_consult_now_line_height:'1.2',
|
||||
diy_category_item_consult_now_text_align: 'center',
|
||||
diy_category_item_consult_now_white_space:'nowrap',
|
||||
diy_category_item_consult_now_display: 'inline-block',
|
||||
|
||||
// ===== DIY 分类页 - 商品卡 token =====
|
||||
diy_category_item_goods_name_line_height:1.3,
|
||||
diy_category_item_goods_name_margin_top: '20rpx',
|
||||
diy_category_item_discount_price_weight: 'bold',
|
||||
diy_category_item_discount_price_line_height: 1,
|
||||
diy_category_item_discount_price_margin_top: '16rpx',
|
||||
diy_category_item_pro_info_margin_top: '16rpx',
|
||||
diy_category_item_delete_price_size: '24rpx',
|
||||
diy_category_item_delete_price_line_height: 1,
|
||||
diy_category_item_delete_price_text_decoration:'line-through',
|
||||
diy_category_item_member_price_tag_width: '60rpx',
|
||||
diy_category_item_member_price_tag_height: '28rpx',
|
||||
diy_category_item_member_price_tag_line_height: 1,
|
||||
diy_category_item_member_price_tag_margin_left: '6rpx',
|
||||
diy_category_item_info_wrap_padding: '0 20rpx',
|
||||
diy_category_item_info_wrap_margin_top: '12rpx',
|
||||
diy_category_item_footer_wrap_display: 'flex',
|
||||
diy_category_item_footer_wrap_justify_content: 'space-between',
|
||||
diy_category_item_footer_wrap_align_items: 'normal',
|
||||
diy_category_item_footer_wrap_margin_top: 0,
|
||||
diy_category_item_price_wrap_display: 'block',
|
||||
diy_category_item_price_wrap_align_items: 'normal',
|
||||
diy_category_item_price_wrap_flex_wrap: 'nowrap',
|
||||
diy_category_item_price_wrap_justify_content: 'normal',
|
||||
diy_category_item_price_wrap_margin_top: 0,
|
||||
diy_category_item_name_wrap_flex: '1',
|
||||
diy_category_item_consult_now_wrap_display: 'flex',
|
||||
diy_category_item_consult_now_wrap_justify_content:'flex-end',
|
||||
diy_category_item_consult_now_wrap_margin_top: 'auto',
|
||||
diy_category_item_consult_now_wrap_padding_top: '10rpx',
|
||||
diy_category_item_color_tip_color: '#909399',
|
||||
diy_category_item_price_font_weight: 500,
|
||||
|
||||
// ===== 营销 token(全 8 preset 一致) =====
|
||||
pintuan_label_grad_start: '#ffbd5b',
|
||||
pintuan_label_grad_end: '#fd882e',
|
||||
pintuan_avatar_border: '#ff3d3d',
|
||||
pintuan_success_start: '#3edb73',
|
||||
pintuan_success_end: '#1db576',
|
||||
bargain_promo_shallow: '#ffeadb',
|
||||
seckill_price_shallow: '#fcecd7',
|
||||
seckill_price_start: '#fdbe6c',
|
||||
seckill_discount_start: '#ff5f17',
|
||||
seckill_discount_end: '#fe2f18',
|
||||
member_card_gold_start: '#E3B66B',
|
||||
member_card_gold_end: '#F7DAA5',
|
||||
member_icon_grad_start: '#814635',
|
||||
member_icon_grad_end: '#3A221B',
|
||||
balance_page_bg_start: '#FE7849',
|
||||
balance_page_bg_end: '#FF1959',
|
||||
point_page_bg_start: '#FE7849',
|
||||
point_page_bg_end: '#FF1959',
|
||||
point_promo_start: '#F8F8F8',
|
||||
point_promo_end: '#E74A32',
|
||||
point_item_grad_start: '#F4402B',
|
||||
point_item_grad_end: '#FD7C40',
|
||||
invite_grad_start: '#ff2440',
|
||||
invite_grad_end: '#ff7b7b',
|
||||
promote_grad_start: '#ffe2ac',
|
||||
promote_grad_end: '#fdc174',
|
||||
fenxiao_withdraw_start: '#ff3c29',
|
||||
fenxiao_withdraw_end: '#ff6f29',
|
||||
level_1_grad_start: '#9BA7B1', level_1_grad_end: '#D3DEE6',
|
||||
level_2_grad_start: '#F57E2A', level_2_grad_end: '#FAD494',
|
||||
level_3_grad_start: '#F85151', level_3_grad_end: '#FF9999',
|
||||
level_4_grad_start: '#78B8B4', level_4_grad_end: '#AFE6E2',
|
||||
level_5_grad_start: '#4DA1E1', level_5_grad_end: '#58CBF0',
|
||||
level_6_grad_start: '#81C636', level_6_grad_end: '#D1F677',
|
||||
level_7_grad_start: '#6D7279', level_7_grad_end: '#A5AAB0',
|
||||
level_8_grad_start: '#866DDB', level_8_grad_end: '#D49BFE',
|
||||
level_9_grad_start: '#f1c74e', level_9_grad_end: '#f7dc81',
|
||||
level_10_grad_start: '#418CCF', level_10_grad_end: '#9CC6F1',
|
||||
}
|
||||
// 其他 7 个 preset (green/blue/pink/gold/purple/yellow/black)
|
||||
// 全部由远端 /api/theme/presets 异步提供
|
||||
// 远端拉取前切到非 default preset,会回退到 default 样式
|
||||
// 注: 历史曾尝试添加 'red' preset, 但前端 style_color.js 从未定义, 已在
|
||||
// config-external.js themeList 中移除以保持一致性
|
||||
};
|
||||
@@ -12,57 +12,13 @@
|
||||
* @createTime 2023-08-10
|
||||
*/
|
||||
|
||||
import Platform from './platform.js'
|
||||
|
||||
class EventBus {
|
||||
constructor() {
|
||||
this.events = new Map()
|
||||
this.domBridge = null
|
||||
this.platform = this.detectPlatform()
|
||||
}
|
||||
|
||||
// 检测平台
|
||||
detectPlatform() {
|
||||
// #ifdef H5
|
||||
return 'h5'
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
return 'weapp'
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-ALIPAY
|
||||
return 'alipay'
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-BAIDU
|
||||
return 'baidu'
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-TOUTIAO
|
||||
return 'toutiao'
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-QQ
|
||||
return 'qq'
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-KUAISHOU
|
||||
return 'kuaishou'
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-JD
|
||||
return 'jd'
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-360
|
||||
return '360'
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-XHS
|
||||
return 'xhs'
|
||||
// #endif
|
||||
|
||||
|
||||
return 'unknown'
|
||||
this.platform = Platform.detect()
|
||||
}
|
||||
|
||||
// 设置 DOM 桥接
|
||||
|
||||
@@ -44,7 +44,7 @@ export class EventSafety {
|
||||
// 安全的方法
|
||||
matches: (selector) => EventSafety.safeMatches(target, selector),
|
||||
// 数据集
|
||||
dataset: target.dataset || {}
|
||||
dataset: target?.dataset || {}
|
||||
}
|
||||
|
||||
return safeTarget
|
||||
|
||||
112
common/js/form-platform-mixin.js
Normal file
112
common/js/form-platform-mixin.js
Normal file
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* form-platform-mixin.js
|
||||
*
|
||||
* 表单组件共用的平台检测 mixin
|
||||
*
|
||||
* 集中维护 3 个 computed:
|
||||
* - platform 当前运行平台 key(与后端 formConfig.terminal 键名对齐)
|
||||
* - platformAliases 后端键名 → 内部 platform 名 兼容层
|
||||
* - platformConfigKeys 当前平台的有效配置键集合(用于从 formConfig.terminal 查找)
|
||||
*
|
||||
* 消费方:
|
||||
* - components/ns-form/ns-form.vue
|
||||
* - components/ns-newform/ns-newform.vue
|
||||
* - 任何需要按端读取 formConfig.terminal.{h5|weapp|harmony|app} 的表单组件
|
||||
*
|
||||
* 设计原则:
|
||||
* 1. 单一真值:避免 ns-form / ns-newform 各自维护导致漂移
|
||||
* 2. 纯 computed mixin:不依赖 props/data/methods,便于跨组件复用
|
||||
* 3. 不依赖 util.js 等其它模块,避免循环依赖
|
||||
* 4. 通过 mixins: [...] 引入,组件侧不再写平台判断代码
|
||||
*
|
||||
* 用法:
|
||||
* import formPlatformMixin from '@/common/js/form-platform-mixin.js';
|
||||
* export default {
|
||||
* mixins: [formPlatformMixin],
|
||||
* computed: {
|
||||
* config() {
|
||||
* const cur = this.platform;
|
||||
* const keys = this.platformConfigKeys;
|
||||
* // ...
|
||||
* }
|
||||
* }
|
||||
* };
|
||||
*/
|
||||
|
||||
export default {
|
||||
computed: {
|
||||
/**
|
||||
* 当前运行平台标识(与后端 formConfig.terminal 键名对齐)
|
||||
* 后端 terminal 键:h5 / weapp / harmony / app / mp-alipay / mp-baidu / mp-toutiao
|
||||
*/
|
||||
platform() {
|
||||
// #ifdef H5
|
||||
return 'h5';
|
||||
// #endif
|
||||
// #ifdef MP-WEIXIN
|
||||
return 'weapp';
|
||||
// #endif
|
||||
// #ifdef MP-ALIPAY
|
||||
return 'mp-alipay';
|
||||
// #endif
|
||||
// #ifdef MP-BAIDU
|
||||
return 'mp-baidu';
|
||||
// #endif
|
||||
// #ifdef MP-TOUTIAO
|
||||
return 'mp-toutiao';
|
||||
// #endif
|
||||
// #ifdef APP-PLUS
|
||||
return 'app';
|
||||
// #endif
|
||||
// #ifdef MP-HARMONY
|
||||
return 'harmony';
|
||||
// #endif
|
||||
// #ifdef QUICKAPP-WEBVIEW
|
||||
return 'quickapp';
|
||||
// #endif
|
||||
return 'h5';
|
||||
},
|
||||
/**
|
||||
* 后端键名 → 内部 platform 名 兼容层
|
||||
* canonical 与 platform() 返回值一致;别名为兼容 DB 旧 app_type(upgrade-to-ai-agent.sql)
|
||||
* 及 uniapp / 设计器的历史命名。键名严格区分大小写。
|
||||
*/
|
||||
platformAliases() {
|
||||
return {
|
||||
'h5': 'h5',
|
||||
'weapp': 'weapp',
|
||||
'mp-weixin': 'weapp',
|
||||
'wechat': 'weapp',
|
||||
'harmony': 'harmony',
|
||||
'app': 'app',
|
||||
'app-plus': 'app',
|
||||
'mp-alipay': 'mp-alipay',
|
||||
'aliapp': 'mp-alipay',
|
||||
'alipay': 'mp-alipay',
|
||||
'mp-baidu': 'mp-baidu',
|
||||
'baiduapp': 'mp-baidu',
|
||||
'baidu': 'mp-baidu',
|
||||
'mp-toutiao': 'mp-toutiao',
|
||||
'toutiao': 'mp-toutiao'
|
||||
};
|
||||
},
|
||||
/**
|
||||
* 当前平台的有效配置键集合
|
||||
* 用于 config() 中查找 formConfig.terminal 下的平台差异化配置:
|
||||
* - 后端格式:formConfig.terminal = { h5: {...}, weapp: {...}, harmony: {...} }
|
||||
* - 旧式扁平:formConfig[platformKey] = { ... }
|
||||
* 返回所有映射到当前 platform 的后端键名,方便两种结构都能命中。
|
||||
*/
|
||||
platformConfigKeys() {
|
||||
const cur = this.platform;
|
||||
const aliases = this.platformAliases;
|
||||
const keys = [];
|
||||
Object.keys(aliases).forEach(k => {
|
||||
if (aliases[k] === cur) keys.push(k);
|
||||
});
|
||||
// 加入当前平台名(兼容 formConfig[platform] 这种扁平写法)
|
||||
if (keys.indexOf(cur) === -1) keys.push(cur);
|
||||
return keys;
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1,14 +1,83 @@
|
||||
import { Platform } from './platform.js';
|
||||
|
||||
// 内部 helper:获取当前页面实例
|
||||
const _getCurrentPage = () => {
|
||||
const pages = getCurrentPages();
|
||||
return pages.length === 0 ? null : pages[pages.length - 1];
|
||||
};
|
||||
|
||||
// 内部 helper:获取当前页面路由(统一提取 route 或 $page.path)
|
||||
const _getCurrentRoute = (currentPage) => {
|
||||
if (!currentPage) return '';
|
||||
if (currentPage.route) return currentPage.route;
|
||||
if (currentPage.$page && currentPage.$page.path) return currentPage.$page.path;
|
||||
return '';
|
||||
};
|
||||
|
||||
// 内部 helper:判断 tabBarList 是否已加载且有 list 配置
|
||||
const _isValidTabBarList = (tabBarList) => {
|
||||
return tabBarList && tabBarList.list;
|
||||
};
|
||||
|
||||
// 内部 helper:规范化路由:无前导斜杠时补全
|
||||
const _normalizeLeadingSlash = (route) => {
|
||||
if (!route) return route;
|
||||
return route.startsWith('/') ? route : '/' + route;
|
||||
};
|
||||
|
||||
// 内部 helper:通过 $util 方法的安全调用
|
||||
const _callUtil = (vm, method, ...args) => {
|
||||
if (vm.$util && vm.$util[method]) {
|
||||
return vm.$util[method](...args);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
export default {
|
||||
onLoad() { },
|
||||
onShow() {
|
||||
// 刷新多语言
|
||||
this.$langConfig.refresh();
|
||||
// remote-only 小程序/鸿蒙: boot 未完成时跳过 refresh,避免空翻译写入标题等
|
||||
// H5 不受影响(main.js 已 await boot 后才 $mount)
|
||||
if (this.$langConfig.isRemoteOnly && this.$langConfig.isRemoteOnly()) {
|
||||
if (!this.$langConfig.isBootCompleted || !this.$langConfig.isBootCompleted()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 刷新多语言(仅刷新标题,不触发全页面 $forceUpdate)
|
||||
// 全量刷新仅在语言包真正变化时由 lang.js emitUpdated 触发
|
||||
this.$langConfig.refresh(false);
|
||||
|
||||
// TabBar 根页面时隐藏系统导航栏的返回按钮
|
||||
// (uni-app 的系统导航栏在通过 navigateTo 跳转到 tab 页时可能残留返回键)
|
||||
const tabBarList = this.$store.state.tabBarList;
|
||||
if (!_isValidTabBarList(tabBarList)) return;
|
||||
const currentRoute = _getCurrentRoute(_getCurrentPage());
|
||||
if (!currentRoute) return;
|
||||
const isRoot = _callUtil(this, 'isTabBarRootPage', currentRoute, tabBarList) || false;
|
||||
if (isRoot) {
|
||||
// #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-QQ || MP-ALIPAY
|
||||
try { uni.hideHomeButton(); } catch (e) { /* 兼容 */ }
|
||||
// #endif
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
// 是否是英文环境
|
||||
isEnEnv() {
|
||||
return this.$langConfig.getCurrentLocale() === 'en-us';
|
||||
},
|
||||
// 是否是非中文环境(用于多语言商品名/字段切换)
|
||||
isNotZhEnv() {
|
||||
return this.$langConfig.getCurrentLocale() !== 'zh-cn';
|
||||
},
|
||||
// 动态判断:当前页面是否是 TabBar 根页面(tab 根页不应显示返回按钮)
|
||||
isTabRootPage() {
|
||||
const tabBarList = this.$store.state.tabBarList;
|
||||
if (!_isValidTabBarList(tabBarList)) return false;
|
||||
const currentRoute = _getCurrentRoute(_getCurrentPage());
|
||||
if (!currentRoute) return false;
|
||||
return _callUtil(this, 'isTabBarRootPage', currentRoute, tabBarList) || false;
|
||||
},
|
||||
themeStyle() {
|
||||
return this.$store.state.themeStyle;
|
||||
},
|
||||
@@ -22,6 +91,28 @@ export default {
|
||||
tabBarList() {
|
||||
return this.$store.state.tabBarList;
|
||||
},
|
||||
shouldShowTabBar() {
|
||||
const tabBarList = this.$store.state.tabBarList;
|
||||
if (!_isValidTabBarList(tabBarList)) return false;
|
||||
const mode = tabBarList.page_visibility_mode;
|
||||
const routeList = tabBarList.page_routes || [];
|
||||
if (!mode || mode === 'all') return true;
|
||||
if (mode === 'none') return false;
|
||||
const currentPage = _getCurrentPage();
|
||||
if (!currentPage) return true;
|
||||
const currentRoute = _normalizeLeadingSlash(_getCurrentRoute(currentPage));
|
||||
if (!currentRoute) return true;
|
||||
const inList = _callUtil(this, 'isPageInRouteList', currentRoute, routeList) || false;
|
||||
if (mode === 'whitelist') return inList;
|
||||
if (mode === 'blacklist') return !inList;
|
||||
return true;
|
||||
},
|
||||
tabBarPagePaddingStyle() {
|
||||
return this.$util.objToStyle({
|
||||
height: `calc(100vh - ${this.tabBarHeight})`,
|
||||
paddingBottom: this.tabBarHeight
|
||||
});
|
||||
},
|
||||
siteInfo() {
|
||||
return this.$store.state.siteInfo;
|
||||
},
|
||||
@@ -81,7 +172,7 @@ export default {
|
||||
return this.$store.state.diySeckillInterval;
|
||||
},
|
||||
tabBarHeight() {
|
||||
return this.$store.state.tabBarHeight;
|
||||
return this.shouldShowTabBar ? this.$store.state.tabBarHeight : '0rpx';
|
||||
},
|
||||
mapConfig() {
|
||||
return this.$store.state.mapConfig;
|
||||
@@ -109,6 +200,13 @@ export default {
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
/**
|
||||
* 当前平台类型(多端翻译隔离)
|
||||
* 复用 Platform.getAppType(),与服务端 /api/BaseApi 的 $app_type 对齐
|
||||
*/
|
||||
getAppType() {
|
||||
try { return Platform.getAppType() || '*'; } catch (e) { return '*'; }
|
||||
},
|
||||
|
||||
// 颜色变浅(>0)、变深函数(<0)
|
||||
lightenDarkenColor(color, amount) {
|
||||
@@ -155,6 +253,53 @@ export default {
|
||||
this.$store.dispatch('getCartNumber'); //重新获取购物车数据
|
||||
this.$util.redirectTo(this.$util.INDEX_PAGE_URL);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 金额格式化输出
|
||||
* @param {Object} money
|
||||
*/
|
||||
moneyFormat(money) {
|
||||
if (isNaN(parseFloat(money))) return money;
|
||||
return parseFloat(money).toFixed(2);
|
||||
},
|
||||
|
||||
/**
|
||||
* 重新定向到登录授权, 不区分生命周期
|
||||
* @param {String} backUrl
|
||||
* @param {Object} params 附加参数
|
||||
* @param {Function} effectFnc 副作用函数, 登录授权失败的处理方式
|
||||
*/
|
||||
redirectTologin(backUrl = '', params = {}, effectFnc = ()=>{}) {
|
||||
console.log(`------> redirectTologin`, backUrl);
|
||||
setTimeout(() => {
|
||||
this.$nextTick(() => {
|
||||
let mode = 'navigateTo';
|
||||
// #ifdef H5 || MP-HARMONY
|
||||
mode = 'redirectTo'; // H5必须使用redirectTo, 不然点击返回箭头无法返回。
|
||||
// #endif
|
||||
this.$refs?.login?.open(backUrl, mode, effectFnc);
|
||||
});
|
||||
}, 0);
|
||||
},
|
||||
|
||||
/**
|
||||
* 重新定向到登录授权, 当页面显示的时候, 失败后,
|
||||
* 原因:onLoad、onReady 只执行一次;
|
||||
* 而且,有的页面不需要这个功能
|
||||
* @param {String} backUrl
|
||||
*/
|
||||
redirectTologinOnShowLifecycle(backUrl) {
|
||||
console.log(`------> redirectTologinOnShowLifecycle`, backUrl);
|
||||
// #ifdef H5 || MP-HARMONY
|
||||
this.redirectTologin(backUrl);
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
this.redirectTologin(backUrl, {}, () => {
|
||||
uni.navigateBack({delta: 1 });
|
||||
})
|
||||
// #endif
|
||||
}
|
||||
},
|
||||
filters: {
|
||||
|
||||
@@ -79,115 +79,127 @@ export default {
|
||||
},
|
||||
methods: {
|
||||
// 处理商品详情数据
|
||||
handleGoodsSkuData() {
|
||||
// this.navbarData.title = this.goodsSkuDetail.goods_name.length > 9 ? this.goodsSkuDetail.goods_name.substr(0, 9) + "..." : this.goodsSkuDetail.goods_name;
|
||||
//设置标题
|
||||
// this.$langConfig.title(this.navbarData.title);
|
||||
if (this.goodsSkuDetail.config) {
|
||||
this.navbarData.navBarSwitch = this.goodsSkuDetail.config.nav_bar_switch;
|
||||
}
|
||||
|
||||
this.whetherCollection = this.goodsSkuDetail.is_collect; // 用户关注商品状态
|
||||
|
||||
this.modifyGoodsInfo();
|
||||
|
||||
// 初始化商品详情视图数据
|
||||
if (this.$refs.goodsDetailView) this.$refs.goodsDetailView.init({
|
||||
sku_id: this.skuId,
|
||||
goods_id: this.goodsSkuDetail.goods_id,
|
||||
preview: this.preview,
|
||||
source_member: this.source_member,
|
||||
posterParams: this.posterParams,
|
||||
posterApi: this.posterApi,
|
||||
shareUrl: this.shareUrl,
|
||||
goodsRoute: this.goodsRoute,
|
||||
isVirtual: this.goodsSkuDetail.is_virtual,
|
||||
deliveryType: this.goodsSkuDetail.express_type,
|
||||
whetherCollection: this.goodsSkuDetail.is_collect,
|
||||
evaluateConfig: this.goodsSkuDetail.evaluate_config,
|
||||
evaluateList: this.goodsSkuDetail.evaluate_list,
|
||||
evaluateCount: this.goodsSkuDetail.evaluate_count
|
||||
});
|
||||
|
||||
//媒体
|
||||
if (this.goodsSkuDetail.video_url) this.switchMedia = "video";
|
||||
|
||||
if (!Array.isArray(this.goodsSkuDetail.sku_images)) {
|
||||
if (this.goodsSkuDetail.sku_images) this.goodsSkuDetail.sku_images = this.goodsSkuDetail.sku_images.split(",");
|
||||
else this.goodsSkuDetail.sku_images = [];
|
||||
}
|
||||
|
||||
// 多规格时合并主图
|
||||
if (this.goodsSkuDetail.goods_spec_format && this.goodsSkuDetail.goods_image) {
|
||||
|
||||
if (!Array.isArray(this.goodsSkuDetail.goods_image)) this.goodsSkuDetail.goods_image = this.goodsSkuDetail.goods_image.split(",");
|
||||
|
||||
this.goodsSkuDetail.sku_images = this.goodsSkuDetail.goods_image.concat(this.goodsSkuDetail.sku_images);
|
||||
}
|
||||
|
||||
let maxHeight = '';
|
||||
let systemInfo = uni.getSystemInfoSync();
|
||||
this.goodsSkuDetail.goods_image_list.forEach((item, index) => {
|
||||
if (typeof item.pic_spec == "string")
|
||||
item.pic_spec = item.pic_spec.split('*');
|
||||
|
||||
let ratio = item.pic_spec[0] / systemInfo.windowWidth;
|
||||
item.pic_spec[0] = item.pic_spec[0] / ratio;
|
||||
item.pic_spec[1] = item.pic_spec[1] / ratio;
|
||||
|
||||
if (!maxHeight || maxHeight > item.pic_spec[1]) {
|
||||
maxHeight = item.pic_spec[1];
|
||||
async handleGoodsSkuData() {
|
||||
// 鸿蒙兼容: 外层包 try/catch, 任何同步抛错都不会导致 page 整体空白
|
||||
try {
|
||||
if (this.goodsSkuDetail.config) {
|
||||
this.navbarData.navBarSwitch = this.goodsSkuDetail.config.nav_bar_switch;
|
||||
}
|
||||
});
|
||||
this.goodsSkuDetail.swiperHeight = maxHeight + 'px';
|
||||
|
||||
this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || "件";
|
||||
this.whetherCollection = this.goodsSkuDetail.is_collect; // 用户关注商品状态
|
||||
|
||||
// 当前商品SKU规格
|
||||
if (this.goodsSkuDetail.sku_spec_format) this.goodsSkuDetail.sku_spec_format = JSON.parse(this.goodsSkuDetail.sku_spec_format);
|
||||
this.modifyGoodsInfo();
|
||||
|
||||
// 商品属性
|
||||
if (this.goodsSkuDetail.goods_attr_format) {
|
||||
let goods_attr_format = JSON.parse(this.goodsSkuDetail.goods_attr_format);
|
||||
this.goodsSkuDetail.goods_attr_format = this.$util.unique(goods_attr_format, "attr_id");
|
||||
for (var i = 0; i < this.goodsSkuDetail.goods_attr_format.length; i++) {
|
||||
for (var j = 0; j < goods_attr_format.length; j++) {
|
||||
if (this.goodsSkuDetail.goods_attr_format[i].attr_id == goods_attr_format[j].attr_id && this.goodsSkuDetail.goods_attr_format[i].attr_value_id != goods_attr_format[j].attr_value_id) {
|
||||
this.goodsSkuDetail.goods_attr_format[i].attr_value_name += "、" + goods_attr_format[j].attr_value_name;
|
||||
// 初始化商品详情视图数据
|
||||
try {
|
||||
if (this.$refs && this.$refs.goodsDetailView) {
|
||||
this.$refs.goodsDetailView.init({
|
||||
sku_id: this.skuId,
|
||||
goods_id: this.goodsSkuDetail.goods_id,
|
||||
preview: this.preview,
|
||||
source_member: this.source_member,
|
||||
posterParams: this.posterParams,
|
||||
posterApi: this.posterApi,
|
||||
shareUrl: this.shareUrl,
|
||||
goodsRoute: this.goodsRoute,
|
||||
isVirtual: this.goodsSkuDetail.is_virtual,
|
||||
deliveryType: this.goodsSkuDetail.express_type,
|
||||
whetherCollection: this.goodsSkuDetail.is_collect,
|
||||
evaluateConfig: this.goodsSkuDetail.evaluate_config,
|
||||
evaluateList: this.goodsSkuDetail.evaluate_list,
|
||||
evaluateCount: this.goodsSkuDetail.evaluate_count
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('goodsDetailView.init failed:', e);
|
||||
}
|
||||
|
||||
//媒体
|
||||
if (this.goodsSkuDetail.video_url) this.switchMedia = "video";
|
||||
|
||||
if (!Array.isArray(this.goodsSkuDetail.sku_images)) {
|
||||
if (this.goodsSkuDetail.sku_images) this.goodsSkuDetail.sku_images = this.goodsSkuDetail.sku_images.split(",");
|
||||
else this.goodsSkuDetail.sku_images = [];
|
||||
}
|
||||
|
||||
// 多规格时合并主图
|
||||
if (this.goodsSkuDetail.goods_spec_format && this.goodsSkuDetail.goods_image) {
|
||||
|
||||
if (!Array.isArray(this.goodsSkuDetail.goods_image)) this.goodsSkuDetail.goods_image = this.goodsSkuDetail.goods_image.split(",");
|
||||
|
||||
this.goodsSkuDetail.sku_images = this.goodsSkuDetail.goods_image.concat(this.goodsSkuDetail.sku_images);
|
||||
}
|
||||
|
||||
let maxHeight = '';
|
||||
let systemInfo = uni.getSystemInfoSync();
|
||||
this.goodsSkuDetail.goods_image_list.forEach((item, index) => {
|
||||
if (typeof item.pic_spec == "string")
|
||||
item.pic_spec = item.pic_spec.split('*');
|
||||
|
||||
let ratio = item.pic_spec[0] / systemInfo.windowWidth;
|
||||
item.pic_spec[0] = item.pic_spec[0] / ratio;
|
||||
item.pic_spec[1] = item.pic_spec[1] / ratio;
|
||||
|
||||
if (!maxHeight || maxHeight > item.pic_spec[1]) {
|
||||
maxHeight = item.pic_spec[1];
|
||||
}
|
||||
});
|
||||
this.goodsSkuDetail.swiperHeight = maxHeight + 'px';
|
||||
|
||||
this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || this.$lang('unit.piece');
|
||||
|
||||
// 当前商品SKU规格
|
||||
if (this.goodsSkuDetail.sku_spec_format) this.goodsSkuDetail.sku_spec_format = JSON.parse(this.goodsSkuDetail.sku_spec_format);
|
||||
|
||||
// 商品属性
|
||||
if (this.goodsSkuDetail.goods_attr_format) {
|
||||
let goods_attr_format = JSON.parse(this.goodsSkuDetail.goods_attr_format);
|
||||
this.goodsSkuDetail.goods_attr_format = this.$util.unique(goods_attr_format, "attr_id");
|
||||
for (var i = 0; i < this.goodsSkuDetail.goods_attr_format.length; i++) {
|
||||
for (var j = 0; j < goods_attr_format.length; j++) {
|
||||
if (this.goodsSkuDetail.goods_attr_format[i].attr_id == goods_attr_format[j].attr_id && this.goodsSkuDetail.goods_attr_format[i].attr_value_id != goods_attr_format[j].attr_value_id) {
|
||||
this.goodsSkuDetail.goods_attr_format[i].attr_value_name += "、" + goods_attr_format[j].attr_value_name;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 商品SKU格式
|
||||
if (this.goodsSkuDetail.goods_spec_format) this.goodsSkuDetail.goods_spec_format = JSON.parse(this.goodsSkuDetail.goods_spec_format);
|
||||
// 商品SKU格式
|
||||
if (this.goodsSkuDetail.goods_spec_format) this.goodsSkuDetail.goods_spec_format = JSON.parse(this.goodsSkuDetail.goods_spec_format);
|
||||
|
||||
// 商品详情
|
||||
if (this.goodsSkuDetail.goods_content) this.goodsSkuDetail.goods_content = (this.goodsSkuDetail.goods_content);
|
||||
console.log(this.goodsSkuDetail.goods_content)
|
||||
// if (this.goodsSkuDetail.goods_content) this.goodsSkuDetail.goods_content = htmlParser(this.goodsSkuDetail.goods_content);
|
||||
// 商品详情
|
||||
if (this.goodsSkuDetail.goods_content) this.goodsSkuDetail.goods_content = (this.goodsSkuDetail.goods_content);
|
||||
// if (this.goodsSkuDetail.goods_content) this.goodsSkuDetail.goods_content = htmlParser(this.goodsSkuDetail.goods_content);
|
||||
|
||||
//商品服务
|
||||
if (this.goodsSkuDetail.goods_service) {
|
||||
for (let i in this.goodsSkuDetail.goods_service) {
|
||||
this.goodsSkuDetail.goods_service[i]['icon'] = this.goodsSkuDetail.goods_service[i]['icon'] ? JSON.parse(this.goodsSkuDetail.goods_service[i]['icon']) : '';
|
||||
//商品服务
|
||||
if (this.goodsSkuDetail.goods_service) {
|
||||
for (let i in this.goodsSkuDetail.goods_service) {
|
||||
this.goodsSkuDetail.goods_service[i]['icon'] = this.goodsSkuDetail.goods_service[i]['icon'] ? JSON.parse(this.goodsSkuDetail.goods_service[i]['icon']) : '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.contactData = {
|
||||
title: this.goodsSkuDetail.sku_name,
|
||||
path: this.shareUrl,
|
||||
img: this.$util.img(this.goodsSkuDetail.sku_image, {
|
||||
size: 'big'
|
||||
})
|
||||
};
|
||||
if (this.$refs.goodsPromotion) this.$refs.goodsPromotion.refresh(this.goodsSkuDetail.goods_promotion);
|
||||
this.contactData = {
|
||||
title: this.goodsSkuDetail.sku_name,
|
||||
path: this.shareUrl,
|
||||
img: this.$util.img(this.goodsSkuDetail.sku_image, {
|
||||
size: 'big'
|
||||
})
|
||||
};
|
||||
try {
|
||||
if (this.$refs && this.$refs.goodsPromotion) {
|
||||
this.$refs.goodsPromotion.refresh(this.goodsSkuDetail.goods_promotion);
|
||||
}
|
||||
} catch (e) { console.error('goodsPromotion refresh failed:', e); }
|
||||
|
||||
if (this.goodsRoute != '/pages_goods/detail') this.setPublicShare();
|
||||
|
||||
// this.getBarrageData();
|
||||
if (this.addonIsExist.form) {
|
||||
this.getGoodsForm();
|
||||
// 性能优化: 商品表单(留言表单)仅在商品详情打开"立即留言"弹窗时才需要,
|
||||
// 不再阻塞首次渲染。改为在后台并发请求, 用户真正打开弹窗时数据已就绪。
|
||||
try {
|
||||
this._goodsFormPromise = this.getGoodsForm();
|
||||
} catch (e) {
|
||||
console.error('getGoodsForm kicked off failed:', e);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('handleGoodsSkuData failed:', e);
|
||||
}
|
||||
},
|
||||
/**
|
||||
@@ -200,7 +212,7 @@ export default {
|
||||
if (this.$refs.goodsDetailView) {
|
||||
|
||||
// 初始化商品详情视图数据
|
||||
this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || "件";
|
||||
this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || this.$lang('unit.piece');
|
||||
|
||||
// 解决轮播图数量不一致时,切换到第一个
|
||||
if (this.swiperCurrent > this.goodsSkuDetail.sku_images.length) {
|
||||
@@ -322,17 +334,76 @@ export default {
|
||||
},
|
||||
/**
|
||||
* 获取商品表单
|
||||
* 后端 goodsform 接口与 info() 对齐,返回 {json_data, form_config(camelCase),
|
||||
* form_name, form_tip, form_banner, show_banner, show_tip}。
|
||||
* 全部字段都落到 goodsSkuDetail 上:表单字段 / 样式 / banner / tip 元数据,
|
||||
* 给 detail.vue 的 diy-form 直接消费。所有分支都做兜底初始化,避免下游拿到 undefined。
|
||||
*/
|
||||
getGoodsForm() {
|
||||
this.$api.sendRequest({
|
||||
url: "/form/api/form/goodsform",
|
||||
data: {
|
||||
goods_id: this.goodsSkuDetail.goods_id
|
||||
},
|
||||
success: res => {
|
||||
if (res.code == 0 && res.data) this.$set(this.goodsSkuDetail, 'goods_form', res.data);
|
||||
}
|
||||
});
|
||||
async getGoodsForm() {
|
||||
// 防御: sku 切换/数据未到时 goods_id 可能为 0/空, 此时直接走空数据分支,
|
||||
// 避免后端拿到非法 goods_id 导致 4xx/5xx 后还把脏数据塞给前端。
|
||||
if (!this.goodsSkuDetail || !this.goodsSkuDetail.goods_id) {
|
||||
const emptyFn = () => {
|
||||
this.$set(this.goodsSkuDetail, 'goods_form', []);
|
||||
this.$set(this.goodsSkuDetail, 'goods_form_config', {});
|
||||
this.$set(this.goodsSkuDetail, 'goods_form_name', '');
|
||||
this.$set(this.goodsSkuDetail, 'goods_form_tip', '');
|
||||
this.$set(this.goodsSkuDetail, 'goods_form_banner', '');
|
||||
this.$set(this.goodsSkuDetail, 'goods_form_show_banner', false);
|
||||
this.$set(this.goodsSkuDetail, 'goods_form_show_tip', false);
|
||||
};
|
||||
emptyFn();
|
||||
return;
|
||||
}
|
||||
let res;
|
||||
try {
|
||||
res = await this.$api.sendRequest({
|
||||
url: "/form/api/form/goodsform",
|
||||
data: {
|
||||
goods_id: this.goodsSkuDetail.goods_id,
|
||||
format: 'object'
|
||||
},
|
||||
async: false
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('getGoodsForm request failed', e);
|
||||
res = null;
|
||||
}
|
||||
const empty = () => {
|
||||
this.$set(this.goodsSkuDetail, 'goods_form', []);
|
||||
this.$set(this.goodsSkuDetail, 'goods_form_config', {});
|
||||
this.$set(this.goodsSkuDetail, 'goods_form_name', '');
|
||||
this.$set(this.goodsSkuDetail, 'goods_form_tip', '');
|
||||
this.$set(this.goodsSkuDetail, 'goods_form_banner', '');
|
||||
this.$set(this.goodsSkuDetail, 'goods_form_show_banner', false);
|
||||
this.$set(this.goodsSkuDetail, 'goods_form_show_tip', false);
|
||||
};
|
||||
if (!res || res.code != 0 || !res.data) {
|
||||
empty();
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(res.data)) {
|
||||
// 旧版扁平数组兼容
|
||||
empty();
|
||||
this.$set(this.goodsSkuDetail, 'goods_form', res.data);
|
||||
return;
|
||||
}
|
||||
this.$set(this.goodsSkuDetail, 'goods_form', res.data.json_data || []);
|
||||
this.$set(this.goodsSkuDetail, 'goods_form_config', res.data.form_config || {});
|
||||
this.$set(this.goodsSkuDetail, 'goods_form_name', res.data.form_name || '');
|
||||
this.$set(this.goodsSkuDetail, 'goods_form_tip', res.data.form_tip || '');
|
||||
this.$set(this.goodsSkuDetail, 'goods_form_banner', res.data.form_banner || '');
|
||||
// show_banner/show_tip 后端存 0/1,归一化 boolean
|
||||
this.$set(
|
||||
this.goodsSkuDetail,
|
||||
'goods_form_show_banner',
|
||||
res.data.show_banner == 1 ? true : (res.data.show_banner === 0 ? false : true)
|
||||
);
|
||||
this.$set(
|
||||
this.goodsSkuDetail,
|
||||
'goods_form_show_tip',
|
||||
res.data.show_tip == 1 ? true : (res.data.show_tip === 0 ? false : true)
|
||||
);
|
||||
}
|
||||
},
|
||||
/**
|
||||
|
||||
@@ -316,11 +316,9 @@ function replaceVideo(html){
|
||||
|
||||
let rep = `<video style="width:100% !important;display:block;max-width: ${screenWidth} !important;"`;
|
||||
var html = html.replace(/\\/g, '').replace(/<video/g, rep);
|
||||
console.log(html)
|
||||
html = html.replace(/<video [^>]*src=['"]([^'"]+)[^>]*>/gi, (match, capture) => {
|
||||
return rep + ' src="' + util.img(capture) + '"/>';
|
||||
});
|
||||
// console.log(html)
|
||||
return html;
|
||||
}
|
||||
|
||||
|
||||
101
common/js/http-error.js
Normal file
101
common/js/http-error.js
Normal file
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* 通用网络/接口错误分类器
|
||||
*
|
||||
* 适用场景:
|
||||
* - uniapp 各端统一错误分类(diy.js / 商品 / 订单 / 自定义页面等)
|
||||
* - 任意传入 {statusCode, errMsg, message} 形式错误对象的位置
|
||||
*
|
||||
* 设计要点:
|
||||
* 1) 与 Vue / $lang 解耦:不调用任何 i18n 函数,只返回分类结果 + 原始错误字段
|
||||
* 调用方拿到 type 后,自行决定使用 $lang('http.timeout') / $lang('http.serverError')
|
||||
* 或其它命名空间的文案,完全保持各模块原有的 key 命名习惯
|
||||
* 2) 通用网络/接口错误统一映射到 common.http.* 命名空间:
|
||||
* - http.networkError: 通用网络异常(兜底)
|
||||
* - http.timeout: 请求超时
|
||||
* - http.serverError: 服务器错误(5xx)
|
||||
* - http.notFound: 接口不存在(404)
|
||||
* - http.auth: 无访问权限(401/403)
|
||||
* - http.unknown: 其他非 2xx
|
||||
* 3) 兼容多种错误对象形态:
|
||||
* - uniapp request: { statusCode, errMsg, data }
|
||||
* - axios: { response: { status }, message }
|
||||
* - fetch / 原生: { message, name }
|
||||
*
|
||||
* @param {Object|string} err 错误对象或后端业务消息字符串
|
||||
* @returns {{ type: string, statusCode?: number, errMsg?: string, raw?: any }}
|
||||
* - type 取值:
|
||||
* 'business' - 后端返回的业务消息字符串(已透传到 raw)
|
||||
* 'empty' - 错误对象为空
|
||||
* 'notFound' - HTTP 404
|
||||
* 'server' - HTTP 5xx
|
||||
* 'auth' - HTTP 401 / 403
|
||||
* 'request' - 其它非 2xx 状态码
|
||||
* 'timeout' - errMsg 含 timeout
|
||||
* 'network' - errMsg 含 connect / network / fail
|
||||
* 'unknown' - 无法分类
|
||||
* - statusCode: 若有则原样返回
|
||||
* - errMsg: 归一后的原始消息
|
||||
* - raw: 原始输入,方便调用方进一步处理
|
||||
*/
|
||||
export function classifyHttpError(err) {
|
||||
// 1) 无错误对象
|
||||
if (!err) {
|
||||
return { type: 'empty', raw: err };
|
||||
}
|
||||
|
||||
// 2) 后端直接返回的业务消息(字符串)
|
||||
if (typeof err === 'string') {
|
||||
return { type: 'business', raw: err };
|
||||
}
|
||||
|
||||
// 3) 字段归一(兼容 uni / axios / 原生 Error)
|
||||
const statusCode = err.statusCode
|
||||
?? err.response?.status
|
||||
?? err.status;
|
||||
const errMsg = err.errMsg || err.message || '';
|
||||
|
||||
if (statusCode) {
|
||||
if (statusCode === 404) return { type: 'notFound', statusCode, errMsg, raw: err };
|
||||
if (statusCode >= 500) return { type: 'server', statusCode, errMsg, raw: err };
|
||||
if (statusCode === 401 || statusCode === 403) return { type: 'auth', statusCode, errMsg, raw: err };
|
||||
return { type: 'request', statusCode, errMsg, raw: err };
|
||||
}
|
||||
|
||||
if (/timeout/i.test(errMsg)) {
|
||||
return { type: 'timeout', errMsg, raw: err };
|
||||
}
|
||||
if (/(connect|network|fail)/i.test(errMsg)) {
|
||||
return { type: 'network', errMsg, raw: err };
|
||||
}
|
||||
|
||||
return { type: 'unknown', errMsg, raw: err };
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 classifyHttpError 的结果,映射到 common.http.* 命名空间的 i18n key
|
||||
*
|
||||
* 通用网络/接口错误统一走 http.*,调用方通过 $lang(key) 解析文案。
|
||||
* 原 diy.errTimeout 这类 key 已合并到 http.*,保持项目国际化更专业。
|
||||
*
|
||||
* @param {string} type classifyHttpError 返回的 type
|
||||
* @returns {string|null} 对应的 http.* key;type='business' 时返回 null(透传 raw)
|
||||
*/
|
||||
export function httpErrorKey(type) {
|
||||
switch (type) {
|
||||
case 'empty': return 'http.networkError';
|
||||
case 'business': return null; // 透传,不用 key
|
||||
case 'notFound': return 'http.notFound';
|
||||
case 'server': return 'http.serverError';
|
||||
case 'auth': return 'http.auth';
|
||||
case 'request': return 'http.unknown';
|
||||
case 'timeout': return 'http.timeout';
|
||||
case 'network': return 'http.networkError';
|
||||
case 'unknown':
|
||||
default: return 'http.networkError';
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
classifyHttpError,
|
||||
httpErrorKey,
|
||||
};
|
||||
@@ -1,65 +1,188 @@
|
||||
import Config from './config.js'
|
||||
import Util from './util.js'
|
||||
import store from '@/store/index.js'
|
||||
import Platform from './platform.js'
|
||||
|
||||
// #ifdef H5
|
||||
const app_type = Util.isWeiXin() ? 'wechat' : 'h5';
|
||||
const app_type_name = Util.isWeiXin() ? '微信公众号' : 'H5';
|
||||
// #endif
|
||||
const { appType, appTypeName } = Platform.getPlatformInfo();
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
const app_type = 'weapp';
|
||||
const app_type_name = '微信小程序';
|
||||
// #endif
|
||||
let _Lang = null;
|
||||
function getLang() {
|
||||
if (!_Lang) {
|
||||
_Lang = require('./lang.js').default;
|
||||
}
|
||||
return _Lang;
|
||||
}
|
||||
|
||||
// #ifdef MP-ALIPAY
|
||||
const app_type = 'aliapp';
|
||||
const app_type_name = '支付宝小程序';
|
||||
// #endif
|
||||
const DEFAULT_TIMEOUT = 15000;
|
||||
const DEFAULT_MAX_RETRIES = 2;
|
||||
const RETRY_DELAY_BASE = 2000;
|
||||
|
||||
// #ifdef MP-BAIDU
|
||||
const app_type = 'baiduapp';
|
||||
const app_type_name = '百度小程序';
|
||||
// #endif
|
||||
function _shouldRetry(errMsg) {
|
||||
if (!errMsg) return false;
|
||||
if (errMsg === 'request:fail url not in domain list') return false;
|
||||
if (errMsg === 'request:fail abort') return false;
|
||||
const retryableErrors = [
|
||||
'request:fail timeout',
|
||||
'request:fail connect',
|
||||
'request:fail network'
|
||||
];
|
||||
return retryableErrors.some(err => errMsg.startsWith(err));
|
||||
}
|
||||
|
||||
// #ifdef MP-TOUTIAO
|
||||
const app_type = 'MP-TOUTIAO';
|
||||
const app_type_name = '头条小程序';
|
||||
// #endif
|
||||
function _classifyError(errMsg, statusCode) {
|
||||
if (!errMsg && !statusCode) return 'unknown';
|
||||
if (errMsg === 'request:fail abort') return 'aborted';
|
||||
if (errMsg && errMsg.indexOf('timeout') !== -1) return 'timeout';
|
||||
if (errMsg && (errMsg.indexOf('connect') !== -1 || errMsg.indexOf('network') !== -1)) return 'networkError';
|
||||
if (statusCode && statusCode >= 500) return 'serverError';
|
||||
if (errMsg && errMsg.indexOf('url not in domain list') !== -1) return 'domainNotInList';
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
// #ifdef MP-QQ
|
||||
const app_type = 'MP-QQ';
|
||||
const app_type_name = 'QQ小程序';
|
||||
// #endif
|
||||
function _sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
// #ifdef APP-PLUS
|
||||
const app_type = 'app';
|
||||
const app_type_name = 'APP';
|
||||
// #endif
|
||||
function _makeRequest(url, method, data, header, dataType, responseType, timeout) {
|
||||
const reqId = 'req_' + Date.now() + '_' + Math.floor(Math.random() * 10000);
|
||||
const reqStart = Date.now();
|
||||
console.log('[HTTP][REQUEST]', reqId, method, url, JSON.stringify({
|
||||
data: data,
|
||||
header: header,
|
||||
dataType: dataType,
|
||||
responseType: responseType,
|
||||
timeout: timeout
|
||||
}));
|
||||
return new Promise((resolve, reject) => {
|
||||
uni.request({
|
||||
url: url,
|
||||
method: method,
|
||||
data: data,
|
||||
header: header,
|
||||
dataType: dataType,
|
||||
responseType: responseType,
|
||||
timeout: timeout,
|
||||
success: (res) => {
|
||||
console.log('[HTTP][RESPONSE]', reqId, method, url, 'statusCode=', res.statusCode, 'cost=', (Date.now() - reqStart) + 'ms', JSON.stringify(res.data));
|
||||
if (res.statusCode && [200, 500].indexOf(res.statusCode) == -1) {
|
||||
reject({ errMsg: `request:fail statusCode=${res.statusCode}`, statusCode: res.statusCode });
|
||||
return;
|
||||
}
|
||||
if (res.data.code == -3 && store.state.siteState > 0) {
|
||||
store.commit('setSiteState', -3);
|
||||
Util.redirectTo('/pages_tool/storeclose/storeclose', {}, 'reLaunch');
|
||||
return;
|
||||
}
|
||||
if (res.data.refreshtoken) {
|
||||
store.commit('setToken', res.data.refreshtoken);
|
||||
}
|
||||
if (res.data.code == -10009 || res.data.code == -10010) {
|
||||
store.commit('setToken', '');
|
||||
store.commit('setMemberInfo', '');
|
||||
}
|
||||
resolve(res.data);
|
||||
},
|
||||
fail: (res) => {
|
||||
console.error('[HTTP][FAIL]', reqId, method, url, 'cost=', (Date.now() - reqStart) + 'ms', JSON.stringify(res));
|
||||
reject(res);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function _requestWithRetry(params, url, method, data, header, dataType, responseType) {
|
||||
const timeout = params.timeout || DEFAULT_TIMEOUT;
|
||||
const maxRetries = params.noRetry ? 0 : (params.maxRetries || DEFAULT_MAX_RETRIES);
|
||||
let lastError = null;
|
||||
let lastStatusCode = null;
|
||||
|
||||
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
if (attempt > 0) {
|
||||
console.log('[HTTP][RETRY]', method, url, 'attempt=', attempt, 'maxRetries=', maxRetries);
|
||||
}
|
||||
const result = await _makeRequest(url, method, data, header, dataType, responseType, timeout);
|
||||
return result;
|
||||
} catch (err) {
|
||||
lastError = err;
|
||||
lastStatusCode = err && err.statusCode;
|
||||
console.warn('[HTTP][RETRY-FAIL]', method, url, 'attempt=', attempt, 'errMsg=', err && err.errMsg, 'statusCode=', lastStatusCode);
|
||||
if (attempt >= maxRetries || !_shouldRetry(err.errMsg)) {
|
||||
break;
|
||||
}
|
||||
const delay = RETRY_DELAY_BASE * Math.pow(2, attempt);
|
||||
console.log('[HTTP][RETRY-WAIT]', method, url, 'delay=', delay + 'ms');
|
||||
await _sleep(delay);
|
||||
}
|
||||
}
|
||||
|
||||
if (params.silentError) {
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
const errorType = _classifyError(lastError && lastError.errMsg, lastStatusCode);
|
||||
const lang = getLang();
|
||||
if (errorType === 'domainNotInList') {
|
||||
uni.showToast({
|
||||
title: lang.lang('http.domainNotInList', { url: Config.baseUrl }),
|
||||
'icon': 'none',
|
||||
duration: 10000
|
||||
});
|
||||
} else {
|
||||
const i18nKey = 'http.' + errorType;
|
||||
uni.showToast({
|
||||
title: lang.lang(i18nKey),
|
||||
'icon': 'none',
|
||||
duration: 10000
|
||||
});
|
||||
}
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
export default {
|
||||
sendRequest(params) {
|
||||
if (!Config.baseUrl) {
|
||||
uni.showToast({
|
||||
title: '未配置请求域名',
|
||||
title: getLang().lang('http.baseUrlNotConfigured'),
|
||||
'icon': 'none',
|
||||
duration: 10000
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
var method = params.data != undefined ? 'POST' : 'GET', // 请求方式
|
||||
url = (Config.baseUrl + params.url).replace(/(?<!:)\/+/g, '/'), // 请求路径
|
||||
const _isRemoteOnly = getLang().isRemoteOnly && getLang().isRemoteOnly();
|
||||
const _bootDone = getLang().isBootCompleted && getLang().isBootCompleted();
|
||||
if (_isRemoteOnly && !_bootDone) {
|
||||
let bootPromise = null;
|
||||
try {
|
||||
const app = getApp();
|
||||
if (app && app.$langReady) bootPromise = app.$langReady;
|
||||
} catch (e) {}
|
||||
if (!bootPromise) bootPromise = getLang().boot();
|
||||
|
||||
if (params.async === false) {
|
||||
return bootPromise.then(() => this._sendRequestNow(params));
|
||||
} else {
|
||||
bootPromise.then(() => this._sendRequestNow(params));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
return this._sendRequestNow(params);
|
||||
},
|
||||
|
||||
_sendRequestNow(params) {
|
||||
|
||||
var method = params.data != undefined ? 'POST' : 'GET',
|
||||
url = (Config.baseUrl + params.url).replace(/(?<!:)\/+/g, '/'),
|
||||
data = {
|
||||
app_type,
|
||||
app_type_name
|
||||
app_type: appType,
|
||||
app_type_name: appTypeName
|
||||
};
|
||||
|
||||
// token
|
||||
data.token = store.state.token || '';
|
||||
data.uniacid = uni.getStorageSync('uniacid') || Config.uniacid; // 从缓存中获取uniacid,或使用默认uniacid,支持快应用
|
||||
data.uniacid = uni.getStorageSync('uniacid') || Config.uniacid;
|
||||
|
||||
// 门店id
|
||||
var default_store_info = store.state.defaultStoreInfo;
|
||||
if (default_store_info) {
|
||||
data.store_id = default_store_info.store_id;
|
||||
@@ -69,126 +192,38 @@ export default {
|
||||
|
||||
if (store_info) data.store_id = store_info.store_id;
|
||||
|
||||
// 参数
|
||||
if (params.data != undefined) Object.assign(data, params.data);
|
||||
|
||||
const header = params.header || {
|
||||
'content-type': 'application/x-www-form-urlencoded;application/json'
|
||||
};
|
||||
const dataType = params.dataType || 'json';
|
||||
const responseType = params.responseType || 'text';
|
||||
|
||||
if (params.async === false) {
|
||||
//同步
|
||||
return new Promise((resolve, reject) => {
|
||||
uni.request({
|
||||
url: url,
|
||||
method: method,
|
||||
data: data,
|
||||
header: params.header || {
|
||||
// 'Accept': 'application/json',
|
||||
'content-type': 'application/x-www-form-urlencoded;application/json'
|
||||
},
|
||||
dataType: params.dataType || 'json',
|
||||
responseType: params.responseType || 'text',
|
||||
success: (res) => {
|
||||
// try {
|
||||
// res.data = JSON.parse(res.data);
|
||||
// } catch (e) {
|
||||
// //TODO handle the exception
|
||||
// console.log('api error:', e);
|
||||
// }
|
||||
if (res.data.code == -3 && store.state.siteState > 0) {
|
||||
store.commit('setSiteState', -3);
|
||||
Util.redirectTo('/pages_tool/storeclose/storeclose', {}, 'reLaunch');
|
||||
return;
|
||||
}
|
||||
if (res.data.refreshtoken) {
|
||||
store.commit('setToken', res.data.refreshtoken);
|
||||
}
|
||||
if (res.data.code == -10009 || res.data.code == -10010) {
|
||||
store.commit('setToken', '');
|
||||
store.commit('setMemberInfo', '');
|
||||
}
|
||||
resolve(res.data);
|
||||
},
|
||||
fail: (res) => {
|
||||
if (res.errMsg && res.errMsg == 'request:fail url not in domain list') {
|
||||
uni.showToast({
|
||||
title: Config.baseUrl + '不在request 合法域名列表中',
|
||||
'icon': 'none',
|
||||
duration: 10000
|
||||
});
|
||||
return;
|
||||
}
|
||||
reject(res);
|
||||
},
|
||||
complete: (res) => {
|
||||
if ((res.errMsg && res.errMsg != "request:ok") || (res.statusCode && [200, 500].indexOf(res.statusCode) == -1)) {
|
||||
uni.showToast({
|
||||
title: Config.baseUrl + '请求失败',
|
||||
'icon': 'none',
|
||||
duration: 10000
|
||||
});
|
||||
return;
|
||||
}
|
||||
reject(res.data);
|
||||
}
|
||||
return _requestWithRetry(params, url, method, data, header, dataType, responseType)
|
||||
.then(res => {
|
||||
typeof params.complete == 'function' && params.complete(res);
|
||||
return res;
|
||||
})
|
||||
.catch(err => {
|
||||
typeof params.complete == 'function' && params.complete();
|
||||
throw err;
|
||||
});
|
||||
});
|
||||
} else {
|
||||
//异步
|
||||
uni.request({
|
||||
url: url,
|
||||
method: method,
|
||||
data: data,
|
||||
header: params.header || {
|
||||
// 'Accept': 'application/json',
|
||||
'content-type': 'application/x-www-form-urlencoded;application/json'
|
||||
},
|
||||
dataType: params.dataType || 'json',
|
||||
responseType: params.responseType || 'text',
|
||||
success: (res) => {
|
||||
// try {
|
||||
// res.data = JSON.parse(res.data);
|
||||
// } catch (e) {
|
||||
// //TODO handle the exception
|
||||
// console.log('api error:', e);
|
||||
// }
|
||||
if (res.data.code == -3 && store.state.siteState > 0) {
|
||||
store.commit('setSiteState', -3);
|
||||
Util.redirectTo('/pages_tool/storeclose/storeclose', {}, 'reLaunch');
|
||||
return;
|
||||
}
|
||||
if (res.data.refreshtoken) {
|
||||
store.commit('setToken', res.data.refreshtoken);
|
||||
}
|
||||
if (res.data.code == -10009 || res.data.code == -10010) {
|
||||
store.commit('setToken', '');
|
||||
store.commit('setMemberInfo', '');
|
||||
}
|
||||
typeof params.success == 'function' && params.success(res.data);
|
||||
},
|
||||
fail: (res) => {
|
||||
if (res.errMsg && res.errMsg == 'request:fail url not in domain list') {
|
||||
uni.showToast({
|
||||
title: Config.baseUrl + '不在request 合法域名列表中',
|
||||
'icon': 'none',
|
||||
duration: 10000
|
||||
});
|
||||
return;
|
||||
}
|
||||
typeof params.fail == 'function' && params.fail(res);
|
||||
},
|
||||
complete: (res) => {
|
||||
if ((res.errMsg && res.errMsg != "request:ok") || (res.statusCode && [200, 500].indexOf(res.statusCode) == -1)) {
|
||||
uni.showToast({
|
||||
title: Config.baseUrl + '请求失败',
|
||||
'icon': 'none',
|
||||
duration: 10000
|
||||
});
|
||||
return;
|
||||
}
|
||||
typeof params.complete == 'function' && params.complete(res.data);
|
||||
}
|
||||
});
|
||||
_requestWithRetry(params, url, method, data, header, dataType, responseType)
|
||||
.then(res => {
|
||||
typeof params.success == 'function' && params.success(res);
|
||||
typeof params.complete == 'function' && params.complete(res);
|
||||
})
|
||||
.catch(err => {
|
||||
typeof params.fail == 'function' && params.fail(err);
|
||||
typeof params.complete == 'function' && params.complete();
|
||||
});
|
||||
}
|
||||
},
|
||||
uploadBase64(params) {
|
||||
console.log('[HTTP][REQUEST] uploadBase64', Config.baseUrl + '/api/upload/headimgBase64');
|
||||
uni.request({
|
||||
url: Config.baseUrl + '/api/upload/headimgBase64',
|
||||
method: 'POST',
|
||||
@@ -196,21 +231,24 @@ export default {
|
||||
'content-type': 'application/x-www-form-urlencoded;application/json'
|
||||
},
|
||||
data: {
|
||||
app_type,
|
||||
app_type_name,
|
||||
app_type: appType,
|
||||
app_type_name: appTypeName,
|
||||
images: params.base64
|
||||
},
|
||||
dataType: 'json',
|
||||
responseType: 'text',
|
||||
success: res => {
|
||||
console.log('[HTTP][RESPONSE] uploadBase64', 'statusCode=', res.statusCode, JSON.stringify(res.data));
|
||||
typeof params.success == 'function' && params.success(res.data);
|
||||
},
|
||||
fail: () => {
|
||||
console.error('[HTTP][FAIL] uploadBase64', JSON.stringify(res));
|
||||
typeof params.fail == 'function' && params.fail(res);
|
||||
}
|
||||
});
|
||||
},
|
||||
pullImage(params) {
|
||||
console.log('[HTTP][REQUEST] pullImage', Config.baseUrl + '/api/upload/headimgPull', 'path=', params.path);
|
||||
uni.request({
|
||||
url: Config.baseUrl + '/api/upload/headimgPull',
|
||||
method: 'POST',
|
||||
@@ -218,37 +256,42 @@ export default {
|
||||
'content-type': 'application/x-www-form-urlencoded;application/json'
|
||||
},
|
||||
data: {
|
||||
app_type,
|
||||
app_type_name,
|
||||
app_type: appType,
|
||||
app_type_name: appTypeName,
|
||||
path: params.path
|
||||
},
|
||||
dataType: 'json',
|
||||
responseType: 'text',
|
||||
success: res => {
|
||||
console.log('[HTTP][RESPONSE] pullImage', 'statusCode=', res.statusCode, JSON.stringify(res.data));
|
||||
typeof params.success == 'function' && params.success(res.data);
|
||||
},
|
||||
fail: () => {
|
||||
console.error('[HTTP][FAIL] pullImage', JSON.stringify(res));
|
||||
typeof params.fail == 'function' && params.fail(res);
|
||||
}
|
||||
});
|
||||
},
|
||||
upload(params) {
|
||||
console.log('[HTTP][REQUEST] upload', Config.baseUrl + params.url, 'name=', params.name || 'file');
|
||||
uni.uploadFile({
|
||||
url: Config.baseUrl + params.url,
|
||||
filePath: params.filePath,
|
||||
name: params.name || 'file',
|
||||
fileType: params.fileType || 'image',
|
||||
formData: {
|
||||
app_type,
|
||||
app_type_name,
|
||||
app_type: appType,
|
||||
app_type_name: appTypeName,
|
||||
},
|
||||
header: {
|
||||
'content-type': 'application/x-www-form-urlencoded;application/json'
|
||||
},
|
||||
success: (res) => {
|
||||
console.log('[HTTP][RESPONSE] upload', Config.baseUrl + params.url, 'statusCode=', res.statusCode, res.data);
|
||||
typeof params.success == 'function' && params.success(JSON.parse(res.data));
|
||||
},
|
||||
fail: (res) => {
|
||||
console.error('[HTTP][FAIL] upload', Config.baseUrl + params.url, JSON.stringify(res));
|
||||
typeof params.fail == 'function' && params.fail(res);
|
||||
}
|
||||
});
|
||||
|
||||
15
common/js/image-config.js
Normal file
15
common/js/image-config.js
Normal file
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* 图片配置文件
|
||||
* 将大图片上传到服务器后,请在此处配置网络URL
|
||||
*/
|
||||
|
||||
// 替换为你上传后的实际图片URL
|
||||
const IMAGE_CONFIG = {
|
||||
// AI客服头像
|
||||
aiAvatar: 'public/static/img/s-agent.jpg',
|
||||
|
||||
// 用户默认头像
|
||||
userAvatar: 'public/static/img/s-user.jpg'
|
||||
};
|
||||
|
||||
export default IMAGE_CONFIG;
|
||||
11
common/js/lang-empty-stub.js
Normal file
11
common/js/lang-empty-stub.js
Normal file
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* remote-only 模式下的空语言包 stub
|
||||
*
|
||||
* 当 source === 'remote-only' 时,webpack NormalModuleReplacementPlugin
|
||||
* 会把所有 @/lang/ 下的 require 替换为这个文件,
|
||||
* 避免本地 lang/ 目录被打进产物。
|
||||
*
|
||||
* 导出格式与真实语言包一致: { lang: {} }
|
||||
*/
|
||||
export const lang = {};
|
||||
export default { lang };
|
||||
440
common/js/lang-loader.js
Normal file
440
common/js/lang-loader.js
Normal file
@@ -0,0 +1,440 @@
|
||||
/**
|
||||
* 远端语言包 bundle 加载器
|
||||
*
|
||||
* 职责:
|
||||
* 1. 从后端 /api/lang/bundle 拉取完整语言树
|
||||
* 2. 做本地 storage 缓存 + 内存缓存
|
||||
* 3. 支持签名校验(可选)
|
||||
* 4. 支持 diff 增量更新(预留)
|
||||
* 5. 对外暴露 loadBundleTree / getCachedBundle / clearBundleCache
|
||||
*
|
||||
* 与 lang.js 的关系:
|
||||
* 当 langConfig.source === 'remote-only' 时,lang.js 不再 require 本地 lang/ 文件,
|
||||
* 而是直接复用本模块加载的 tree。
|
||||
*/
|
||||
import { langConfig } from './config-external.js';
|
||||
import Config from './config.js';
|
||||
import { Platform } from './platform.js';
|
||||
|
||||
|
||||
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
||||
|
||||
// 内存缓存: { [memKey]: { version, tree, ts } }
|
||||
const bundleCache = {};
|
||||
|
||||
// 关键修复: 缓存 fetchBundle 迟到的成功结果
|
||||
// 即使 Promise.race 已 timeout, uni.request 内部可能继续完成
|
||||
// 缓存这份迟到结果, 给上层 catch 后的"补救"逻辑使用
|
||||
// 结构: { `${lang}_${appType}_${uniacid}`: { data, ts, lang, appType, uniacid } }
|
||||
const _lastSuccessfulResult = {};
|
||||
|
||||
// 缓存 TTL(与 BUNDLE_CACHE_TTL 一致): 10 分钟
|
||||
const _LAST_RESULT_TTL = 10 * 60 * 1000;
|
||||
|
||||
// 并发去重
|
||||
const bundleInflight = {};
|
||||
|
||||
/**
|
||||
* 三维隔离 key: <uniacid>_<appType>_<lang>
|
||||
*/
|
||||
function getBundleMemKey(uniacid, appType, lang) {
|
||||
return `${uniacid || 0}_${appType || '*'}_${lang}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* storage key: 与 memKey 维度一致
|
||||
*/
|
||||
function getBundleStorageKey(uniacid, appType, lang) {
|
||||
return `${langConfig.remote.storagePrefix || 'LANG_BUNDLE_'}${getBundleMemKey(uniacid, appType, lang)}`;
|
||||
}
|
||||
|
||||
function getCurrentLocale() {
|
||||
try {
|
||||
return uni.getStorageSync('lang') || langConfig.defaultLang || 'zh-cn';
|
||||
} catch (e) {
|
||||
return langConfig.defaultLang || 'zh-cn';
|
||||
}
|
||||
}
|
||||
|
||||
function getCurrentUniacid() {
|
||||
try {
|
||||
const u = uni.getStorageSync('uniacid');
|
||||
return u ? parseInt(u, 10) || 0 : 0;
|
||||
} catch (e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function getCurrentAppType() {
|
||||
try { return Platform.getAppType() || '*'; } catch (e) { return '*'; }
|
||||
}
|
||||
|
||||
/**
|
||||
* 深度合并两个对象,source 覆盖 target
|
||||
*/
|
||||
function deepMerge(target, source) {
|
||||
if (target === null || typeof target !== 'object') return source;
|
||||
if (source === null || typeof source !== 'object') return source;
|
||||
if (Array.isArray(target) || Array.isArray(source)) return source;
|
||||
|
||||
for (const key in source) {
|
||||
if (!Object.prototype.hasOwnProperty.call(source, key)) continue;
|
||||
if (FORBIDDEN_KEYS.has(key)) continue;
|
||||
const srcVal = source[key];
|
||||
const tgtVal = target[key];
|
||||
if (
|
||||
srcVal !== null && typeof srcVal === 'object' && !Array.isArray(srcVal) &&
|
||||
tgtVal !== null && typeof tgtVal === 'object' && !Array.isArray(tgtVal)
|
||||
) {
|
||||
target[key] = deepMerge(tgtVal, srcVal);
|
||||
} else {
|
||||
target[key] = srcVal;
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* 简易签名校验
|
||||
* 后端: hash_hmac('sha256', version + json_encode(tree), secret)
|
||||
* 前端: 同样算法
|
||||
*/
|
||||
function validateSign(tree, version, sign, secret) {
|
||||
if (!secret || !sign) return true;
|
||||
// 前端没有 crypto-js,用简单字符串拼接做校验(仅基础防篡改)
|
||||
// 如需强校验,建议引入 crypto-js 或小程序/APP 端使用原生加密 API
|
||||
// 关键修复: 用 try-catch 保护 btoa(),避免在小程序环境(无 btoa)中抛 ReferenceError
|
||||
let _btoaResult = '';
|
||||
try {
|
||||
const payload = JSON.stringify(tree);
|
||||
// 兼容小程序环境: 没有原生 btoa 时降级
|
||||
if (typeof btoa === 'function') {
|
||||
_btoaResult = btoa(version + ':' + payload).replace(/[^a-zA-Z0-9]/g, '').slice(0, 32);
|
||||
} else if (typeof uni !== 'undefined' && typeof uni.arrayBufferToBase64 === 'function') {
|
||||
// 微信小程序/uni-app 提供 arrayBufferToBase64
|
||||
const _encoder = (typeof TextEncoder !== 'undefined')
|
||||
? new TextEncoder().encode(version + ':' + payload)
|
||||
: null;
|
||||
if (_encoder) {
|
||||
_btoaResult = uni.arrayBufferToBase64(_encoder.buffer).replace(/[^a-zA-Z0-9]/g, '').slice(0, 32);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// 签名计算失败也不应阻断 bundle 加载,静默失败
|
||||
}
|
||||
// 后端返回的是 hash_hmac('sha256', version + payload, secret)
|
||||
// 这里只做格式校验,不强校验(因为无 crypto 库)
|
||||
return typeof sign === 'string' && sign.length > 0;
|
||||
}
|
||||
|
||||
// 缓存 TTL(ms): 与后端 Cache::set 600s 对齐,过期后后台刷新
|
||||
const BUNDLE_CACHE_TTL = (langConfig.remote.cacheTtl || 600) * 1000;
|
||||
|
||||
/**
|
||||
* 从 storage 读取缓存(检查 TTL 过期)
|
||||
* @returns {Object|null} 未过期返回 {tree,version,ts}, 过期返回 null
|
||||
*/
|
||||
function readStorageCache(sk) {
|
||||
try {
|
||||
const cached = uni.getStorageSync(sk);
|
||||
if (cached && cached.tree && typeof cached.tree === 'object') {
|
||||
// TTL 检查: 超过 cacheTtl 视为过期
|
||||
if (cached.ts && (Date.now() - cached.ts < BUNDLE_CACHE_TTL)) {
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
} catch (e) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查内存缓存是否过期
|
||||
*/
|
||||
function isMemoryCacheExpired(record) {
|
||||
if (!record || !record.ts) return true;
|
||||
return (Date.now() - record.ts) >= BUNDLE_CACHE_TTL;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入 storage 缓存
|
||||
*/
|
||||
function writeStorageCache(sk, data) {
|
||||
try {
|
||||
uni.setStorageSync(sk, data);
|
||||
} catch (e) {
|
||||
// storage 写满时静默失败
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从后端拉取 bundle
|
||||
*
|
||||
* 关键修复: 即使 Promise.race 在 timeout 时已经 reject,
|
||||
* uni.request 内部仍可能继续执行并成功返回。
|
||||
* 之前这些"迟到"的成功响应被完全丢弃,导致:
|
||||
* 1. fetchBundle 抛 timeout 错
|
||||
* 2. _bootImpl 进 catch, 不写 remoteTreeCache
|
||||
* 3. uni.request 终于成功, 但没人接收, 结果被 GC
|
||||
* 现在改为: uni.request 完成后, **无论 Promise.race 状态如何**,
|
||||
* 都把结果写入 _lastSuccessfulResult 缓存。
|
||||
* _bootImpl 可以在 catch 后**主动等待**这份迟到数据(最多 3 秒),
|
||||
* 从而真正用上远端返回的完整 bundle。
|
||||
*/
|
||||
async function fetchBundle(lang, appType, uniacid, timeout) {
|
||||
const url = langConfig.remote.bundleUrl || '/api/lang/bundle';
|
||||
const data = { lang };
|
||||
if (appType && appType !== '*') data.app_type = appType;
|
||||
// uniacid 必须传给后端,后端按 (uniacid × app_type) 二维查询租户专属覆写
|
||||
if (uniacid !== undefined && uniacid !== null) data.uniacid = uniacid;
|
||||
|
||||
// 直接用 uni.request 包装 Promise,不依赖 http.sendRequest
|
||||
// (sendRequest 的异步分支不返回 Promise,只有 async:false 分支才返回)
|
||||
// 去重双斜杠: baseUrl 末尾可能带 /, bundleUrl 开头也带 /
|
||||
const fullUrl = (Config.baseUrl || '').replace(/\/+$/, '') + url;
|
||||
|
||||
// 关键修复: 用一个 "completionLatch" 跟踪 uni.request 是否最终完成(成功或失败)
|
||||
// 即使 Promise.race 已经 timeout reject, uni.request 内部仍可能继续完成
|
||||
// 我们保留这份迟到结果到 _lastSuccessfulResult, 给上层补救的机会
|
||||
const inflightKey = `${lang}_${appType}_${uniacid}`;
|
||||
|
||||
const res = await Promise.race([
|
||||
new Promise((resolve, reject) => {
|
||||
uni.request({
|
||||
url: fullUrl,
|
||||
method: 'POST',
|
||||
data: data,
|
||||
header: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
dataType: 'json',
|
||||
success: (response) => {
|
||||
// 关键: 即使 Promise.race 已 reject, 仍然把成功结果写入全局缓存
|
||||
// 给 loadBundleTree catch 后 "补救" 的机会
|
||||
try {
|
||||
if (response && response.data && response.data.code === 0 && response.data.data && response.data.data.tree) {
|
||||
_lastSuccessfulResult[inflightKey] = {
|
||||
data: response.data,
|
||||
ts: Date.now(),
|
||||
lang, appType, uniacid,
|
||||
};
|
||||
}
|
||||
} catch (e) {}
|
||||
resolve(response.data);
|
||||
},
|
||||
fail: (err) => {
|
||||
reject(new Error(err.errMsg || 'bundle request failed'));
|
||||
},
|
||||
});
|
||||
}),
|
||||
new Promise((_, reject) => setTimeout(() => {
|
||||
reject(new Error('timeout'));
|
||||
}, timeout)),
|
||||
]);
|
||||
|
||||
if (!res || res.code !== 0 || !res.data) {
|
||||
throw new Error(res && res.message ? res.message : 'bundle fetch failed');
|
||||
}
|
||||
|
||||
return res.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载 bundle tree
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {string} lang 语言
|
||||
* @param {string} [appType] 平台类型
|
||||
* @param {number} [uniacid] 租户 id
|
||||
* @param {boolean} [allowCache=true] 是否允许使用缓存
|
||||
* @param {boolean} [force=false] 是否强制刷新
|
||||
* @returns {Promise<{tree:Object, version:string, source:string}>}
|
||||
*/
|
||||
export async function loadBundleTree(options = {}) {
|
||||
const lang = options.lang || getCurrentLocale();
|
||||
const appType = options.appType || getCurrentAppType();
|
||||
const uniacid = options.uniacid !== undefined ? options.uniacid : getCurrentUniacid();
|
||||
const allowCache = options.allowCache !== false;
|
||||
const force = options.force === true;
|
||||
|
||||
const mk = getBundleMemKey(uniacid, appType, lang);
|
||||
const sk = getBundleStorageKey(uniacid, appType, lang);
|
||||
|
||||
if (bundleInflight[mk]) {
|
||||
return bundleInflight[mk];
|
||||
}
|
||||
|
||||
const task = (async () => {
|
||||
try {
|
||||
// 1) 内存缓存未过期直接返回
|
||||
if (!force && allowCache && bundleCache[mk] && !isMemoryCacheExpired(bundleCache[mk])) {
|
||||
return { tree: bundleCache[mk].tree, version: bundleCache[mk].version, source: 'memory' };
|
||||
}
|
||||
|
||||
// 2) 读取 storage 缓存(已含 TTL 检查)
|
||||
let cached = null;
|
||||
if (!force && allowCache) {
|
||||
cached = readStorageCache(sk);
|
||||
if (cached && !bundleCache[mk]) {
|
||||
bundleCache[mk] = cached;
|
||||
}
|
||||
}
|
||||
|
||||
// 3) 远端拉取
|
||||
const timeout = langConfig.remote.requestTimeout || 4000;
|
||||
const payload = await fetchBundle(lang, appType, uniacid, timeout);
|
||||
const tree = payload.tree || {};
|
||||
const version = String(payload.version || '');
|
||||
const sign = payload.sign || '';
|
||||
|
||||
// 4) 签名校验(可选)
|
||||
const secret = langConfig.remote.signSecret || '';
|
||||
const signValid = validateSign(tree, version, sign, secret);
|
||||
if (!signValid) {
|
||||
throw new Error('bundle sign invalid');
|
||||
}
|
||||
|
||||
// 5) 更新缓存
|
||||
const record = { version, tree, ts: Date.now() };
|
||||
bundleCache[mk] = record;
|
||||
writeStorageCache(sk, record);
|
||||
|
||||
return { tree, version, source: 'remote' };
|
||||
} catch (e) {
|
||||
// 关键修复: 补救迟到数据
|
||||
// fetchBundle 因 timeout 抛错时, uni.request 内部可能仍然成功(只是没 Promise 接收)
|
||||
// 之前这些"迟到"数据被完全丢弃,导致 boot 失败后永远等不到远端数据
|
||||
// 现在: catch 后等待 _lastSuccessfulResult 出现(最多 3 秒), 期间如果迟到数据到达则用之
|
||||
const inflightKey = `${lang}_${appType}_${uniacid}`;
|
||||
// 等待 _lastSuccessfulResult 出现(超时后 uni.request 内部 success 回调可能稍后才触发)
|
||||
const waitStart = Date.now();
|
||||
const WAIT_MAX_MS = 3000;
|
||||
const WAIT_POLL_MS = 100;
|
||||
while (Date.now() - waitStart < WAIT_MAX_MS) {
|
||||
const lateResult = _lastSuccessfulResult[inflightKey];
|
||||
if (lateResult && (Date.now() - lateResult.ts) < _LAST_RESULT_TTL) {
|
||||
// 有"迟到"数据, 直接用
|
||||
const resp = lateResult.data;
|
||||
// resp 结构: { code, message, data: { version, tree, sign } }
|
||||
const dataNode = resp && resp.data;
|
||||
const tree = (dataNode && dataNode.tree) || {};
|
||||
const version = String((dataNode && dataNode.version) || '');
|
||||
const sign = (dataNode && dataNode.sign) || '';
|
||||
const signValid = validateSign(tree, version, sign, langConfig.remote.signSecret || '');
|
||||
if (signValid) {
|
||||
const record = { version, tree, ts: Date.now() };
|
||||
bundleCache[mk] = record;
|
||||
writeStorageCache(sk, record);
|
||||
return { tree, version, source: 'remote-late' };
|
||||
}
|
||||
}
|
||||
// 等待 WAIT_POLL_MS
|
||||
await new Promise((r) => setTimeout(r, WAIT_POLL_MS));
|
||||
}
|
||||
// 6) 失败时回退到缓存
|
||||
// 关键修复: force=true 时**不回退**到 bundleCache
|
||||
// 旧逻辑: force 失败 → 回退到旧 cache → 标记新 ts → 永远不被刷新 → bundle 缺 key
|
||||
// 新逻辑: force 失败 → 抛错, 让上层 _bootImpl 进入 catch 块走真正的"无 cache 兜底"
|
||||
if (force) {
|
||||
throw e;
|
||||
}
|
||||
if (allowCache && bundleCache[mk]) {
|
||||
return { tree: bundleCache[mk].tree, version: bundleCache[mk].version, source: 'cache', error: e.message };
|
||||
}
|
||||
throw e;
|
||||
} finally {
|
||||
delete bundleInflight[mk];
|
||||
}
|
||||
})();
|
||||
|
||||
bundleInflight[mk] = task;
|
||||
return task;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取已缓存的 bundle(不触发网络请求)
|
||||
* 注意: 受 TTL 限制,过期缓存返回 null
|
||||
*/
|
||||
export function getCachedBundle(options = {}) {
|
||||
const lang = options.lang || getCurrentLocale();
|
||||
const appType = options.appType || getCurrentAppType();
|
||||
const uniacid = options.uniacid !== undefined ? options.uniacid : getCurrentUniacid();
|
||||
const mk = getBundleMemKey(uniacid, appType, lang);
|
||||
const sk = getBundleStorageKey(uniacid, appType, lang);
|
||||
|
||||
if (bundleCache[mk]) return bundleCache[mk];
|
||||
const cached = readStorageCache(sk);
|
||||
if (cached) {
|
||||
bundleCache[mk] = cached;
|
||||
return cached;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取任意已缓存的 bundle(不检查 TTL),仅用于 boot 失败兜底
|
||||
*
|
||||
* 与 getCachedBundle 的区别:
|
||||
* - getCachedBundle: 受 BUNDLE_CACHE_TTL 限制,过期返回 null(用于日常 $lang 渲染)
|
||||
* - getCachedBundleAny: 不检查 TTL,只要内存或 storage 中有就返回(用于失败兜底)
|
||||
*
|
||||
* 设计意图:
|
||||
* boot() 强制重试失败时,如果用户本地还有哪怕过期的 bundle,
|
||||
* 也比"$lang() 全返回空串"用户体验更好 — 至少能展示残缺文案。
|
||||
* 这是显式的"宁可用过期缓存,也不空白"的取舍。
|
||||
*
|
||||
* 优先返回内存缓存(更快),其次返回 storage 缓存。
|
||||
*
|
||||
* @returns {{version:string, tree:Object, ts:number, source:'memory'|'storage'}|null}
|
||||
*/
|
||||
export function getCachedBundleAny(options = {}) {
|
||||
const lang = options.lang || getCurrentLocale();
|
||||
const appType = options.appType || getCurrentAppType();
|
||||
const uniacid = options.uniacid !== undefined ? options.uniacid : getCurrentUniacid();
|
||||
const mk = getBundleMemKey(uniacid, appType, lang);
|
||||
const sk = getBundleStorageKey(uniacid, appType, lang);
|
||||
|
||||
// 1) 内存缓存优先(任意 TTL,过期也返回)
|
||||
if (bundleCache[mk] && bundleCache[mk].tree) {
|
||||
return { ...bundleCache[mk], source: 'memory' };
|
||||
}
|
||||
|
||||
// 2) storage 兜底(任意 TTL,不调用 readStorageCache 因为它内部会查 TTL)
|
||||
try {
|
||||
const raw = uni.getStorageSync(sk);
|
||||
if (raw && raw.tree && typeof raw.tree === 'object') {
|
||||
// 写回内存缓存,方便下次 getCachedBundle / getCachedBundleAny 命中
|
||||
bundleCache[mk] = raw;
|
||||
return { ...raw, source: 'storage' };
|
||||
}
|
||||
} catch (e) { /* 忽略 */ }
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除 bundle 缓存
|
||||
*/
|
||||
export function clearBundleCache(options = {}) {
|
||||
const lang = options.lang || getCurrentLocale();
|
||||
const appType = options.appType || getCurrentAppType();
|
||||
const uniacid = options.uniacid !== undefined ? options.uniacid : getCurrentUniacid();
|
||||
const mk = getBundleMemKey(uniacid, appType, lang);
|
||||
const sk = getBundleStorageKey(uniacid, appType, lang);
|
||||
|
||||
delete bundleCache[mk];
|
||||
try { uni.removeStorageSync(sk); } catch (e) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否有缓存可用(用于启动时快速判断)
|
||||
*/
|
||||
export function hasBundleCache(options = {}) {
|
||||
return getCachedBundle(options) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并本地语言包与远端 bundle tree(混合模式用)
|
||||
*/
|
||||
export function mergeLocalWithBundle(localTree, bundleTree) {
|
||||
if (!localTree || typeof localTree !== 'object') return bundleTree || {};
|
||||
if (!bundleTree || typeof bundleTree !== 'object') return localTree || {};
|
||||
return deepMerge(deepMerge({}, localTree), bundleTree);
|
||||
}
|
||||
1477
common/js/lang.js
1477
common/js/lang.js
File diff suppressed because it is too large
Load Diff
@@ -7,14 +7,12 @@
|
||||
*/
|
||||
|
||||
import Util from './util.js'
|
||||
import Lang from './lang.js';
|
||||
|
||||
var ERROR_CONF = {
|
||||
KEY_ERR: 311,
|
||||
KEY_ERR_MSG: 'key格式错误',
|
||||
PARAM_ERR: 310,
|
||||
PARAM_ERR_MSG: '请求参数信息有误',
|
||||
SYSTEM_ERR: 600,
|
||||
SYSTEM_ERR_MSG: '系统错误',
|
||||
WX_ERR_CODE: 1000,
|
||||
WX_OK_CODE: 200
|
||||
};
|
||||
@@ -385,7 +383,7 @@ var Utils = {
|
||||
*/
|
||||
checkParamKeyEmpty(param, key) {
|
||||
if (!param[key]) {
|
||||
var errconf = this.buildErrorConfig(ERROR_CONF.PARAM_ERR, ERROR_CONF.PARAM_ERR_MSG + key +'参数格式有误');
|
||||
var errconf = this.buildErrorConfig(ERROR_CONF.PARAM_ERR, Lang.lang('common.mapWxJssdk.paramFormatError', { param: key }));
|
||||
param.fail(errconf);
|
||||
param.complete(errconf);
|
||||
return true;
|
||||
@@ -410,7 +408,7 @@ var Utils = {
|
||||
checkLocation(param) {
|
||||
var location = this.getLocationParam(param.location);
|
||||
if (!location || !location.latitude || !location.longitude) {
|
||||
var errconf = this.buildErrorConfig(ERROR_CONF.PARAM_ERR, ERROR_CONF.PARAM_ERR_MSG + ' location参数格式有误');
|
||||
var errconf = this.buildErrorConfig(ERROR_CONF.PARAM_ERR, Lang.lang('common.mapWxJssdk.locationParamFormatError'));
|
||||
param.fail(errconf);
|
||||
param.complete(errconf);
|
||||
return false;
|
||||
@@ -623,7 +621,7 @@ var Utils = {
|
||||
break;
|
||||
}
|
||||
default:{
|
||||
param.complete(that.buildErrorConfig(ERROR_CONF.SYSTEM_ERR, ERROR_CONF.SYSTEM_ERR_MSG));
|
||||
param.complete(that.buildErrorConfig(ERROR_CONF.SYSTEM_ERR, Lang.lang('common.mapWxJssdk.systemError')));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -664,7 +662,7 @@ class QQMapWX {
|
||||
*/
|
||||
constructor(options) {
|
||||
if (!options.key) {
|
||||
throw Error('key值不能为空');
|
||||
throw Error(Lang.lang('common.mapWxJssdk.keyCannotBeEmpty'));
|
||||
}
|
||||
this.key = options.key;
|
||||
};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import util from '@/common/js/util.js'
|
||||
import TransformCoordinate from './transformCoordinate.js'
|
||||
import Lang from '@/common/js/lang.js'
|
||||
|
||||
function openMapByDefault(latitude, longitude, name) {
|
||||
uni.openLocation({
|
||||
@@ -8,7 +9,7 @@ function openMapByDefault(latitude, longitude, name) {
|
||||
name: name,
|
||||
fail: (e) => {
|
||||
uni.showModal({
|
||||
content: '打开地图失败,请稍后重试'
|
||||
content: Lang.lang('common.map.openMapFailed')
|
||||
})
|
||||
},
|
||||
})
|
||||
@@ -89,16 +90,14 @@ export default {
|
||||
let platform = util.getDeviceInfo().platform;
|
||||
switch (platform) {
|
||||
case 'android':
|
||||
console.log('运行Android上')
|
||||
case 'harmony':
|
||||
openMapByAndroid(arr[1], arr[0], name)
|
||||
break;
|
||||
case 'ios':
|
||||
console.log('运行iOS上')
|
||||
openMapByIos(arr[1], arr[0], name)
|
||||
break;
|
||||
default:
|
||||
openMapByDefault(arr[1], arr[0], name)
|
||||
console.log('运行在开发者工具上')
|
||||
break;
|
||||
}
|
||||
// #endif
|
||||
|
||||
762
common/js/media-upload.js
Normal file
762
common/js/media-upload.js
Normal file
@@ -0,0 +1,762 @@
|
||||
// common/js/media-upload.js
|
||||
// ai-chat / ai-agent 媒体上传: 图片 (PHP 中转 + STS 直传) / 音视频 / 其他文件
|
||||
//
|
||||
// PR-FRONTEND-MEDIA-UPLOAD (2026-09-16): 之前 ai-chat-tools-panel.vue 引用了
|
||||
// uploadImage / uploadMedia, 但本文件从未落库, 选图 / 选文件立即抛
|
||||
// "Cannot find module '@/common/js/media-upload.js'". 此次按
|
||||
// docs/ai-agent-integration.md §3.4 Step 1 落地, 顺手补 store import (设计稿漏).
|
||||
//
|
||||
// 调用方:
|
||||
// ai-chat-tools-panel.vue → selectImage() / _uploadOneFile()
|
||||
// ai-chat-message.vue → 直接用 aiService.sendMessage 传 attachments (本模块不出场)
|
||||
//
|
||||
// 上传策略:
|
||||
// 图片: 优先 PHP 中转 (≤2MB 走 backend), 超过或商家选了 oss_sts/auto → STS 直传
|
||||
// 音视频/文件: 一律 STS 直传 (体积大概率 >2MB)
|
||||
//
|
||||
// 端点:
|
||||
// PHP 中转: POST /<addon>/api/upload/<image|file> multipart/form-data
|
||||
// STS 凭证: POST /<addon>/api/upload/ossSts application/json
|
||||
// STS 直传: PUT <provider>/<key> 云存储协议 (4-field STS 或 single-URL)
|
||||
|
||||
import aiService from './ai-service.js'
|
||||
import Config from './config.js'
|
||||
import store from '@/store/index.js'
|
||||
|
||||
const SIZE_LIMIT_PHP_PASSTHROUGH = 2 * 1024 * 1024 // 2MB
|
||||
const SIZE_LIMIT_H5_COMPRESS = 3 * 1024 * 1024 // 3MB (从 10MB 下调,移动端 H5 体验更流畅)
|
||||
// PR-FRONTEND-MEDIA-INLINE-BASE64 (2026-09-16): WB Agent J7 inline base64 上限 5MB
|
||||
// 与 backend WbAgentOsClient::INLINE_MEDIA_LIMIT = 5242880 对齐
|
||||
// 超过这个 size 后 buildMediaBlocks 会改走 URL fetch 路径, 上限失效
|
||||
const SIZE_LIMIT_INLINE_BASE64 = 5 * 1024 * 1024 // 5MB (与后端 INLINE_MEDIA_LIMIT 对齐)
|
||||
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): 现代格式 mime 同步后端 guessMimeFromPath
|
||||
// STS 直传绕过后端 mime 推断, 前端必须自带, 否则附件 mime 降级 application/octet-stream
|
||||
const EXT_MIME_MAP = {
|
||||
jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif', webp: 'image/webp',
|
||||
heic: 'image/heic', heif: 'image/heif', avif: 'image/avif',
|
||||
bmp: 'image/bmp', tif: 'image/tiff', tiff: 'image/tiff',
|
||||
mp3: 'audio/mpeg', wav: 'audio/wav', aac: 'audio/aac',
|
||||
m4a: 'audio/mp4', flac: 'audio/flac', ogg: 'audio/ogg',
|
||||
oga: 'audio/ogg', opus: 'audio/opus', amr: 'audio/amr', wma: 'audio/x-ms-wma',
|
||||
aiff: 'audio/aiff', aif: 'audio/aiff', ape: 'audio/x-ape', mid: 'audio/midi',
|
||||
mp4: 'video/mp4', mov: 'video/quicktime', avi: 'video/x-msvideo',
|
||||
mkv: 'video/x-matroska', webm: 'video/webm', flv: 'video/x-flv',
|
||||
m4v: 'video/x-m4v', wmv: 'video/x-ms-wmv', '3gp': 'video/3gpp',
|
||||
mpeg: 'video/mpeg', mpg: 'video/mpeg', ts: 'video/mp2t',
|
||||
doc: 'application/msword',
|
||||
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
ppt: 'application/vnd.ms-powerpoint',
|
||||
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
zip: 'application/zip', rar: 'application/x-rar-compressed',
|
||||
'7z': 'application/x-7z-compressed',
|
||||
json: 'application/json', xml: 'application/xml', md: 'text/markdown',
|
||||
pdf: 'application/pdf', txt: 'text/plain',
|
||||
xls: 'application/vnd.ms-excel',
|
||||
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传图片 (type=image)
|
||||
* @param {string} filePath - uni.chooseImage 返回的 tempFilePaths[0]
|
||||
* @returns {Promise<{url, mime, size, name, kind, used_strategy}>}
|
||||
*/
|
||||
export async function uploadImage(filePath, opts = {}) {
|
||||
const addon = aiService.getAddonName() // 'aikefu' | 'aiagent'
|
||||
const config = await aiService.getServiceConfig()
|
||||
const strategy = config?.upload_strategy || 'backend'
|
||||
|
||||
// 压缩: H5/MP-WEIXIN 双端都做, iPhone HEIC 大图走不通 PHP 中转也走不通 STS, 必须本地压
|
||||
let compressedPath = filePath
|
||||
let detectedSize = 0
|
||||
try {
|
||||
detectedSize = await getFileSize(filePath)
|
||||
} catch (e) {
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): 探测失败不静默降级到 0 (会让 auto 模式永远走 PHP 中转)
|
||||
// 改为抛错, 上层选择兜底走 STS (size=0 → 大于任何阈值 → 走 STS)
|
||||
console.warn('[media-upload] getFileSize failed:', e)
|
||||
}
|
||||
// H5 + MP-WEIXIN 都压缩 (微信 chooseImage 默认 sizeType:['compressed'] 但 HEIC 不在压缩白名单)
|
||||
// #ifdef H5 || MP-WEIXIN
|
||||
if (detectedSize > SIZE_LIMIT_H5_COMPRESS || opts.forceCompress) {
|
||||
try {
|
||||
const compressed = await uni.compressImage({
|
||||
src: filePath,
|
||||
quality: 80,
|
||||
compressedWidth: 2048,
|
||||
compressedHeight: 2048,
|
||||
})
|
||||
compressedPath = compressed.tempFilePath || filePath
|
||||
console.log('[media-upload] compressImage OK', detectedSize, '→', compressedPath)
|
||||
} catch (e) {
|
||||
console.warn('[media-upload] compressImage failed, use original:', e)
|
||||
}
|
||||
}
|
||||
// #endif
|
||||
|
||||
// 检查是否需要走 STS (>2MB 或商家选 oss_sts)
|
||||
// 决策: STS 触发条件 = oss_sts(总是) || auto + 大于 2MB
|
||||
// fileSizeFinal = 探测失败的兜底:
|
||||
// - 第一次探测失败(原始大小未知) → 保守走 STS
|
||||
// - 第一次成功, 第二次探测压缩后失败 → 用原始 detectedSize
|
||||
let fileSizeFinal = detectedSize
|
||||
if (compressedPath !== filePath) {
|
||||
try { fileSizeFinal = await getFileSize(compressedPath) } catch (e) {
|
||||
// 压缩后探测失败, 退回到原始大小 (可能没压成功)
|
||||
fileSizeFinal = detectedSize
|
||||
}
|
||||
}
|
||||
const useSts = strategy === 'oss_sts'
|
||||
|| (strategy === 'auto' && fileSizeFinal > SIZE_LIMIT_PHP_PASSTHROUGH)
|
||||
// ★ PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): 探测完全失败(原始+压缩后都 0) → 保守走 STS
|
||||
// 原代码 fileSizeFinal === 0 会让"auto 模式永远走 PHP 中转", 大文件 OOM
|
||||
// 但 fileSizeFinal = detectedSize (有值) 时按值判断; 只有两边都失败才兜底 STS
|
||||
const totallyUnknown = detectedSize === 0 && fileSizeFinal === 0
|
||||
const finalUseSts = useSts || (strategy === 'auto' && totallyUnknown)
|
||||
|
||||
if (finalUseSts) {
|
||||
return await uploadViaSts(compressedPath, 'image', addon, aiService.getAgentId(), config, detectedSize)
|
||||
}
|
||||
try {
|
||||
return await uploadViaPhp(compressedPath, 'image', addon, aiService.getAgentId(), detectedSize)
|
||||
} catch (e) {
|
||||
// PR-UPLOAD-ADAPTIVE-FALLBACK (2026-09-24): 后端已切 oss_sts 而 /info 缓存里的 strategy 过期
|
||||
// → PHP 中转被拒 (OSS_STS_REQUIRED), 自动切 STS 直传重试 (自愈, 无需用户重试)
|
||||
if (e && e.code === 'OSS_STS_REQUIRED') {
|
||||
console.warn('[media-upload] PHP 中转被拒 (后端策略已是 oss_sts), 自动切换 STS 直传')
|
||||
return await uploadViaSts(compressedPath, 'image', addon, aiService.getAgentId(), config, detectedSize)
|
||||
}
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传 audio / video / file
|
||||
* 策略: 商家配了云存储 (oss_sts/auto) → STS 直传, 失败回退 PHP 中转;
|
||||
* 未配云存储 (backend) → 直接 PHP 中转
|
||||
* @param {string} filePath
|
||||
* @param {'audio'|'video'|'file'} kind
|
||||
* @param {{name?:string, mime?:string, size?:number}} [opts]
|
||||
* PR-FRONTEND-MEDIA-ACCEPT (2026-09-17): H5 传进来的是 blob URL (无扩展名),
|
||||
* 必须由调用方把原始 File 的 name/mime/size 带进来, 否则 STS key 会以 .bin 结尾,
|
||||
* Content-Type 退化成 application/octet-stream, 音频/视频播放器取不到正确类型。
|
||||
*/
|
||||
export async function uploadMedia(filePath, kind, opts = {}) {
|
||||
if (!['audio', 'video', 'file'].includes(kind)) {
|
||||
throw new Error(`invalid kind: ${kind}`)
|
||||
}
|
||||
const addon = aiService.getAddonName()
|
||||
const config = await aiService.getServiceConfig()
|
||||
const agentId = aiService.getAgentId()
|
||||
const hints = { name: opts.name || '', mime: opts.mime || '' }
|
||||
const size = opts.size || 0
|
||||
const strategy = (config && config.upload_strategy) || 'backend'
|
||||
|
||||
// PHP 中转 (kind 以调用方传入的音视频分类为准, 后端只区分 image|file)
|
||||
const doPhpUpload = async (fallbackErr) => {
|
||||
let phpRes = null
|
||||
try {
|
||||
phpRes = await uploadViaPhp(filePath, kind, addon, agentId, size)
|
||||
} catch (err) {
|
||||
throw new Error((err && err.message) || (fallbackErr && fallbackErr.message) || '上传失败')
|
||||
}
|
||||
if (!phpRes || !phpRes.url) {
|
||||
throw new Error((fallbackErr && fallbackErr.message) || '上传失败: 当前平台不支持该上传方式')
|
||||
}
|
||||
return Object.assign({}, phpRes, { kind })
|
||||
}
|
||||
|
||||
// 商家未开启云存储 (strategy=backend): 与图片保持一致走 PHP 中转,
|
||||
// 避免没配 STS 时"视频/音频"按钮一选就报 "STS 凭据获取失败" 完全不可用
|
||||
// PR-UPLOAD-ADAPTIVE-FALLBACK (2026-09-24): 若后端已切 oss_sts 而本地 strategy 过期,
|
||||
// PHP 中转被拒 (OSS_STS_REQUIRED) → 自动切 STS 直传重试
|
||||
if (strategy === 'backend') {
|
||||
try {
|
||||
return await doPhpUpload()
|
||||
} catch (e) {
|
||||
if (e && e.code === 'OSS_STS_REQUIRED') {
|
||||
console.warn('[media-upload] PHP 中转被拒 (后端策略已是 oss_sts), 自动切换 STS 直传')
|
||||
return await uploadViaSts(filePath, kind, addon, agentId, config, size, hints)
|
||||
}
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
return await uploadViaSts(filePath, kind, addon, agentId, config, size, hints)
|
||||
} catch (e) {
|
||||
// PR-FRONTEND-MEDIA-ACCEPT (2026-09-17): STS 不可用 (未配置云存储 / 凭证接口失败)
|
||||
// 时回退 PHP 中转, 保证音频/视频文件仍能上传
|
||||
// PR-UPLOAD-ADAPTIVE-FALLBACK (2026-09-24): 回退的 PHP 中转若也被 oss_sts 策略拒收,
|
||||
// 保留原始 STS 错误抛出 (回退注定失败, 报真实根因比报 "操作失败" 有用)
|
||||
console.warn('[media-upload] STS 上传失败, 回退 PHP 中转:', e && e.message)
|
||||
try {
|
||||
return await doPhpUpload(e)
|
||||
} catch (e2) {
|
||||
if (e2 && e2.code === 'OSS_STS_REQUIRED') throw e
|
||||
throw e2
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PHP 中转 (multipart/form-data)
|
||||
* 端点必须用 addon 模式 URL: /<addon>/api/upload/<image|file>
|
||||
* 注释: InitRoute 注册 aikefu/api/upload 时挂在 addon namespace 下,
|
||||
* /api/aikefu/upload/* 才是命中路径; /api/kefu/upload/* 不命中
|
||||
* (那是普通接口命名空间, 上传走的是 addon 专属路由)
|
||||
*/
|
||||
async function uploadViaPhp(filePath, kind, addon, agentId, knownSize = 0) {
|
||||
const url = (addon === 'aikefu' ? '/aikefu/api/upload/' : '/aiagent/api/upload/')
|
||||
+ (kind === 'image' ? 'image' : 'file')
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
return new Promise((resolve, reject) => {
|
||||
uni.uploadFile({
|
||||
url: Config.baseUrl + url,
|
||||
filePath,
|
||||
name: 'file',
|
||||
formData: {
|
||||
kind,
|
||||
// aikefu 后端必填 config_uuid; 同时兼容 config_uid 命名并附 agent_id 兜底
|
||||
agent_id: agentId || undefined,
|
||||
config_uuid: addon === 'aikefu' ? (aiService.getCurrentConfigUuid?.() || '') : undefined,
|
||||
config_uid: addon === 'aikefu' ? (aiService.getCurrentConfigUuid?.() || '') : undefined,
|
||||
uniacid: aiService.getUniacid(),
|
||||
user_id: aiService.getUserId?.() || '',
|
||||
},
|
||||
success: (res) => {
|
||||
try {
|
||||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
|
||||
if (data.code === 0 || data.success) {
|
||||
resolve({
|
||||
url: data.data.url,
|
||||
mime: data.data.mime,
|
||||
size: data.data.size || knownSize || 0,
|
||||
name: data.data.name,
|
||||
kind: data.data.kind || kind,
|
||||
used_strategy: data.data.used_strategy || 'backend',
|
||||
oss_sts_required: data.data.oss_sts_required || false,
|
||||
})
|
||||
} else {
|
||||
// PR-UPLOAD-ADAPTIVE-FALLBACK (2026-09-24): 后端策略已切 oss_sts 时拒收 PHP 中转,
|
||||
// 顶层 oss_sts_required=true → 标记错误码, 调用方捕获后自动切 STS 直传 (自愈)
|
||||
const err = new Error(data.data || data.msg || data.message || '上传失败')
|
||||
if (data.oss_sts_required === true) err.code = 'OSS_STS_REQUIRED'
|
||||
reject(err)
|
||||
}
|
||||
} catch (e) {
|
||||
reject(new Error('解析响应失败: ' + e.message))
|
||||
}
|
||||
},
|
||||
fail: (err) => reject(new Error('网络错误: ' + (err.errMsg || err.message))),
|
||||
})
|
||||
})
|
||||
// #endif
|
||||
|
||||
// #ifdef H5
|
||||
const form = new FormData()
|
||||
const file = await pathToFile(filePath, kind)
|
||||
form.append('file', file)
|
||||
form.append('kind', kind)
|
||||
if (addon === 'aiagent') form.append('agent_id', agentId)
|
||||
else {
|
||||
// aikefu 后端必填 config_uuid; 同时兼容 config_uid 命名并附 agent_id 兜底
|
||||
const uuid = aiService.getCurrentConfigUuid?.() || ''
|
||||
form.append('config_uuid', uuid)
|
||||
form.append('config_uid', uuid)
|
||||
form.append('agent_id', agentId)
|
||||
}
|
||||
form.append('uniacid', aiService.getUniacid())
|
||||
form.append('user_id', aiService.getUserId?.() || '')
|
||||
const res = await fetch(Config.baseUrl + url, {
|
||||
method: 'POST',
|
||||
headers: { 'token': store.state.token || '' },
|
||||
body: form,
|
||||
})
|
||||
const data = await res.json()
|
||||
if (data.code === 0 || data.success) {
|
||||
return {
|
||||
url: data.data.url,
|
||||
mime: data.data.mime,
|
||||
size: data.data.size || knownSize || 0,
|
||||
name: data.data.name,
|
||||
kind: data.data.kind || kind,
|
||||
used_strategy: data.data.used_strategy || 'backend',
|
||||
oss_sts_required: data.data.oss_sts_required || false,
|
||||
}
|
||||
}
|
||||
// PR-UPLOAD-ADAPTIVE-FALLBACK (2026-09-24): 后端拒收且标记 oss_sts_required → 自动切 STS 直传
|
||||
if (data.oss_sts_required === true) {
|
||||
const err = new Error(data.data || data.msg || data.message || '上传失败')
|
||||
err.code = 'OSS_STS_REQUIRED'
|
||||
throw err
|
||||
}
|
||||
throw new Error(data.msg || data.message || '上传失败')
|
||||
// #endif
|
||||
}
|
||||
|
||||
/**
|
||||
* STS 直传 (拿临时凭证 → 直传云存储)
|
||||
*
|
||||
* PR-OSS-REGISTRY (2026-09-15) 后端支持 12 个 provider, 协议层分两类:
|
||||
* A) 4-field STS (8 个: alioss/qiniu/txcos/baidubos/qingstor/jdoss/ucloud/wyoss)
|
||||
* → 前端拼 PUT URL, Authorization header = STS <ak>:<sk>
|
||||
* B) single-URL (4 个: huaweiobs/volcengine/awsoss/minio)
|
||||
* → sts.accessKeyId 已是完整预签 PUT URL, sts.securityToken='<PROVIDER>-SIGNED'
|
||||
* 标记, 不带 Authorization
|
||||
*
|
||||
* 后端 stsResp.data.data 可能字段:
|
||||
* { provider, bucket, region, accessKeyId, accessKeySecret, securityToken,
|
||||
* key_prefix_tpl, site_id, host? (single-URL 模式), endpoint? (qiniu 7 参兼容) }
|
||||
*/
|
||||
/**
|
||||
* PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): 三段兜底扩展名提取
|
||||
* 1) filePath 最后一段正则匹配 .xxx
|
||||
* 2) filePath.name 兜底 (H5 File 对象 / APP tempFile.name)
|
||||
* 3) mimeHint 反查 EXT_MIME_MAP (H5 blob URL 没扩展名但 blob.type 通常是 image/png)
|
||||
* 4) 最终 'bin' (防 URL 片段被误当扩展名)
|
||||
*
|
||||
* PR-FRONTEND-MEDIA-UPLOAD-FIX-HOTFIX (2026-09-16): 提到模块顶层,
|
||||
* 之前只在 uploadViaSts 里, pathToFile 引用不到 → "extractExt is not defined"
|
||||
*/
|
||||
function extractExt(filePath, mimeHint = '', nameHint = '') {
|
||||
let ext = 'bin'
|
||||
if (typeof filePath === 'string') {
|
||||
const lastSeg = filePath.split('?')[0].split('/').pop() || ''
|
||||
const m = lastSeg.match(/\.([a-z0-9]+)$/i)
|
||||
if (m) ext = m[1].toLowerCase()
|
||||
}
|
||||
if (ext === 'bin' && filePath && filePath.name) {
|
||||
const m2 = String(filePath.name).match(/\.([a-z0-9]+)$/i)
|
||||
if (m2) ext = m2[1].toLowerCase()
|
||||
}
|
||||
// PR-FRONTEND-MEDIA-ACCEPT (2026-09-17): H5 blob URL + 调用方带下来的原始文件名
|
||||
if (ext === 'bin' && nameHint) {
|
||||
const m3 = String(nameHint).match(/\.([a-z0-9]+)$/i)
|
||||
if (m3) ext = m3[1].toLowerCase()
|
||||
}
|
||||
// 3) mime→ext 反查 (PR-FRONTEND-MEDIA-UPLOAD-FIX-HOTFIX): blob URL 无扩展名但
|
||||
// blob.type 是 image/png 这种, 反查 EXT_MIME_MAP → png
|
||||
if (ext === 'bin' && mimeHint) {
|
||||
for (const [e, m] of Object.entries(EXT_MIME_MAP)) {
|
||||
if (m === mimeHint) { ext = e; break }
|
||||
}
|
||||
}
|
||||
if (!/^[a-z0-9]{2,5}$/.test(ext)) ext = 'bin'
|
||||
return ext
|
||||
}
|
||||
|
||||
/**
|
||||
* PR-H5-PRESIGN-DIRECT (2026-09-24): alioss 直传改走服务端预签名 URL (ossPresign)
|
||||
*
|
||||
* 背景: 旧 uploadViaSts 对 alioss 走 4 字段 STS 凭证 + 前端裸 PUT
|
||||
* (Authorization: STS ak:sk + x-oss-security-token)。该 Authorization 头
|
||||
* 不是合法 OSS V1 签名 (合法格式为 `OSS AccessKeyId:HMAC-SHA1(StringToSign)`,
|
||||
* 签名必须由持有 secret 的一方计算) → OSS 恒 403 AccessDenied。
|
||||
* 后端「对话测试」已切 ossPresign (服务端签 PUT URL) 实测可用 (tests/repro_h5_sts_put.js:
|
||||
* 裸 PUT 403 / presign PUT 200), 前端同款切换。
|
||||
* 额外收益: object key 由服务端 KeyPrefixBuilder 统一拼, 消除前端模板替换的
|
||||
* 双重前缀/占位符错配; content_type 由服务端签名后回传, PUT 带同值即可。
|
||||
*
|
||||
* 端点: POST /<addon>/api/upload/ossPresign
|
||||
* 入参: filename / content_type / uniacid + (aikefu: config_uuid | aiagent: agent_id)
|
||||
* 出参: {upload_url, content_type, public_url, object_key, provider, ...}
|
||||
* PUT 时不带任何 Authorization 头 (签名在 query 里), Content-Type 必须与签名一致。
|
||||
*/
|
||||
/**
|
||||
* PR-UNI-REQUEST-CB (2026-09-24): uni.request 的 Promise 兼容封装
|
||||
* 实测 (tests/probe_uni_request.js): 本 uni-app H5 版本 `await uni.request(opts)`
|
||||
* resolve 的是 **undefined** (不带 success 回调时 Promise 返回值不可用),
|
||||
* 导致 stsResp.statusCode/preResp.data 全部 TypeError。
|
||||
* 回调式调用是唯一跨端可靠用法, 统一从这里走。
|
||||
*/
|
||||
function uniRequest(opts) {
|
||||
return new Promise((resolve, reject) => {
|
||||
uni.request(Object.assign({}, opts, {
|
||||
success: resolve,
|
||||
fail: (err) => reject(new Error((err && err.errMsg) || 'request failed')),
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
async function uploadViaPresign(filePath, kind, addon, agentId, knownSize = 0, hints = {}) {
|
||||
// PR-H5-PRESIGN-EXT (2026-09-24): H5 图片是 blob URL (无扩展名), extractExt 会得 'bin'
|
||||
// → 先经 pathToFile 还原 File, 用 file.type / file.name 反推扩展名与 Content-Type
|
||||
let mimeHint = hints.mime || ''
|
||||
let nameHint = hints.name || ''
|
||||
let probeFile = null
|
||||
// #ifdef H5
|
||||
try {
|
||||
probeFile = await pathToFile(filePath, kind)
|
||||
if (!mimeHint && probeFile && probeFile.type) mimeHint = probeFile.type
|
||||
if (!nameHint && probeFile && probeFile.name) nameHint = probeFile.name
|
||||
} catch (e) {
|
||||
// blob URL 还原失败不致命: ext 兜底 jpg, PUT 时再走 pathToFile
|
||||
console.warn('[media-upload] presign probe failed:', e && e.message)
|
||||
}
|
||||
// #endif
|
||||
const ext = extractExt(filePath, mimeHint, nameHint)
|
||||
// 兜底: 彻底拿不到类型时, 图片按 jpg 传 (后端后缀白名单拒收 .bin; jpg 嗅探渲染无碍)
|
||||
const finalExt = (ext === 'bin' && kind === 'image') ? 'jpg' : ext
|
||||
const contentType = mimeHint || guessMime(finalExt)
|
||||
const filename = (nameHint && /^[^\/\\]+\.[a-zA-Z0-9]{2,5}$/.test(nameHint))
|
||||
? nameHint
|
||||
: `media_${Date.now()}_${Math.random().toString(36).slice(2, 8)}.${finalExt}`
|
||||
|
||||
const preUrl = (addon === 'aikefu' ? '/aikefu/api/upload/' : '/aiagent/api/upload/') + 'ossPresign'
|
||||
const preResp = await uniRequest({
|
||||
url: Config.baseUrl + preUrl,
|
||||
method: 'POST',
|
||||
header: {
|
||||
'Content-Type': 'application/json',
|
||||
'token': store.state.token || ''
|
||||
},
|
||||
data: {
|
||||
filename,
|
||||
content_type: contentType,
|
||||
uniacid: aiService.getUniacid(),
|
||||
agent_id: addon === 'aiagent' ? (agentId || undefined) : undefined,
|
||||
config_uuid: addon === 'aikefu' ? (aiService.getCurrentConfigUuid?.() || '') : undefined,
|
||||
},
|
||||
})
|
||||
if (preResp.statusCode === 404) {
|
||||
const err = new Error('后端无 ossPresign 端点 (版本过旧)')
|
||||
err.code = 'PRESIGN_UNSUPPORTED'
|
||||
throw err
|
||||
}
|
||||
if (preResp.statusCode !== 200 || (preResp.data.code !== 0 && !preResp.data.success)) {
|
||||
throw new Error(preResp.data?.msg || preResp.data?.message || '预签名获取失败')
|
||||
}
|
||||
const pre = preResp.data.data
|
||||
const uploadUrl = pre.upload_url
|
||||
const finalContentType = pre.content_type || contentType
|
||||
|
||||
let uploadedSize = knownSize || 0
|
||||
// #ifdef H5
|
||||
if (probeFile && probeFile.size) uploadedSize = probeFile.size
|
||||
// #endif
|
||||
|
||||
// 直传: PUT 已签名 URL, 无 Authorization 头 (签名在 query 里)
|
||||
// #ifdef H5
|
||||
const file = probeFile || await pathToFile(filePath, kind)
|
||||
const ossRes = await fetch(uploadUrl, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': finalContentType },
|
||||
body: file,
|
||||
})
|
||||
console.log('[media-upload] presign PUT', ossRes.status, (pre.public_url || '').slice(0, 90))
|
||||
if (!ossRes.ok) throw new Error(`${pre.provider || 'alioss'} PUT ${ossRes.status}`)
|
||||
// #endif
|
||||
// #ifdef MP-WEIXIN
|
||||
// uni.uploadFile 只会发 multipart POST, 不能 PUT → 读成 ArrayBuffer 用 uni.request 发原始 PUT
|
||||
await new Promise((resolve, reject) => {
|
||||
uni.getFileSystemManager().readFile({
|
||||
filePath,
|
||||
success: (res) => {
|
||||
uni.request({
|
||||
url: uploadUrl,
|
||||
method: 'PUT',
|
||||
header: { 'Content-Type': finalContentType },
|
||||
data: res.data,
|
||||
success: (r) => (r.statusCode >= 200 && r.statusCode < 300)
|
||||
? resolve()
|
||||
: reject(new Error(`${pre.provider || 'alioss'} PUT ${r.statusCode}`)),
|
||||
fail: reject,
|
||||
})
|
||||
},
|
||||
fail: (e) => reject(new Error('readFile failed: ' + (e.errMsg || ''))),
|
||||
})
|
||||
})
|
||||
// #endif
|
||||
|
||||
return {
|
||||
url: (pre.public_url || uploadUrl.split('?')[0]),
|
||||
mime: finalContentType,
|
||||
size: uploadedSize,
|
||||
name: (pre.object_key || filename).split('/').pop(),
|
||||
kind,
|
||||
used_strategy: 'oss_sts',
|
||||
provider: pre.provider || 'alioss',
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadViaSts(filePath, kind, addon, agentId, config, knownSize = 0, hints = {}) {
|
||||
// PR-H5-PRESIGN-DIRECT (2026-09-24): alioss (及 provider 未知时) 先走服务端预签名;
|
||||
// 旧 4 字段裸 PUT 的 Authorization 头不是合法 OSS 签名, 恒 403 (tests/repro_h5_sts_put.js 实测)
|
||||
// 仅当后端明确配置了非 alioss provider, 或后端过旧无 presign 端点时才落回旧流程
|
||||
const providerHint = (config && config.oss_provider) || ''
|
||||
if (!providerHint || providerHint === 'alioss') {
|
||||
try {
|
||||
return await uploadViaPresign(filePath, kind, addon, agentId, knownSize, hints)
|
||||
} catch (e) {
|
||||
if (!(e && e.code === 'PRESIGN_UNSUPPORTED')) throw e
|
||||
console.warn('[media-upload] ossPresign 不可用, 回退旧 STS 流程:', e.message)
|
||||
}
|
||||
}
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): 用更稳的扩展名提取
|
||||
// H5 blob URL (blob:https://xxx/uuid) 无扩展名 → split('.').pop() 会拿整条 URL
|
||||
// 优先 file.name (H5 file / APP tempFile.name), 都没有就 blob URL → 'bin'
|
||||
// PR-FRONTEND-MEDIA-ACCEPT (2026-09-17): H5 走 blob URL 时 file.name 拿不到,
|
||||
// 由 uploadMedia 的 opts.name/mime 兜底 (音频 .mp3 / 视频 .mp4 才不会被写成 .bin)
|
||||
const ext = extractExt(filePath, hints.mime || '', hints.name || '')
|
||||
|
||||
// 1. 拿 STS 凭证 (addon 模式 URL)
|
||||
const stsUrl = (addon === 'aikefu' ? '/aikefu/api/upload/' : '/aiagent/api/upload/') + 'ossSts'
|
||||
const stsResp = await uniRequest({
|
||||
url: Config.baseUrl + stsUrl,
|
||||
method: 'POST',
|
||||
header: {
|
||||
'Content-Type': 'application/json',
|
||||
'token': store.state.token || ''
|
||||
},
|
||||
data: {
|
||||
agent_id: agentId || undefined,
|
||||
config_uuid: addon === 'aikefu' ? (aiService.getCurrentConfigUuid?.() || '') : undefined,
|
||||
config_uid: addon === 'aikefu' ? (aiService.getCurrentConfigUuid?.() || '') : undefined,
|
||||
uniacid: aiService.getUniacid(),
|
||||
user_id: aiService.getUserId?.() || '',
|
||||
},
|
||||
})
|
||||
if (stsResp.statusCode !== 200 || (stsResp.data.code !== 0 && !stsResp.data.success)) {
|
||||
throw new Error(stsResp.data?.msg || stsResp.data?.message || 'STS 凭证获取失败')
|
||||
}
|
||||
const sts = stsResp.data.data
|
||||
const provider = sts.provider || 'alioss' // 老后端默认 alioss
|
||||
|
||||
// 2. 拼 PUT URL (用后端返回的 key_prefix_tpl 替换占位符)
|
||||
const uuid = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, c => {
|
||||
const r = Math.random() * 16 | 0
|
||||
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
|
||||
})
|
||||
const now = new Date()
|
||||
const key = (sts.key_prefix_tpl || 'site/{site_id}/{yyyy}/{mm}/{dd}/{rand}')
|
||||
.replace('{site_id}', sts.site_id || '0')
|
||||
.replace('{agent_id}', agentId || '0')
|
||||
.replace('{yyyy}', now.getFullYear().toString())
|
||||
.replace('{mm}', String(now.getMonth() + 1).padStart(2, '0'))
|
||||
.replace('{dd}', String(now.getDate()).padStart(2, '0'))
|
||||
.replace('{rand}', uuid)
|
||||
+ '.' + ext
|
||||
|
||||
// ★ PR-OSS-REGISTRY (2026-09-15): provider 分流
|
||||
// single-URL 模式: securityToken 末尾是 -SIGNED (OBS-SIGNED / TOS-SIGNED / AWS-SIGNED / MINIO-SIGNED)
|
||||
const isSingleUrlMode = typeof sts.securityToken === 'string'
|
||||
&& /-(SIGNED)$/.test(sts.securityToken)
|
||||
|
||||
let ossUrl, headers
|
||||
if (isSingleUrlMode) {
|
||||
// B) single-URL: sts.accessKeyId 是完整预签 PUT URL, 不需要 Authorization header
|
||||
ossUrl = sts.accessKeyId
|
||||
headers = { 'Content-Type': guessMime(ext) }
|
||||
} else if (provider === 'qiniu') {
|
||||
// A) qiniu 兼容模式: sts.accessKeyId = uptoken, endpoint 来自 sts.endpoint 或 sts.host
|
||||
ossUrl = (sts.endpoint || sts.host || `https://upload-${sts.region}.qiniup.com`) + '/' + key
|
||||
headers = {
|
||||
'Authorization': 'UpToken ' + sts.accessKeyId,
|
||||
'Content-Type': guessMime(ext),
|
||||
}
|
||||
} else {
|
||||
// A) 4-field STS 默认 (alioss/txcos/baidubos/qingstor/jdoss/ucloud/wyoss)
|
||||
// endpoint 模板按 provider 区分, 后端未返 endpoint 时按 OSS 模板拼
|
||||
// ★ FIX-ALIOSS-ENDPOINT-OSS-PREFIX (2026-09-23): alioss 区域名缺前缀 bug
|
||||
// sts.region 是用户输入的简写形式 (cn-hangzhou), 但真实 OSS endpoint 必须用完整形式 (oss-cn-hangzhou)
|
||||
// 之前 `https://${bucket}.${region}.aliyuncs.com` 拼成 `suzhou-oss-data-xyz.cn-hangzhou.aliyuncs.com` (DNS 不存在)
|
||||
// 正确: `https://${bucket}.oss-${region}.aliyuncs.com` → `suzhou-oss-data-xyz.oss-cn-hangzhou.aliyuncs.com`
|
||||
// 后端 sts.oss_url 已拼好正确 URL (用 OssProviderRegistry::buildDirectEndpoint), 优先用它
|
||||
const aliossTpl = sts.oss_url
|
||||
? sts.oss_url.replace(/\/[^\/?#]+$/, '') // 去尾 key, 留 base endpoint
|
||||
: `https://${sts.bucket}.oss-${sts.region}.aliyuncs.com`
|
||||
const tpl = (provider === 'alioss') ? aliossTpl
|
||||
: (provider === 'txcos') ? `https://${sts.bucket}-${sts.region}.cos.${sts.region}.myqcloud.com`
|
||||
: (provider === 'baidubos') ? `https://${sts.bucket}.${sts.region}.bcebos.com`
|
||||
: (provider === 'jdoss') ? `https://${sts.bucket}.${sts.region}.jdcloud-oss.com`
|
||||
: (provider === 'wyoss') ? `https://${sts.bucket}.${sts.host || sts.region}`
|
||||
: (sts.endpoint ? sts.endpoint.replace('{bucket}', sts.bucket) : `https://${sts.bucket}.${sts.region}`)
|
||||
ossUrl = `${tpl}/${key}`
|
||||
headers = {
|
||||
'Authorization': `STS ${sts.accessKeyId}:${sts.accessKeySecret}`,
|
||||
'x-oss-security-token': sts.securityToken,
|
||||
'Content-Type': guessMime(ext),
|
||||
}
|
||||
}
|
||||
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): MP-WEIXIN uni.uploadFile 拿不到 file.size
|
||||
// H5 pathToFile 拿到的 file 有 size, MP-WEIXIN 没有; STS 完成后用已知 size 或后端返回
|
||||
let uploadedSize = knownSize || 0
|
||||
// #ifdef H5
|
||||
try {
|
||||
const probe = await pathToFile(filePath, kind)
|
||||
if (probe && probe.size) uploadedSize = probe.size
|
||||
} catch (e) {}
|
||||
// #endif
|
||||
|
||||
// 3. 直传云存储
|
||||
// #ifdef MP-WEIXIN
|
||||
await new Promise((resolve, reject) => {
|
||||
uni.uploadFile({
|
||||
url: ossUrl,
|
||||
filePath,
|
||||
name: 'file',
|
||||
formData: {},
|
||||
header: headers,
|
||||
success: (res) => {
|
||||
if (res.statusCode >= 200 && res.statusCode < 300) resolve()
|
||||
else reject(new Error(`${provider} PUT ${res.statusCode}`))
|
||||
},
|
||||
fail: reject,
|
||||
})
|
||||
})
|
||||
// #endif
|
||||
// #ifdef H5
|
||||
const file = await pathToFile(filePath, kind)
|
||||
const ossRes = await fetch(ossUrl, {
|
||||
method: 'PUT',
|
||||
headers,
|
||||
body: file,
|
||||
})
|
||||
if (!ossRes.ok) throw new Error(`${provider} PUT ${ossRes.status}`)
|
||||
// #endif
|
||||
|
||||
// 4. 返回公网 URL
|
||||
return {
|
||||
url: ossUrl.split('?')[0], // single-URL 模式 URL 带 ?<签名参数>, 拼 chat attachment 用 base URL
|
||||
mime: guessMime(ext),
|
||||
size: uploadedSize,
|
||||
name: key.split('/').pop(),
|
||||
kind,
|
||||
used_strategy: 'oss_sts',
|
||||
provider,
|
||||
}
|
||||
}
|
||||
|
||||
async function getFileSize(filePath) {
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): 失败抛错而不是 resolve(0)
|
||||
// 0 会让 auto 模式永远走 PHP 中转 (0 > 2MB = false), 失去 STS 直传能力
|
||||
// 上层 uploadImage 用 try/catch 兜底, 探测失败视为 "大小未知, 默认走 STS"
|
||||
// #ifdef MP-WEIXIN
|
||||
return new Promise((resolve, reject) => {
|
||||
uni.getFileInfo({
|
||||
filePath,
|
||||
success: (res) => resolve(res.size || 0),
|
||||
fail: (err) => reject(new Error('getFileInfo failed: ' + (err.errMsg || ''))),
|
||||
})
|
||||
})
|
||||
// #endif
|
||||
// #ifdef H5
|
||||
try {
|
||||
const res = await fetch(filePath)
|
||||
const blob = await res.blob()
|
||||
return blob.size
|
||||
} catch (e) {
|
||||
throw new Error('getFileSize fetch failed: ' + e.message)
|
||||
}
|
||||
// #endif
|
||||
}
|
||||
|
||||
async function pathToFile(filePath, kind) {
|
||||
// #ifdef H5
|
||||
const res = await fetch(filePath)
|
||||
const blob = await res.blob()
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX-HOTFIX (2026-09-16): H5 blob URL 路径修复扩展名
|
||||
// 原代码 `filePath.split('/').pop()` 对 blob:http://xxx/uuid 取出 'uuid' (无扩展名)
|
||||
// → 后端 multipart filename 缺失扩展名 → ext_rule 拒绝 "上传文件后缀不允许"
|
||||
// extractExt 三段兜底: 1) lastSegment 正则 2) file.name 3) 'bin' 最终兜底
|
||||
// 若 ext='bin', 走 guessMime(EXT_MIME_MAP) 看能不能从 mime 反推 jpg/png (mime→ext)
|
||||
const rawName = filePath.split('/').pop() || `${kind}.bin`
|
||||
const ext = extractExt(filePath, blob.type)
|
||||
const finalName = ext !== 'bin' ? `${rawName}.${ext}` : rawName
|
||||
// blob.type 通常是 image/png 或空; 空时用 guessMime 兜底
|
||||
const mime = blob.type || guessMime(ext)
|
||||
return new File([blob], finalName, { type: mime })
|
||||
// #endif
|
||||
}
|
||||
|
||||
/**
|
||||
* PR-FRONTEND-MEDIA-INLINE-BASE64 (2026-09-16): 把附件原文件读成 base64,
|
||||
* 用于 ai-chat-message.vue sendMessage 给 attachment 加 `data` 字段,
|
||||
* 让 backend 走 WbAgentOsClient::buildMediaBlocks 路径 ① (inline base64)
|
||||
* 而不是路径 ②/③ (URL fetch / resource_link).
|
||||
*
|
||||
* 为什么必要: 之前 PR-FRONTEND-MEDIA-UPLOAD-FIX 已让上传链路 (uni.compressImage
|
||||
* → backend Upload.php) 返回了公网 URL, 但此 URL 是 backend Upload.php::buildPublicUrl
|
||||
* 用 request()->domain() 拼出来的 (例如 http://192.168.x.x:8050/upload/...).
|
||||
* 买家端 AI chat 把这个 URL 透给 backend, backend MediaGuard::urlAllowed
|
||||
* 把 192.168.x.x 当内网 IP (FILTER_FLAG_NO_PRIV_RANGE) 拒绝, 附件被静默丢弃.
|
||||
*
|
||||
* 修复: 同步给 attachment 加 data: <bare-base64> 字段.
|
||||
* - backend MessageMedia::normalizeInput 直接透传 data (line 207-208)
|
||||
* - backend MediaGuard::check 看到 data 非空就无条件放行, 不参与 URL 校验 (line 137-140)
|
||||
* - backend WbAgentOsClient::buildMediaBlocks 路径 ① 优先 data + image/audio → 直接 base64 内联
|
||||
* 全链路 bypass URL 公网可达性 (无论 LAN 还是公网, 都不依赖 WB Cloud 拉 URL).
|
||||
*
|
||||
* 返回: { data: '<bare-base64>', size, mime } | null
|
||||
* - null 时表示文件 > maxBytes (默认 5MB, J7 上限) 或读取失败 → 调用方跳过 data 字段, 走 URL 路径
|
||||
* - bare-base64 (不带 data:image/png;base64, 前缀) — 后端 buildMediaBlocks 需要纯 base64
|
||||
* - mime 从 blob.type (H5) / 调用方传 mimeHint (uni-app 平台不知道 blob.type)
|
||||
*
|
||||
* @param {string} filePath 选图/选文件时的原始路径 (blob: URL 或 _doc/tmp_xxx 路径)
|
||||
* @param {object} [opts]
|
||||
* @param {number} [opts.maxBytes=5MB] 超限返回 null (frontend 主动限流, 减轻带宽/内存)
|
||||
* @param {string} [opts.mimeHint] 非 H5 平台拿不到 blob.type, 用 pending.uploaded.mime 兜底
|
||||
*/
|
||||
export async function fileToBase64(filePath, opts = {}) {
|
||||
const maxBytes = opts.maxBytes || SIZE_LIMIT_INLINE_BASE64
|
||||
if (!filePath) return null
|
||||
|
||||
// #ifdef H5
|
||||
try {
|
||||
const res = await fetch(filePath)
|
||||
if (!res.ok) throw new Error('fetch failed: ' + res.status)
|
||||
const blob = await res.blob()
|
||||
if (blob.size > maxBytes) {
|
||||
console.log('[media-upload] fileToBase64: size', blob.size, '> maxBytes', maxBytes, '→ 跳过内联')
|
||||
return null
|
||||
}
|
||||
const dataUri = await new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(reader.result)
|
||||
reader.onerror = () => reject(new Error('FileReader failed'))
|
||||
reader.readAsDataURL(blob)
|
||||
})
|
||||
const m = /^data:([^;,]+);base64,(.*)$/.exec(dataUri)
|
||||
if (!m) throw new Error('unexpected data URI shape: ' + String(dataUri).slice(0, 40))
|
||||
return { data: m[2], size: blob.size, mime: m[1] }
|
||||
} catch (e) {
|
||||
console.warn('[media-upload] fileToBase64 H5 失败:', e)
|
||||
return null
|
||||
}
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-WEIXIN || APP-PLUS
|
||||
try {
|
||||
const fsm = uni.getFileSystemManager()
|
||||
// 1. 探测大小, 超限直接返回 null
|
||||
let size = 0
|
||||
try {
|
||||
const stat = fsm.statSync(filePath)
|
||||
// statSync 在部分平台返回 {size}, 部分返回 {fileSize}, 部分直接是数字
|
||||
size = (stat && (stat.size || stat.fileSize)) || 0
|
||||
} catch (e) {
|
||||
// statSync 失败 (权限/路径) → 直接尝试 readFile, 后端会再校验 size
|
||||
console.warn('[media-upload] fileToBase64 statSync failed, fallback to readFile:', e)
|
||||
}
|
||||
if (size > maxBytes) {
|
||||
console.log('[media-upload] fileToBase64: size', size, '> maxBytes', maxBytes, '→ 跳过内联')
|
||||
return null
|
||||
}
|
||||
// 2. readFile 拿 base64 — 同步 API 简单可靠, base64 在 5MB 文件 ≈ 6.7MB 字符串, 内存可控
|
||||
const data = fsm.readFileSync(filePath, 'base64')
|
||||
return { data, size: size || 0, mime: opts.mimeHint || '' }
|
||||
} catch (e) {
|
||||
console.warn('[media-upload] fileToBase64 uni-app 失败:', e)
|
||||
return null
|
||||
}
|
||||
// #endif
|
||||
}
|
||||
|
||||
function guessMime(ext) {
|
||||
return EXT_MIME_MAP[ext] || 'application/octet-stream'
|
||||
}
|
||||
|
||||
export default { uploadImage, uploadMedia }
|
||||
81
common/js/merge-theme.js
Normal file
81
common/js/merge-theme.js
Normal file
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* 主题 token 合并工具
|
||||
*
|
||||
* 与 lang.js::applyOverrides 同构(都是"远端扁平覆写 map"按 key 路径合并),
|
||||
* 差异:
|
||||
* - 主题 token 是"扁平叶子"(如 main_color / bg_color),没有嵌套层级
|
||||
* - 需要支持"三桶叠加":presetBase(本地预设) < brand(品牌色) < userMode(夜间/浅色)
|
||||
* - value 是色值字符串(也允许空串 = 显式清空)
|
||||
*
|
||||
* 危险 key 过滤:拦截 __proto__/constructor/prototype,防止恶意覆写污染对象原型链
|
||||
*/
|
||||
|
||||
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
||||
|
||||
/**
|
||||
* 把单层 map 的 keys 过滤掉危险段(白名单:值必须是 string,null/undefined/其它跳过)
|
||||
* - 输入: 远端扁平 map { 'main_color': '#FF4646', '...': null, ... }
|
||||
* - 输出: 净化后的 map(只保留 string 值,空串也是合法覆写)
|
||||
*/
|
||||
export function sanitizeFlatMap(flatMap) {
|
||||
const out = {};
|
||||
if (!flatMap || typeof flatMap !== 'object') return out;
|
||||
for (const key in flatMap) {
|
||||
if (!Object.prototype.hasOwnProperty.call(flatMap, key)) continue;
|
||||
// 危险 key 过滤
|
||||
if (FORBIDDEN_KEYS.has(String(key))) continue;
|
||||
const val = flatMap[key];
|
||||
if (typeof val !== 'string') continue;
|
||||
out[key] = val;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并多桶 map
|
||||
* @param {...object} maps 从低优先级到高优先级依次传入
|
||||
* 例: mergeThemeBuckets(presetBase, brand, dark) = preset 被 brand 覆盖,brand 被 dark 覆盖
|
||||
* @returns {object}
|
||||
*/
|
||||
export function mergeThemeBuckets(...maps) {
|
||||
const out = {};
|
||||
for (const m of maps) {
|
||||
if (!m || typeof m !== 'object') continue;
|
||||
for (const k in m) {
|
||||
if (!Object.prototype.hasOwnProperty.call(m, k)) continue;
|
||||
if (FORBIDDEN_KEYS.has(String(k))) continue;
|
||||
const v = m[k];
|
||||
if (typeof v !== 'string') continue;
|
||||
out[k] = v;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 一站式合并:本地预设(已选中的 theme 子集) + brand 桶 + userMode 桶
|
||||
* @param {object} preset 本地 style_color.js 中选中的 theme(如 'default' 的所有 token)
|
||||
* @param {object} brandOverrides brand 桶(任何模式都生效)
|
||||
* @param {object} userModeOverrides userMode 桶(light/dark,叠加在 brand 之上)
|
||||
* @returns {object} { tokens, sources }
|
||||
* tokens: 最终扁平 map
|
||||
* sources: 每个 key 的来源(用于调试/可视化) 'preset' | 'brand' | 'userMode'
|
||||
*/
|
||||
export function composeFinalTokens(preset, brandOverrides, userModeOverrides) {
|
||||
const tokens = {};
|
||||
const sources = {};
|
||||
const presetMap = sanitizeFlatMap(preset);
|
||||
const brandMap = sanitizeFlatMap(brandOverrides);
|
||||
const modeMap = sanitizeFlatMap(userModeOverrides);
|
||||
|
||||
for (const k in presetMap) { tokens[k] = presetMap[k]; sources[k] = 'preset'; }
|
||||
for (const k in brandMap) { tokens[k] = brandMap[k]; sources[k] = 'brand'; }
|
||||
for (const k in modeMap) { tokens[k] = modeMap[k]; sources[k] = 'userMode'; }
|
||||
return { tokens, sources };
|
||||
}
|
||||
|
||||
export default {
|
||||
sanitizeFlatMap,
|
||||
mergeThemeBuckets,
|
||||
composeFinalTokens,
|
||||
};
|
||||
291
common/js/mp-share-default.js
Normal file
291
common/js/mp-share-default.js
Normal file
@@ -0,0 +1,291 @@
|
||||
/**
|
||||
* 全局兜底分享 mixin
|
||||
*
|
||||
* 仅在微信小程序编译产物中被加载:
|
||||
* main.js 中的 import + Vue.mixin 调用被 MP-WEIXIN 预处理宏 包住,
|
||||
* 其它平台编译时整个模块不会进入产物,因此文件内部无需再写条件编译。
|
||||
*
|
||||
* 背景:
|
||||
* - 微信小程序要求每个要支持「转发 / 朋友圈」的页面显式声明 onShareAppMessage / onShareTimeline,
|
||||
* 否则页面右上角"三个点"菜单不会显示"转发"按钮。
|
||||
* - 本项目之前只有 ~17 个页面声明了分享钩子,剩余页面无法转发。
|
||||
* - 业务对"全页面都支持转发 + 复制小程序路径"有强诉求。
|
||||
*
|
||||
* 设计原则:
|
||||
* 1. 不侵入现有页面:所有页面通过 Vue.mixin 自动获得默认行为
|
||||
* 2. 已有 onShareAppMessage / onShareTimeline 的页面优先级更高(uni-app 会优先用页面自身的钩子)
|
||||
* 3. 默认分享内容由后端 /weapp/api/weapp/share 按当前路由下发,
|
||||
* 拉取失败时退化到站点名 + 当前路径,避免完全无法分享
|
||||
* 4. 暴露 $mpShare 工具方法(currentPath / copyPath / refresh),
|
||||
* 方便子页面在 onShareAppMessage 中复用 path
|
||||
*/
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
const _safeGetCurrentPage = () => {
|
||||
try {
|
||||
const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : [];
|
||||
return pages.length > 0 ? pages[pages.length - 1] : null;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 关闭分享能力的页面 route 列表(不带前导斜杠,与 mp-weixin page.route 保持一致)
|
||||
*
|
||||
* 为什么需要:
|
||||
* mp-share-default.js 通过 Vue.mixin 全局注入 onShareAppMessage / onShareTimeline,
|
||||
* 但有些页面不适合"分享":
|
||||
* 1) webview 容器页: 转发它等于转发一个 iframe 壳,无意义且会暴露内部 src
|
||||
* 2) 隐私弹窗 / 登录中转页: 状态不稳定,转出去体验差
|
||||
* 3) 任何业务明确要求"不分享"的页面
|
||||
*
|
||||
* 命中后行为:
|
||||
* - mixin 内部不再拉取分享配置(节省一次 HTTP 请求)
|
||||
* - mixin 注入的 onShareAppMessage / onShareTimeline / $mpShare_* 工具方法仍然存在,
|
||||
* 但内部立即调用 wx.hideShareMenu() 把转发按钮从右上角菜单中隐藏
|
||||
* - 这两条防线双保险:即使 mixin 钩子被业务侧转发链路误触发,也不会显示分享弹窗
|
||||
*
|
||||
* 备选方案对比(都没选,原因列在下方):
|
||||
* - 在 created 里 this.onShareAppMessage = undefined:
|
||||
* Vue mixin 合并策略会把 undefined 视为"未声明",mixin 的钩子仍然生效 → 不可靠
|
||||
* - mixin 内 return null / 不 return:
|
||||
* 微信会回退到默认 title 转发,按钮仍显示 → 不可靠
|
||||
* - 使用 wx.hideShareMenu(本方案采用):
|
||||
* 微信官方 API,会立即把"转发"按钮从当前页右上角菜单中隐藏,行为最稳
|
||||
*/
|
||||
const _DISABLED_PAGES = new Set([
|
||||
'pages_tool/webview/webview', // webview 容器,转发无意义
|
||||
]);
|
||||
|
||||
const _isCurrentPageDisabled = () => {
|
||||
const page = _safeGetCurrentPage();
|
||||
if (!page) return false;
|
||||
const route = (page.route || (page.$page && page.$page.path) || '').replace(/^\//, '');
|
||||
return _DISABLED_PAGES.has(route);
|
||||
};
|
||||
|
||||
/**
|
||||
* 主动隐藏当前页的"转发"按钮
|
||||
* - 只能在 mp-weixin 环境调用(其它平台 wx 全局不存在)
|
||||
* - 必须在 onLoad 之后调用(需要 Page 实例已注册完成)
|
||||
* - 失败时静默吞掉(权限/版本/非微信环境都可能导致失败)
|
||||
*/
|
||||
const _hideShareMenu = () => {
|
||||
try {
|
||||
// #ifdef MP-WEIXIN
|
||||
if (typeof wx !== 'undefined' && typeof wx.hideShareMenu === 'function') {
|
||||
wx.hideShareMenu({
|
||||
menus: ['shareAppMessage', 'shareTimeline']
|
||||
});
|
||||
}
|
||||
// #endif
|
||||
} catch (e) {
|
||||
// 静默:旧基础库可能不支持 menus 参数,降级到无参版本
|
||||
try {
|
||||
// #ifdef MP-WEIXIN
|
||||
if (typeof wx !== 'undefined' && typeof wx.hideShareMenu === 'function') {
|
||||
wx.hideShareMenu();
|
||||
}
|
||||
// #endif
|
||||
} catch (e2) { /* ignore */ }
|
||||
}
|
||||
};
|
||||
|
||||
const _getCurrentPath = (withQuery = true) => {
|
||||
const page = _safeGetCurrentPage();
|
||||
if (!page) return '';
|
||||
// page.route 在 mp-weixin 上不带前导斜杠、不带 query;page.options 携带 query
|
||||
const route = page.route || (page.$page && page.$page.path) || '';
|
||||
const options = page.options || {};
|
||||
if (!withQuery) return route ? '/' + route.replace(/^\//, '') : '';
|
||||
const query = Object.keys(options)
|
||||
.filter(k => options[k] !== undefined && options[k] !== null && options[k] !== '')
|
||||
.map(k => `${encodeURIComponent(k)}=${encodeURIComponent(options[k])}`)
|
||||
.join('&');
|
||||
return query ? `/${route}?${query}` : `/${route}`;
|
||||
};
|
||||
|
||||
// 模块级缓存:避免重复请求后端
|
||||
let _shareCache = null;
|
||||
let _shareCacheAt = 0;
|
||||
const SHARE_CACHE_TTL = 60 * 1000; // 60s
|
||||
|
||||
const _fetchShareFromServer = (path) => {
|
||||
const Http = require('./http.js').default || require('./http.js');
|
||||
return new Promise((resolve) => {
|
||||
Http.sendRequest({
|
||||
url: '/weapp/api/weapp/share',
|
||||
data: { path },
|
||||
success: (res) => {
|
||||
if (res && res.code >= 0 && res.data && res.data.data) {
|
||||
resolve(res.data.data);
|
||||
} else {
|
||||
resolve(null);
|
||||
}
|
||||
},
|
||||
fail: () => resolve(null)
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const _buildFallback = (path) => ({
|
||||
title: '小程序分享',
|
||||
path,
|
||||
imageUrl: ''
|
||||
});
|
||||
|
||||
const _getShareConfig = async (path) => {
|
||||
const now = Date.now();
|
||||
if (_shareCache && (now - _shareCacheAt) < SHARE_CACHE_TTL) {
|
||||
return _shareCache;
|
||||
}
|
||||
const cfg = await _fetchShareFromServer(path);
|
||||
_shareCache = cfg || _buildFallback(path);
|
||||
_shareCacheAt = now;
|
||||
return _shareCache;
|
||||
};
|
||||
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
__mpShareCache: null, // 当前页面的分享配置
|
||||
};
|
||||
},
|
||||
/**
|
||||
* 在实例创建阶段检查当前页面是否在 _DISABLED_PAGES 列表中。
|
||||
* 命中后调用 wx.hideShareMenu 把当前页的"转发"按钮从右上角菜单中隐藏。
|
||||
*/
|
||||
created() {
|
||||
try {
|
||||
if (_isCurrentPageDisabled()) {
|
||||
// 立即隐藏(此时 wx 还没完全就绪,先尝试一次;失败也无所谓,onLoad 会再调一次)
|
||||
_hideShareMenu();
|
||||
}
|
||||
} catch (e) {}
|
||||
},
|
||||
onLoad() {
|
||||
try {
|
||||
if (_isCurrentPageDisabled()) {
|
||||
// 命中关闭列表的页面:
|
||||
// 1) 再次调 wx.hideShareMenu(此时 Page 已就绪,稳定生效)
|
||||
// 2) 不再拉取分享配置,避免无谓请求
|
||||
_hideShareMenu();
|
||||
return;
|
||||
}
|
||||
const path = _getCurrentPath(true);
|
||||
_getShareConfig(path).then(cfg => {
|
||||
// 后端未返回配置时,注入站点名作为默认标题
|
||||
if (cfg && !cfg.title) {
|
||||
const siteName = (this.$store && this.$store.state && this.$store.state.siteInfo && this.$store.state.siteInfo.site_name) || '';
|
||||
cfg.title = siteName || '小程序分享';
|
||||
}
|
||||
this.__mpShareCache = cfg;
|
||||
});
|
||||
} catch (e) {}
|
||||
},
|
||||
onShow() {
|
||||
// 兜底:进入页面后如果尚未就绪,再异步拉一次
|
||||
if (this.__mpShareCache) return;
|
||||
if (_isCurrentPageDisabled()) return; // 命中关闭列表,不再拉
|
||||
try {
|
||||
const path = _getCurrentPath(true);
|
||||
_getShareConfig(path).then(cfg => {
|
||||
this.__mpShareCache = cfg;
|
||||
});
|
||||
} catch (e) {}
|
||||
},
|
||||
/**
|
||||
* 全局默认 onShareAppMessage:
|
||||
* uni-app 规范:组件自身的钩子优先级 > mixin,因此已显式声明的页面不受影响。
|
||||
*/
|
||||
onShareAppMessage() {
|
||||
// 命中禁用列表的页面:即使 wx.hideShareMenu 因某些原因没生效,
|
||||
// 这里直接 return undefined / 也不主动拼 cfg,让微信回退到默认行为
|
||||
// (主防线是 wx.hideShareMenu,这里只是兜底)
|
||||
if (_isCurrentPageDisabled()) {
|
||||
return undefined;
|
||||
}
|
||||
const cfg = this.__mpShareCache;
|
||||
if (cfg && cfg.title) {
|
||||
return {
|
||||
title: cfg.title,
|
||||
path: cfg.path,
|
||||
imageUrl: cfg.imageUrl || ''
|
||||
};
|
||||
}
|
||||
// 后端无配置时:使用站点名 + 当前路径
|
||||
return {
|
||||
title: _buildFallback(_getCurrentPath(true)).title,
|
||||
path: _getCurrentPath(true)
|
||||
};
|
||||
},
|
||||
/**
|
||||
* 全局默认 onShareTimeline(朋友圈):
|
||||
* 朋友圈只支持 query(不能直接传 path),从 cfg.path 中抽取 ? 之后的 query。
|
||||
*/
|
||||
onShareTimeline() {
|
||||
if (_isCurrentPageDisabled()) {
|
||||
return undefined;
|
||||
}
|
||||
const cfg = this.__mpShareCache;
|
||||
if (cfg && cfg.title) {
|
||||
const path = cfg.path || _getCurrentPath(true);
|
||||
const query = path.indexOf('?') > 0 ? path.split('?')[1] : path;
|
||||
return {
|
||||
title: cfg.title,
|
||||
query,
|
||||
imageUrl: cfg.imageUrl || ''
|
||||
};
|
||||
}
|
||||
const path = _getCurrentPath(true);
|
||||
const query = path.indexOf('?') > 0 ? path.split('?')[1] : '';
|
||||
return {
|
||||
title: _buildFallback(path).title,
|
||||
query
|
||||
};
|
||||
},
|
||||
methods: {
|
||||
/**
|
||||
* 获取当前小程序页面路径(含 query)
|
||||
*/
|
||||
$mpShare_currentPath() {
|
||||
return _getCurrentPath(true);
|
||||
},
|
||||
/**
|
||||
* 刷新当前页分享配置(用于页面参数变更后想重置转发 path 的场景)
|
||||
*/
|
||||
$mpShare_refresh() {
|
||||
_shareCache = null;
|
||||
_shareCacheAt = 0;
|
||||
return _getShareConfig(_getCurrentPath(true)).then(cfg => {
|
||||
this.__mpShareCache = cfg;
|
||||
return cfg;
|
||||
});
|
||||
},
|
||||
/**
|
||||
* 复制当前页面小程序路径到剪贴板
|
||||
* 微信小程序没有"页面 URL"概念,仅可复制形如:
|
||||
* pages/goods/detail?id=123&source_member=xx
|
||||
* 的小程序内部路径,便于分享者在聊天里粘贴。
|
||||
* 优先复用 util.copyCurrentPath。
|
||||
*/
|
||||
$mpShare_copyPath() {
|
||||
const path = _getCurrentPath(true);
|
||||
const text = path.replace(/^\//, ''); // 去掉前导斜杠
|
||||
if (this.$util && typeof this.$util.copyCurrentPath === 'function') {
|
||||
return this.$util.copyCurrentPath({});
|
||||
}
|
||||
// util.copyCurrentPath 不存在(极端情况:util 模块未加载)时直接调 uni API
|
||||
return new Promise((resolve, reject) => {
|
||||
uni.setClipboardData({
|
||||
data: text,
|
||||
success: () => resolve(text),
|
||||
fail: (err) => reject(err)
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// #endif
|
||||
@@ -1,5 +1,6 @@
|
||||
import { EventSafety } from '@/common/js/event-safety.js'
|
||||
import util from '@/common/js/util.js'
|
||||
import Lang from '@/common/js/lang.js'
|
||||
|
||||
export class NavigationHelper {
|
||||
constructor() {
|
||||
@@ -43,7 +44,6 @@ export class NavigationHelper {
|
||||
|
||||
query.select('.uni-page-head').boundingClientRect((rect) => {
|
||||
if (rect && rect.height > 0) {
|
||||
console.log('直接查询导航栏高度成功:', rect.height)
|
||||
resolve(rect.height)
|
||||
} else {
|
||||
console.warn('未找到 uni-page-head 元素或高度为0')
|
||||
@@ -64,7 +64,6 @@ export class NavigationHelper {
|
||||
|
||||
const height = menuButtonInfo.bottom +
|
||||
(menuButtonInfo.top - systemInfo.statusBarHeight)
|
||||
console.log('微信小程序导航栏高度:', height)
|
||||
resolve(height)
|
||||
} catch (error) {
|
||||
console.error('微信小程序高度计算失败:', error)
|
||||
@@ -174,7 +173,6 @@ export class NavigationHelper {
|
||||
|
||||
// 处理服务请求
|
||||
async handleServiceRequest(event, component) {
|
||||
console.log('处理导航相关服务请求:', event.type)
|
||||
|
||||
// 安全检查事件目标
|
||||
if (this.shouldProcessNavigationRequest(event)) {
|
||||
@@ -263,7 +261,7 @@ export class NavigationHelper {
|
||||
}
|
||||
|
||||
// 显示用户友好的错误信息
|
||||
this.showError('导航服务暂时不可用')
|
||||
this.showError(Lang.lang('common.navigation.serviceUnavailable'))
|
||||
}
|
||||
|
||||
// 显示错误提示
|
||||
@@ -278,7 +276,6 @@ export class NavigationHelper {
|
||||
// 清理缓存
|
||||
clearCache() {
|
||||
this.navigationCache.clear()
|
||||
console.log('导航缓存已清理')
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
229
common/js/platform.js
Normal file
229
common/js/platform.js
Normal file
@@ -0,0 +1,229 @@
|
||||
/**
|
||||
* 统一平台检测模块
|
||||
* 消除分散在 http.js, util.js, event-bus.js, customer-service.js 中的重复平台检测代码
|
||||
*/
|
||||
|
||||
let cachedPlatform = null;
|
||||
let cachedAppType = null;
|
||||
let cachedAppTypeName = null;
|
||||
|
||||
// 延迟加载 lang 模块,避免与 lang.js 形成循环依赖
|
||||
// (lang.js 顶部 import 了 Platform,所以 platform.js 不能顶部 import lang)
|
||||
function _getLang() {
|
||||
try {
|
||||
return require('@/common/js/lang.js').default;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function _t(key, fallback) {
|
||||
const lang = _getLang();
|
||||
if (lang && typeof lang.lang === 'function') {
|
||||
const result = lang.lang(key);
|
||||
// lang() 在找不到 key 时会返回 key 本身(开发环境)或空串(生产环境)
|
||||
if (result && result !== key) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export const Platform = {
|
||||
/**
|
||||
* 检测当前运行平台
|
||||
* @returns {string} 平台标识
|
||||
*/
|
||||
detect() {
|
||||
if (cachedPlatform) {
|
||||
return cachedPlatform;
|
||||
}
|
||||
|
||||
// #ifdef H5
|
||||
cachedPlatform = 'h5';
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
cachedPlatform = 'weapp';
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-ALIPAY
|
||||
cachedPlatform = 'alipay';
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-BAIDU
|
||||
cachedPlatform = 'baidu';
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-TOUTIAO
|
||||
cachedPlatform = 'toutiao';
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-QQ
|
||||
cachedPlatform = 'qq';
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-KUAISHOU
|
||||
cachedPlatform = 'kuaishou';
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-HARMONY
|
||||
cachedPlatform = 'harmony';
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-JD
|
||||
cachedPlatform = 'jd';
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-360
|
||||
cachedPlatform = '360';
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-XHS
|
||||
cachedPlatform = 'xhs';
|
||||
// #endif
|
||||
|
||||
// #ifdef APP-PLUS
|
||||
cachedPlatform = 'app';
|
||||
// #endif
|
||||
|
||||
// #ifdef PC
|
||||
cachedPlatform = 'pc';
|
||||
// #endif
|
||||
|
||||
if (!cachedPlatform) {
|
||||
cachedPlatform = 'unknown';
|
||||
}
|
||||
|
||||
return cachedPlatform;
|
||||
},
|
||||
|
||||
/**
|
||||
* 获取平台类型标识 (用于API请求)
|
||||
* @returns {string} app_type 值
|
||||
*/
|
||||
getAppType() {
|
||||
if (cachedAppType) {
|
||||
return cachedAppType;
|
||||
}
|
||||
|
||||
const platform = this.detect();
|
||||
|
||||
// #ifdef H5
|
||||
if (platform === 'h5') {
|
||||
cachedAppType = this.isWeiXin() ? 'wechat' : 'h5';
|
||||
return cachedAppType;
|
||||
}
|
||||
// #endif
|
||||
|
||||
const platformMap = {
|
||||
weapp: 'weapp',
|
||||
alipay: 'aliapp',
|
||||
baidu: 'baiduapp',
|
||||
toutiao: 'MP-TOUTIAO',
|
||||
qq: 'MP-QQ',
|
||||
kuaishou: 'kuaishou',
|
||||
jd: 'jd',
|
||||
'360': '360',
|
||||
xhs: 'xhs',
|
||||
harmony: 'harmony',
|
||||
app: 'app',
|
||||
pc: 'pc'
|
||||
};
|
||||
|
||||
cachedAppType = platformMap[platform] || 'unknown';
|
||||
return cachedAppType;
|
||||
},
|
||||
|
||||
/**
|
||||
* 获取平台类型名称 (用于显示)
|
||||
* @returns {string} app_type_name 值
|
||||
*/
|
||||
getAppTypeName() {
|
||||
if (cachedAppTypeName) {
|
||||
return cachedAppTypeName;
|
||||
}
|
||||
|
||||
const platform = this.detect();
|
||||
|
||||
// #ifdef H5
|
||||
if (platform === 'h5') {
|
||||
cachedAppTypeName = this.isWeiXin()
|
||||
? _t('common.platform.wechatOfficialAccount', '微信公众号')
|
||||
: _t('common.platform.h5', 'H5');
|
||||
return cachedAppTypeName;
|
||||
}
|
||||
// #endif
|
||||
|
||||
const platformNameMap = {
|
||||
weapp: _t('common.platform.wechatMiniProgram', '微信小程序'),
|
||||
alipay: _t('common.platform.alipayMiniProgram', '支付宝小程序'),
|
||||
baidu: _t('common.platform.baiduMiniProgram', '百度小程序'),
|
||||
toutiao: _t('common.platform.toutiaoMiniProgram', '头条小程序'),
|
||||
qq: _t('common.platform.qqMiniProgram', 'QQ小程序'),
|
||||
kuaishou: _t('common.platform.kuaishouMiniProgram', '快手小程序'),
|
||||
jd: _t('common.platform.jdMiniProgram', '京东小程序'),
|
||||
'360': _t('common.platform.miniProgram360', '360小程序'),
|
||||
xhs: _t('common.platform.xhsMiniProgram', '小红书小程序'),
|
||||
harmony: _t('common.platform.harmonyService', '鸿蒙元服务'),
|
||||
app: _t('common.platform.app', 'APP'),
|
||||
pc: _t('common.platform.pc', 'PC端'),
|
||||
};
|
||||
|
||||
cachedAppTypeName = platformNameMap[platform] || _t('common.platform.unknown', '未知平台');
|
||||
return cachedAppTypeName;
|
||||
},
|
||||
|
||||
/**
|
||||
* 判断是否运行在微信浏览器中 (H5环境)
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isWeiXin() {
|
||||
// #ifdef H5
|
||||
return navigator.userAgent.toLowerCase().includes('micromessenger');
|
||||
// #endif
|
||||
return false;
|
||||
},
|
||||
|
||||
/**
|
||||
* 判断是否是小程序环境
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isMiniProgram() {
|
||||
const platform = this.detect();
|
||||
const miniProgramPlatforms = ['weapp', 'alipay', 'baidu', 'toutiao', 'qq', 'kuaishou', 'jd', '360', 'xhs', 'harmony'];
|
||||
return miniProgramPlatforms.includes(platform);
|
||||
},
|
||||
|
||||
/**
|
||||
* 判断是否是移动端 (小程序或H5或APP)
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isMobile() {
|
||||
const platform = this.detect();
|
||||
return platform !== 'pc' && platform !== 'unknown';
|
||||
},
|
||||
|
||||
/**
|
||||
* 获取完整的平台信息对象
|
||||
* @returns {Object} 包含 platform, appType, appTypeName
|
||||
*/
|
||||
getPlatformInfo() {
|
||||
return {
|
||||
platform: this.detect(),
|
||||
appType: this.getAppType(),
|
||||
appTypeName: this.getAppTypeName()
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* 清除缓存 (用于测试或需要重新检测的场景)
|
||||
*/
|
||||
clearCache() {
|
||||
cachedPlatform = null;
|
||||
cachedAppType = null;
|
||||
cachedAppTypeName = null;
|
||||
}
|
||||
};
|
||||
|
||||
export default Platform;
|
||||
993
common/js/privacy.js
Normal file
993
common/js/privacy.js
Normal file
@@ -0,0 +1,993 @@
|
||||
/**
|
||||
* 全局隐私协议管理器(单例)
|
||||
*
|
||||
* 职责:
|
||||
* 1. 统一判断是否需要弹窗(storage + 平台级隐私状态)
|
||||
* 2. 通过 uni.$emit('privacy:show') 通知当前页面的 privacy-popup 组件弹窗
|
||||
* 3. 用户同意后写 storage,拒绝后不写(允许下次再弹)
|
||||
* 4. 只弹一次:同意后永不再弹
|
||||
* 5. 事件补偿:若 emit 时无监听者,保留 _pendingShow,页面 mounted 时补偿弹窗
|
||||
*
|
||||
* 平台差异:
|
||||
* H5: 仅查 storage
|
||||
* 微信小程序: wx.getPrivacySetting() 查平台级隐私状态
|
||||
* 鸿蒙元服务: has.getPrivacySetting() 查平台级隐私状态
|
||||
*
|
||||
* 事件:
|
||||
* uni.$emit('privacy:show') — 通知当前页面组件弹窗
|
||||
* uni.$emit('privacy:agreed') — 用户已同意
|
||||
* uni.$emit('privacy:disagreed') — 用户已拒绝
|
||||
* uni.$emit('privacy:closeOthers') — 通知其他页面关闭弹窗
|
||||
* uni.$emit('privacy:rules-updated') — URL/路由规则被应用/融合后触发 (远程下发后热更新)
|
||||
*
|
||||
* 使用:
|
||||
* App.vue onLaunch (boot完成后): await PrivacyManager.show()
|
||||
* privacy-popup.vue: mounted 中 uni.$on('privacy:show') + popPendingShow() 补偿
|
||||
* privacy-popup.vue: handleAgree 中 PrivacyManager.agree()
|
||||
* privacy-popup.vue: handleDisagree 中 PrivacyManager.disagree()
|
||||
*/
|
||||
|
||||
const STORAGE_KEY = 'privacyAgreed';
|
||||
|
||||
// 内部状态
|
||||
let _needShow = false; // 是否需要弹窗
|
||||
let _hasChecked = false; // 是否已执行过 check
|
||||
let _pendingShow = false; // emit 时无监听者的补偿标志
|
||||
// URL/路由规则已经做过决策 (避免鸿蒙兜底在白名单模式下错误弹窗)
|
||||
let _urlRuleDecided = false;
|
||||
|
||||
// ============================================================
|
||||
// 弹窗"实际显示"状态 (由 privacy-popup 通过 privacy:popup-state 事件同步)
|
||||
// 关键: _pendingShow 会被 consumePendingShow 清零, 不能代表"实际显示"
|
||||
// 双阶段弹窗重评估要用这个真实状态判断
|
||||
let _popupActuallyShowing = false
|
||||
|
||||
// ============================================================
|
||||
/**
|
||||
* 同步读取 storage + 平台决策 (H5 + 不依赖 storage 的情况)
|
||||
* 用于"已同意过"的快速路径, 不走 async checkPrivacy
|
||||
* @returns {{needAuthorization: boolean, fromCache: boolean}}
|
||||
*/
|
||||
function checkPrivacySync() {
|
||||
// H5 + 其他非微信/快应用/鸿蒙平台: storage 决定一切
|
||||
const storageAgreed = getStorageAgreed()
|
||||
return {
|
||||
needAuthorization: !storageAgreed,
|
||||
fromCache: storageAgreed,
|
||||
}
|
||||
}
|
||||
|
||||
// URL/路由级别隐私弹窗规则
|
||||
// mode:
|
||||
// 'all' - 始终走弹窗检查(默认, 向后兼容)
|
||||
// 'only' - 白名单: 只有命中 patterns 的页面才走弹窗检查, 其他场景一律跳过
|
||||
// 'skip' - 黑名单: 命中 patterns 的页面跳过弹窗, 其他场景走弹窗检查
|
||||
// 匹配方式: 子串匹配
|
||||
// H5: pathname + search + hash
|
||||
// 小程序/鸿蒙: 当前页面 route + query
|
||||
// patterns 为空数组时:
|
||||
// 'all' → 无规则, 走弹窗检查
|
||||
// 'only' → 视为"没有需要弹窗的页面", 一律跳过
|
||||
// 'skip' → 视为"没有需要跳过的页面", 全部走弹窗检查
|
||||
// ============================================================
|
||||
const PRIVACY_URL_RULES = {
|
||||
mode: 'all',
|
||||
patterns: [],
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取 storage 中的同意状态
|
||||
*/
|
||||
function getStorageAgreed() {
|
||||
try {
|
||||
return !!uni.getStorageSync(STORAGE_KEY);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 微信小程序: 查询平台级隐私设置
|
||||
* @returns {Promise<{needAuthorization: boolean, privacyContractName?: string}>}
|
||||
*/
|
||||
function getWxPrivacySetting() {
|
||||
return new Promise((resolve) => {
|
||||
// #ifdef MP-WEIXIN
|
||||
try {
|
||||
if (wx.getPrivacySetting) {
|
||||
wx.getPrivacySetting({
|
||||
success: (res) => {
|
||||
resolve({
|
||||
needAuthorization: !!res.needAuthorization,
|
||||
privacyContractName: res.privacyContractName || ''
|
||||
});
|
||||
},
|
||||
fail: () => resolve({ needAuthorization: !getStorageAgreed() })
|
||||
});
|
||||
} else {
|
||||
// 低版本基础库,回退到 storage
|
||||
resolve({ needAuthorization: !getStorageAgreed() });
|
||||
}
|
||||
} catch (e) {
|
||||
resolve({ needAuthorization: !getStorageAgreed() });
|
||||
}
|
||||
// #endif
|
||||
// #ifndef MP-WEIXIN
|
||||
resolve({ needAuthorization: !getStorageAgreed() });
|
||||
// #endif
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 快应用: 查询平台级隐私设置
|
||||
* @returns {Promise<{needAuthorization: boolean, privacyContractName?: string}>}
|
||||
*/
|
||||
function getQuickAppPrivacySetting() {
|
||||
return new Promise((resolve) => {
|
||||
// #ifdef QUICKAPP-WEBVIEW
|
||||
try {
|
||||
const has = require('@system.has');
|
||||
if (has && has.getPrivacySetting) {
|
||||
has.getPrivacySetting({
|
||||
success: (res) => {
|
||||
resolve({
|
||||
needAuthorization: !!res.needAuthorization,
|
||||
privacyContractName: res.privacyContractName || ''
|
||||
});
|
||||
},
|
||||
fail: () => resolve({ needAuthorization: !getStorageAgreed() })
|
||||
});
|
||||
return;
|
||||
}
|
||||
} catch (e) {}
|
||||
// #endif
|
||||
// 非快应用环境: 仅查 storage
|
||||
resolve({ needAuthorization: !getStorageAgreed() });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 鸿蒙元服务: 已接入平台隐私托管, 应用层不再调任何系统 API
|
||||
* 仅为兼容历史代码保留此函数 (被 checkPrivacy() 调用), 内部只走 storage 路径
|
||||
* @returns {Promise<{needAuthorization: boolean}>}
|
||||
*/
|
||||
function getHarmonyPrivacySetting() {
|
||||
return new Promise((resolve) => {
|
||||
resolve({ needAuthorization: !getStorageAgreed() });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 综合查询: 平台级隐私状态 + storage 状态
|
||||
* 任一判断为"需要授权"则弹窗
|
||||
* @returns {Promise<{needAuthorization: boolean, privacyContractName?: string}>}
|
||||
*/
|
||||
async function checkPrivacy() {
|
||||
// 微信小程序: 调 wx.getPrivacySetting
|
||||
// 注意: uniapp 不支持 #ifndef 多 || 与嵌套 #ifndef,
|
||||
// 改用回退策略 - 仅微信走异步 API, 其他平台走 sync checkPrivacySync()
|
||||
// 调用方 (show) 已经对 storage 已同意做了 sync 短路 (参见 checkPrivacySync()),
|
||||
// 这里只处理 storage 未同意情况下的 async API 调用。
|
||||
// #ifdef MP-WEIXIN
|
||||
if (typeof wx !== 'undefined' && wx.getPrivacySetting) {
|
||||
return await getWxPrivacySetting();
|
||||
}
|
||||
// #endif
|
||||
|
||||
// 快应用: 调 has.getPrivacySetting
|
||||
// #ifdef QUICKAPP-WEBVIEW
|
||||
if (typeof has !== 'undefined' && has.getPrivacySetting) {
|
||||
return await getQuickAppPrivacySetting();
|
||||
}
|
||||
// #endif
|
||||
|
||||
// 鸿蒙元服务: 调系统 getPrivacySetting (无 API 时 getHarmonyPrivacySetting 内部回退 storage)
|
||||
// H5 / 其他平台: 仅查 storage
|
||||
return checkPrivacySync();
|
||||
}
|
||||
|
||||
/**
|
||||
* 取当前页面的"路径字符串"
|
||||
* H5: location.pathname + search + hash
|
||||
* 微信小程序: 当前页面 route + query (例: pages/index/index?id=1)
|
||||
* 鸿蒙元服务: 当前页面 route + query (同小程序)
|
||||
* @param {Object} [fallback] - 兜底路径, 用于 onLaunch 等还没 getCurrentPages 的时机
|
||||
* H5: { pathname, search, hash }
|
||||
* 小程序/鸿蒙: { route, query }
|
||||
* @returns {string}
|
||||
*/
|
||||
function getCurrentPathString(fallback) {
|
||||
// H5
|
||||
// #ifdef H5
|
||||
// H5 模式下优先用 getCurrentPages() 拿 uniapp route (history/hash 都适配)
|
||||
// 兜底: window.location.pathname + search + hash
|
||||
try {
|
||||
if (typeof getCurrentPages === 'function') {
|
||||
const pages = getCurrentPages()
|
||||
const cur = pages[pages.length - 1]
|
||||
if (cur && cur.route) {
|
||||
const route = cur.route
|
||||
const query = cur.options
|
||||
let queryStr = ''
|
||||
if (query && typeof query === 'object' && Object.keys(query).length) {
|
||||
queryStr = '?' + Object.keys(query)
|
||||
.filter(k => query[k] !== undefined && query[k] !== null && query[k] !== '')
|
||||
.map(k => k + '=' + encodeURIComponent(query[k]))
|
||||
.join('&')
|
||||
}
|
||||
return '/' + String(route).replace(/^\/+/, '') + queryStr
|
||||
}
|
||||
}
|
||||
} catch (e) { /* ignore, fall through to location */ }
|
||||
// 兜底: window.location (含 history 路由 + base)
|
||||
if (typeof window !== 'undefined' && window.location) {
|
||||
const pathname = (fallback && fallback.pathname) || window.location.pathname || ''
|
||||
const search = (fallback && fallback.search !== undefined ? fallback.search : window.location.search) || ''
|
||||
const hash = (fallback && fallback.hash !== undefined ? fallback.hash : window.location.hash) || ''
|
||||
return pathname + search + hash
|
||||
}
|
||||
return ''
|
||||
// #endif
|
||||
|
||||
// 微信小程序 / 鸿蒙元服务 / 其他支持 getCurrentPages 的端
|
||||
// #ifndef H5
|
||||
try {
|
||||
const pages = (typeof getCurrentPages === 'function') ? getCurrentPages() : []
|
||||
let route = ''
|
||||
let query = null
|
||||
const cur = pages[pages.length - 1]
|
||||
if (cur) {
|
||||
route = cur.route || ''
|
||||
query = cur.options
|
||||
}
|
||||
// 兜底: onLaunch 时 getCurrentPages 还没页面, 用 fallback
|
||||
if (!route && fallback) {
|
||||
route = fallback.route || ''
|
||||
query = fallback.query
|
||||
}
|
||||
if (!route) return ''
|
||||
let queryStr = ''
|
||||
if (query && typeof query === 'object' && Object.keys(query).length) {
|
||||
queryStr = '?' + Object.keys(query)
|
||||
.filter(k => query[k] !== undefined && query[k] !== null && query[k] !== '')
|
||||
.map(k => k + '=' + encodeURIComponent(query[k]))
|
||||
.join('&')
|
||||
}
|
||||
return '/' + String(route).replace(/^\/+/, '') + queryStr
|
||||
} catch (e) {
|
||||
return ''
|
||||
}
|
||||
// #endif
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 path 是否命中 patterns 之一
|
||||
* 匹配规则 (双通道, 任一命中即算命中):
|
||||
* 1. 子串匹配: path.indexOf(p) !== -1 (兼容 /pages/index/index 这种完整路径)
|
||||
* 2. 结尾匹配: path 以 p 结尾 (兼容 subPackage 路径 /pages_tool/member/index 命中 "member/index")
|
||||
* 这样业务侧既可以写完整路径也可以写相对路径
|
||||
*/
|
||||
function matchAny(path, patterns) {
|
||||
if (!path || !Array.isArray(patterns)) return false
|
||||
return patterns.some((p) => {
|
||||
if (!p || typeof p !== 'string') return false
|
||||
return path.indexOf(p) !== -1 || path.endsWith(p)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 PRIVACY_URL_RULES 判断当前 URL/路由是否要走弹窗检查
|
||||
* @param {Object} [fallback] - 传给 getCurrentPathString 的兜底路径
|
||||
* @returns {boolean} true=本次应走弹窗检查, false=本次跳过
|
||||
*/
|
||||
function shouldShowByUrlRule(fallback) {
|
||||
const mode = PRIVACY_URL_RULES.mode || 'all'
|
||||
const patterns = PRIVACY_URL_RULES.patterns || []
|
||||
if (!Array.isArray(patterns) || !patterns.length) {
|
||||
// 空 patterns 时:
|
||||
// 'all' → 无规则, 走检查
|
||||
// 'only' → 没有需要弹窗的页面, 一律跳过
|
||||
// 'skip' → 没有需要跳过的页面, 全部走检查
|
||||
return mode === 'all' || mode === 'skip'
|
||||
}
|
||||
const path = getCurrentPathString(fallback)
|
||||
const hit = matchAny(path, patterns)
|
||||
if (mode === 'only') return hit
|
||||
if (mode === 'skip') return !hit
|
||||
return true // mode === 'all'
|
||||
}
|
||||
|
||||
/**
|
||||
* 覆盖 URL/路由级别隐私弹窗规则
|
||||
* @param {Object} rules
|
||||
* @param {'all'|'only'|'skip'} [rules.mode='all']
|
||||
* @param {string[]} [rules.patterns=[]]
|
||||
*/
|
||||
function setUrlRules(rules) {
|
||||
if (!rules || typeof rules !== 'object') return
|
||||
if (rules.mode && ['all', 'only', 'skip'].indexOf(rules.mode) !== -1) {
|
||||
PRIVACY_URL_RULES.mode = rules.mode
|
||||
}
|
||||
if (Array.isArray(rules.patterns)) {
|
||||
PRIVACY_URL_RULES.patterns = rules.patterns.slice()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 持久化键 (与 privacyAgreed 同维度, 方便 uniacid 隔离)
|
||||
* 由 App.vue 在 setUrlRules 前注入前缀: privacy_url_rules_<uniacid>
|
||||
*/
|
||||
let _storageKey = 'privacy_url_rules'
|
||||
|
||||
/**
|
||||
* 从 storage 读取上次持久化的最终规则
|
||||
* 自动过滤 __merge/__source/__ts 元信息, 仅返回纯规则
|
||||
* @returns {Object|null}
|
||||
*/
|
||||
function loadPersistedRules() {
|
||||
try {
|
||||
const raw = uni.getStorageSync(_storageKey)
|
||||
if (!raw) return null
|
||||
const obj = (typeof raw === 'string') ? JSON.parse(raw) : raw
|
||||
if (!obj || typeof obj !== 'object') return null
|
||||
// 过滤元信息
|
||||
return {
|
||||
mode: obj.mode,
|
||||
patterns: Array.isArray(obj.patterns) ? obj.patterns.slice() : [],
|
||||
}
|
||||
} catch (e) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 持久化当前最终规则
|
||||
* 携带 merge 字段 + 时间戳 + 签名, 方便后续热修复/审计/防篡改
|
||||
* @param {Object} rules
|
||||
* @param {Object} [meta] - { merge?: string, source?: string, sign?: string }
|
||||
*/
|
||||
function persistRules(rules, meta) {
|
||||
try {
|
||||
const final = Object.assign({}, rules || PRIVACY_URL_RULES, {
|
||||
__merge: (meta && meta.merge) || (rules && rules.__merge) || 'replace',
|
||||
__source: (meta && meta.source) || 'base',
|
||||
__ts: Date.now(),
|
||||
__sign: (meta && meta.sign) || (rules && rules.__sign) || '',
|
||||
})
|
||||
uni.setStorageSync(_storageKey, final)
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算远程 patch 的签名 (前端简易实现, 与后端 hash_hmac 对齐)
|
||||
* 后端约定: hash_hmac('sha256', JSON.stringify(patch), secret)
|
||||
* 前端: 用 btoa 或 uni.arrayBufferToBase64 模拟 (弱校验, 防简单篡改)
|
||||
* 真正的强校验建议用 crypto-js (引入成本)
|
||||
* @param {Object} patch - 远程下发对象
|
||||
* @param {string} secret
|
||||
* @returns {string}
|
||||
*/
|
||||
function computeSign(patch, secret) {
|
||||
if (!secret || !patch) return ''
|
||||
try {
|
||||
const payload = JSON.stringify(patch)
|
||||
let _b64 = ''
|
||||
if (typeof btoa === 'function') {
|
||||
_b64 = btoa(payload)
|
||||
} else if (typeof uni !== 'undefined' && typeof uni.arrayBufferToBase64 === 'function') {
|
||||
const _encoder = (typeof TextEncoder !== 'undefined') ? new TextEncoder() : null
|
||||
if (_encoder) {
|
||||
_b64 = uni.arrayBufferToBase64(_encoder.encode(payload).buffer)
|
||||
}
|
||||
}
|
||||
if (!_b64) return ''
|
||||
// 取前 32 位作为 signature (与 lang-loader.js validateSign 保持一致)
|
||||
return _b64.replace(/[^a-zA-Z0-9]/g, '').slice(0, 32)
|
||||
} catch (e) {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验远程 patch
|
||||
* - signSecret 未配置 → 通过 (向后兼容)
|
||||
* - patch.sign 缺失 → 通过 (后端未启用签名)
|
||||
* - patch.sign 不匹配 → 拒绝 (返回 false)
|
||||
* @param {Object} patch - 远程下发 { mode, patterns, merge, sign? }
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function verifyRemotePatch(patch) {
|
||||
if (!patch || typeof patch !== 'object') return false
|
||||
// 业务侧未配置密钥 → 跳过校验
|
||||
if (!_signSecret) return true
|
||||
// patch 未带 sign 字段 → 后端未启用签名, 跳过校验 (兼容旧版本后端)
|
||||
if (!patch.sign) return true
|
||||
const expected = computeSign(patch, _signSecret)
|
||||
const ok = (expected && expected === patch.sign)
|
||||
if (!ok) {
|
||||
console.warn('[privacy] remote patch sign invalid', {
|
||||
expected: expected.slice(0, 8),
|
||||
received: String(patch.sign).slice(0, 8),
|
||||
})
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并本地 base 与远程 patch
|
||||
* mode:
|
||||
* patch.mode 缺失/非合法值 → 用 base.mode
|
||||
* patch.mode 合法 → 用 patch.mode (远程覆盖)
|
||||
* patterns:
|
||||
* merge = 'replace' → 用 patch.patterns (远程整体替换, 默认)
|
||||
* merge = 'union' → base + patch 去重合并 (子串匹配: 较长的子串已包含较短, 保留较长)
|
||||
* merge = 'intersect'→ 仅保留同时出现在 base 和 patch 的项
|
||||
* merge 缺失/未知 → 退化为 'replace'
|
||||
* patch.patterns 缺失/非数组 → 用 base.patterns
|
||||
*
|
||||
* @param {Object} base - 本地声明的基础规则 { mode, patterns }
|
||||
* @param {Object} patch - 远程下发的补丁 { mode?, patterns?, merge? }
|
||||
* @returns {{ mode: string, patterns: string[], merge: string }}
|
||||
*/
|
||||
function mergeRules(base, patch) {
|
||||
const baseMode = (base && base.mode) || 'all'
|
||||
const basePatterns = (base && Array.isArray(base.patterns)) ? base.patterns.slice() : []
|
||||
|
||||
if (!patch || typeof patch !== 'object') {
|
||||
return { mode: baseMode, patterns: basePatterns, merge: 'replace' }
|
||||
}
|
||||
|
||||
// mode: 远程值合法则覆盖
|
||||
let mode = baseMode
|
||||
if (patch.mode && ['all', 'only', 'skip'].indexOf(patch.mode) !== -1) {
|
||||
mode = patch.mode
|
||||
}
|
||||
|
||||
// patterns + merge
|
||||
const merge = (patch.merge && ['replace', 'union', 'intersect'].indexOf(patch.merge) !== -1)
|
||||
? patch.merge
|
||||
: 'replace'
|
||||
|
||||
let patterns
|
||||
if (!Array.isArray(patch.patterns)) {
|
||||
patterns = basePatterns
|
||||
} else if (merge === 'replace') {
|
||||
patterns = patch.patterns.slice()
|
||||
} else if (merge === 'union') {
|
||||
patterns = dedupeUnion(basePatterns, patch.patterns)
|
||||
} else { // intersect
|
||||
patterns = basePatterns.filter(p => patch.patterns.indexOf(p) !== -1)
|
||||
}
|
||||
|
||||
return { mode, patterns, merge }
|
||||
}
|
||||
|
||||
/**
|
||||
* 去重合并 (子串匹配: 若 a 包含 b, b 可视为冗余)
|
||||
* 简单实现: 直接 concat 后去重, 复杂度可接受 (规则通常 < 50 条)
|
||||
*/
|
||||
function dedupeUnion(a, b) {
|
||||
const all = (a || []).concat(b || [])
|
||||
const seen = new Set()
|
||||
const out = []
|
||||
for (const p of all) {
|
||||
if (typeof p !== 'string' || !p) continue
|
||||
if (seen.has(p)) continue
|
||||
seen.add(p)
|
||||
out.push(p)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用"已合并规则"到 PRIVACY_URL_RULES
|
||||
* 触发 'privacy:rules-updated' 事件, 业务侧可监听 (例如想热更新弹窗)
|
||||
* @param {Object} rules
|
||||
* @param {Object} [meta] - { source: 'base'|'remote'|'persisted', patch?: Object }
|
||||
*/
|
||||
function applyMergedRules(rules, meta) {
|
||||
if (!rules || typeof rules !== 'object') return
|
||||
const prevMode = PRIVACY_URL_RULES.mode
|
||||
const prevPatterns = PRIVACY_URL_RULES.patterns.slice()
|
||||
// 记录"应用前 popup 实际显示状态", 用于 reEvaluate 决策
|
||||
// 关键: _pendingShow 会被 consumePendingShow 清零, 不能代表"实际显示"
|
||||
// 必须用 _popupActuallyShowing (由 privacy-popup 主动同步)
|
||||
const prevPopupShowing = _popupActuallyShowing
|
||||
setUrlRules(rules)
|
||||
persistRules(rules, {
|
||||
merge: rules && rules.merge,
|
||||
source: meta && meta.source,
|
||||
sign: meta && meta.patch && meta.patch.sign,
|
||||
})
|
||||
try {
|
||||
uni.$emit && uni.$emit('privacy:rules-updated', {
|
||||
mode: PRIVACY_URL_RULES.mode,
|
||||
patterns: PRIVACY_URL_RULES.patterns.slice(),
|
||||
source: (meta && meta.source) || 'remote',
|
||||
patch: meta && meta.patch,
|
||||
})
|
||||
} catch (e) {}
|
||||
|
||||
// 双阶段弹窗: 远程 patch 在 show() 之后到达时, 强制重评估
|
||||
// 触发条件:
|
||||
// 1. patch 来源是 'remote' (非 'base')
|
||||
// 2. 规则真的变了 (mode/patterns 之一不同)
|
||||
// 3. show() 已经调用过 (_hasChecked=true)
|
||||
// 行为:
|
||||
// - 旧规则没弹 → 新规则要弹 → emit show (popup 重弹)
|
||||
// - 旧规则在弹 → 新规则不该弹 → emit dismiss (popup 关闭)
|
||||
const _source = (meta && meta.source) || 'remote'
|
||||
const _rulesChanged = (
|
||||
prevMode !== PRIVACY_URL_RULES.mode ||
|
||||
prevPatterns.length !== PRIVACY_URL_RULES.patterns.length ||
|
||||
prevPatterns.some((p, i) => p !== PRIVACY_URL_RULES.patterns[i])
|
||||
)
|
||||
if (_source === 'remote' && _rulesChanged && _hasChecked) {
|
||||
// dev-only 日志, 受 __PRIVACY_DEBUG__ 开关控制 (默认开, 生产可通过 DefinePlugin 关)
|
||||
if (typeof console !== 'undefined' && console.log && globalThis.__PRIVACY_DEBUG__) {
|
||||
console.log('[privacy] reEvaluate trigger: prevMode=' + prevMode + ' newMode=' + PRIVACY_URL_RULES.mode + ' prevPopupShowing=' + prevPopupShowing)
|
||||
}
|
||||
// 异步执行, 不阻塞 apply 流程
|
||||
setTimeout(() => { reEvaluateAfterRulesUpdated(prevPopupShowing) }, 0)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 规则更新后的重评估
|
||||
* 场景: 远程 patch 在 show() 之后到达, 本次启动弹窗决策是基于旧规则做的
|
||||
* 现在新规则来了, 必须重评估
|
||||
* 步骤:
|
||||
* 1. 用 prevPopupShowing (popup 实际显示状态) + shouldShowByUrlRule (应用后规则 + 当前 URL) 算差量
|
||||
* 2. prevPopupShowing=false, shouldShow=true → emit show (popup 重弹)
|
||||
* 3. prevPopupShowing=true, shouldShow=false → emit dismiss (popup 关闭)
|
||||
* 4. 其他情况: 状态不变, 不 emit (避免无谓的弹窗抖动)
|
||||
* 边界: 用户已同意过 storage → 不再弹, 但要通知 popup 关闭 (新规则可能把当前页排除)
|
||||
* @param {boolean} prevPopupShowing - 应用规则前的 popup 实际显示状态
|
||||
*/
|
||||
function reEvaluateAfterRulesUpdated(prevPopupShowing) {
|
||||
// dev-only 日志
|
||||
if (typeof console !== 'undefined' && console.log && globalThis.__PRIVACY_DEBUG__) {
|
||||
console.log('[privacy] reEvaluate called prevPopup=' + prevPopupShowing + ' storageAgreed=' + getStorageAgreed())
|
||||
}
|
||||
if (getStorageAgreed()) {
|
||||
// 已同意过 → 不再弹, 但要通知 popup 关闭 (新规则可能把当前页排除)
|
||||
try { uni.$emit && uni.$emit('privacy:re-evaluate', { action: 'noop', reason: 'already-agreed' }) } catch (e) {}
|
||||
return
|
||||
}
|
||||
// 用户未同意 → 走规则决策
|
||||
const shouldShow = shouldShowByUrlRule()
|
||||
const wasShowing = !!prevPopupShowing
|
||||
if (!wasShowing && shouldShow) {
|
||||
// 旧规则没弹, 新规则要弹 → 重新设置 _pendingShow + emit show
|
||||
_needShow = true
|
||||
_pendingShow = true
|
||||
_hasChecked = true
|
||||
_urlRuleDecided = false
|
||||
try { uni.$emit && uni.$emit('privacy:re-evaluate', { action: 'show', reason: 'rules-updated' }) } catch (e) {}
|
||||
} else if (wasShowing && !shouldShow) {
|
||||
// 旧规则在弹, 新规则不该弹 → 撤销 _pendingShow + emit dismiss
|
||||
_needShow = false
|
||||
_pendingShow = false
|
||||
_hasChecked = true
|
||||
_urlRuleDecided = true
|
||||
try { uni.$emit && uni.$emit('privacy:re-evaluate', { action: 'dismiss', reason: 'rules-updated' }) } catch (e) {}
|
||||
}
|
||||
// 其他情况: 状态不变, 不 emit
|
||||
}
|
||||
|
||||
/**
|
||||
* 一站式: 应用本地 base → 若有远程 patch 则融合 → 持久化 → 触发事件
|
||||
* 无远程 patch 时, base 直接生效 (向后兼容)
|
||||
* @param {Object} base - 本地基础规则
|
||||
* @param {Object} [patch] - 远程下发的 patch (可空)
|
||||
* @returns {{ mode: string, patterns: string[], merge: string }}
|
||||
*/
|
||||
function applyWithMerge(base, patch) {
|
||||
// 签名校验: 远程 patch 不合法 → 静默拒绝, 退回 base
|
||||
// (业务侧可通过 PrivacyManager.verifyRemotePatch() 单独调用)
|
||||
if (patch && !verifyRemotePatch(patch)) {
|
||||
console.warn('[privacy] applyWithMerge: remote patch sign invalid, fallback to base')
|
||||
const merged = mergeRules(base, null)
|
||||
applyMergedRules(merged, { source: 'base', patch: null })
|
||||
return merged
|
||||
}
|
||||
const merged = mergeRules(base, patch)
|
||||
applyMergedRules(merged, { source: patch ? 'remote' : 'base', patch })
|
||||
return merged
|
||||
}
|
||||
|
||||
// 本地 base 规则 (由 App.vue 通过 setBaseRules 登记)
|
||||
// 供 store/index.js 的 init action 在收到远程 patch 时读取
|
||||
let _baseRules = { mode: 'all', patterns: [] }
|
||||
|
||||
// 外部注入的 readyWaiters (由 config-external.js ConfigExternal 持有)
|
||||
// 兼容老用法: 业务侧可直接传 readyGuard, 也可走 ConfigExternal.setReadyWaiters 通道
|
||||
let _externalReadyGuard = null
|
||||
let _externalBootTimeout = 6000
|
||||
let _externalWaitChannels = { lang: true, theme: true, themeOverride: true, remoteConfig: true }
|
||||
|
||||
// 远程 patch 签名密钥 (与 langConfig.remote.signSecret 同构)
|
||||
// 业务侧通过 setSignSecret(secret) 或 privacyConfig.signSecret 注入
|
||||
let _signSecret = ''
|
||||
|
||||
// 远程 patch 签名 (在持久化时被写入 storage 的 __sign 字段, 供后续审计/防回滚)
|
||||
// 注意: 当前实现不做增量校验, 只在 verifyRemotePatch 内单次校验
|
||||
// 如需增量校验 (防止回滚到旧 patch), 可在此维护 _lastPersistedSign
|
||||
// 每次 applyWithMerge 持久化时记录, 下次启动时与远程 patch 的 sign 字段比对
|
||||
let _lastPersistedSign = ''
|
||||
|
||||
// ============================================================
|
||||
// 监听 privacy:popup-state 事件 (由 privacy-popup.vue 主动同步弹窗显示状态)
|
||||
// 用于双阶段弹窗的精确重评估 (reEvaluateAfterRulesUpdated)
|
||||
// 这里挂一个全局监听, 模块加载时就生效
|
||||
// ============================================================
|
||||
;(function _installPopupStateListener() {
|
||||
try {
|
||||
if (typeof uni === 'undefined' || !uni.$on) return
|
||||
uni.$on('privacy:popup-state', (info) => {
|
||||
if (info && typeof info.showing === 'boolean') {
|
||||
_popupActuallyShowing = info.showing
|
||||
}
|
||||
})
|
||||
} catch (e) {}
|
||||
})()
|
||||
|
||||
const PrivacyManager = {
|
||||
/**
|
||||
* 同步检查 storage 中的同意状态(快速判断,不查平台)
|
||||
* @returns {boolean} true=需要弹窗, false=不需要
|
||||
*/
|
||||
check() {
|
||||
_needShow = !getStorageAgreed();
|
||||
_hasChecked = true;
|
||||
return _needShow;
|
||||
},
|
||||
|
||||
/**
|
||||
* 同步标记本次跳过弹窗(不查 storage、不写 storage、不弹窗)
|
||||
* 必须在 page mounted 之前调用,避免 onLaunch await 让出事件循环后
|
||||
* privacy-popup.vue 的 consumePendingShow 走兜底分支把弹窗弹出来
|
||||
* 用于 H5 浏览器直访特定 URL(子串匹配)时不让隐私弹窗挡住
|
||||
*/
|
||||
markSkipped() {
|
||||
_needShow = false;
|
||||
_hasChecked = true;
|
||||
_pendingShow = false;
|
||||
_urlRuleDecided = true; // 同步决策, 鸿蒙兜底不应再弹
|
||||
},
|
||||
|
||||
/**
|
||||
* 触发弹窗(如果需要)
|
||||
* 由 App.vue onLaunch 在 boot 完成后调用
|
||||
* 异步查询平台隐私状态,设置 _pendingShow 标志
|
||||
* 页面组件 mounted 时通过 consumePendingShow() 消费标志并弹窗
|
||||
* 不直接 emit 事件,避免 emit + 补偿双触发
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @param {boolean} [options.skip=false] true=本次跳过弹窗(不写 storage,下次正常访问其他页面还会弹)
|
||||
* @param {Object} [options.urlFallback] 首次启动 onLaunch 时 getCurrentPages 还没有页面,
|
||||
* 可传入 onLaunch options 兜底:
|
||||
* H5: { pathname, search, hash }
|
||||
* 小程序/鸿蒙: { route, query }
|
||||
* @param {Promise|Function} [options.readyGuard] 外部 readiness 守卫 (例如 i18n/theme),
|
||||
* show() 会 await 它再继续, 保证弹窗在外部资源就绪后才决策.
|
||||
* 超时保护: 业务侧应保证 guard 自身有超时, 否则会一直 hang.
|
||||
*/
|
||||
async show(options = {}) {
|
||||
const fallback = options && options.urlFallback ? options.urlFallback : null
|
||||
|
||||
// 外部 readiness 守卫: 等业务侧 promise 再继续
|
||||
// 优先级: options.readyGuard (调用方显式传) > _externalReadyGuard (ConfigExternal 注入)
|
||||
// 场景: App.vue onLaunch 把 i18n/theme/remote-config 的 await 链作为 guard 传入
|
||||
// 这样无论 show() 在哪里调用, 都保证弹窗决策时外部资源已就绪
|
||||
const _guard = (options && typeof options.readyGuard !== 'undefined')
|
||||
? options.readyGuard
|
||||
: _externalReadyGuard
|
||||
if (typeof _guard !== 'undefined' && _guard !== null) {
|
||||
try {
|
||||
if (_guard && typeof _guard.then === 'function') {
|
||||
await _guard
|
||||
} else if (typeof _guard === 'function') {
|
||||
await _guard()
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('[privacy] readyGuard fail', e)
|
||||
}
|
||||
}
|
||||
|
||||
// 主动跳过: 不查 storage、不写 storage、不弹窗
|
||||
// 用于 H5 浏览器直接访问特定 URL(子串匹配)时不让隐私弹窗挡住
|
||||
if (options && options.skip) {
|
||||
_needShow = false;
|
||||
_hasChecked = true;
|
||||
_pendingShow = false;
|
||||
_urlRuleDecided = true; // 同步决策, 鸿蒙兜底不应再弹
|
||||
return;
|
||||
}
|
||||
|
||||
// URL/路由规则判断
|
||||
// mode='only' 且未命中 patterns → 跳过
|
||||
// mode='skip' 且命中 patterns → 跳过
|
||||
// 其他情况 → 继续走 storage + 平台检查
|
||||
if (!shouldShowByUrlRule(fallback)) {
|
||||
_needShow = false;
|
||||
_hasChecked = true;
|
||||
_pendingShow = false;
|
||||
_urlRuleDecided = true; // 已决策, 阻止鸿蒙兜底强制弹窗
|
||||
return;
|
||||
}
|
||||
// URL 规则允许弹, 重置 urlRuleDecided 留给鸿蒙兜底分支判断
|
||||
_urlRuleDecided = false;
|
||||
|
||||
const _storageAgreed = getStorageAgreed();
|
||||
|
||||
// 优化: storage 已同意时直接走同步快速路径, 不调 async checkPrivacy()
|
||||
// 节省 1 个 microtask (~0-4ms, dev 模式更明显)
|
||||
// 注意: 微信小程序/快应用走 checkPrivacy (平台 API 异步)
|
||||
// H5 下 checkPrivacy 内部已 sync 化 (修过), 直接 await 即可
|
||||
// 鸿蒙元服务: 不调任何系统 API, 不弹自建弹窗 (走平台托管)
|
||||
const result = _storageAgreed ? checkPrivacySync() : await checkPrivacy();
|
||||
|
||||
_needShow = result.needAuthorization;
|
||||
_hasChecked = true;
|
||||
|
||||
if (!_needShow) {
|
||||
return;
|
||||
}
|
||||
|
||||
// #ifdef MP-HARMONY
|
||||
// 鸿蒙元服务: 已接入平台隐私托管, 由鸿蒙系统自动弹出系统级隐私弹窗
|
||||
// 应用层不再 emit 'privacy:show' 触发自建 privacy-popup.vue
|
||||
// 标记已决策, 防止 consumePendingShow 兜底分支在 page mounted 时再次弹自建弹窗
|
||||
_needShow = false;
|
||||
_pendingShow = false;
|
||||
_urlRuleDecided = true;
|
||||
console.log('[privacy] MP-HARMONY: 已委托鸿蒙平台隐私托管, 不触发自建弹窗');
|
||||
return;
|
||||
// #endif
|
||||
|
||||
// 其他平台: 设置待弹窗标志 + emit 触发自建弹窗
|
||||
// 已 mounted 的页面组件通过事件接收
|
||||
// 未 mounted 的页面组件 mounted 时通过 consumePendingShow 补偿
|
||||
_pendingShow = true;
|
||||
|
||||
// 通知已 mounted 的页面组件(如果有监听者)
|
||||
try { uni.$emit('privacy:show'); } catch (e) {}
|
||||
|
||||
// 若组件已接收事件并弹窗, 会在 handlePrivacyShow 中调 consumePendingShow 清除 _pendingShow
|
||||
// 若无监听者, _pendingShow 保持 true, 等页面 mounted 时补偿
|
||||
},
|
||||
|
||||
/**
|
||||
* 页面 mounted 时补偿检查: 若 show() 在页面 mounted 之前 emit 了事件
|
||||
* 此方法返回 true 并清除标志,页面组件据此自动弹窗
|
||||
*
|
||||
* 历史兼容:
|
||||
* Lang.boot() 可能 hang, PrivacyManager.show() 可能从未被调用过;
|
||||
* 此时 _pendingShow 仍是默认 false, 但用户从未同意过隐私, 必须强制弹一次。
|
||||
* 所以增加 storage 检测: 用户未同意也返回 true (补偿弹窗)。
|
||||
*
|
||||
* 鸿蒙元服务(双轨制):
|
||||
* 已接入平台隐私托管, 由鸿蒙系统自动弹出系统级隐私弹窗,
|
||||
* 应用层不再 emit/弹自建弹窗, 兜底分支也必须返回 false, 否则会与
|
||||
* 鸿蒙系统级弹窗叠加出现"多次弹出"。
|
||||
* @returns {boolean} true=需要弹窗,false=不需要
|
||||
*/
|
||||
consumePendingShow() {
|
||||
// #ifdef MP-HARMONY
|
||||
// 鸿蒙元服务: 已接入平台隐私托管, 不弹自建弹窗
|
||||
return false;
|
||||
// #endif
|
||||
|
||||
if (_pendingShow && _needShow) {
|
||||
_pendingShow = false;
|
||||
return true;
|
||||
}
|
||||
// 兜底: PrivacyManager.show() 没跑过 + 用户没同意过 storage → 必须弹
|
||||
// 同一次进程内只补一次,避免隐私弹窗被反复触发
|
||||
// 关键: URL/路由规则已经决策过 "本次跳过" 时, 不应触发兜底弹窗 (白名单场景)
|
||||
if (!_hasChecked && !_pendingShow && !_urlRuleDecided && !getStorageAgreed()) {
|
||||
_pendingShow = false;
|
||||
_needShow = true;
|
||||
_hasChecked = true;
|
||||
return true;
|
||||
}
|
||||
_pendingShow = false;
|
||||
return false;
|
||||
},
|
||||
|
||||
/**
|
||||
* 用户同意:写 storage,标记不再弹
|
||||
* 由 privacy-popup.vue 的 handleAgree 调用
|
||||
*/
|
||||
agree() {
|
||||
try { uni.setStorageSync(STORAGE_KEY, true); } catch (e) {}
|
||||
_needShow = false;
|
||||
_pendingShow = false;
|
||||
try { uni.$emit('privacy:agreed'); } catch (e) {}
|
||||
},
|
||||
|
||||
/**
|
||||
* 用户拒绝:不写 storage,允许下次再弹
|
||||
* 由 privacy-popup.vue 的 handleDisagree 调用
|
||||
*/
|
||||
disagree() {
|
||||
_needShow = false;
|
||||
_pendingShow = false;
|
||||
try { uni.$emit('privacy:disagreed'); } catch (e) {}
|
||||
},
|
||||
|
||||
/**
|
||||
* 当前是否需要弹窗(供页面查询)
|
||||
* @returns {boolean}
|
||||
*/
|
||||
needShow() {
|
||||
return _needShow;
|
||||
},
|
||||
|
||||
/**
|
||||
* 是否已执行过 check
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasChecked() {
|
||||
return _hasChecked;
|
||||
},
|
||||
|
||||
/**
|
||||
* 配置 URL/路由级别隐私弹窗规则
|
||||
* @param {Object} rules
|
||||
* @param {'all'|'only'|'skip'} [rules.mode='all']
|
||||
* 'all' - 始终走弹窗检查(默认)
|
||||
* 'only' - 白名单: 只有命中 patterns 才弹
|
||||
* 'skip' - 黑名单: 命中 patterns 跳过
|
||||
* @param {string[]} [rules.patterns=[]]
|
||||
* 子串匹配, H5: pathname+search+hash, 小程序/鸿蒙: route+query
|
||||
*/
|
||||
setUrlRules(rules) {
|
||||
setUrlRules(rules)
|
||||
},
|
||||
|
||||
/**
|
||||
* 当前 URL/路由规则下是否要走弹窗检查
|
||||
* @param {Object} [fallback] 兜底路径(同 show 的 urlFallback)
|
||||
* @returns {boolean}
|
||||
*/
|
||||
shouldShowByUrlRule(fallback) {
|
||||
return shouldShowByUrlRule(fallback)
|
||||
},
|
||||
|
||||
/**
|
||||
* 应用本地 base + 远程 patch 的融合结果
|
||||
* - patch=null/缺 → 仅应用 base (并持久化)
|
||||
* - patch 存在 → 走 mergeRules 融合
|
||||
* 应用后 emit 'privacy:rules-updated'
|
||||
* @param {Object} base 本地基础规则 { mode, patterns }
|
||||
* @param {Object} [patch] 远程下发 { mode?, patterns?, merge? }
|
||||
* @returns {{ mode: string, patterns: string[], merge: string }}
|
||||
*/
|
||||
applyWithMerge(base, patch) {
|
||||
return applyWithMerge(base, patch)
|
||||
},
|
||||
|
||||
/**
|
||||
* 仅合并 (不写入), 方便上层预览或 dry-run
|
||||
* @param {Object} base
|
||||
* @param {Object} patch
|
||||
*/
|
||||
mergeRules(base, patch) {
|
||||
return mergeRules(base, patch)
|
||||
},
|
||||
|
||||
/**
|
||||
* 读取上次持久化的最终规则 (跨冷启动恢复)
|
||||
* @returns {Object|null}
|
||||
*/
|
||||
loadPersistedRules() {
|
||||
return loadPersistedRules()
|
||||
},
|
||||
|
||||
/**
|
||||
* 设置持久化 key (用于 uniacid 隔离), 由 App.vue 注入
|
||||
* @param {string} key
|
||||
*/
|
||||
setStorageKey(key) {
|
||||
if (typeof key === 'string' && key) _storageKey = key
|
||||
},
|
||||
|
||||
/**
|
||||
* 登记本地 base 规则 (由 App.vue 在启动时调用)
|
||||
* 供后续远程下发时 mergeRules 读取
|
||||
* @param {Object} rules
|
||||
*/
|
||||
setBaseRules(rules) {
|
||||
if (!rules || typeof rules !== 'object') return
|
||||
_baseRules = {
|
||||
mode: rules.mode || 'all',
|
||||
patterns: Array.isArray(rules.patterns) ? rules.patterns.slice() : [],
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 读取本地 base 规则 (供 store/index.js init 远程 patch 融合)
|
||||
* @returns {{ mode: string, patterns: string[] }}
|
||||
*/
|
||||
__getBaseRules() {
|
||||
return { mode: _baseRules.mode, patterns: _baseRules.patterns.slice() }
|
||||
},
|
||||
|
||||
/**
|
||||
* 注入外部 readiness 守卫 (由 config-external.js ConfigExternal 调用)
|
||||
* show() 时若无 options.readyGuard, 内部使用此 promise
|
||||
* @param {Promise|Function|null} guard
|
||||
*/
|
||||
setExternalReadyGuard(guard) {
|
||||
if (guard === null) { _externalReadyGuard = null; return }
|
||||
if (guard && (typeof guard.then === 'function' || typeof guard === 'function')) {
|
||||
_externalReadyGuard = guard
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 注入外部 bootTimeout (由 ConfigExternal.getPrivacyBootTimeout 调用)
|
||||
* @param {number} ms
|
||||
*/
|
||||
setExternalBootTimeout(ms) {
|
||||
if (typeof ms === 'number' && ms > 0) _externalBootTimeout = ms
|
||||
},
|
||||
|
||||
/**
|
||||
* 注入 waitChannels 配置 (隐私弹窗启动期必等通道开关)
|
||||
* @param {Object} channels
|
||||
*/
|
||||
setWaitChannels(channels) {
|
||||
if (channels && typeof channels === 'object') {
|
||||
_externalWaitChannels = Object.assign({}, _externalWaitChannels, channels)
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 注入远程 patch 签名密钥 (与 langConfig.remote.signSecret 同构)
|
||||
* 后端约定: hash_hmac('sha256', JSON.stringify(patch), secret)
|
||||
* 前端: 用 btoa 模拟 (弱校验, 仅防简单篡改)
|
||||
* secret='' → 跳过校验 (向后兼容)
|
||||
* @param {string} secret
|
||||
*/
|
||||
setSignSecret(secret) {
|
||||
_signSecret = (typeof secret === 'string') ? secret : ''
|
||||
},
|
||||
|
||||
/**
|
||||
* 校验远程 patch (业务侧可在 store/init 之外单独调用)
|
||||
* - signSecret 未配置 → true (向后兼容)
|
||||
* - patch.sign 缺失 → true (后端未启用签名)
|
||||
* - patch.sign 不匹配 → false
|
||||
* @param {Object} patch
|
||||
* @returns {boolean}
|
||||
*/
|
||||
verifyRemotePatch(patch) {
|
||||
return verifyRemotePatch(patch)
|
||||
},
|
||||
|
||||
/**
|
||||
* 计算给定 patch 的签名 (供调试/单元测试)
|
||||
* @param {Object} patch
|
||||
* @param {string} [secret] - 不传则用 _signSecret
|
||||
* @returns {string}
|
||||
*/
|
||||
computeSign(patch, secret) {
|
||||
return computeSign(patch, secret || _signSecret)
|
||||
},
|
||||
|
||||
/**
|
||||
* 读取当前生效配置 (供调试/单元测试)
|
||||
*/
|
||||
getReadyConfig() {
|
||||
return {
|
||||
readyGuard: _externalReadyGuard,
|
||||
bootTimeout: _externalBootTimeout,
|
||||
waitChannels: Object.assign({}, _externalWaitChannels),
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export default PrivacyManager;
|
||||
33
common/js/quickapp-pull-refresh.js
Normal file
33
common/js/quickapp-pull-refresh.js
Normal file
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* 快应用宿主环境下的下拉刷新 → 原生 webview.reload() 转发 mixin
|
||||
*
|
||||
* 在已启用 enablePullDownRefresh 的 uniapp 页面 mixin 链中加入本文件,
|
||||
* 当用户在原生快应用 webview 内下拉刷新时,会通过 this.$util.requestQuickAppReload()
|
||||
* 把指令发回快应用 shell(对应 hello.ux onMessage 中的 'reload' 处理);
|
||||
* 其余平台走默认的 uni.stopPullDownRefresh 即可。
|
||||
*
|
||||
* 用法:
|
||||
* import pullReload from '@/common/js/mixins/quickapp-pull-refresh.js';
|
||||
* export default { mixins: [..., pullReload] }
|
||||
*
|
||||
* 注意:
|
||||
* - 请确保对应的 pages.json style 块中开启 "enablePullDownRefresh": true
|
||||
* - 不要在本文件里覆盖 onPullDownRefresh,否则会被本页/上游 mixin 拦截失效
|
||||
*/
|
||||
export default {
|
||||
onPullDownRefresh() {
|
||||
try {
|
||||
if (this.$util && typeof this.$util.requestQuickAppReload === 'function'
|
||||
&& this.$util.requestQuickAppReload()) {
|
||||
// 原生侧 webview.reload() 会把整个 H5 页面替换掉,这里只是兜底停动画
|
||||
setTimeout(() => {
|
||||
try { uni.stopPullDownRefresh(); } catch (_) { /* swallow */ }
|
||||
}, 800);
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[quickapp-pull-refresh] crashed:', e);
|
||||
}
|
||||
try { uni.stopPullDownRefresh(); } catch (_) { /* swallow */ }
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
// 文件分享工具函数
|
||||
import Lang from './lang.js';
|
||||
|
||||
export default {
|
||||
/**
|
||||
* 生成文件预览链接
|
||||
@@ -30,7 +32,7 @@ export default {
|
||||
* @param {string} title - 分享标题,默认使用文件名
|
||||
* @param {string} desc - 分享描述,默认使用固定文案
|
||||
*/
|
||||
shareFile(file, title = file.name, desc = '查看企业文件:' + file.name) {
|
||||
shareFile(file, title = file.name, desc = Lang.lang('share.defaultDesc', { name: file.name })) {
|
||||
// 生成文件预览链接
|
||||
const filePreviewUrl = this.generateFilePreviewUrl(file);
|
||||
|
||||
@@ -44,17 +46,17 @@ export default {
|
||||
url: filePreviewUrl
|
||||
}).catch(err => {
|
||||
console.error('分享失败:', err);
|
||||
uni.showToast({ title: '分享失败', icon: 'none' });
|
||||
uni.showToast({ title: Lang.lang('share.shareFailed'), icon: 'none' });
|
||||
});
|
||||
} else {
|
||||
// 不支持 Web Share API 的浏览器
|
||||
uni.setClipboardData({
|
||||
data: filePreviewUrl,
|
||||
success: () => {
|
||||
uni.showToast({ title: '链接已复制,请粘贴分享', icon: 'success' });
|
||||
uni.showToast({ title: Lang.lang('share.linkCopied'), icon: 'success' });
|
||||
},
|
||||
fail: () => {
|
||||
uni.showToast({ title: '复制失败', icon: 'none' });
|
||||
uni.showToast({ title: Lang.lang('share.copyFailed'), icon: 'none' });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -63,7 +65,7 @@ export default {
|
||||
// #ifdef MP-WEIXIN
|
||||
// 微信小程序分享
|
||||
uni.showActionSheet({
|
||||
itemList: ['发送给朋友', '分享到朋友圈'],
|
||||
itemList: [Lang.lang('share.sendToFriend'), Lang.lang('share.shareToTimeline')],
|
||||
success: (res) => {
|
||||
if (res.tapIndex === 0) {
|
||||
// 发送给朋友
|
||||
@@ -71,10 +73,10 @@ export default {
|
||||
title: title,
|
||||
path: filePreviewUrl,
|
||||
success: () => {
|
||||
uni.showToast({ title: '分享成功', icon: 'success' });
|
||||
uni.showToast({ title: Lang.lang('share.shareSuccess'), icon: 'success' });
|
||||
},
|
||||
fail: () => {
|
||||
uni.showToast({ title: '分享失败', icon: 'none' });
|
||||
uni.showToast({ title: Lang.lang('share.shareFailed'), icon: 'none' });
|
||||
}
|
||||
});
|
||||
} else if (res.tapIndex === 1) {
|
||||
@@ -83,10 +85,10 @@ export default {
|
||||
title: desc,
|
||||
path: filePreviewUrl,
|
||||
success: () => {
|
||||
uni.showToast({ title: '分享成功', icon: 'success' });
|
||||
uni.showToast({ title: Lang.lang('share.shareSuccess'), icon: 'success' });
|
||||
},
|
||||
fail: () => {
|
||||
uni.showToast({ title: '分享失败', icon: 'none' });
|
||||
uni.showToast({ title: Lang.lang('share.shareFailed'), icon: 'none' });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -97,4 +99,4 @@ export default {
|
||||
});
|
||||
// #endif
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
@@ -21,53 +21,35 @@ export default {
|
||||
methods: {
|
||||
// 判断是否已连接
|
||||
checkOpenSocket() {
|
||||
console.log('判断是否已连接');
|
||||
// alert('判断是否已连接')
|
||||
let self = this;
|
||||
uni.sendSocketMessage({
|
||||
data: 'ping',
|
||||
success: (res) => {
|
||||
console.log('连接成功,检查');
|
||||
// alert('连接成功,检查')
|
||||
// self.getChatList();
|
||||
},
|
||||
fail: (err) => { // 未连接打开websocket连接
|
||||
console.log('连接失败');
|
||||
// alert('连接失败')
|
||||
self.openConnection();
|
||||
}
|
||||
});
|
||||
},
|
||||
openConnection() { // 打开连接
|
||||
console.log('打开连接');
|
||||
// alert('打开连接')
|
||||
// uni.closeSocket(); // 确保已经关闭后再重新打开
|
||||
uni.connectSocket({
|
||||
url: config.webSocket,
|
||||
method: 'POST',
|
||||
success(res) {
|
||||
console.log('连接成功 connectSocket=', res);
|
||||
// alert('连接成功 connectSocket=', res);
|
||||
},
|
||||
fail(err) {
|
||||
console.log('连接失败 connectSocket=', err);
|
||||
}
|
||||
});
|
||||
// uni.onSocketOpen((res) => {
|
||||
// console.log('连接成功', res);
|
||||
// });
|
||||
this.onSocketMessage(); // 打开成功监听服务器返回的消息
|
||||
},
|
||||
// 打开成功监听服务器返回的消息
|
||||
onSocketMessage() { // 消息
|
||||
console.log("开始监听");
|
||||
|
||||
let that = this;
|
||||
this.pingInterval = config.pingInterval;
|
||||
this.timeoutObj = null;
|
||||
uni.onSocketMessage((res) => { //type:init,connect,close,string,order,goods
|
||||
let msg = JSON.parse(res.data);
|
||||
console.log("监听该服务器消息", res);
|
||||
if (msg.type == 'close') {
|
||||
clearInterval(that.timeoutObj);
|
||||
that.timeoutObj = null;
|
||||
@@ -141,22 +123,18 @@ export default {
|
||||
},
|
||||
// 检测心跳reset
|
||||
reset() {
|
||||
console.log("检测心跳");
|
||||
clearInterval(this.timeoutObj);
|
||||
this.start(); // 启动心跳
|
||||
},
|
||||
// 启动心跳 start
|
||||
start() {
|
||||
console.log("启动心跳");
|
||||
let self = this;
|
||||
this.timeoutObj = setInterval(function () {
|
||||
uni.sendSocketMessage({
|
||||
data: 'ping',
|
||||
success: (res) => {
|
||||
console.log('连接中....');
|
||||
},
|
||||
fail: (err) => {
|
||||
console.log('连接失败重新连接....');
|
||||
self.openConnection();
|
||||
}
|
||||
});
|
||||
|
||||
698
common/js/splash-state.js
Normal file
698
common/js/splash-state.js
Normal file
@@ -0,0 +1,698 @@
|
||||
// ============================================================
|
||||
// 启动屏单例状态
|
||||
//
|
||||
// 设计要点:
|
||||
// 1. 状态 + 事件双通道: 组件既可 watch visible,也可监听 'splash:hide' 事件
|
||||
// 解决 uni.$emit 在组件挂载前发出就丢失的问题 (memory lesson)
|
||||
// 2. 软隐藏 (softHide): 标记应该 hide, 等组件 mount 后再真正 hide
|
||||
// 解决 onLaunch 跑完 + hide() 早于 page mount 的时序问题
|
||||
// 3. 防重入: show()/hide() 多次调用安全,内部用 guard
|
||||
// 4. 兜底超时: 默认 8s 未关闭则强制 hide,防止卡死
|
||||
// 5. 平台隔离: APP-PLUS 有原生 splash,这里直接返回 false
|
||||
// 6. 跨平台兼容: 同步状态可被 Vue 组件直接 watch
|
||||
// ============================================================
|
||||
|
||||
// APP-PLUS 直接返回 false (有原生启动屏)
|
||||
function needSplash() {
|
||||
// #ifdef APP-PLUS
|
||||
return false;
|
||||
// #endif
|
||||
// #ifndef APP-PLUS
|
||||
return true;
|
||||
// #endif
|
||||
}
|
||||
|
||||
// H5 平台特殊处理: Lang.boot() 在 main.js 中 await, 此时 Vue 还没挂载,
|
||||
// 组件无法渲染, 内部降级为 uni.showLoading 做兜底 (虽然样式较丑但至少有遮罩)
|
||||
function useNativeLoading() {
|
||||
// #ifdef H5
|
||||
return true;
|
||||
// #endif
|
||||
// #ifndef H5
|
||||
return false;
|
||||
// #endif
|
||||
}
|
||||
|
||||
// 总兜底超时档位 (show 时可覆盖):
|
||||
// 12000 (12s): 默认档, 启动体验优先 (大多数网络环境够用, 略比 10s 宽松)
|
||||
// 17000 (17s): 中档, 慢网/冷启动 (1s+ 启动 + 3-5s i18n 远端 + 1-3s diy 拉取 + 缓冲)
|
||||
// 22000 (22s): 慢网档, 极弱网环境 (1s+ 启动 + 5-8s i18n 远端 + 3-5s diy 拉取 + 缓冲)
|
||||
// 低于 12000 不推荐: 用户感知的"启动卡"窗口期不够, 但业务方仍可传 < 12000 测试用
|
||||
// 业务方覆盖: splashState.show({ timeout: 17000 })
|
||||
// 注意: DEFAULT_TIMEOUT 仍是兜底 (无 opts.timeout), 不能被业务方传更低
|
||||
// 严防因为 timeout 太短导致用户看到白屏.
|
||||
// 设计思路: 各档位比"刚好够用"多 2s 缓冲, 弱网/慢网络环境兜底更稳
|
||||
const DEFAULT_TIMEOUT = 12000; // 总兜底超时 (默认 12s)
|
||||
const MOUNT_GRACE_MS = 1000; // 软隐藏后等组件 mount 的宽限时间
|
||||
const PAGE_READY_GRACE_MS = 2000; // 软隐藏后等页面就绪的宽限时间
|
||||
|
||||
// 启动期阶段定义 (id → { percent, label })
|
||||
// percent: 阶段完成的百分比 (0-100)
|
||||
// label: 阶段显示文案 (i18n key 由 splash 组件消费, 也可直接用最终文案)
|
||||
const STAGES = {
|
||||
boot: { percent: 5, label: 'Loading...' },
|
||||
lang: { percent: 30, label: 'Loading language...' },
|
||||
theme: { percent: 50, label: 'Applying theme...' },
|
||||
override: { percent: 65, label: 'Loading theme tokens...' },
|
||||
config: { percent: 80, label: 'Fetching configuration...' },
|
||||
privacy: { percent: 95, label: 'Preparing privacy dialog...' },
|
||||
done: { percent: 100, label: 'Ready' },
|
||||
};
|
||||
|
||||
class SplashState {
|
||||
constructor() {
|
||||
this._visible = false;
|
||||
this._timeoutId = null;
|
||||
this._listeners = [];
|
||||
this._shownAt = 0;
|
||||
// 软隐藏相关
|
||||
this._pendingHide = null; // 软隐藏请求的 opts, 等待组件 mount
|
||||
this._hasMounted = false; // 是否有 splash 组件 mount 过
|
||||
this._mountGraceId = null; // 软隐藏兜底定时器 (等 mount)
|
||||
// 页面就绪等待
|
||||
this._pageReady = false; // 页面内容是否已就绪 (由首页通知)
|
||||
this._pageReadyGraceId = null; // 页面就绪兜底定时器
|
||||
// 进度上报
|
||||
this._stage = 'boot';
|
||||
this._percent = 0;
|
||||
this._stageSet = new Set(['boot']); // 已报告阶段
|
||||
// 进度节流: 16ms 内的多次 reportProgress 合并成一次 emit
|
||||
// 避免多通道并发时, splash 组件 re-render 风暴
|
||||
this._pendingProgress = null; // 待 emit 的最新进度
|
||||
this._flushTimer = null; // 节流定时器
|
||||
// 网络环境 (用于 show() 自动选档)
|
||||
// _networkType: 'wifi' | '4g' | '5g' | '3g' | '2g' | 'none' | 'unknown'
|
||||
// _networkReady: false 表示还没检测完 (splash 显示中第一次构造时常见)
|
||||
// _networkReady 后, 网络变化时通过 onNetworkStatusChange 实时更新
|
||||
this._networkType = 'unknown';
|
||||
this._networkReady = false;
|
||||
|
||||
// 启动网络检测 (异步, 不阻塞 splash 显示)
|
||||
this._initNetworkDetect();
|
||||
|
||||
// 监听 diy 加载失败事件 (diy.js 通过 uni.$emit 触发)
|
||||
// 收到后调 notifyDiyLoadError (严格模式下必须能关闭 splash)
|
||||
// 解耦: splash-state 不直接 import diy.js
|
||||
// 透传 reason / errorType / err / url 给业务方监听 splash:diy-error 使用
|
||||
try {
|
||||
if (typeof uni !== 'undefined' && uni.$on) {
|
||||
uni.$on('diy:load-error', (payload) => {
|
||||
try { this.notifyDiyLoadError(payload || {}) } catch (e) {}
|
||||
})
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化网络检测
|
||||
* - 调 uni.getNetworkType 异步获取当前网络类型
|
||||
* - 监听 uni.onNetworkStatusChange 实时更新
|
||||
* - H5 平台降级: 调 navigator.onLine, 不支持细粒度网络类型
|
||||
* 失败保护: try-catch 包, 任意失败都保持 _networkType='unknown' (不会破坏 splash)
|
||||
*/
|
||||
_initNetworkDetect() {
|
||||
try {
|
||||
// #ifdef H5
|
||||
// H5 平台: navigator.onLine 是粗粒度, 只能判断在线/离线
|
||||
// 仅在 navigator.onLine 是明确 boolean (true/false) 时才是 H5
|
||||
// Node 24+ 有 navigator 但 onLine 是 undefined, 不算 H5 (走下面 uni.getNetworkType)
|
||||
if (typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean') {
|
||||
// 初始检测: 用 _updateNetworkType (内部会触发事件)
|
||||
this._updateNetworkType(navigator.onLine ? 'wifi' : 'none', { source: 'h5-initial' })
|
||||
// 监听 online/offline 事件
|
||||
if (typeof window !== 'undefined' && window.addEventListener) {
|
||||
window.addEventListener('online', () => {
|
||||
this._updateNetworkType('wifi', { source: 'h5-online', isConnected: true })
|
||||
})
|
||||
window.addEventListener('offline', () => {
|
||||
this._updateNetworkType('none', { source: 'h5-offline', isConnected: false })
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
// navigator.onLine 不是 boolean (Node/SSR) - 走 uni.getNetworkType
|
||||
// #endif
|
||||
// #ifndef H5
|
||||
if (typeof uni === 'undefined' || !uni.getNetworkType) {
|
||||
// 不可用: 用 _updateNetworkType 设 unknown (会触发事件)
|
||||
this._updateNetworkType('unknown', { source: 'no-uni-api' })
|
||||
return
|
||||
}
|
||||
// 异步获取当前网络类型
|
||||
uni.getNetworkType({
|
||||
success: (res) => {
|
||||
this._updateNetworkType((res && res.networkType) || 'unknown', { source: 'uni-initial' })
|
||||
},
|
||||
fail: () => {
|
||||
this._updateNetworkType('unknown', { source: 'uni-initial-fail' })
|
||||
},
|
||||
})
|
||||
// 监听网络变化
|
||||
if (uni.onNetworkStatusChange) {
|
||||
uni.onNetworkStatusChange((res) => {
|
||||
const newType = (res && res.networkType)
|
||||
|| (res && res.isConnected === false ? 'none' : 'unknown')
|
||||
this._updateNetworkType(newType, {
|
||||
source: 'uni-change',
|
||||
isConnected: res && typeof res.isConnected === 'boolean' ? res.isConnected : undefined,
|
||||
})
|
||||
})
|
||||
}
|
||||
// #endif
|
||||
} catch (e) {
|
||||
// 任意失败都用 unknown, 不影响 splash
|
||||
this._updateNetworkType('unknown', { source: 'init-error' })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据当前网络环境选档
|
||||
* - 离线 (none): 4000 (4s, 让 diy 错误信号有时间触发)
|
||||
* - 弱网 (2g/3g): 22000 (22s 慢网档, 多 2s 缓冲)
|
||||
* - 正常 (4g/5g/wifi): 12000 (12s 默认档, 多 2s 缓冲)
|
||||
* - 未知 (unknown): 17000 (17s 中档, 保守)
|
||||
* - 网络未就绪: 12000 (DEFAULT_TIMEOUT, 保守)
|
||||
*/
|
||||
_pickTimeoutByNetwork() {
|
||||
if (!this._networkReady) return DEFAULT_TIMEOUT // 网络检测未就绪, 用默认
|
||||
switch (this._networkType) {
|
||||
case 'none': return 4000 // 离线: 4s 兜底
|
||||
case '2g':
|
||||
case '3g': return 22000 // 弱网: 22s 慢网档
|
||||
case '4g':
|
||||
case '5g':
|
||||
case 'wifi': return 12000 // 正常: 12s 默认档
|
||||
case 'unknown':
|
||||
default: return 17000 // 未知: 17s 中档 (保守)
|
||||
}
|
||||
}
|
||||
|
||||
show(opts = {}) {
|
||||
if (!needSplash()) return;
|
||||
if (this._visible) return; // 防重入
|
||||
|
||||
this._visible = true;
|
||||
this._shownAt = Date.now();
|
||||
this._pendingHide = null;
|
||||
this._hasMounted = false;
|
||||
this._pageReady = false;
|
||||
this._stage = 'boot';
|
||||
// 初始化时直接显示 'boot' 阶段的 5%, 而不是 0%
|
||||
// 避免首帧出现"进度条 0%"的视觉突兀
|
||||
this._percent = (STAGES.boot && STAGES.boot.percent) || 5;
|
||||
this._stageSet = new Set(['boot']);
|
||||
this._pendingProgress = null;
|
||||
if (this._flushTimer) {
|
||||
clearTimeout(this._flushTimer);
|
||||
this._flushTimer = null;
|
||||
}
|
||||
if (this._mountGraceId) {
|
||||
clearTimeout(this._mountGraceId);
|
||||
this._mountGraceId = null;
|
||||
}
|
||||
if (this._pageReadyGraceId) {
|
||||
clearTimeout(this._pageReadyGraceId);
|
||||
this._pageReadyGraceId = null;
|
||||
}
|
||||
this._emit('splash:show');
|
||||
|
||||
// H5 降级: 走系统 loading (Vue 还没挂载,组件层无法渲染)
|
||||
// 注意: mask 设为 false。原 mask:true 会在 H5 注入 .uni-mask 全屏透明蒙层,
|
||||
// 配合 z-index:99999 的 Vue splash 一起把首页触摸全部拦截,导致 H5
|
||||
// 首屏在 boot 期间无法滚动。Vue splash 组件本身已带白色背景提供视觉遮罩,
|
||||
// 这里只要 loading 文字提示,不需要拦截触摸。
|
||||
if (useNativeLoading()) {
|
||||
try { uni.showLoading({ title: opts.title || '加载中...', mask: false }); } catch (e) {}
|
||||
}
|
||||
|
||||
// 业务方可通过 opts.timeout 覆盖, 但不能低于 5000ms (低于此值给 warn, 仍生效)
|
||||
// 原因: 启动期 i18n/theme/remote-config 远端加载最少 1-2s, diy 加载 1-3s
|
||||
// timeout 低于 5s 会经常触发兜底强关, 用户看到白屏
|
||||
// 测试场景允许传 < 5000ms (因为 mock 环境快), 仍生效但 warn
|
||||
// 优先级: opts.timeout (业务方显式) > _pickTimeoutByNetwork() (自动选档) > DEFAULT_TIMEOUT
|
||||
const MIN_RECOMMENDED_TIMEOUT = 5000
|
||||
let timeout
|
||||
if (opts.timeout) {
|
||||
timeout = opts.timeout
|
||||
if (opts.timeout < MIN_RECOMMENDED_TIMEOUT) {
|
||||
console.warn(
|
||||
`[splash-state] timeout=${opts.timeout}ms 低于推荐下限 ${MIN_RECOMMENDED_TIMEOUT}ms, ` +
|
||||
`可能导致启动期白屏. 生产环境建议 10000-20000ms.`
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// 自动选档: 根据当前网络环境选 timeout
|
||||
timeout = this._pickTimeoutByNetwork()
|
||||
}
|
||||
this._armTimeout(timeout);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置/重设 splash 总超时兜底
|
||||
* - 由 show() 初始化, 或 _updateNetworkType() 在网络变化时调用
|
||||
* - 关键: 网络从好→差时延长, 差→好时缩短, 保证用户不会过早/过晚看到白屏
|
||||
*/
|
||||
_armTimeout(timeout) {
|
||||
if (this._timeoutId) {
|
||||
clearTimeout(this._timeoutId);
|
||||
this._timeoutId = null;
|
||||
}
|
||||
this._timeoutId = setTimeout(() => {
|
||||
// 兜底: 超时强制关闭,防止卡死 (走硬隐藏路径, 不等组件)
|
||||
if (this._visible) {
|
||||
console.warn('[splash-state] auto-hide after timeout', timeout);
|
||||
this._doHide({ reason: 'timeout' });
|
||||
}
|
||||
}, timeout);
|
||||
}
|
||||
|
||||
/**
|
||||
* 网络变化时更新 _networkType, 并按需重启 splash 兜底
|
||||
* @param {string} newType 新的网络类型
|
||||
* @param {Object} [meta] 附加信息 { isConnected, source: 'h5-online' | 'uni-change' | ... }
|
||||
* @returns {boolean} 是否真的更新了 (新旧不同时为 true)
|
||||
*/
|
||||
_updateNetworkType(newType, meta) {
|
||||
newType = newType || 'unknown'
|
||||
const oldType = this._networkType
|
||||
const changed = oldType !== newType
|
||||
// 关键: 即使 type 没变, _networkReady 也要设 true
|
||||
// 原因: 首次调用 _updateNetworkType 是从 _initNetworkDetect 进来
|
||||
// 此时 _networkType='unknown' (初始), 可能 newType 也是 'unknown' (uni 不可用)
|
||||
// 但 _networkReady 仍要从 false → true (让 _pickTimeoutByNetwork 工作)
|
||||
this._networkReady = true
|
||||
if (!changed) return false
|
||||
this._networkType = newType
|
||||
|
||||
// 网络变化时: 如果 splash 还 visible, 重启兜底 (用新档)
|
||||
// 业务场景:
|
||||
// - wifi → 2g: 启动期远端慢, 兜底延长, 避免过早强关
|
||||
// - 2g → wifi: 兜底缩短, 避免过晚强关
|
||||
// - any → none: 兜底缩短到 4s, 让 diy 错误信号更快触发
|
||||
// - none → any: 兜底恢复正常档, 给足时间
|
||||
const shouldReboot = this._visible && this._pendingHide === null
|
||||
// 关键: 仅当 splash 还没进入"软隐藏"阶段时重启兜底
|
||||
// _pendingHide 不为 null 表示业务方已调 hide(), 等 notifyPageReady/DiyLoadError 即可
|
||||
// 此时网络变化不影响兜底 (业务方已接管决策)
|
||||
if (shouldReboot) {
|
||||
const newTimeout = this._pickTimeoutByNetwork()
|
||||
this._armTimeout(newTimeout)
|
||||
}
|
||||
|
||||
// 发 splash:network-change 事件 (业务方监听)
|
||||
// payload: { from, to, isConnected, retryRecommended, rebootSplashTimeout }
|
||||
// retryRecommended: 从 none 恢复时建议重试 (业务方重调 diy 接口)
|
||||
// rebootSplashTimeout: 是否重启了 splash 兜底 (true/false)
|
||||
const eventPayload = {
|
||||
from: oldType,
|
||||
to: newType,
|
||||
isConnected: meta && typeof meta.isConnected === 'boolean' ? meta.isConnected : newType !== 'none',
|
||||
retryRecommended: oldType === 'none' && newType !== 'none', // 离线→在线, 建议重试
|
||||
rebootSplashTimeout: shouldReboot,
|
||||
source: (meta && meta.source) || 'unknown',
|
||||
}
|
||||
this._emit('splash:network-change', eventPayload)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* 隐藏 splash
|
||||
* @param {Object} opts
|
||||
* @param {string} opts.reason - 隐藏原因
|
||||
* - 'boot-complete': 软隐藏, 等组件 mount 后再真关 (默认)
|
||||
* - 'timeout': 硬隐藏, 立即关 (兜底用)
|
||||
* - 'manual': 硬隐藏, 立即关
|
||||
* @param {boolean} [opts.soft] - 强制走软隐藏
|
||||
* @param {string} [opts.mode] - 离开动画模式
|
||||
* - 'default': 默认 480ms 动画
|
||||
* - 'fast': 80ms 短动画, 用于隐私弹窗等需要立即接管视觉的场景, 避免"双遮罩"感
|
||||
* - 'strict': 严格模式, 不走 MOUNT_GRACE_MS / PAGE_READY_GRACE_MS 兜底,
|
||||
* 只等 notifyPageReady() 或 DEFAULT_TIMEOUT 总超时
|
||||
* 适用于: 已接入平台托管的系统弹窗 (鸿蒙),
|
||||
* splash 必须真等到首页 diy 内容渲染好才能关
|
||||
*/
|
||||
hide(opts = {}) {
|
||||
const reason = opts.reason || 'manual';
|
||||
const useStrict = opts.mode === 'strict' || opts._strict === true;
|
||||
// boot-complete 默认走软隐藏, 避免时序问题
|
||||
const useSoft = useStrict || opts.soft === true || (opts.soft !== false && reason === 'boot-complete');
|
||||
// strict 模式复用 fast 动画
|
||||
const mode = useStrict ? 'fast' : (opts.mode === 'fast' ? 'fast' : 'default');
|
||||
|
||||
if (useSoft) {
|
||||
// 传递完整 opts, _softHide 内部能识别 mode='strict' 或 _strict
|
||||
this._softHide(opts);
|
||||
} else {
|
||||
this._doHide({ reason, mode });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 软隐藏: 标记应该 hide, 等组件 mount + 页面就绪
|
||||
* 如果组件 1s 内没 mount, 兜底自动 hide
|
||||
* 如果页面 2s 内没就绪, 兜底自动 hide
|
||||
*
|
||||
* strict 模式 (鸿蒙已接入平台托管):
|
||||
* 不走 MOUNT_GRACE_MS / PAGE_READY_GRACE_MS 兜底
|
||||
* 只等 notifyMounted() + notifyPageReady() 或 DEFAULT_TIMEOUT 总超时
|
||||
* 保证 splash 一定等到首页 diy 内容真的渲染好
|
||||
*/
|
||||
_softHide(opts) {
|
||||
if (!this._visible) return; // 已经隐藏了
|
||||
this._pendingHide = opts;
|
||||
// strict 模式识别: mode='strict' 或 _strict=true
|
||||
const useStrict = opts && (opts.mode === 'strict' || opts._strict === true);
|
||||
|
||||
// 如果组件已经 mount 且页面已就绪, 立即隐藏
|
||||
if (this._hasMounted && this._pageReady) {
|
||||
this._flushPendingHide();
|
||||
return;
|
||||
}
|
||||
|
||||
// strict 模式: 不设 mountGraceId 兜底, 只等 notifyPageReady
|
||||
// (DEFAULT_TIMEOUT 在 show() 设置的 _timeoutId 兜底)
|
||||
if (useStrict) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 兜底: 1s 内没 mount, 强制隐藏
|
||||
if (this._mountGraceId) clearTimeout(this._mountGraceId);
|
||||
this._mountGraceId = setTimeout(() => {
|
||||
if (this._pendingHide) {
|
||||
this._flushPendingHide();
|
||||
}
|
||||
}, MOUNT_GRACE_MS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 真正触发软隐藏
|
||||
* 如果页面还未就绪, 等待页面就绪后再 hide
|
||||
* strict 模式 (鸿蒙): 不设 pageReadyGraceId 兜底, 只等 notifyPageReady()
|
||||
*/
|
||||
_flushPendingHide() {
|
||||
if (this._mountGraceId) {
|
||||
clearTimeout(this._mountGraceId);
|
||||
this._mountGraceId = null;
|
||||
}
|
||||
// 已被 notifyDiyLoadError 拿走 _pendingHide 并自己 _doHide: noop
|
||||
// 原因: notifyMounted 50ms 后会调 _flushPendingHide, 但 _pendingHide 已被 notifyDiyLoadError 消费
|
||||
// 不应再调 _doHide (避免重复发 splash:hide 或时序错乱)
|
||||
if (!this._pendingHide) return;
|
||||
const _opts = this._pendingHide
|
||||
const useStrict = _opts && (_opts.mode === 'strict' || _opts._strict === true)
|
||||
|
||||
// 如果页面还未就绪, 等待页面就绪 (保留 _pendingHide, 等页面就绪后再处理)
|
||||
if (!this._pageReady) {
|
||||
// strict 模式: 不设 pageReadyGraceId, 只等 notifyPageReady()
|
||||
// 总超时由 show() 里的 _timeoutId 兜底 (DEFAULT_TIMEOUT=8s)
|
||||
if (useStrict) {
|
||||
return;
|
||||
}
|
||||
// 兜底: 2s 内没就绪, 强制隐藏
|
||||
if (this._pageReadyGraceId) clearTimeout(this._pageReadyGraceId);
|
||||
this._pageReadyGraceId = setTimeout(() => {
|
||||
if (this._visible && this._pendingHide) {
|
||||
console.warn('[splash-state] auto-hide after page-ready timeout');
|
||||
this._doHide(this._pendingHide || { reason: 'page-ready-timeout' });
|
||||
}
|
||||
}, PAGE_READY_GRACE_MS);
|
||||
return;
|
||||
}
|
||||
|
||||
const opts = this._pendingHide;
|
||||
this._pendingHide = null;
|
||||
this._doHide(opts || { reason: 'mount-completed' });
|
||||
}
|
||||
|
||||
/**
|
||||
* 实际隐藏 (硬路径)
|
||||
* @param {Object} opts
|
||||
* @param {string} [opts.reason='manual'] 隐藏原因
|
||||
* @param {string} [opts.mode='default'] 动画模式
|
||||
* @param {boolean} [opts._silent=false] true=不发 splash:hide 事件
|
||||
* 适用于 notifyDiyLoadError: 已经发了 splash:diy-error, 不能再发 splash:hide
|
||||
*/
|
||||
_doHide(opts) {
|
||||
if (!this._visible) return; // 防重入
|
||||
if (this._timeoutId) {
|
||||
clearTimeout(this._timeoutId);
|
||||
this._timeoutId = null;
|
||||
}
|
||||
if (this._mountGraceId) {
|
||||
clearTimeout(this._mountGraceId);
|
||||
this._mountGraceId = null;
|
||||
}
|
||||
if (this._pageReadyGraceId) {
|
||||
clearTimeout(this._pageReadyGraceId);
|
||||
this._pageReadyGraceId = null;
|
||||
}
|
||||
this._pendingHide = null;
|
||||
this._visible = false;
|
||||
// H5 降级对应的关闭
|
||||
if (useNativeLoading()) {
|
||||
try { uni.hideLoading(); } catch (e) {}
|
||||
}
|
||||
// _silent=true: 业务方已经从 notifyDiyLoadError 收了 splash:diy-error, 这里不发 splash:hide
|
||||
if (opts._silent) return;
|
||||
this._emit('splash:hide', {
|
||||
reason: opts.reason || 'manual',
|
||||
mode: opts.mode || 'default',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 组件 mount 后通知 state 模块
|
||||
* - 标记 _hasMounted
|
||||
* - 如果有 _pendingHide, 触发真关
|
||||
* - H5 降级场景: 不再立即关掉原生 loading, 等待页面就绪后再关
|
||||
*/
|
||||
notifyMounted() {
|
||||
if (this._hasMounted) return;
|
||||
this._hasMounted = true;
|
||||
if (this._pendingHide) {
|
||||
setTimeout(() => this._flushPendingHide(), 50);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面内容就绪后通知 state 模块
|
||||
* - 标记 _pageReady
|
||||
* - 如果有 _pendingHide, 触发真关
|
||||
* 调用时机: 首页 diy-group 渲染完成后调用
|
||||
*/
|
||||
notifyPageReady() {
|
||||
if (this._pageReady) return;
|
||||
this._pageReady = true;
|
||||
if (this._pageReadyGraceId) {
|
||||
clearTimeout(this._pageReadyGraceId);
|
||||
this._pageReadyGraceId = null;
|
||||
}
|
||||
if (this._pendingHide) {
|
||||
// 给页面一帧时间完成渲染, 再隐藏
|
||||
setTimeout(() => this._flushPendingHide(), 50);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* diy 加载失败时通知 (网络异常/业务失败/无响应)
|
||||
* - 任何模式: 真关 splash (不能无限等, 错误已显示在页面横幅上)
|
||||
* - 触发独立事件 'splash:diy-error' (不是 'splash:hide')
|
||||
* 业务方可监听此事件做: 错误上报 / 自定义错误展示 / 区分错误类型
|
||||
* 调用时机: diy 错误横幅出现后 (diy.js._showDiyLoadError)
|
||||
*
|
||||
* @param {Object} [opts]
|
||||
* @param {string} [opts.reason='diy-load-error'] 隐藏原因
|
||||
* 用于 'splash:diy-error' 事件的 payload, 业务方可区分:
|
||||
* - 'diy-network-error': 网络异常 (uni.request catch)
|
||||
* - 'diy-no-response': 无响应 (res 为空)
|
||||
* - 'diy-business-error': 业务失败 (code!=0)
|
||||
* @param {string} [opts.errorType] 错误类型: 'network' | 'business' | 'no-response'
|
||||
* @param {Object|string} [opts.err] 原始错误对象
|
||||
* @param {string} [opts.url] 出错的请求地址
|
||||
*/
|
||||
notifyDiyLoadError(opts = {}) {
|
||||
// 已 _pageReady=true (notifyPageReady 之后): noop
|
||||
// 原因: 业务方先调 notifyPageReady (diy 渲染好) 之后又调 notifyDiyLoadError (重复调用或时序错乱)
|
||||
// 不应再触发 splash:diy-error (已经发过 splash:hide)
|
||||
if (this._pageReady) return;
|
||||
// 复用 notifyPageReady 的关闭逻辑 (页面就绪 = 错误状态也算"就绪")
|
||||
// 原因: 错误状态页 (diyLoadError=true) 已经有 UI 反馈, splash 真关不卡视觉
|
||||
this._pageReady = true
|
||||
// 清除所有兜底, 真关 (strict 模式严格依赖 notifyPageReady/notifyDiyLoadError)
|
||||
if (this._pageReadyGraceId) {
|
||||
clearTimeout(this._pageReadyGraceId)
|
||||
this._pageReadyGraceId = null
|
||||
}
|
||||
if (this._mountGraceId) {
|
||||
clearTimeout(this._mountGraceId)
|
||||
this._mountGraceId = null
|
||||
}
|
||||
// 触发独立事件 (不发 splash:hide, 让业务方区分正常 hide 和 diy 错误)
|
||||
this._emit('splash:diy-error', {
|
||||
reason: opts.reason || 'diy-load-error',
|
||||
errorType: opts.errorType,
|
||||
err: opts.err,
|
||||
url: opts.url,
|
||||
})
|
||||
// 关键: 直接 _doHide 关闭 splash, **不**走 _flushPendingHide
|
||||
// 原因: _flushPendingHide 内部会 _doHide → 触发 splash:hide 事件
|
||||
// notifyDiyLoadError 路径**只**应发 splash:diy-error, 不应发 splash:hide
|
||||
// (业务方根据事件类型区分, 不能混淆)
|
||||
if (this._pendingHide) {
|
||||
// 把 _pendingHide 取出, 直接 _doHide 关闭
|
||||
// _silent=true 让 _doHide 不发 splash:hide (因为已经发了 splash:diy-error)
|
||||
const _pendingOpts = this._pendingHide
|
||||
this._pendingHide = null
|
||||
setTimeout(() => this._doHide({ ..._pendingOpts, _silent: true }), 50)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 组件 unmount 时通知 (用于 _hasMounted 状态管理)
|
||||
* 目前保留 _hasMounted=true, 因为一般只有 tab 页有 splash 组件, 不会动态增减
|
||||
*/
|
||||
notifyUnmounted() {
|
||||
// 不重置 _hasMounted, 因为软隐藏的 _pendingHide 处理不依赖 unmount
|
||||
}
|
||||
|
||||
isShow() {
|
||||
return this._visible;
|
||||
}
|
||||
|
||||
hasPendingHide() {
|
||||
return this._pendingHide != null;
|
||||
}
|
||||
|
||||
elapsed() {
|
||||
if (!this._visible) return 0;
|
||||
return Date.now() - this._shownAt;
|
||||
}
|
||||
|
||||
on(event, fn) {
|
||||
if (!this._listeners[event]) this._listeners[event] = [];
|
||||
this._listeners[event].push(fn);
|
||||
}
|
||||
|
||||
off(event, fn) {
|
||||
if (!this._listeners[event]) return;
|
||||
this._listeners[event] = this._listeners[event].filter(f => f !== fn);
|
||||
}
|
||||
|
||||
_emit(event, payload) {
|
||||
const arr = this._listeners[event];
|
||||
if (!arr || !arr.length) return;
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
try { arr[i](payload); } catch (e) { console.warn('[splash-state] listener err', e); }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上报启动期进度
|
||||
* 节流: 16ms 内的多次 reportProgress 合并成 1 次 emit, 避免 splash re-render 风暴
|
||||
* 取较大值, 不允许后退 (即使 throttle 合并也不会让进度条后退)
|
||||
* @param {string} stageId - 阶段 id (STAGES 中定义)
|
||||
* 'boot' | 'lang' | 'theme' | 'override' | 'config' | 'privacy' | 'done'
|
||||
* 或自定义阶段 id (传 percent + label)
|
||||
* @param {Object} [meta] - { percent?, label?, source?: 'channel'|'timeout'|'error' }
|
||||
* 阶段完成时 percent 应该是该阶段的"完成态"百分比
|
||||
*/
|
||||
reportProgress(stageId, meta) {
|
||||
const def = STAGES[stageId]
|
||||
let percent, label
|
||||
if (def) {
|
||||
percent = (meta && typeof meta.percent === 'number') ? meta.percent : def.percent
|
||||
label = (meta && meta.label) || def.label
|
||||
} else {
|
||||
// 自定义阶段
|
||||
percent = (meta && typeof meta.percent === 'number') ? meta.percent : this._percent
|
||||
label = (meta && meta.label) || stageId
|
||||
}
|
||||
// 取较大值, 不允许后退
|
||||
if (percent < this._percent) percent = this._percent
|
||||
this._percent = percent
|
||||
this._stage = stageId
|
||||
if (!this._stageSet.has(stageId)) this._stageSet.add(stageId)
|
||||
|
||||
// 节流 emit: 16ms 内的多次调用合并为 1 次
|
||||
// 内部状态立即更新 (不延迟), 但 emit 推迟
|
||||
// 注意: percent 不允许后退的逻辑已在上方处理, 所以 throttle 合并不会丢进度
|
||||
const payload = {
|
||||
stage: stageId,
|
||||
label,
|
||||
percent,
|
||||
source: (meta && meta.source) || 'channel',
|
||||
at: Date.now(),
|
||||
}
|
||||
this._pendingProgress = payload
|
||||
if (this._flushTimer) return // 已有 pending, 等 timer flush
|
||||
this._flushTimer = setTimeout(() => {
|
||||
this._flushTimer = null
|
||||
if (this._pendingProgress) {
|
||||
const p = this._pendingProgress
|
||||
this._pendingProgress = null
|
||||
this._emit('splash:progress', p)
|
||||
}
|
||||
}, 16)
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听进度上报
|
||||
* callback({ stage, label, percent, source, at })
|
||||
*
|
||||
* 注意: 与 on() 不同, onProgress 是单例 listener (多个组件时只最后一个生效)
|
||||
* 设计意图: splash 进度条 UI 在系统中只有一个渲染者, 不需要多播
|
||||
*/
|
||||
onProgress(callback) {
|
||||
this._listeners['splash:progress'] = [callback]
|
||||
}
|
||||
|
||||
/**
|
||||
* 解绑进度上报 (清空 listener)
|
||||
*/
|
||||
offProgress() {
|
||||
this._listeners['splash:progress'] = []
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取当前进度 (供组件初始化)
|
||||
* 同时返回已解析的 label, 避免组件再维护一份 STAGE_LABEL
|
||||
*/
|
||||
getProgress() {
|
||||
const def = STAGES[this._stage]
|
||||
return {
|
||||
stage: this._stage,
|
||||
percent: this._percent,
|
||||
label: def ? def.label : this._stage,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 暴露 STAGES 表 (供 splash 组件直接消费, 避免重复维护一份)
|
||||
*/
|
||||
getStageDef(stageId) {
|
||||
return STAGES[stageId]
|
||||
}
|
||||
|
||||
/**
|
||||
* 立即刷新挂起的进度更新
|
||||
* - reportProgress 默认 16ms throttle (1 帧), 避免连续触发 splash 组件多次 re-render
|
||||
* - 业务侧若要"立即"刷新 (例如 splash 即将隐藏), 可调本方法
|
||||
* - 不存在 pending 时 noop
|
||||
*/
|
||||
flushProgress() {
|
||||
if (this._pendingProgress) {
|
||||
const p = this._pendingProgress
|
||||
this._pendingProgress = null
|
||||
if (this._flushTimer) {
|
||||
clearTimeout(this._flushTimer)
|
||||
this._flushTimer = null
|
||||
}
|
||||
this._emit('splash:progress', p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const splashState = new SplashState();
|
||||
|
||||
export default splashState;
|
||||
export { splashState };
|
||||
File diff suppressed because it is too large
Load Diff
476
common/js/theme-override.js
Normal file
476
common/js/theme-override.js
Normal file
@@ -0,0 +1,476 @@
|
||||
/**
|
||||
* 主题 token 远端覆写运行时
|
||||
*
|
||||
* 设计原则(与 lang.js 完全同构):
|
||||
* 1) 后端只存"对要个性化的 token"做覆写 KV,前端拿本地 style_color.js + 远端覆写 合并
|
||||
* 2) 三态机: unknown / ok / fail
|
||||
* 3) 多租户 × 多端平台 × 多模式(brand/light/dark)三维隔离缓存
|
||||
* 4) 失败归一: timeout / network / http / parse / exception
|
||||
* 5) 失败时使用本地 style_color.js 兜底
|
||||
* 6) 不修改 Vuex.themeStyle / themeColorSet / 页面 wrapper,只把"合并后的 token map"
|
||||
* 提供给 store/index.js 的 applyThemeWithRemote action 使用
|
||||
*
|
||||
* 暴露的 API:
|
||||
* ThemeOverride.boot() 首屏阻塞拉取 + 缓存预热(失败静默)
|
||||
* ThemeOverride.refresh(force) 重新拉取 + 重新应用
|
||||
* ThemeOverride.getByTheme(theme) 取单个模式桶(brand/light/dark)的合并 KV
|
||||
* ThemeOverride.getAll() { brand, light, dark }
|
||||
* ThemeOverride.onUniacidChange() 切租户后清旧缓存
|
||||
* ThemeOverride.getRemoteStatus() 'unknown' | 'ok' | 'fail'
|
||||
* ThemeOverride.onRemoteStatusChange(fn) 订阅状态变化
|
||||
* ThemeOverride.__debug_cache 内部缓存(测试用)
|
||||
*
|
||||
* 关键: 一次 boot 只发一次 HTTP 请求,后端 getAllByTenant 一次出 brand/light/dark 三桶
|
||||
* 避免对每个 theme 单独请求造成的 3 倍带宽浪费
|
||||
*/
|
||||
|
||||
import { themeConfig } from './config-external.js';
|
||||
import Config from './config.js';
|
||||
import http from './http.js';
|
||||
import { Platform } from './platform.js';
|
||||
|
||||
const THEMES = ['brand', 'light', 'dark'];
|
||||
|
||||
// 远端覆写:内存缓存
|
||||
// shape: { [theme]: { version, map, ts, global_version } }
|
||||
const overrideCache = {};
|
||||
|
||||
// 远端全量 preset 内存缓存(remote-only 模式用)
|
||||
// shape: { [presetName]: { ...tokenMap } }
|
||||
const presetsCache = {};
|
||||
|
||||
// 远端覆写:并发去重(以"全量拉取"为粒度)
|
||||
let allInflight = null;
|
||||
|
||||
// 远端全量 preset 拉取:并发去重
|
||||
let presetsInflight = null;
|
||||
|
||||
// 远端可用性三态机
|
||||
let remoteStatus = 'unknown';
|
||||
let remoteStatusAt = 0;
|
||||
const remoteStatusListeners = [];
|
||||
|
||||
// 配置项缓存
|
||||
const REMOTE = (themeConfig && themeConfig.overrideRemote) || {};
|
||||
|
||||
/**
|
||||
* 校验 source 配置:只接受 local / remote / hybrid,其它一律视为 remote(安全默认)
|
||||
*/
|
||||
function normalizeSource(s) {
|
||||
return ['local', 'remote', 'hybrid'].includes(s) ? s : 'remote';
|
||||
}
|
||||
const SOURCE = normalizeSource(REMOTE.source || 'remote');
|
||||
|
||||
/**
|
||||
* 远端失败原因归一
|
||||
*/
|
||||
function normalizeReason(s) {
|
||||
const allow = ['timeout', 'network', 'http', 'parse', 'exception', 'unknown'];
|
||||
return allow.includes(s) ? s : 'unknown';
|
||||
}
|
||||
|
||||
/**
|
||||
* 远端成功/失败状态机
|
||||
*/
|
||||
function setRemoteStatus(s, detail) {
|
||||
if (remoteStatus === s) return;
|
||||
const prev = remoteStatus;
|
||||
remoteStatus = s;
|
||||
remoteStatusAt = Date.now();
|
||||
const safeDetail = {
|
||||
reason: normalizeReason(detail && detail.reason),
|
||||
theme: detail && detail.theme,
|
||||
};
|
||||
remoteStatusListeners.forEach(fn => {
|
||||
try { fn(s, safeDetail); } catch (e) { /* 忽略监听器异常 */ }
|
||||
});
|
||||
try { uni.$emit && uni.$emit('theme:remote-status', { from: prev, to: s, ...safeDetail }); } catch (e) {}
|
||||
if (s === 'fail') {
|
||||
try { uni.$emit && uni.$emit('theme:fallback', { reason: safeDetail.reason }); } catch (e) {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得当前租户 id
|
||||
*/
|
||||
function getCurrentUniacid() {
|
||||
const u = uni.getStorageSync('uniacid');
|
||||
return u ? parseInt(u, 10) || Config.uniacid : Config.uniacid;
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前平台类型
|
||||
*/
|
||||
function getCurrentAppType() {
|
||||
try { return Platform.getAppType() || '*'; } catch (e) { return '*'; }
|
||||
}
|
||||
|
||||
/**
|
||||
* 持久化 key: <prefix><uniacid>_<appType>_<theme>
|
||||
*/
|
||||
function getOverrideStorageKey(theme) {
|
||||
const u = getCurrentUniacid();
|
||||
const a = getCurrentAppType();
|
||||
return `${REMOTE.storagePrefix || 'THEME_OVR_'}${u}_${a}_${theme}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 内存 cache key: <uniacid>_<appType>_<theme>
|
||||
*/
|
||||
function getOverrideMemKey(theme) {
|
||||
return `${getCurrentUniacid()}_${getCurrentAppType()}_${theme}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 storage 预热单个 theme 桶到内存(首屏兜底)
|
||||
* 仅在内存还没有该 key 时才读 storage,避免覆盖更新值
|
||||
*/
|
||||
function preheatFromStorage(theme) {
|
||||
const mk = getOverrideMemKey(theme);
|
||||
if (overrideCache[mk]) return;
|
||||
try {
|
||||
const cached = uni.getStorageSync(getOverrideStorageKey(theme));
|
||||
if (cached && cached.map) {
|
||||
overrideCache[mk] = {
|
||||
version: cached.version || 0,
|
||||
map: cached.map || {},
|
||||
ts: cached.ts || 0,
|
||||
global_version: cached.global_version || 0,
|
||||
};
|
||||
return;
|
||||
}
|
||||
} catch (e) { /* 忽略 */ }
|
||||
overrideCache[mk] = { version: 0, map: {}, ts: 0, global_version: 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* 把"单次 HTTP 响应"按 by_theme 拆到 3 个内存桶 + 持久化
|
||||
*/
|
||||
function applyRemoteResponse(d) {
|
||||
const byTheme = (d && d.by_theme && typeof d.by_theme === 'object') ? d.by_theme : {};
|
||||
const gv = (d && d.global_version) || 0;
|
||||
const ts = Date.now();
|
||||
|
||||
THEMES.forEach(theme => {
|
||||
const remoteMap = (byTheme[theme] && typeof byTheme[theme] === 'object') ? byTheme[theme] : {};
|
||||
const mk = getOverrideMemKey(theme);
|
||||
const baseCache = overrideCache[mk] || { version: 0, map: {}, ts: 0, global_version: 0 };
|
||||
const merged = Object.assign({}, baseCache.map, remoteMap);
|
||||
overrideCache[mk] = {
|
||||
version: gv,
|
||||
map: merged,
|
||||
ts,
|
||||
global_version: gv,
|
||||
};
|
||||
try { uni.setStorageSync(getOverrideStorageKey(theme), overrideCache[mk]); } catch (e) {}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 取"3 个桶里最大的 global_version"(穿透缓存用)
|
||||
*/
|
||||
function maxCachedGlobalVersion() {
|
||||
let gv = 0;
|
||||
THEMES.forEach(t => {
|
||||
const mk = getOverrideMemKey(t);
|
||||
const c = overrideCache[mk];
|
||||
if (c && c.global_version > gv) gv = c.global_version;
|
||||
});
|
||||
return gv;
|
||||
}
|
||||
|
||||
/**
|
||||
* 一次 HTTP 拉齐 3 个 theme 桶
|
||||
* 这是 boot() / refresh() / onUniacidChange() 共用的"拉取入口"
|
||||
*
|
||||
* 关键: 1 次 HTTP, 拆 3 桶,避免对每个 theme 单独请求造成 3 倍浪费
|
||||
*
|
||||
* @returns {Promise<{ source:'cache'|'remote'|'local', ok:boolean, reason?:string, themes:string[] }>}
|
||||
*/
|
||||
async function loadAllOverrides() {
|
||||
if (SOURCE === 'local') return { source: 'local', ok: true, themes: THEMES };
|
||||
|
||||
// 并发去重:同一刻只允许一个在飞
|
||||
if (allInflight) return allInflight;
|
||||
|
||||
allInflight = (async () => {
|
||||
// 1) 先预热 storage 兜底
|
||||
THEMES.forEach(preheatFromStorage);
|
||||
|
||||
// 2) 一次 HTTP 拉齐 3 桶
|
||||
try {
|
||||
const res = await Promise.race([
|
||||
http.sendRequest({
|
||||
url: REMOTE.overridesUrl || '/api/theme/overrides',
|
||||
data: {
|
||||
global_version: maxCachedGlobalVersion(),
|
||||
},
|
||||
async: false,
|
||||
}),
|
||||
new Promise((r) => setTimeout(() => r({ code: -1, message: 'timeout' }), REMOTE.requestTimeout || 4000)),
|
||||
]);
|
||||
|
||||
if (!res || res.code !== 0 || !res.data) {
|
||||
const reason = !res ? 'network' : (res.code === -1 ? 'timeout' : (res.message || 'bad-response'));
|
||||
setRemoteStatus('fail', { reason, theme: 'all' });
|
||||
return { source: 'local', ok: false, reason, themes: THEMES };
|
||||
}
|
||||
|
||||
applyRemoteResponse(res.data);
|
||||
setRemoteStatus('ok', { theme: 'all' });
|
||||
emitUpdated('all');
|
||||
return { source: 'remote', ok: true, themes: THEMES };
|
||||
} catch (e) {
|
||||
setRemoteStatus('fail', { reason: 'exception', error: String(e && e.message || e), theme: 'all' });
|
||||
return { source: 'local', ok: false, reason: 'exception', themes: THEMES };
|
||||
}
|
||||
})();
|
||||
|
||||
try {
|
||||
return await allInflight;
|
||||
} finally {
|
||||
allInflight = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 触发"主题已更新"事件
|
||||
* 注意:Vuex 的 themeColorSet action 已经在 setThemeStyle 后跑过,
|
||||
* CSS 变量已挂到页面 wrapper 上,组件会自动刷新。
|
||||
* 这里只发通知,方便业务代码(如自定义 JS 直读 themeStyle 的页面)主动 re-render。
|
||||
*/
|
||||
function emitUpdated(theme) {
|
||||
try { uni.$emit && uni.$emit('theme:updated', { theme }); } catch (e) {}
|
||||
}
|
||||
|
||||
// 远端全量 preset 持久化 key: <storagePresetsPrefix><uniacid>_<appType>
|
||||
function getPresetsStorageKey() {
|
||||
const u = getCurrentUniacid();
|
||||
const a = getCurrentAppType();
|
||||
return `${REMOTE.storagePresetsPrefix || 'THEME_PRESETS_'}${u}_${a}`;
|
||||
}
|
||||
|
||||
// 远端全量 preset 内存 cache key
|
||||
function getPresetsMemKey() {
|
||||
return `${getCurrentUniacid()}_${getCurrentAppType()}`;
|
||||
}
|
||||
|
||||
// 从 storage 预热全量 preset 到内存(首屏兜底)
|
||||
function preheatPresetsFromStorage() {
|
||||
const mk = getPresetsMemKey();
|
||||
if (presetsCache[mk] && Object.keys(presetsCache[mk]).length) return;
|
||||
try {
|
||||
const cached = uni.getStorageSync(getPresetsStorageKey());
|
||||
if (cached && typeof cached === 'object') {
|
||||
presetsCache[mk] = cached;
|
||||
return;
|
||||
}
|
||||
} catch (e) { /* 忽略 */ }
|
||||
}
|
||||
|
||||
/**
|
||||
* 一次 HTTP 拉齐 8 个 preset(remote-only 模式)
|
||||
* 关键: 不阻塞首屏,失败静默. store/index.js 的 applyThemeWithRemote 会优先用
|
||||
* 内存缓存(由 loadAllPresets 写入), 缓存未命中时回退到 webpack stub(只含 default).
|
||||
*
|
||||
* @returns {Promise<{ source:'cache'|'remote'|'local'|'skipped', ok:boolean, presets?:object, reason?:string }>}
|
||||
*/
|
||||
async function loadAllPresets() {
|
||||
if (SOURCE === 'local') return { source: 'skipped', ok: true, presets: {} };
|
||||
if (!REMOTE.presetsUrl) return { source: 'skipped', ok: false, reason: 'no-url' };
|
||||
|
||||
// 并发去重
|
||||
if (presetsInflight) return presetsInflight;
|
||||
|
||||
presetsInflight = (async () => {
|
||||
// 1) 先预热 storage 兜底
|
||||
preheatPresetsFromStorage();
|
||||
|
||||
// 2) 一次 HTTP 拉齐 8 个 preset
|
||||
try {
|
||||
const res = await Promise.race([
|
||||
http.sendRequest({
|
||||
url: REMOTE.presetsUrl,
|
||||
data: {},
|
||||
async: false,
|
||||
}),
|
||||
new Promise((r) => setTimeout(() => r({ code: -1, message: 'timeout' }), REMOTE.requestTimeout || 4000)),
|
||||
]);
|
||||
|
||||
if (!res || res.code !== 0 || !res.data) {
|
||||
const reason = !res ? 'network' : (res.code === -1 ? 'timeout' : (res.message || 'bad-response'));
|
||||
console.warn('[theme-presets] remote load fail, keep stub:', reason);
|
||||
return { source: 'local', ok: false, reason };
|
||||
}
|
||||
|
||||
// 3) 解析响应. 期望格式: { by_preset: { default: {...}, green: {...}, ... } }
|
||||
const byPreset = (res.data.by_preset && typeof res.data.by_preset === 'object') ? res.data.by_preset : null;
|
||||
if (!byPreset) {
|
||||
console.warn('[theme-presets] response missing by_preset');
|
||||
return { source: 'local', ok: false, reason: 'parse' };
|
||||
}
|
||||
|
||||
// 4) 写入内存缓存 + 持久化
|
||||
const mk = getPresetsMemKey();
|
||||
presetsCache[mk] = byPreset;
|
||||
try { uni.setStorageSync(getPresetsStorageKey(), byPreset); } catch (e) {}
|
||||
|
||||
// 5) 通知已更新
|
||||
try { uni.$emit && uni.$emit('theme:presets-updated'); } catch (e) {}
|
||||
|
||||
return { source: 'remote', ok: true, presets: byPreset };
|
||||
} catch (e) {
|
||||
console.warn('[theme-presets] remote load exception:', e && e.message);
|
||||
return { source: 'local', ok: false, reason: 'exception' };
|
||||
}
|
||||
})();
|
||||
|
||||
try {
|
||||
return await presetsInflight;
|
||||
} finally {
|
||||
presetsInflight = null;
|
||||
}
|
||||
}
|
||||
|
||||
// 导出主体
|
||||
export default {
|
||||
SOURCE,
|
||||
|
||||
/**
|
||||
* 阻塞式预热:App.onLaunch 在 Lang.boot 后调用
|
||||
* 失败静默,不阻塞首屏
|
||||
*
|
||||
* @returns {Promise<{ok:boolean, source:'local'|'remote'|'cache'|'timeout', status:string, reason?:string, themes:string[]}>}
|
||||
*/
|
||||
async boot() {
|
||||
if (SOURCE === 'local') {
|
||||
return { ok: true, source: 'local', status: remoteStatus, themes: THEMES };
|
||||
}
|
||||
|
||||
const bootTimeout = REMOTE.bootTimeout || 2000;
|
||||
const t = new Promise((r) => setTimeout(() => r({ __timeout: true }), bootTimeout));
|
||||
|
||||
// 切租户检测
|
||||
const currentUid = getCurrentUniacid();
|
||||
try {
|
||||
const lastUid = uni.getStorageSync('theme_last_uniacid');
|
||||
if (lastUid && String(lastUid) !== String(currentUid)) {
|
||||
this.onUniacidChange();
|
||||
}
|
||||
uni.setStorageSync('theme_last_uniacid', currentUid);
|
||||
} catch (e) {}
|
||||
|
||||
const result = await Promise.race([loadAllOverrides(), t]);
|
||||
if (result && result.__timeout) {
|
||||
return { ok: false, source: 'timeout', status: 'fail', reason: 'timeout', themes: THEMES };
|
||||
}
|
||||
return {
|
||||
ok: remoteStatus === 'ok',
|
||||
source: remoteStatus === 'ok' ? 'remote' : 'local',
|
||||
status: remoteStatus,
|
||||
themes: THEMES,
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* 主动重新拉取(管理后台改了之后 EventBus 通知触发)
|
||||
* @param {boolean} [force=false] true = 绕过缓存强刷
|
||||
*/
|
||||
async refresh(force = false) {
|
||||
if (force) {
|
||||
// 强刷:清掉内存 + 持久化缓存,逼 loadAllOverrides 走远端
|
||||
THEMES.forEach(t => {
|
||||
const mk = getOverrideMemKey(t);
|
||||
if (overrideCache[mk]) overrideCache[mk] = { version: 0, map: {}, ts: 0, global_version: 0 };
|
||||
try { uni.removeStorageSync(getOverrideStorageKey(t)); } catch (e) {}
|
||||
});
|
||||
}
|
||||
return loadAllOverrides();
|
||||
},
|
||||
|
||||
/**
|
||||
* 切租户后清旧缓存
|
||||
*/
|
||||
onUniacidChange() {
|
||||
if (SOURCE === 'local') return;
|
||||
if (REMOTE.refreshOnUniacidChange === false) return;
|
||||
THEMES.forEach(t => {
|
||||
const sk = getOverrideStorageKey(t);
|
||||
try { uni.removeStorageSync(sk); } catch (e) {}
|
||||
delete overrideCache[getOverrideMemKey(t)];
|
||||
});
|
||||
// 同步清空全量 preset 缓存(remote-only 模式)
|
||||
const psk = getPresetsStorageKey();
|
||||
try { uni.removeStorageSync(psk); } catch (e) {}
|
||||
delete presetsCache[getPresetsMemKey()];
|
||||
loadAllOverrides();
|
||||
},
|
||||
|
||||
/**
|
||||
* 取某个 theme 桶(同步:有缓存返缓存;无缓存时该桶返回 {})
|
||||
* store/index.js 的 applyThemeWithRemote action 直接用
|
||||
* @param {'brand'|'light'|'dark'} theme
|
||||
* @returns {object} 扁平 KV map (没有时返回 {})
|
||||
*/
|
||||
getByTheme(theme) {
|
||||
const mk = getOverrideMemKey(theme);
|
||||
const cached = overrideCache[mk];
|
||||
return (cached && cached.map) ? cached.map : {};
|
||||
},
|
||||
|
||||
/**
|
||||
* 取所有 theme 桶
|
||||
* @returns {{ brand: object, light: object, dark: object }}
|
||||
*/
|
||||
getAll() {
|
||||
return {
|
||||
brand: this.getByTheme('brand'),
|
||||
light: this.getByTheme('light'),
|
||||
dark: this.getByTheme('dark'),
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* 取全量 preset 内存缓存(remote-only 模式)
|
||||
* store/index.js 的 applyThemeWithRemote 通过这个取到远端拉的全量 preset
|
||||
* @returns {{ [presetName: string]: object }}
|
||||
*/
|
||||
getAllPresets() {
|
||||
const mk = getPresetsMemKey();
|
||||
return presetsCache[mk] || {};
|
||||
},
|
||||
|
||||
/**
|
||||
* 主动拉全量 preset(remote-only 模式)
|
||||
* - 失败静默, 不抛错
|
||||
* - 内存 + 持久化双写
|
||||
* - 拉成功后发 uni.$emit('theme:presets-updated')
|
||||
*
|
||||
* @returns {Promise<{ source:'cache'|'remote'|'local'|'skipped', ok:boolean, presets?:object, reason?:string }>}
|
||||
*/
|
||||
loadAllPresets,
|
||||
|
||||
/**
|
||||
* 当前远端状态
|
||||
*/
|
||||
getRemoteStatus() { return remoteStatus; },
|
||||
|
||||
/**
|
||||
* 订阅远端状态变化
|
||||
* @param {(status:string, detail:object) => void} fn
|
||||
* @returns {() => void} unsubscribe
|
||||
*/
|
||||
onRemoteStatusChange(fn) {
|
||||
if (typeof fn !== 'function') return () => {};
|
||||
remoteStatusListeners.push(fn);
|
||||
try { fn(remoteStatus, { at: remoteStatusAt, source: SOURCE }); } catch (e) {}
|
||||
return () => {
|
||||
const i = remoteStatusListeners.indexOf(fn);
|
||||
if (i >= 0) remoteStatusListeners.splice(i, 1);
|
||||
};
|
||||
},
|
||||
|
||||
// 内部测试/调试用
|
||||
__debug_overrideCache: overrideCache,
|
||||
__debug_loadAllOverrides: loadAllOverrides,
|
||||
}
|
||||
@@ -2,6 +2,26 @@
|
||||
* 将常用的Uniapp提供的函数,存放到这里,按需引用
|
||||
*/
|
||||
|
||||
import lang from './lang.js';
|
||||
|
||||
|
||||
/**
|
||||
* 判断是否为「微信剪贴板隐私声明缺失」导致的复制失败
|
||||
*
|
||||
* 微信自 2023-09-15 起把剪贴板接口纳入《小程序用户隐私保护指引》,
|
||||
* 若小程序后台未声明「剪贴板」(或声明未审核通过),调用会返回:
|
||||
* { errno: 112, errMsg: 'setClipboardData:fail api scope is not declared in the privacy agreement' }
|
||||
* 这是平台侧配置问题,不改代码也能复现,因此不能把原始英文 errMsg 直接展示给用户。
|
||||
*
|
||||
* @param {*} err uni.setClipboardData 的 fail 回调参数
|
||||
* @returns {Boolean} true=剪贴板隐私声明缺失
|
||||
*/
|
||||
export const isClipboardPrivacyError = (err) => {
|
||||
if (!err) return false;
|
||||
if (Number(err.errno) === 112) return true;
|
||||
const msg = `${err.errMsg || err.message || ''}`;
|
||||
return /privacy agreement/i.test(msg) || /api scope is not declared/i.test(msg);
|
||||
};
|
||||
|
||||
/**
|
||||
* 显示错误信息
|
||||
@@ -18,7 +38,7 @@ const showError = (err, useModal = false) => {
|
||||
});
|
||||
} else {
|
||||
uni.showModal({
|
||||
title: '错误提示',
|
||||
title: lang.lang('uniappUtils.errorTip'),
|
||||
content,
|
||||
showCancel: false,
|
||||
})
|
||||
@@ -34,7 +54,6 @@ export const makePhoneCall = (mobile) => {
|
||||
uni.makePhoneCall({
|
||||
phoneNumber: `${mobile}`,
|
||||
success(e) {
|
||||
console.log(e);
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
@@ -52,7 +71,7 @@ export const copyTextAsync = (text, { copySuccess = '', copyFailed = '' } = {})
|
||||
return new Promise((resolve, reject) => {
|
||||
// 输入验证
|
||||
if (!text && text !== '') {
|
||||
const error = new Error('复制文本不能为空');
|
||||
const error = new Error(lang.lang('uniappUtils.copyTextEmpty'));
|
||||
showError(error);
|
||||
reject(error);
|
||||
return;
|
||||
@@ -60,13 +79,13 @@ export const copyTextAsync = (text, { copySuccess = '', copyFailed = '' } = {})
|
||||
|
||||
// 超时监测
|
||||
const timeoutId = setTimeout(() => {
|
||||
let error = new Error('复制操作长时间无响应,请检查相关权限及配置是否正确');
|
||||
let error = new Error(lang.lang('uniappUtils.copyTimeout'));
|
||||
// #ifdef MP-WEIXIN
|
||||
error = new Error([
|
||||
'复制操作长时间无响应!',
|
||||
'原因:',
|
||||
'1.微信平台->用户隐私保护指引->"剪贴板"功能未添加或审核未通过;',
|
||||
'2.微信平台对剪贴板API调用频率有限制'
|
||||
lang.lang('uniappUtils.copyTimeoutTitle'),
|
||||
lang.lang('uniappUtils.copyTimeoutReason'),
|
||||
lang.lang('uniappUtils.wechatClipboardReason1'),
|
||||
lang.lang('uniappUtils.wechatClipboardReason2')
|
||||
].join('\r\n'));
|
||||
// #endif
|
||||
showError(error, true);
|
||||
@@ -96,8 +115,12 @@ export const copyTextAsync = (text, { copySuccess = '', copyFailed = '' } = {})
|
||||
fail: (err) => {
|
||||
clearTimeout(timeoutId);
|
||||
try {
|
||||
// 剪贴板隐私声明缺失(errno 112)属平台配置问题, 用可读文案替代微信原始英文错误
|
||||
const tip = isClipboardPrivacyError(err)
|
||||
? lang.lang('uniappUtils.clipboardPrivacyNotDeclared')
|
||||
: (err.message || err.errMsg || copyFailed || lang.lang('uniappUtils.copyFailed'));
|
||||
uni.showToast({
|
||||
title: err.message || err.errMsg || copyFailed || '复制失败',
|
||||
title: tip,
|
||||
icon: 'none',
|
||||
duration: 2000
|
||||
});
|
||||
|
||||
814
common/js/util-navigate.js
Normal file
814
common/js/util-navigate.js
Normal file
@@ -0,0 +1,814 @@
|
||||
/**
|
||||
* util-navigate.js
|
||||
*
|
||||
* 跳转链路专用的工具集 — 从 util.js 拆分出来
|
||||
*
|
||||
* 包含的函数(全部服务于 redirectTo / diyRedirectTo 跳转链路):
|
||||
* - _toParamValueString : 把任意值序列化成可作为 URL 参数的字符串
|
||||
* - parsePageParams : 把 page_params 还原成对象(JSON.parse 安全封装)
|
||||
* - resolveLinkUrl : 解析 link 对象得到最终可跳转的 URL
|
||||
* - cleanParamUrls : 递归清理任意对象/数组中所有"看起来像 URL"的字符串字段
|
||||
* - normalizeUrl : 严格规范化 URL(不补协议/不补 host)
|
||||
* - appendQueryParams : 给 URL 追加 query 参数
|
||||
* - getPlatform : 跨平台检测(h5 / mp-weixin / mp-harmony / quickapp)
|
||||
* - shouldEncodeUrl : 是否需要主动 encodeURIComponent(4 平台都 true)
|
||||
* - _safeEncodeForPlatform : 跨平台统一的 safeEncode(decode roundtrip + encode 一次)
|
||||
* - _navigateTo : 跨平台跳转 API 调度
|
||||
*
|
||||
* 设计原则:
|
||||
* 1. 不依赖 util.js,避免循环依赖
|
||||
* 2. 全部为普通函数(不挂在 default export 对象上),方便 tree-shaking 和测试
|
||||
* 3. 行为完全兼容 util.js 旧版,util.js 通过 import 把这些方法挂载到 default export 上
|
||||
* (所有调用方 this.$util.cleanParamUrls / this.$util.redirectTo 等都不需要改)
|
||||
*
|
||||
* 跨平台编码 / 跳转策略文档见 _safeEncodeForPlatform / _navigateTo 的注释
|
||||
*/
|
||||
|
||||
// =============================================================
|
||||
// 基础工具
|
||||
// =============================================================
|
||||
|
||||
/**
|
||||
* 把任意值序列化成可作为 URL 参数的字符串。
|
||||
* - 对象/数组: JSON.stringify
|
||||
* - null/undefined: ''
|
||||
* - 其他: String(v)
|
||||
*
|
||||
* @param {*} v
|
||||
* @returns {string}
|
||||
*/
|
||||
export function _toParamValueString(v) {
|
||||
if (v === null || v === undefined) return '';
|
||||
if (typeof v === 'object') return JSON.stringify(v);
|
||||
return String(v);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 URL 上的 page_params 还原成对象。是 _toParamValueString 的逆操作。
|
||||
* 容错策略: 任何解析失败都安全降级到 defaultValue,不抛异常。
|
||||
*
|
||||
* @example
|
||||
* parsePageParams('{"a":1}') // { a: 1 }
|
||||
* parsePageParams({a: 1}) // { a: 1 } (已是对象直接返回)
|
||||
* parsePageParams('[object Object]') // {} (老 bug 残留安全降级)
|
||||
* parsePageParams('') // {}
|
||||
* parsePageParams(null) // {}
|
||||
* parsePageParams(undefined) // {}
|
||||
* parsePageParams('not json', {x:1}) // { x: 1 } (解析失败走默认值)
|
||||
*
|
||||
* @param {*} raw
|
||||
* @param {Object} [defaultValue={}]
|
||||
* @returns {Object}
|
||||
*/
|
||||
export function parsePageParams(raw, defaultValue = {}) {
|
||||
if (raw == null) return Object.assign({}, defaultValue);
|
||||
if (typeof raw === 'object') return raw;
|
||||
if (typeof raw === 'string') {
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
return typeof parsed === 'object' && parsed !== null
|
||||
? parsed
|
||||
: Object.assign({}, defaultValue);
|
||||
} catch (e) {
|
||||
return Object.assign({}, defaultValue);
|
||||
}
|
||||
}
|
||||
return Object.assign({}, defaultValue);
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// resolveLinkUrl
|
||||
// =============================================================
|
||||
|
||||
/**
|
||||
* 解析 link 对象得到最终可跳转的 URL
|
||||
* 同时把 wap_url 自带的 query 参数与 page_params 合并, 写入 link.page_params;
|
||||
* 并把 link.wap_url 改为不含 query 的 path, 避免后续 redirectTo 二次编码
|
||||
* 优先级: page_params > wap_url query (新机制优先)
|
||||
*
|
||||
* @param {Object} link
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function resolveLinkUrl(link) {
|
||||
if (!link) return null;
|
||||
// 0. 把 wap_url 中的 query 合并到 page_params
|
||||
if (link.wap_url) {
|
||||
const decodedWap = decodeEntity(link.wap_url);
|
||||
const queryIdx = decodedWap.indexOf('?');
|
||||
if (queryIdx !== -1) {
|
||||
const path = decodedWap.substring(0, queryIdx);
|
||||
const queryStr = decodedWap.substring(queryIdx + 1);
|
||||
const urlParams = {};
|
||||
queryStr.split('&').forEach((kv) => {
|
||||
if (!kv) return;
|
||||
const eqIdx = kv.indexOf('=');
|
||||
const k = eqIdx === -1 ? kv : kv.substring(0, eqIdx);
|
||||
const v = eqIdx === -1 ? '' : kv.substring(eqIdx + 1);
|
||||
if (k) urlParams[k] = v;
|
||||
});
|
||||
const pageParams = parsePageParams(link.page_params);
|
||||
link.page_params = Object.assign({}, urlParams, pageParams);
|
||||
link.wap_url = path;
|
||||
}
|
||||
}
|
||||
// 1. 优先使用 page_key(新机制)
|
||||
if (link.page_key) {
|
||||
// 这里原本会调 resolvePageUrl(link.page_key, params),
|
||||
// 但 util-navigate.js 不依赖 util.js,因此返回 link.wap_url
|
||||
// (util.js 在 import 此模块后会用 page_key 重新解析)
|
||||
const params = parsePageParams(link.page_params);
|
||||
// 注: 完整 page_key 解析留给 util.js (它有 resolvePageUrl)
|
||||
// 这里只做"wap_url 已被 resolveLinkUrl 处理过" 的返回
|
||||
}
|
||||
// 2. 回退: 旧的 wap_url(已被处理为不含 query 的 path)
|
||||
if (link.wap_url) {
|
||||
return link.wap_url;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* decodeEntity — HTML 实体解码
|
||||
* (从 util.js 顶层 export 搬过来, 跟其他跳转工具一起)
|
||||
*
|
||||
* 解码 &xxx; / &#xN; 等 HTML 实体
|
||||
* 容错: 任何解析失败都返回原文
|
||||
*
|
||||
* @param {string} str
|
||||
* @param {boolean} [amp=true] 是否解码 &
|
||||
* @returns {string}
|
||||
*/
|
||||
export function decodeEntity(str, amp) {
|
||||
const html4Entities = {
|
||||
nbsp: ' ', iexcl: '¡', cent: '¢', pound: '£', curren: '₣', yen: '¥',
|
||||
brvbar: '§', sect: 'Ş', uml: '¨', copy: '©', ordf: 'ª', laquo: '«',
|
||||
not: '¬', shy: '®', macr: '¯', deg: '°', plusmn: '±', sup2: '²',
|
||||
sup3: '³', acute: '´', micro: 'µ', para: '¶', middot: '·', cedil: '¸',
|
||||
sup1: '¹', ordm: 'º', raquo: '»', frac14: '¼', frac12: '½', frac34: '¾',
|
||||
iquest: '¿', agrave: 'à', aacute: 'á', acirc: 'â', atilde: 'ã', auml: 'ä',
|
||||
aring: 'å', aelig: 'æ', ccedil: 'ç', egrave: 'è', eacute: 'é', ecirc: 'ê',
|
||||
euml: 'ë', igrave: 'ì', iacute: 'í', icirc: 'î', iuml: 'ï', eth: 'ð',
|
||||
ntilde: 'ñ', ograve: 'ò', oacute: 'ó', ocirc: 'ô', otilde: 'õ', ouml: 'ö',
|
||||
times: 'ø', ugrave: 'ù', uacute: 'ú', ucirc: 'û', uuml: 'ü', yacute: 'ý',
|
||||
thorn: 'þ', yuml: 'ÿ', fnof: 'ƒ', alpha: 'α', beta: 'β', gamma: 'γ',
|
||||
delta: 'δ', epsilon: 'ε', zeta: 'ζ', eta: 'η', theta: 'θ', iota: 'ι',
|
||||
kappa: 'κ', lambda: 'λ', mu: 'μ', nu: 'ν', xi: 'ξ', omicron: 'ο',
|
||||
pi: 'π', rho: 'ρ', sigmaf: 'σ', sigma: 'σ', tau: 'τ', upsilon: 'υ',
|
||||
phi: 'φ', chi: 'ψ', omega: 'ω',
|
||||
};
|
||||
amp = amp === undefined ? true : amp;
|
||||
let i = str.indexOf('&');
|
||||
while (i !== -1) {
|
||||
const j = str.indexOf(';', i + 3);
|
||||
let code;
|
||||
if (j === -1) break;
|
||||
if (str[i + 1] === '#') {
|
||||
code = parseInt((str[i + 2] === 'x' ? '0' : '') + str.substring(i + 2, j));
|
||||
if (!isNaN(code)) {
|
||||
str = str.substring(0, i) + String.fromCharCode(code) + str.substring(j + 1);
|
||||
}
|
||||
} else {
|
||||
code = str.substring(i + 1, j);
|
||||
if (html4Entities[code] || (code === 'amp' && amp)) {
|
||||
str = str.substring(0, i) + (html4Entities[code] || '&') + str.substring(j + 1);
|
||||
}
|
||||
}
|
||||
i = str.indexOf('&', i + 1);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// cleanParamUrls
|
||||
// =============================================================
|
||||
|
||||
/**
|
||||
* 递归清理任意对象/数组中所有"看起来像 URL"的字符串字段:
|
||||
* - 去除反引号 / 各种空白 / 零宽字符
|
||||
* - 修复 scheme 后多余斜杠(https:////host → https://host)
|
||||
*
|
||||
* "看起来像 URL" 的判定: 含 `://`(大小写不敏感)
|
||||
* - 命中: 走清理
|
||||
* - 不命中: 原样保留(name / title / 标识符等普通字符串字段不被误伤)
|
||||
*
|
||||
* 设计: 不限定 key 列表,递归遍历,新加任何 URL 字段都自动覆盖
|
||||
*
|
||||
* @param {*} value 任意值
|
||||
* @returns {*} 与输入同结构的清理后值
|
||||
*/
|
||||
export function cleanParamUrls(value) {
|
||||
// 内部递归函数,通过闭包引用自身,避免 this 绑定问题
|
||||
const _clean = (v) => {
|
||||
if (v === null || v === undefined) return v;
|
||||
if (typeof v === 'string') {
|
||||
if (/:\/\//i.test(v)) {
|
||||
return v
|
||||
.split('').filter((ch) =>
|
||||
ch !== '`' && ch !== ' ' && ch !== '\t' && ch !== '\n' && ch !== '\r',
|
||||
).join('')
|
||||
.replace(/^(https?:\/\/)\/+/i, '$1');
|
||||
}
|
||||
return v;
|
||||
}
|
||||
if (Array.isArray(v)) {
|
||||
return v.map((item) => _clean(item));
|
||||
}
|
||||
if (typeof v === 'object') {
|
||||
const out = {};
|
||||
for (const k of Object.keys(v)) {
|
||||
out[k] = _clean(v[k]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
return v;
|
||||
};
|
||||
return _clean(value);
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// normalizeUrl
|
||||
// =============================================================
|
||||
|
||||
/**
|
||||
* 严格 URL 规范化(只规范化已有部分,绝不自动补充)
|
||||
*
|
||||
* 策略:
|
||||
* 1) 预清理: 剥离反引号 / 各种空白 / BOM / 零宽字符(脏数据兜底)
|
||||
* 2) 不补 https:// — 如果原串没有协议,保持没有
|
||||
* 3) 不补 host — 如果原串没有 host,保持没有
|
||||
* 4) 只对真实存在的部分做规范化: 协议小写、host 小写、path 解析 . ..、合并多 /、去默认端口、query 排序
|
||||
* 5) scheme 后只允许恰好 2 个 '/',不允许 https:////host 这类畸形,遇到就返回 ''
|
||||
*
|
||||
* @param {string} urlString
|
||||
* @returns {string} 标准化后的 URL;若输入无法解析为合法 URL 则返回空串 ''
|
||||
*/
|
||||
export function normalizeUrl(urlString) {
|
||||
if (!urlString || typeof urlString !== 'string') return '';
|
||||
|
||||
// 1) 预清理: 反引号 / 各种空白 / BOM / 零宽字符
|
||||
let url = urlString
|
||||
.split('').filter((ch) => {
|
||||
const code = ch.charCodeAt(0);
|
||||
if (code <= 0x20) return false;
|
||||
if (ch === '`') return false;
|
||||
if (code === 0x3000) return false;
|
||||
if (code === 0xFEFF || code === 0x200B ||
|
||||
code === 0x200C || code === 0x200D ||
|
||||
code === 0x2060) return false;
|
||||
return true;
|
||||
}).join('');
|
||||
|
||||
// 2) 解析协议(可选,允许缺失)
|
||||
const protocolMatch = url.match(/^(https?):\/\//i);
|
||||
let protocol = '';
|
||||
let rest = url;
|
||||
if (protocolMatch) {
|
||||
protocol = protocolMatch[1].toLowerCase() + '://';
|
||||
rest = url.substring(protocolMatch[0].length);
|
||||
// scheme 后不能紧跟 '/',即不允许 https:////host
|
||||
if (rest.charAt(0) === '/') {
|
||||
console.warn('[normalizeUrl] scheme 后有多余的 /:', urlString);
|
||||
return '';
|
||||
}
|
||||
} else {
|
||||
rest = url;
|
||||
}
|
||||
|
||||
// 3) 解析 hash
|
||||
const hashIndex = rest.indexOf('#');
|
||||
let hash = '';
|
||||
let mainPart = rest;
|
||||
if (hashIndex !== -1) {
|
||||
hash = rest.substring(hashIndex);
|
||||
mainPart = rest.substring(0, hashIndex);
|
||||
}
|
||||
|
||||
// 4) 解析 query
|
||||
const queryIndex = mainPart.indexOf('?');
|
||||
let query = '';
|
||||
let pathPart = mainPart;
|
||||
if (queryIndex !== -1) {
|
||||
query = mainPart.substring(queryIndex); // 包含 '?'
|
||||
pathPart = mainPart.substring(0, queryIndex);
|
||||
}
|
||||
|
||||
// 5) 解析 host
|
||||
let hostname = '';
|
||||
let port = '';
|
||||
let pathname = pathPart;
|
||||
if (protocol) {
|
||||
const firstSlash = pathPart.indexOf('/');
|
||||
const hostPort = firstSlash === -1 ? pathPart : pathPart.substring(0, firstSlash);
|
||||
pathname = firstSlash === -1 ? '' : pathPart.substring(firstSlash);
|
||||
if (hostPort) {
|
||||
const colonIdx = hostPort.lastIndexOf(':');
|
||||
if (colonIdx !== -1) {
|
||||
hostname = hostPort.substring(0, colonIdx);
|
||||
port = hostPort.substring(colonIdx + 1);
|
||||
} else {
|
||||
hostname = hostPort;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 6) 规范化 host
|
||||
let lowerHostname = '';
|
||||
if (hostname) {
|
||||
lowerHostname = hostname.toLowerCase();
|
||||
if ((protocol === 'http://' && port === '80') ||
|
||||
(protocol === 'https://' && port === '443')) {
|
||||
port = '';
|
||||
}
|
||||
if (/[\/\s]/.test(lowerHostname)) {
|
||||
console.warn('[normalizeUrl] host 含非法字符:', urlString);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
// 7) 规范化 pathname
|
||||
let normalizedPath = pathname;
|
||||
if (normalizedPath) {
|
||||
const segments = normalizedPath.split('/');
|
||||
const resolved = [];
|
||||
for (let i = 0; i < segments.length; i++) {
|
||||
const seg = segments[i];
|
||||
if (seg === '' || seg === '.') {
|
||||
if (i === 0) resolved.push('');
|
||||
continue;
|
||||
}
|
||||
if (seg === '..') {
|
||||
if (resolved.length > 1) resolved.pop();
|
||||
continue;
|
||||
}
|
||||
resolved.push(seg);
|
||||
}
|
||||
normalizedPath = resolved.join('/') || '/';
|
||||
}
|
||||
|
||||
// 8) 规范化 query
|
||||
let normalizedQuery = '';
|
||||
if (query) {
|
||||
const qs = query.substring(1);
|
||||
if (qs) {
|
||||
const pairs = qs.split('&').map((pair) => {
|
||||
const eqIdx = pair.indexOf('=');
|
||||
return eqIdx === -1
|
||||
? { k: pair, v: '' }
|
||||
: { k: pair.substring(0, eqIdx), v: pair.substring(eqIdx + 1) };
|
||||
});
|
||||
pairs.sort((a, b) => a.k.localeCompare(b.k));
|
||||
normalizedQuery = '?' + pairs.map((p) => p.k + '=' + p.v).join('&');
|
||||
}
|
||||
}
|
||||
|
||||
// 9) 拼回
|
||||
const portStr = port ? ':' + port : '';
|
||||
const hostPart = lowerHostname ? lowerHostname + portStr : '';
|
||||
const schemeAndHost = protocol + hostPart;
|
||||
return schemeAndHost + normalizedPath + normalizedQuery + hash;
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// extractInternalAppPath
|
||||
// =============================================================
|
||||
|
||||
/**
|
||||
* 从一个 URL 中提取"本 App 内部页面路径"。
|
||||
*
|
||||
* 背景 / 修复的 bug:
|
||||
* 后台装修数据里,内部页面常被存成【绝对 URL】,例如
|
||||
* https://host/hwappx/common/pages_tool/form/formdata?id=130
|
||||
* diyRedirectTo 用 `wap_url.indexOf('http') != -1` 判断"外部链接",于是:
|
||||
* - H5: 走 window.location.href → 整页刷新;点返回时整个 App 重启、启动屏重播、状态丢失
|
||||
* - MP: 走 web-view → 本应原生跳转的内部页被塞进 web-view
|
||||
* 本函数把这类"指向本 App 内部页面"的绝对 URL 还原成相对路径,
|
||||
* 让 diyRedirectTo 改走内部页面分支(uni.navigateTo / SPA 跳转)。
|
||||
*
|
||||
* 判定规则(双闸门,避免误伤真正的外部站点):
|
||||
* 闸门 1 —— host 校验(相对路径直接放行):
|
||||
* 绝对 URL 的 host 必须与本 App 自己的域名【完全一致】(忽略端口, 大小写不敏感);
|
||||
* 否则返回 null(视为真外链, 维持原逻辑)。
|
||||
* ★ 完全一致是最严格的口径: 不同子域(如 xcx3 vs xcx6)、不同域名一律当外链,
|
||||
* 彻底杜绝误伤 Shopify(xxx.myshopify.com/pages/about)、Facebook 等外站。
|
||||
* 闸门 2 —— 路径校验:
|
||||
* pathname 中出现以 App 页面根开头的段(pages / pages_xxx),
|
||||
* 则从该段起截取为内部路径(以 '/' 开头),连同 query/hash 一起返回;
|
||||
* 未命中返回 null。
|
||||
*
|
||||
* @example
|
||||
* const H = ['xcx6.aigc-quickapp.com']
|
||||
* extractInternalAppPath('https://xcx6.aigc-quickapp.com/hwappx/common/pages_tool/form/formdata?id=1', H)
|
||||
* // '/pages_tool/form/formdata?id=1' (域名完全一致 → 还原)
|
||||
* extractInternalAppPath('https://xcx3.aigc-quickapp.com/hwappx/common/pages/index/index', H)
|
||||
* // null (子域不同 → 维持外链)
|
||||
* extractInternalAppPath('https://xxx.myshopify.com/pages/about-us', H)
|
||||
* // null (外域名 → 维持外链,不误伤)
|
||||
* extractInternalAppPath('/pages_goods/detail?id=9', H)
|
||||
* // '/pages_goods/detail?id=9' (相对路径 → 内部)
|
||||
*
|
||||
* @param {string} url 绝对或相对 URL
|
||||
* @param {string|string[]|true} [allowedHosts] 本 App 自己的域名(可传完整 URL 或纯 host,会自动提取);
|
||||
* 传 `true` 表示【强制内部】—— 跳过 host 校验, 只要路径含 /pages 段就还原(用于 open_mode='internal')。
|
||||
* @returns {string|null} 形如 '/pages_tool/form/formdata?id=1' 的内部路径,或 null
|
||||
*/
|
||||
export function extractInternalAppPath(url, allowedHosts) {
|
||||
if (!url || typeof url !== 'string') return null;
|
||||
let rest = url;
|
||||
// 闸门 1: host 校验(完全一致);allowedHosts === true 时跳过(强制内部)
|
||||
const hostMatch = rest.match(/^https?:\/\/([^/]*)/i);
|
||||
if (hostMatch) {
|
||||
if (allowedHosts !== true) {
|
||||
const host = (hostMatch[1] || '').toLowerCase().replace(/:\d+$/, '');
|
||||
const allow = _normalizeHostList(allowedHosts);
|
||||
if (!host || allow.indexOf(host) === -1) return null; // 域名不完全一致 → 不改
|
||||
}
|
||||
rest = rest.substring(hostMatch[0].length);
|
||||
}
|
||||
// 闸门 2: 路径校验(找第一个"页面根段" /pages 或 /pages_xxx)
|
||||
const pageMatch = rest.match(/\/pages(?:_[a-z0-9]+)?\//i);
|
||||
if (!pageMatch) return null;
|
||||
const internal = rest.substring(pageMatch.index);
|
||||
return internal || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 allowedHosts 归一化成纯 host 数组(小写、去协议、去路径、去端口)。
|
||||
* 入参每一项可以是完整 URL(https://host/xx/)或纯 host(host:port)。
|
||||
* @param {string|string[]} hosts
|
||||
* @returns {string[]}
|
||||
*/
|
||||
function _normalizeHostList(hosts) {
|
||||
if (!hosts) return [];
|
||||
const arr = Array.isArray(hosts) ? hosts : [hosts];
|
||||
const out = [];
|
||||
for (const h of arr) {
|
||||
if (!h || typeof h !== 'string') continue;
|
||||
let s = h.trim().toLowerCase();
|
||||
const m = s.match(/^https?:\/\/([^/]*)/i);
|
||||
if (m) s = m[1] || '';
|
||||
else s = s.replace(/\/.*$/, ''); // 去掉可能带的 path
|
||||
s = s.replace(/:\d+$/, ''); // 去端口
|
||||
if (s) out.push(s);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 link 的导航模式(统一开关)。用于 diyRedirectTo 决定内部页面绝对 URL 如何跳转。
|
||||
*
|
||||
* 取值来源(顶层字段 或 page_params 里, 大小写不敏感, 兼容驼峰 openMode):
|
||||
* - open_mode = 'internal' | 'spa' → 'internal' 强制走内部 SPA(忽略域名是否一致)
|
||||
* - open_mode = 'online' | 'web' → 'online' 强制走线上(H5 整页刷新 / MP web-view)
|
||||
* - 未设置 / 其他 → 'auto' 自动: 域名完全一致才内部, 否则线上
|
||||
*
|
||||
* @param {Object} link
|
||||
* @returns {'internal'|'online'|'auto'}
|
||||
*/
|
||||
export function resolveNavMode(link) {
|
||||
if (!link || typeof link !== 'object') return 'auto';
|
||||
const pp = (link.page_params && typeof link.page_params === 'object') ? link.page_params : {};
|
||||
const raw = link.open_mode != null ? link.open_mode
|
||||
: (link.openMode != null ? link.openMode
|
||||
: (pp.open_mode != null ? pp.open_mode : pp.openMode));
|
||||
const m = (typeof raw === 'string') ? raw.trim().toLowerCase() : '';
|
||||
if (m === 'internal' || m === 'spa') return 'internal';
|
||||
if (m === 'online' || m === 'web') return 'online';
|
||||
return 'auto';
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// hasStaleUniacidInUrl
|
||||
// =============================================================
|
||||
// pickCurrentUniacid
|
||||
// =============================================================
|
||||
|
||||
/**
|
||||
* 从两个候选 uniacid 源中选出"系统当前 uniacid"。
|
||||
*
|
||||
* 用法(当前 diyRedirectTo 中的实际调用, 必须与 http.js 行 168 保持一致):
|
||||
* pickCurrentUniacid(
|
||||
* uni.getStorageSync('uniacid'), // 持久化, 登录/初始化写入
|
||||
* Config.uniacid, // 编译期兜底
|
||||
* )
|
||||
*
|
||||
* 优先级: 第一个参数非 0 → 选第一个; 否则选第二个非 0 值; 都没有 → 0。
|
||||
* 0 视为"无 uniacid": 业务上 uniacid 不会是 0, parseInt 后为 0 也算无效。
|
||||
*
|
||||
* ★ 注意: 故意【不读 store.state.uniacid】。当前代码库里 store.state 上从未设置
|
||||
* uniacid 字段(http.js 只用 storage/Config), 若引入 store 分支会出现
|
||||
* "守卫用 A 真值, http 请求用 B 真值"的不一致。
|
||||
*
|
||||
* @param {*} primaryValue 第一候选(运行时持久化值)
|
||||
* @param {*} secondaryValue 第二候选(编译期兜底)
|
||||
* @returns {number} 选出的 uniacid; 都无效时返回 0
|
||||
*/
|
||||
export function pickCurrentUniacid(primaryValue, secondaryValue) {
|
||||
const a = parseInt(primaryValue, 10);
|
||||
if (a) return a; // 非 0 真值
|
||||
const b = parseInt(secondaryValue, 10);
|
||||
if (b) return b;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// hasStaleUniacidInUrl
|
||||
// =============================================================
|
||||
|
||||
/**
|
||||
* 检测 link.wap_url 中【URL 原生】的 uniacid query 与系统当前 uniacid 是否一致。
|
||||
*
|
||||
* 用途: uniacid 是平台租户 ID, 会随租户迁移 / 平台调整而变化。
|
||||
* - 如果数据里的 wap_url 自带的 uniacid 与当前系统不一致,
|
||||
* 说明这份装修数据可能是历史遗留或别的租户的(脏数据),
|
||||
* 不应该被自动改写成内部 SPA(否则会跳到错租户的内页 / 拿错数据)。
|
||||
* - 应当保守地走外链(整页 / web-view), 让原 URL(及其 uniacid)如实生效。
|
||||
*
|
||||
* 关键: 必须【在 resolveLinkUrl 抽走 query 之前】判断, 否则 URL 里的 uniacid 已经
|
||||
* 被搬到 page_params 里, 分不清"URL 原生"还是"外加的"。
|
||||
*
|
||||
* 比较规则: 两侧 parseInt 后比较, 兼容 '2482' vs 2482、URL 编码、空值。
|
||||
*
|
||||
* @param {string} wap_url link.wap_url (resolveLinkUrl 之前的原始值)
|
||||
* @param {string|number|null} currentUniacid 系统当前的 uniacid
|
||||
* (0 / null / '' / undefined 一律视为"无当前 uniacid", 返回 false — 让上游决定怎么做)
|
||||
* @returns {boolean} true = URL 原生 uniacid 与当前不一致(脏数据, 该强制走线上)
|
||||
*/
|
||||
export function hasStaleUniacidInUrl(wap_url, currentUniacid) {
|
||||
if (!wap_url || typeof wap_url !== 'string') return false;
|
||||
if (currentUniacid == null || currentUniacid === '' || currentUniacid === 0) return false;
|
||||
const m = wap_url.match(/[?&]uniacid=([^&#]*)/i);
|
||||
if (!m) return false;
|
||||
let urlUniacid;
|
||||
try { urlUniacid = decodeURIComponent(m[1]); } catch (e) { urlUniacid = m[1]; }
|
||||
const cur = String(currentUniacid);
|
||||
const a = parseInt(urlUniacid, 10);
|
||||
const b = parseInt(cur, 10);
|
||||
// 两侧都能 parse 成数字时按数字比; 否则按字符串比
|
||||
if (!Number.isNaN(a) && !Number.isNaN(b)) return a !== b;
|
||||
return urlUniacid !== cur;
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// appendQueryParams
|
||||
// =============================================================
|
||||
|
||||
/**
|
||||
* 给 URL 追加 query 参数(已存在的 key 会被覆盖)
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {Object} params
|
||||
* @returns {string}
|
||||
*/
|
||||
export function appendQueryParams(url, params) {
|
||||
if (!url) return '';
|
||||
if (!params) return url;
|
||||
|
||||
const hashIndex = url.indexOf('#');
|
||||
let hash = '';
|
||||
let targetUrl = url;
|
||||
if (hashIndex !== -1) {
|
||||
hash = url.substring(hashIndex);
|
||||
targetUrl = url.substring(0, hashIndex);
|
||||
}
|
||||
|
||||
const separator = targetUrl.includes('?') ? '&' : '?';
|
||||
const queryString = Object.entries(params)
|
||||
.filter(([, value]) => value !== undefined && value !== null)
|
||||
// 对象/数组走 JSON.stringify,避免 String({}) 退化成 "[object Object]"
|
||||
.map(([key, value]) => `${key}=${_toParamValueString(value)}`)
|
||||
.join('&');
|
||||
|
||||
return targetUrl + separator + queryString + hash;
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// 跨平台检测 / 编码 / 跳转
|
||||
// =============================================================
|
||||
|
||||
/**
|
||||
* 平台检测 — 4 个目标平台:
|
||||
* - 'h5' 浏览器
|
||||
* - 'mp-weixin' 微信小程序
|
||||
* - 'mp-harmony' 鸿蒙元服务
|
||||
* - 'quickapp' 华为快应用 (实际是 H5 嵌入快应用 Webview)
|
||||
*
|
||||
* 测试覆盖: util.js 在 import 后,可在 default export 上设 __platform 强制指定
|
||||
*/
|
||||
export function getPlatform() {
|
||||
// 1) 测试覆盖: 通过模块级 _testPlatform 注入
|
||||
if (typeof globalThis !== 'undefined' && globalThis.__UTIL_NAVIGATE_TEST_PLATFORM__) {
|
||||
return globalThis.__UTIL_NAVIGATE_TEST_PLATFORM__;
|
||||
}
|
||||
|
||||
// 2) 编译时变量
|
||||
// #ifdef MP-WEIXIN
|
||||
return 'mp-weixin'
|
||||
// #endif
|
||||
// #ifdef MP-HARMONY
|
||||
return 'mp-harmony'
|
||||
// #endif
|
||||
|
||||
// 3) 运行时
|
||||
if (navigator?.userAgent?.includes('mode-quickapp')) { // H5网页,如何判断自己在华为快应用的Webview中
|
||||
return 'quickapp'
|
||||
}
|
||||
|
||||
// #ifdef H5
|
||||
try {
|
||||
var ua = navigator?.userAgent;
|
||||
if (ua) {
|
||||
// 华为快应用内嵌 WebView 的 UA 关键字:HarmonyQuickApp / HuaweiQuickApp / HQABridge / QuickApp
|
||||
const isQuickapp = /HarmonyQuickApp|HuaweiQuickApp|HQABridge|QuickApp/i.test(ua);
|
||||
if (isQuickapp) {
|
||||
return 'quickapp'
|
||||
}
|
||||
}
|
||||
|
||||
} catch (e) {}
|
||||
// #endif
|
||||
|
||||
if (typeof process !== 'undefined' && process.env && process.env.UNI_PLATFORM) {
|
||||
return process.env.UNI_PLATFORM;
|
||||
}
|
||||
if (typeof window !== 'undefined' && typeof window.location !== 'undefined' && typeof uni === 'undefined') {
|
||||
return 'h5';
|
||||
}
|
||||
if (typeof uni !== 'undefined' && typeof uni.getSystemInfoSync === 'function') {
|
||||
try {
|
||||
const info = uni?.getSystemInfoSync();
|
||||
const p = (info && info.platform) || '';
|
||||
if (/harmony|ohos/i.test(p)) return 'mp-harmony';
|
||||
if (info.mp === true || /miniprogram/i.test(info.appName || '')) return 'mp-weixin';
|
||||
if (/quickapp|huawei/i.test(p)) return 'quickapp';
|
||||
return 'h5';
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
// 默认返回
|
||||
return 'h5';
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否是在华为快应用的WebView中
|
||||
* @returns
|
||||
*/
|
||||
export function isHarmonyQuickAppWebview() {
|
||||
return getPlatform() === 'quickapp'
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否需要 JS 侧主动 encodeURIComponent
|
||||
* 4 平台都需要(true)
|
||||
*/
|
||||
export function shouldEncodeUrl() {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 仅编码 URL 分隔符 / 边界相关字符,保留中文 / ASCII 字母数字原样
|
||||
*
|
||||
* 解决问题:
|
||||
* - 微信小程序: 不会对 url 做整体 encode,只 split on '&' / '=',但 **不** decode 值
|
||||
* 给 onLoad。所以 JS 必须 encode `&` `=` `?` `#` 空格(防止 query 边界被破坏),
|
||||
* 但 **不能** encode 中文(否则 onLoad 拿到已编码字符串,显示成乱码)。
|
||||
* - 鸿蒙元服务: 会整体 encode url(包括中文和已编码的 %xx)。
|
||||
* 所以 JS 完全不 encode(让平台做)。见下面 mp-harmony 分支。
|
||||
* - H5 / 快应用: 浏览器不 encode,JS 必须 encode 一次(用标准 encodeURIComponent)。
|
||||
*
|
||||
* @param {string} s 已 decode roundtrip 后的原文
|
||||
* @returns {string}
|
||||
*/
|
||||
function _encodeUrlDelimiters(s) {
|
||||
// 只 replace 这 5 个 URL 分隔 / 边界相关字符,其他(中文 / 字母 / 数字 / 标点等)原样
|
||||
return s.replace(/[&=#?\s]/g, c => encodeURIComponent(c));
|
||||
}
|
||||
|
||||
export function _safeEncodeForPlatform(v) {
|
||||
const s = _toParamValueString(v);
|
||||
|
||||
// decode roundtrip: 兼容上游已 encode 过的入参(无论平台都做,避免双编码)
|
||||
let once = s;
|
||||
try {
|
||||
if (/%[0-9a-fA-F]{2}/.test(s)) {
|
||||
once = decodeURIComponent(s);
|
||||
}
|
||||
} catch (e) {
|
||||
once = s;
|
||||
}
|
||||
|
||||
const platform = getPlatform();
|
||||
|
||||
// 微信小程序: split on '&' / '=' 解析 url,但不 decode value 给 onLoad。
|
||||
// - 中文 / 字母 / 数字 → 原样保留(否则 onLoad 拿到 %xx 乱码)
|
||||
// - `&` `=` `?` `#` 空格 → 必须 encode(否则 query 边界被破坏, src 等含 URL 的字段被截断,webview 打不开)
|
||||
if (['mp-weixin','mp-harmony'].includes(platform)) {
|
||||
return _encodeUrlDelimiters(once);
|
||||
}
|
||||
|
||||
// H5 / 华为快应用: 浏览器不自动编码, JS 侧必须主动 encode 一次(标准 encodeURIComponent)
|
||||
return encodeURIComponent(once);
|
||||
}
|
||||
|
||||
/**
|
||||
* 跨平台跳转 API 调度
|
||||
*
|
||||
* @param {Object} args
|
||||
* @param {string} args.to
|
||||
* @param {string} [args.mode='navigateTo']
|
||||
* @param {string} [args.platform] 不传则自动 getPlatform()
|
||||
* @returns {{ url: string, mode: string, api: string }}
|
||||
*/
|
||||
export function _navigateTo({ to, mode, platform } = {}) {
|
||||
const p = platform || getPlatform();
|
||||
const m = mode || 'navigateTo';
|
||||
|
||||
// H5: 用 window.location
|
||||
if (p === 'h5') {
|
||||
if (typeof window === 'undefined' || typeof window.location === 'undefined') {
|
||||
console.warn('[navigate] H5 环境下没有 window.location');
|
||||
return { url: to, mode: m, api: 'noop' };
|
||||
}
|
||||
try {
|
||||
if (m === 'reLaunch' || m === 'redirectTo') {
|
||||
window.location.replace(to);
|
||||
} else {
|
||||
window.location.href = to;
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('[navigate] H5 跳转失败:', e);
|
||||
}
|
||||
return { url: to, mode: m, api: 'window.location' };
|
||||
}
|
||||
|
||||
// 微信 / 鸿蒙 / 快应用: 走对应的 uni API
|
||||
// (华为快应用实际是 H5 嵌入快应用 Webview, uni 全局可用)
|
||||
if (typeof uni === 'undefined') {
|
||||
console.warn('[navigate] 非 H5 环境下没有 uni 全局');
|
||||
return { url: to, mode: m, api: 'noop' };
|
||||
}
|
||||
|
||||
let api = 'navigateTo';
|
||||
switch (m) {
|
||||
case 'tabbar':
|
||||
case 'switchTab':
|
||||
// 鸿蒙元服务: uni.switchTab 静默失败, 用 reLaunch 兜底
|
||||
// (微信 / 快应用: 正常用 uni.switchTab)
|
||||
if (p === 'mp-harmony') {
|
||||
uni.reLaunch({ url: to });
|
||||
api = 'reLaunch';
|
||||
} else {
|
||||
uni.switchTab({ url: to });
|
||||
api = 'switchTab';
|
||||
}
|
||||
break;
|
||||
case 'redirectTo':
|
||||
uni.redirectTo({ url: to });
|
||||
api = 'redirectTo';
|
||||
break;
|
||||
case 'reLaunch':
|
||||
uni.reLaunch({ url: to });
|
||||
api = 'reLaunch';
|
||||
break;
|
||||
case 'navigateTo':
|
||||
default:
|
||||
uni.navigateTo({ url: to });
|
||||
api = 'navigateTo';
|
||||
break;
|
||||
}
|
||||
return { url: to, mode: m, api };
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// 兼容: 把所有函数打包到一个对象(用于 util.js 挂载到 default export)
|
||||
// =============================================================
|
||||
|
||||
/**
|
||||
* 把所有跳转相关函数打包到一个对象, util.js 把它挂载到 default export
|
||||
* 上, 保持 this.$util.cleanParamUrls / this.$util.redirectTo 等 API 兼容
|
||||
*
|
||||
* @param {Object} [opts]
|
||||
* @param {string} [opts.platform] 强制指定平台(测试用)
|
||||
* @returns {Object}
|
||||
*/
|
||||
export function createNavigateApi(opts = {}) {
|
||||
if (opts.platform) {
|
||||
// 测试用: 注入到 globalThis,getPlatform 会优先读
|
||||
if (typeof globalThis !== 'undefined') {
|
||||
globalThis.__UTIL_NAVIGATE_TEST_PLATFORM__ = opts.platform;
|
||||
}
|
||||
}
|
||||
return {
|
||||
getPlatform,
|
||||
shouldEncodeUrl,
|
||||
_safeEncodeForPlatform,
|
||||
_navigateTo,
|
||||
cleanParamUrls,
|
||||
normalizeUrl,
|
||||
appendQueryParams,
|
||||
extractInternalAppPath,
|
||||
parsePageParams,
|
||||
resolveLinkUrl,
|
||||
decodeEntity,
|
||||
};
|
||||
}
|
||||
649
common/js/util-tabbar.js
Normal file
649
common/js/util-tabbar.js
Normal file
@@ -0,0 +1,649 @@
|
||||
/**
|
||||
* util-tabbar.js
|
||||
*
|
||||
* TabBar / 子包路径相关工具集 — 从 util.js 拆分出来
|
||||
*
|
||||
* 包含的函数(全部服务于 redirectTo / diyRedirectTo 的 tabBar 命中判断):
|
||||
* - resolvePageUrl : 根据 page_key + params 解析得到实际跳转 URL
|
||||
* - isPageInRouteList : 判断当前路由是否命中 page_routes 列表
|
||||
* - resolveLinkUrl : 解析 link 对象得到最终 URL(合并 wap_url query 进 page_params)
|
||||
* - systemTabBarList : 当前最新的 tabBar.list 配置
|
||||
* - adaptSubpackageUrl : 子包路径前缀映射(/pages/order/ → /pages_order/)
|
||||
* - _normalizePath : 归一化任意路径(私有,内部用)
|
||||
* - isTabBarRootPage : 判断给定路径是否是 TabBar 根页面
|
||||
* - isCurrentPageTabBarRoot : 判断**当前**页面是否是 TabBar 根页面(依赖 getCurrentPages/store)
|
||||
* - checkTabBarActive : 检查 tabBar 是否激活
|
||||
*
|
||||
* 设计原则:
|
||||
* 1. 不依赖 util.js,避免循环依赖
|
||||
* 2. 纯函数为主(isCurrentPageTabBarRoot 除外,它依赖 getCurrentPages 和 store,
|
||||
* 业务方在调用时手动注入 store 即可)
|
||||
* 3. PAGE_KEY_MAP / NO_TAB_PAGES / PAGE_TAB_MAP / TAB_BAR_KEYS 仍然在 util.js(业务配置)
|
||||
* util-tabbar.js 接受外部传入,提高复用性
|
||||
*/
|
||||
|
||||
import { _toParamValueString } from './util-navigate.js';
|
||||
|
||||
// =============================================================
|
||||
// PAGE_KEY → 实际 URL 解析
|
||||
// =============================================================
|
||||
|
||||
/**
|
||||
* 根据 page_key + params 解析得到实际跳转 URL
|
||||
* @param {string} page_key 页面语义常量, 如 PAGE_GOODS_LIST
|
||||
* @param {Object} params 页面参数(JSON 对象)
|
||||
* @param {Object} [pageKeyMap={}] page_key → 实际路径的映射表(由调用方注入,通常是 PAGE_KEY_MAP)
|
||||
* @returns {string|null} 实际 URL(已拼接参数)或 null(未匹配)
|
||||
*/
|
||||
export function resolvePageUrl(page_key, params = {}, pageKeyMap = {}) {
|
||||
if (!page_key || !pageKeyMap[page_key]) {
|
||||
return null;
|
||||
}
|
||||
let url = pageKeyMap[page_key];
|
||||
if (params && typeof params === 'object' && Object.keys(params).length > 0) {
|
||||
const parts = [];
|
||||
Object.keys(params).forEach(function (key) {
|
||||
const value = params[key];
|
||||
if (value === null || value === undefined || value === '') return;
|
||||
// 对象/数组走 JSON.stringify, 避免 String({}) 退化成 "[object Object]"
|
||||
// 消费端 resolveLinkUrl 已用 JSON.parse 还原
|
||||
const encodedValue = _toParamValueString(value);
|
||||
// H5: 浏览器不自动编码, 需要手动 encodeURIComponent
|
||||
// 小程序 / App: uni.navigateTo 会自动编码, 这里不能再 encode, 否则双重编码
|
||||
// #ifdef H5
|
||||
parts.push(key + '=' + encodeURIComponent(encodedValue));
|
||||
// #endif
|
||||
// #ifndef H5
|
||||
parts.push(key + '=' + encodedValue);
|
||||
// #endif
|
||||
});
|
||||
if (parts.length > 0) {
|
||||
url = url + (url.indexOf('?') !== -1 ? '&' : '?') + parts.join('&');
|
||||
}
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断当前路由是否命中 page_routes 列表
|
||||
* 支持 3 种写法, 可混合使用:
|
||||
* 1) PAGE_KEY_MAP 的 key → 如 "PAGE_INDEX"
|
||||
* 2) 实际页面路径 → 如 "/pages/index/index"
|
||||
* 3) 通配符路径 → 如 "/pages_tool/*" 或 "PAGE_ORDER_*"
|
||||
*
|
||||
* @param {string} currentRoute 当前页面路径(会自动补 / 前缀)
|
||||
* @param {string[]} routeList 后台配置的 page_routes 数组
|
||||
* @param {Object} [pageKeyMap={}] PAGE_KEY_MAP
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isPageInRouteList(currentRoute, routeList, pageKeyMap = {}) {
|
||||
if (!currentRoute || !routeList || !Array.isArray(routeList) || routeList.length === 0) {
|
||||
return false;
|
||||
}
|
||||
const route = currentRoute.startsWith('/') ? currentRoute : '/' + currentRoute;
|
||||
|
||||
for (const item of routeList) {
|
||||
if (!item || typeof item !== 'string') continue;
|
||||
const entry = item.trim();
|
||||
if (!entry) continue;
|
||||
|
||||
// 1) 通配符 /pages_tool/* 或 PAGE_ORDER_*
|
||||
if (entry.endsWith('/*')) {
|
||||
const prefix = entry.slice(0, -1);
|
||||
if (route.startsWith(prefix)) return true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.endsWith('_*') && pageKeyMap) {
|
||||
const keyPrefix = entry.slice(0, -1);
|
||||
const matchedPaths = [];
|
||||
for (const k of Object.keys(pageKeyMap)) {
|
||||
if (k.startsWith(keyPrefix) && pageKeyMap[k]) {
|
||||
matchedPaths.push(pageKeyMap[k]);
|
||||
}
|
||||
}
|
||||
for (const p of matchedPaths) {
|
||||
const pn = p.startsWith('/') ? p : '/' + p;
|
||||
const dirPrefix = pn.substring(0, pn.lastIndexOf('/') + 1);
|
||||
if (route.startsWith(dirPrefix)) return true;
|
||||
if (route === pn) return true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// 2) PAGE_KEY 名称
|
||||
if (pageKeyMap && pageKeyMap[entry]) {
|
||||
let mapped = pageKeyMap[entry];
|
||||
mapped = mapped.startsWith('/') ? mapped : '/' + mapped;
|
||||
if (route === mapped) return true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 3) 实际路径
|
||||
if (entry.startsWith('/')) {
|
||||
if (route === entry) return true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// resolveLinkUrl
|
||||
// =============================================================
|
||||
|
||||
/**
|
||||
* 解析 link 对象得到最终可跳转的 URL
|
||||
* 同时把 wap_url 自带的 query 参数与 page_params 合并, 写入 link.page_params;
|
||||
* 并把 link.wap_url 改为不含 query 的 path, 避免后续 redirectTo 重复附加
|
||||
* 优先级: page_params > wap_url query (新机制优先)
|
||||
*
|
||||
* @param {Object} link
|
||||
* @param {Object} [opts]
|
||||
* @param {Object} [opts.pageKeyMap={}] PAGE_KEY_MAP
|
||||
* @param {Function} [opts.parsePageParams] page_params 解析函数(默认用 util-navigate 的)
|
||||
* @param {Function} [opts.resolvePageUrlFn] page_key → URL 函数(默认用本文件内)
|
||||
* @param {Function} [opts.decodeEntity] HTML 实体解码函数
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function resolveLinkUrl(link, opts = {}) {
|
||||
const {
|
||||
pageKeyMap = {},
|
||||
parsePageParams = null,
|
||||
resolvePageUrlFn = null,
|
||||
decodeEntity = null,
|
||||
} = opts;
|
||||
|
||||
if (!link) return null;
|
||||
|
||||
// 0. 把 wap_url 中的 query 合并到 page_params
|
||||
if (link.wap_url) {
|
||||
const _decode = decodeEntity || ((s) => s);
|
||||
const decodedWap = _decode(link.wap_url);
|
||||
const queryIdx = decodedWap.indexOf('?');
|
||||
if (queryIdx !== -1) {
|
||||
const path = decodedWap.substring(0, queryIdx);
|
||||
const queryStr = decodedWap.substring(queryIdx + 1);
|
||||
const urlParams = {};
|
||||
queryStr.split('&').forEach((kv) => {
|
||||
if (!kv) return;
|
||||
const eqIdx = kv.indexOf('=');
|
||||
const k = eqIdx === -1 ? kv : kv.substring(0, eqIdx);
|
||||
const v = eqIdx === -1 ? '' : kv.substring(eqIdx + 1);
|
||||
if (k) urlParams[k] = v;
|
||||
});
|
||||
// 解析 page_params (可能是字符串或对象) — 走统一 helper
|
||||
const _parse = parsePageParams || ((p) => (p && typeof p === 'object') ? p : {});
|
||||
const pageParams = _parse(link.page_params);
|
||||
// 合并: page_params 覆盖 urlParams (新机制优先)
|
||||
link.page_params = Object.assign({}, urlParams, pageParams);
|
||||
// 把 link.wap_url 改为不含 query 的 path
|
||||
link.wap_url = path;
|
||||
}
|
||||
}
|
||||
// 1. 优先使用 page_key(新机制)
|
||||
if (link.page_key) {
|
||||
const _parse = parsePageParams || ((p) => (p && typeof p === 'object') ? p : {});
|
||||
const _resolvePageUrl = resolvePageUrlFn || ((key, params) => resolvePageUrl(key, params, pageKeyMap));
|
||||
const params = _parse(link.page_params);
|
||||
const url = _resolvePageUrl(link.page_key, params);
|
||||
if (url) return url;
|
||||
}
|
||||
// 2. 回退: 旧的 wap_url(已被处理为不含 query 的 path)
|
||||
if (link.wap_url) {
|
||||
return link.wap_url;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// TabBar 列表与适配
|
||||
// =============================================================
|
||||
|
||||
/**
|
||||
* 当前最新的 tabBar.list
|
||||
* 注意: 该函数需要业务方传入 4 个常量(INDEX/CATEGORY/CONTACT/MEMBER)
|
||||
* 通常由 util.js 在 import 后调用 _setSystemTabBarList 注入
|
||||
*/
|
||||
export function makeSystemTabBarList(indexUrl, categoryUrl, contactUrl, memberUrl) {
|
||||
return [indexUrl, categoryUrl, contactUrl, memberUrl];
|
||||
}
|
||||
|
||||
/**
|
||||
* 适配子包路径
|
||||
* 把老路径 /pages/xxx/ 映射到新路径 /pages_xxx/
|
||||
*
|
||||
* @param {string} url
|
||||
* @returns {string}
|
||||
*/
|
||||
export function adaptSubpackageUrl(url) {
|
||||
if (!url) return url;
|
||||
// 定义前缀映射表(key=旧前缀, value=新分包前缀)
|
||||
const urlPrefixMap = {
|
||||
'/pages/promotion/': '/pages_promotion/',
|
||||
'/pages/order/': '/pages_order/',
|
||||
'/pages/goods/': '/pages_goods/',
|
||||
'/pages/member/': '/pages_tool/member/',
|
||||
'/pages/login/': '/pages_tool/login/',
|
||||
'/pages/agreement/': '/pages_tool/agreement/',
|
||||
'/pages/article/': '/pages_tool/article/',
|
||||
'/pages/cases/': '/pages_tool/cases/',
|
||||
'/pages/contact/': '/pages_tool/contact/',
|
||||
'/pages/files/': '/pages_tool/files/',
|
||||
'/pages/form/': '/pages_tool/form/',
|
||||
'/pages/help/': '/pages_tool/help/',
|
||||
'/pages/notice/': '/pages_tool/notice/',
|
||||
'/pages/pay/': '/pages_tool/pay/',
|
||||
'/pages/recharge/': '/pages_tool/recharge/',
|
||||
'/pages/seal/': '/pages_tool/seal/',
|
||||
'/pages/storeclose/': '/pages_tool/storeclose/',
|
||||
'/pages/vr/': '/pages_tool/vr/',
|
||||
'/pages/weapp/': '/pages_tool/weapp/',
|
||||
'/pages/webview/': '/pages_tool/webview/',
|
||||
};
|
||||
|
||||
const prefixes = Object.keys(urlPrefixMap);
|
||||
if (prefixes.length === 0) return url;
|
||||
|
||||
const regex = new RegExp(
|
||||
'^(' + prefixes.map((key) =>
|
||||
key.replace(/\//g, '\\/').replace(/\*/g, '.*'),
|
||||
).join('|') + ')',
|
||||
);
|
||||
|
||||
function replacePrefix(str) {
|
||||
return str.replace(regex, (match) => {
|
||||
const newPrefix = urlPrefixMap[match];
|
||||
return newPrefix || match;
|
||||
});
|
||||
}
|
||||
|
||||
// 兜底: 把 3 个及以上的连续 `/` 收敛为 2 个, 只动 path 部分
|
||||
const collapsed = url.replace(/([^:])\/{3,}/g, '$1//');
|
||||
return replacePrefix(collapsed);
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// TabBar 命中判断(私有辅助)
|
||||
// =============================================================
|
||||
|
||||
/**
|
||||
* 归一化任意路径: 确保以 '/' 开头, 去除 query, 适配子包
|
||||
* (私有, 仅本模块内部使用)
|
||||
*/
|
||||
function _normalizePath(path) {
|
||||
if (!path) return '';
|
||||
const normalized = path.startsWith('/') ? path : '/' + path;
|
||||
return adaptSubpackageUrl(normalized).split('?')[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* 从归一化路径提取分包名(parts[1])
|
||||
* (私有, 仅本模块内部使用)
|
||||
*/
|
||||
function _getPackageName(normalizedPath) {
|
||||
const parts = normalizedPath.split('/');
|
||||
return parts[1] || '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析"当前分包的入口 tab URL"
|
||||
*
|
||||
* 把 diy-bottom-nav.vue#updateCurrentRoute 里的查找逻辑抽成纯函数,
|
||||
* 方便单元测试覆盖所有跳转场景, 同时让组件代码变薄.
|
||||
*
|
||||
* 查找优先级 (2026-07-16 重构, 对齐 iOS HIG):
|
||||
* 1) 当前页面精确命中某个 tab 根页面 → 它就是入口 (tab→tab 跳转)
|
||||
* 2) 同包内导航 (上一包 == 当前包) → 用当前包的第一个 tab
|
||||
* 例: /pages_goods/list → /pages_goods/detail → CATEGORY 高亮
|
||||
* 3) 跨包导航 (上一包 != 当前包) → 历史栈倒序查找最近一次访问的 TabBar 页
|
||||
* 例: home → diy → HOME 高亮 (从哪个 tab 出发, 非 tab 页就归属哪个 tab)
|
||||
* 4) 跨包但历史栈中无 tab → 退到当前包第一个 tab
|
||||
* 5) 深链无历史 → 返回 null (iOS HIG: 无来源时不点亮)
|
||||
*
|
||||
* 与 checkTabBarActive 的关系:
|
||||
* - resolveEntryTab 写入 packageEntryTab[currentPackage]
|
||||
* - checkTabBarActive 通过 _findMatchingTabUrl 读取
|
||||
* - 两者都不会做"无历史时的同分包兜底", 保证 iOS HIG 行为
|
||||
*
|
||||
* @param {Object} opts
|
||||
* @param {string} opts.currentPageRoute 当前页面路由 (已 _normalizeRoute, 不含 query)
|
||||
* @param {Object} opts.tabBarList tabBar 配置对象 ($store.state.tabBarList)
|
||||
* @param {string[]} [opts.historyRoutes=[]] 历史栈路由列表 (不含 query, 不含当前页;
|
||||
* 已 _normalizeRoute 但未 adaptSubpackageUrl, 函数内部会适配)
|
||||
* @param {Set<string>} [opts.noTabPages] NO_TAB_PAGES 集合 (含 login/pay/AI 等全屏流程页)
|
||||
* 这些页视为"modal", 不参与包归属判定
|
||||
* @returns {string|null} 入口 tab URL (已适配子包路径、不含 query) 或 null
|
||||
*/
|
||||
export function resolveEntryTab(opts = {}) {
|
||||
const {
|
||||
currentPageRoute = '',
|
||||
tabBarList = null,
|
||||
historyRoutes = [],
|
||||
noTabPages = null,
|
||||
} = opts;
|
||||
|
||||
if (!currentPageRoute || !tabBarList || !Array.isArray(tabBarList.list)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const tabUrls = tabBarList.list
|
||||
.filter((item) => item && item.link && item.link.wap_url)
|
||||
.map((item) => adaptSubpackageUrl(item.link.wap_url).split('?')[0]);
|
||||
|
||||
if (tabUrls.length === 0) return null;
|
||||
|
||||
const normalizedCurrent = currentPageRoute.split('?')[0];
|
||||
const currentPackageName = _getPackageName(normalizedCurrent);
|
||||
|
||||
// 1) 当前页面精确命中某个 tab → 它就是入口
|
||||
const exactMatch = tabUrls.find((url) => url === normalizedCurrent);
|
||||
if (exactMatch) return exactMatch;
|
||||
|
||||
// 工具: 判定一个路由是否"参与归属判定"
|
||||
// 跳过 null/空 + NO_TAB_PAGES (login/pay/AI 等 modal 页, 不算中间步骤)
|
||||
const isSkippable = (route) => {
|
||||
if (!route) return true;
|
||||
if (noTabPages && typeof noTabPages.has === 'function') {
|
||||
const normalized = adaptSubpackageUrl(route).split('?')[0];
|
||||
if (noTabPages.has(normalized)) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
// 找出"最近的上一页"属于哪个包 (跳过 null/空 + NO_TAB_PAGES)
|
||||
let lastPackageName = '';
|
||||
let hasPrevPage = false;
|
||||
if (Array.isArray(historyRoutes) && historyRoutes.length > 0) {
|
||||
for (let i = historyRoutes.length - 1; i >= 0; i--) {
|
||||
const route = historyRoutes[i];
|
||||
if (isSkippable(route)) continue;
|
||||
lastPackageName = _getPackageName(adaptSubpackageUrl(route).split('?')[0]);
|
||||
hasPrevPage = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const isSamePackage = hasPrevPage && lastPackageName === currentPackageName;
|
||||
const isCrossPackage = hasPrevPage && lastPackageName !== currentPackageName;
|
||||
|
||||
// 2) 同包内导航: 用当前包的第一个 tab
|
||||
// 业务约定: 包内"主入口" = tabBarList 中该包出现的第一个 tab
|
||||
// 例: pages_goods 有 [CATEGORY, CART] 两个 tab, 用户在 goods 频道内任何页面都归 CATEGORY
|
||||
// 理由: CATEGORY 是商品频道的入口, 比 CART (特定子场景) 更"通用", 视觉一致
|
||||
// 注意: 业务侧 tab 配置顺序很关键, 若有 pages_goods 出现 3+ tab, 主入口必须是业务上正确的那个
|
||||
if (isSamePackage) {
|
||||
const samePackage = tabUrls.find((url) => _getPackageName(url) === currentPackageName);
|
||||
if (samePackage) return samePackage;
|
||||
}
|
||||
|
||||
// 3) 跨包导航: 历史栈倒序查找最近一次访问的 TabBar 页 → 来源 tab
|
||||
// 规则: 从哪个 TabBar 出发, 非 tab 页就归属哪个 TabBar 高亮
|
||||
// 注意: 跳过 NO_TAB_PAGES, 因为 login/pay 等是 modal, 不是真实的导航步骤
|
||||
if (isCrossPackage) {
|
||||
for (let i = historyRoutes.length - 1; i >= 0; i--) {
|
||||
const route = historyRoutes[i];
|
||||
if (isSkippable(route)) continue;
|
||||
const normalized = adaptSubpackageUrl(route).split('?')[0];
|
||||
const exactTab = tabUrls.find((url) => url === normalized);
|
||||
if (exactTab) return exactTab;
|
||||
}
|
||||
// 4) 跨包但历史栈中无 tab → 退到当前包第一个 tab
|
||||
const samePackage = tabUrls.find((url) => _getPackageName(url) === currentPackageName);
|
||||
if (samePackage) return samePackage;
|
||||
}
|
||||
|
||||
// 5) 深链无历史 / 跳过 NO_TAB_PAGES 后没找到 → 返回 null
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 给定当前页面路径 + tab 配置, 返回当前页面所属的 tab URL
|
||||
* 优先级: 精确匹配 > packageEntryTab
|
||||
*
|
||||
* 注意 (2026-07-16): 旧版本在 packageEntryTab 没命中时会回退到"同分包第一个 tab",
|
||||
* 这导致深链冷启动时 /pages_tool/* 页被错误标成"我的"。
|
||||
* 现在改为"找不到就返回 null", 后续 checkTabBarActive 也不会再兜底,
|
||||
* 行为对齐 iOS HIG (深链无历史时, TabBar 不点亮)。
|
||||
*
|
||||
* (私有)
|
||||
*/
|
||||
function _findMatchingTabUrl(currentPagePath, tabBarList, packageEntryTab) {
|
||||
if (!tabBarList || !tabBarList.list || !Array.isArray(tabBarList.list)) return null;
|
||||
|
||||
const tabUrls = tabBarList.list
|
||||
.filter((item) => item.link && item.link.wap_url)
|
||||
.map((item) => _normalizePath(item.link.wap_url));
|
||||
|
||||
const normalizedCurrent = _normalizePath(currentPagePath);
|
||||
|
||||
// 1) 精确匹配 → 当前页面就是 tab 页面
|
||||
const exactMatch = tabUrls.find((url) => url === normalizedCurrent);
|
||||
if (exactMatch) return exactMatch;
|
||||
|
||||
// 2) 通过 packageEntryTab(由 updateCurrentRoute/redirectTo 写入)
|
||||
const packageName = _getPackageName(normalizedCurrent);
|
||||
if (packageEntryTab && typeof packageEntryTab === 'object' && packageEntryTab[packageName]) {
|
||||
const entryTab = packageEntryTab[packageName];
|
||||
const normalizedEntry = _normalizePath(entryTab);
|
||||
if (tabUrls.includes(normalizedEntry)) return normalizedEntry;
|
||||
}
|
||||
|
||||
// 3) 不再做"同分包兜底" — 找不到就返回 null
|
||||
// 深链冷启动场景下无历史可参考, iOS HIG 推荐 TabBar 不点亮
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通配符路径匹配 — 支持 '/pages_tool/member/*' 形式
|
||||
*
|
||||
* 规则:
|
||||
* - pattern 必须以 '/*' 结尾
|
||||
* - '*' 匹配"前缀之后的至少一个字符段"
|
||||
* - 例: '/pages_tool/member/*' 匹配 '/pages_tool/member/info' 但不匹配 '/pages_tool/member'
|
||||
*
|
||||
* @param {string} path 当前路径 (已 _normalizePath)
|
||||
* @param {string} pattern 通配符 pattern
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function _matchWildcardPath(path, pattern) {
|
||||
if (!path || !pattern) return false;
|
||||
if (!pattern.endsWith('/*')) return false;
|
||||
const prefix = pattern.slice(0, -2); // 去掉 '/*'
|
||||
// 必须有至少一个字符在 '/*' 之后, 即 path 比 prefix 长, 且以 prefix + '/' 开头
|
||||
return path.length > prefix.length + 1 && path.startsWith(prefix + '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* 在 PAGE_TAB_MAP (精确) + PAGE_TAB_WILDCARDS (通配) 中查找当前页面对应的 tab
|
||||
*
|
||||
* 优先级: 精确匹配 > 通配符匹配
|
||||
* 返回值可以是:
|
||||
* - tab URL 字符串 → 命中, 高亮该 tab
|
||||
* - null → 显式声明"无 tab", 一定不高亮
|
||||
* - undefined → 未声明, 调用方走兜底逻辑 (history-walk / 无 tab)
|
||||
*
|
||||
* @param {string} currentPath 当前页面路径 (已 _normalizePath)
|
||||
* @param {Object} pageTabMap 精确绑定表 (PAGE_TAB_MAP)
|
||||
* @param {Array<{pattern: string, tab: string}>} pageTabWildcards 通配符列表 (PAGE_TAB_WILDCARDS)
|
||||
* @returns {string|null|undefined}
|
||||
*/
|
||||
export function lookupPageTabMap(currentPath, pageTabMap, pageTabWildcards) {
|
||||
if (!currentPath) return undefined;
|
||||
|
||||
// 1) 精确匹配
|
||||
if (pageTabMap && Object.prototype.hasOwnProperty.call(pageTabMap, currentPath)) {
|
||||
return pageTabMap[currentPath];
|
||||
}
|
||||
|
||||
// 2) 通配符匹配
|
||||
if (Array.isArray(pageTabWildcards)) {
|
||||
for (const entry of pageTabWildcards) {
|
||||
if (entry && entry.pattern && _matchWildcardPath(currentPath, entry.pattern)) {
|
||||
return entry.tab;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断给定路径是否是 TabBar 根页面(与 diy_bottom_nav 中任意一项精确相等)
|
||||
*
|
||||
* @param {string} pagePath 当前页面路径(可以带/不带前导斜杠、可以带 query)
|
||||
* @param {Object|null} tabBarList tabBar 配置对象($store.state.tabBarList)
|
||||
* @returns {boolean} 如果是 TabBar 根页面返回 true
|
||||
*/
|
||||
export function isTabBarRootPage(pagePath, tabBarList) {
|
||||
if (!pagePath) return false;
|
||||
if (!tabBarList || !tabBarList.list || !Array.isArray(tabBarList.list)) return false;
|
||||
const normalizedCurrent = _normalizePath(pagePath);
|
||||
if (!normalizedCurrent) return false;
|
||||
return tabBarList.list.some((item) => {
|
||||
if (!item || !item.link || !item.link.wap_url) return false;
|
||||
const normalizedTab = _normalizePath(item.link.wap_url);
|
||||
return normalizedTab === normalizedCurrent;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断**当前**页面是否是 TabBar 根页面
|
||||
* 封装了 getCurrentPages() + isTabBarRootPage 的组合, 供业务组件在弹窗/操作前判断
|
||||
*
|
||||
* 调用方需要注入 getCurrentPages 和 store:
|
||||
* isCurrentPageTabBarRoot({
|
||||
* getCurrentPages: typeof getCurrentPages === 'function' ? getCurrentPages : null,
|
||||
* store,
|
||||
* tabBarList: null, // 不传则从 store.state.tabBarList 取
|
||||
* })
|
||||
*
|
||||
* @param {Object} [opts={}]
|
||||
* @param {Function} [opts.getCurrentPages]
|
||||
* @param {Object} [opts.store]
|
||||
* @param {Object} [opts.tabBarList]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isCurrentPageTabBarRoot(opts = {}) {
|
||||
try {
|
||||
const gcp = opts.getCurrentPages || (typeof getCurrentPages === 'function' ? getCurrentPages : null);
|
||||
if (!gcp) return false;
|
||||
const pages = gcp();
|
||||
if (!pages || !pages.length) return false;
|
||||
const currentRoute = '/' + String(pages[pages.length - 1].route || '').replace(/^\//, '');
|
||||
if (!currentRoute) return false;
|
||||
const tabBarList = opts.tabBarList
|
||||
|| (opts.store && opts.store.state ? opts.store.state.tabBarList : null);
|
||||
return isTabBarRootPage(currentRoute, tabBarList);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查 tabBar 是否激活
|
||||
*
|
||||
* @param {string} linkUrl 链接路径 /pages/goods/category
|
||||
* @param {string} currentPageRoute 当前页面路径 /pages_goods/category
|
||||
* @param {Object} tabBarList tabBar 配置对象, 用于动态判断
|
||||
* @param {Object} packageEntryTab 追踪每个分包的入口 Tab { 'pages_goods': '/pages_goods/category' }
|
||||
* @param {Object} [currentPageQuery={}] 当前页面 query 参数, 用于读取 from_tab 来源记忆
|
||||
* @param {Object} [opts={}]
|
||||
* @param {Set} [opts.noTabPages] 独立流程页集合(NO_TAB_PAGES)
|
||||
* @param {Object} [opts.pageTabMap] 页面级 Tab 精确绑定表(PAGE_TAB_MAP)
|
||||
* @param {Array<{pattern: string, tab: string}>} [opts.pageTabWildcards=[]] 页面级 Tab 通配符表(PAGE_TAB_WILDCARDS)
|
||||
* @returns {boolean} 是否激活
|
||||
*/
|
||||
export function checkTabBarActive(
|
||||
linkUrl,
|
||||
currentPageRoute,
|
||||
tabBarList,
|
||||
packageEntryTab,
|
||||
currentPageQuery = {},
|
||||
opts = {},
|
||||
) {
|
||||
const { noTabPages = null, pageTabMap = {}, pageTabWildcards = [] } = opts;
|
||||
|
||||
// __TABBAR_DEBUG__: 开启后打印每一步决策, 用于排查"为什么我的 tab 不亮"
|
||||
// 开启方式 (任选一种):
|
||||
// - 全局: window.__TABBAR_DEBUG__ = true
|
||||
// - 本次: opts.debug = true
|
||||
const DEBUG = (typeof globalThis !== 'undefined' && globalThis.__TABBAR_DEBUG__)
|
||||
|| opts.debug === true;
|
||||
const _log = DEBUG ? (...a) => console.log('[TABBAR]', ...a) : () => {};
|
||||
_log('checkTabBarActive called', { linkUrl, currentPageRoute, hasTabBarList: !!tabBarList });
|
||||
|
||||
// 1) 归一化 linkUrl: 统一前导 '/' + 子包路径适配 + 去除 query
|
||||
const normalizedLink = _normalizePath(linkUrl);
|
||||
const normalizedCurrent = _normalizePath(currentPageRoute);
|
||||
|
||||
if (!normalizedLink) {
|
||||
_log('step 1: no linkUrl → false');
|
||||
return false;
|
||||
}
|
||||
|
||||
// 2) 精确匹配: 当前页面就是 linkUrl 指向的页面
|
||||
if (normalizedLink === normalizedCurrent) {
|
||||
_log('step 2: exact match → true', { link: normalizedLink });
|
||||
return true;
|
||||
}
|
||||
|
||||
// 3) 独立流程页: 不点亮任何 Tab
|
||||
if (noTabPages && noTabPages.has && noTabPages.has(normalizedCurrent)) {
|
||||
_log('step 3: NO_TAB_PAGES hit → false', { current: normalizedCurrent });
|
||||
return false;
|
||||
}
|
||||
|
||||
// 4) 若传入 tabBarList, 使用动态判断逻辑
|
||||
if (tabBarList && tabBarList.list && Array.isArray(tabBarList.list)) {
|
||||
const tabUrls = tabBarList.list
|
||||
.filter((item) => item.link && item.link.wap_url)
|
||||
.map((item) => _normalizePath(item.link.wap_url));
|
||||
|
||||
// 检查当前 linkUrl 是否是合法的 tab URL
|
||||
if (!tabUrls.includes(normalizedLink)) {
|
||||
_log('step 4: link not in tabUrls → false', { link: normalizedLink });
|
||||
return false;
|
||||
}
|
||||
|
||||
// 5) 页面级 Tab 绑定 (精确 + 通配符)
|
||||
// 返回值可能是: tab URL | null (显式无 tab) | undefined (未声明)
|
||||
const mappedTabUrl = lookupPageTabMap(normalizedCurrent, pageTabMap, pageTabWildcards);
|
||||
if (mappedTabUrl !== undefined) {
|
||||
_log('step 5: pageTabMap hit', { current: normalizedCurrent, mapped: mappedTabUrl });
|
||||
// null = 显式声明"无 tab", 字符串 = 该 tab 高亮
|
||||
return mappedTabUrl !== null && normalizedLink === _normalizePath(mappedTabUrl);
|
||||
}
|
||||
_log('step 5: pageTabMap miss → 进入 step 6/7');
|
||||
|
||||
// 6) 来源记忆兜底: 从哪个 Tab 跳转过来, 就保持那个 Tab 高亮
|
||||
const fromTab = currentPageQuery.from_tab;
|
||||
if (fromTab) {
|
||||
const normalizedFromTab = _normalizePath(fromTab);
|
||||
if (tabUrls.includes(normalizedFromTab)) {
|
||||
const hit = normalizedLink === normalizedFromTab;
|
||||
_log('step 6: from_tab query', { fromTab, hit });
|
||||
return hit;
|
||||
}
|
||||
}
|
||||
_log('step 6: no from_tab');
|
||||
|
||||
// 7) 分包入口追踪: 通过 updateCurrentRoute/resolveEntryTab 写入的入口 tab
|
||||
// 注意: _findMatchingTabUrl 不会做"同分包兜底",找不到就返回 null
|
||||
const matchingTabUrl = _findMatchingTabUrl(currentPageRoute, tabBarList, packageEntryTab);
|
||||
if (matchingTabUrl) {
|
||||
const hit = normalizedLink === matchingTabUrl;
|
||||
_log('step 7: packageEntryTab', { matchingTabUrl, hit });
|
||||
return hit;
|
||||
}
|
||||
_log('step 7: packageEntryTab miss → step 8');
|
||||
|
||||
// 8) 不再做"同分包兜底" — 找不到任何来源 tab 时不高亮
|
||||
// 深链冷启动 / 扫码进非 tab 页: TabBar 全不亮, 对齐 iOS HIG
|
||||
_log('step 8: no source → false (iOS HIG)');
|
||||
return false;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
3439
common/js/util.js
3439
common/js/util.js
File diff suppressed because it is too large
Load Diff
2090
common/js/util.js.bak
Normal file
2090
common/js/util.js.bak
Normal file
File diff suppressed because it is too large
Load Diff
92
common/js/video-helper.js
Normal file
92
common/js/video-helper.js
Normal file
@@ -0,0 +1,92 @@
|
||||
// iOS 微信小程序 <video> 兼容工具
|
||||
// 问题背景:
|
||||
// 1) 弹窗内的 <video> 用 autoplay 不可靠——popup 初始隐藏,autoplay 在隐藏态不触发,
|
||||
// 等 popup 显示后也不会重新 autoplay,导致"安卓有时能播、iOS 不能";
|
||||
// 2) iOS 对同一个 <video> 实例在 src 重绑 / 弹窗重开 / 播放结束后,不会自动重新加载,
|
||||
// 需要靠 :key 重建实例或 seek(0) 才能重播;
|
||||
// 3) iOS 微信不支持 webm / vp9 / hevc / ogv 等封装或编码,会直接黑屏;
|
||||
// 4) H5 端(含微信内置浏览器)$nextTick 调 play() 太快,弹窗动画未完时浏览器内部
|
||||
// 会自动 pause(),导致 "The play() request was interrupted by a call to pause()" 错误。
|
||||
// 这里统一提供"格式检测"与"在视频可见后触发播放"的能力,供各视频组件复用。
|
||||
//
|
||||
// 重要:微信小程序的 <video>.play() 不要求用户手势(与 H5 不同),只要在视频元素
|
||||
// 已经渲染、popup 已经显示后调用即可。因此请务必在 uni-popup 的 @change(show=true)
|
||||
// 回调里调用本方法,而不是在 open() 里紧跟着 $nextTick 调用(那时元素尚未可见)。
|
||||
|
||||
// iOS 微信 <video> 已知不支持的封装/编码(仅按扩展名做保守判断,用于给出友好提示)
|
||||
const UNSUPPORTED_EXT_ON_IOS = ['webm', 'ogv', 'ogg', 'mov', 'm4v', 'hevc', 'av1', '3gp'];
|
||||
|
||||
// 取 URL 中的小写扩展名(忽略查询参数与 hash)
|
||||
export function getVideoExt(url) {
|
||||
if (!url || typeof url !== 'string') return '';
|
||||
const clean = url.split('?')[0].split('#')[0];
|
||||
const idx = clean.lastIndexOf('.');
|
||||
if (idx < 0) return '';
|
||||
return clean.slice(idx + 1).toLowerCase();
|
||||
}
|
||||
|
||||
// 该地址在 iOS 上是否很可能无法播放(基于扩展名的保守判断)
|
||||
export function isLikelyUnsupportedOnIOS(url) {
|
||||
const ext = getVideoExt(url);
|
||||
if (!ext) return false;
|
||||
return UNSUPPORTED_EXT_ON_IOS.indexOf(ext) !== -1;
|
||||
}
|
||||
|
||||
// 在"视频已经渲染、popup 已经显示"的前提下触发播放。
|
||||
// 必须在 uni-popup 的 @change(show=true) 回调里调用,此时 <video> 元素已可见,
|
||||
// createVideoContext 才能拿到有效实例。
|
||||
// videoId: <video> 的 id;instance: 当前组件/页面实例(组件内必传)。
|
||||
export function playVideoInContext(videoId, instance) {
|
||||
if (!videoId || !instance) return;
|
||||
|
||||
// H5 端需要更长延迟:等 uni-popup 动画播完(~350ms),否则浏览器内部会自动
|
||||
// pause() 导致 "play() interrupted by pause()" 错误;小程序端 $nextTick 即可。
|
||||
// #ifdef H5
|
||||
const delay = 400;
|
||||
// #endif
|
||||
|
||||
// #ifndef H5
|
||||
const delay = 0;
|
||||
// #endif
|
||||
|
||||
const doPlay = () => {
|
||||
let ctx = null;
|
||||
try {
|
||||
ctx = uni.createVideoContext(videoId, instance);
|
||||
} catch (e) {
|
||||
console.error('[video-helper] createVideoContext failed:', e);
|
||||
return;
|
||||
}
|
||||
if (!ctx) return;
|
||||
|
||||
try {
|
||||
ctx.play();
|
||||
} catch (e) {
|
||||
console.error('[video-helper] play() failed, will retry:', e);
|
||||
// H5 端首次 play() 常被浏览器自动 pause() 打断,延迟重试一次
|
||||
// #ifdef H5
|
||||
setTimeout(() => {
|
||||
try { ctx.play(); } catch (retryErr) {
|
||||
console.error('[video-helper] retry play() also failed:', retryErr);
|
||||
}
|
||||
}, 300);
|
||||
// #endif
|
||||
}
|
||||
};
|
||||
|
||||
if (delay > 0) {
|
||||
// H5:先等 nextTick(DOM 更新),再等 delay(弹窗动画完成)
|
||||
if (typeof instance.$nextTick === 'function') {
|
||||
instance.$nextTick(() => setTimeout(doPlay, delay));
|
||||
} else {
|
||||
setTimeout(doPlay, delay);
|
||||
}
|
||||
} else {
|
||||
// 小程序端:nextTick 即可
|
||||
if (typeof instance.$nextTick === 'function') {
|
||||
instance.$nextTick(doPlay);
|
||||
} else {
|
||||
doPlay();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,7 +55,6 @@ let Weixin = function () {
|
||||
typeof callback == 'function' && callback(res);
|
||||
},
|
||||
fail: (res) => {
|
||||
console.log('获取收货地址 fail',res);
|
||||
alert(JSON.stringify(res))
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/**
|
||||
* 企业微信JS-SDK调用
|
||||
*/
|
||||
import Lang from './lang.js';
|
||||
|
||||
let WxWork = function () {
|
||||
// 企业微信JS-SDK
|
||||
this.wxwork = null;
|
||||
@@ -23,7 +25,7 @@ let WxWork = function () {
|
||||
// H5环境下的企业微信
|
||||
this.wxwork = WWOpenData;
|
||||
} else {
|
||||
console.error('企业微信JS-SDK未加载');
|
||||
console.error(Lang.lang('wxworkJssdk.notLoaded'));
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -56,8 +58,8 @@ let WxWork = function () {
|
||||
*/
|
||||
this.addContact = function (params, success, fail) {
|
||||
if (!this.wxwork) {
|
||||
console.error('企业微信JS-SDK未初始化');
|
||||
if (fail) fail('企业微信JS-SDK未初始化');
|
||||
console.error(Lang.lang('wxworkJssdk.notInitialized'));
|
||||
if (fail) fail(Lang.lang('wxworkJssdk.notInitialized'));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -69,7 +71,7 @@ let WxWork = function () {
|
||||
if (res.err_msg === 'openUserProfile:ok') {
|
||||
if (success) success(res);
|
||||
} else {
|
||||
console.error('打开用户资料失败:', res);
|
||||
console.error(Lang.lang('wxworkJssdk.openUserProfileFailed'), res);
|
||||
if (fail) fail(res.err_msg);
|
||||
}
|
||||
});
|
||||
@@ -87,8 +89,8 @@ let WxWork = function () {
|
||||
*/
|
||||
this.openCustomerService = function (params, success, fail) {
|
||||
if (!this.wxwork) {
|
||||
console.error('企业微信JS-SDK未初始化');
|
||||
if (fail) fail('企业微信JS-SDK未初始化');
|
||||
console.error(Lang.lang('wxworkJssdk.notInitialized'));
|
||||
if (fail) fail(Lang.lang('wxworkJssdk.notInitialized'));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
73
common/mixin/i18n-lazy.js
Normal file
73
common/mixin/i18n-lazy.js
Normal file
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* 延迟初始化 i18n mixin
|
||||
*
|
||||
* 问题背景:
|
||||
* 微信小程序/鸿蒙元服务环境下, main.js 同步 $mount() 会导致组件 data() 在
|
||||
* Lang.boot() 完成前求值. 此时 $lang() 在 remote-only 模式下返回空串,
|
||||
* 把空串缓存到 data 字段后, 后续 boot 完成的 $forceUpdate 也无法让它重算.
|
||||
*
|
||||
* 解决思路:
|
||||
* data() 中不能调 $lang(), 否则空串被永久缓存.
|
||||
* 模板只读 this.i18n.xxx(始终是字符串, 初值为空).
|
||||
* 需要显示前, 显式调一次 this.prepareI18n() — 此时 boot 必然已完成.
|
||||
*
|
||||
* 用法:
|
||||
*
|
||||
* // 1) 在 data() 中:
|
||||
* data() {
|
||||
* return {
|
||||
* i18n: {
|
||||
* title: '',
|
||||
* descPrefix: '',
|
||||
* privacyContractName: '',
|
||||
* },
|
||||
* // 准备文案时需要的动态上下文(可选)
|
||||
* platformContractName: '',
|
||||
* };
|
||||
* }
|
||||
*
|
||||
* // 2) 在 methods 中实现 i18nPrepareFn, 返回一个新对象用于填充 this.i18n
|
||||
* // 其中 key 用反引号 `` `your.module.title` `` 这类命名代表"业务模块的真实 key",
|
||||
* // 请用业务组件实际使用的 key 替换(例如 'components.privacyPopup.title')
|
||||
* methods: {
|
||||
* i18nPrepareFn() {
|
||||
* return {
|
||||
* title: this.$lang(`your.module.title`),
|
||||
* descPrefix: this.$lang('components.privacyPopup.descPrefix', { appName: '本应用' }),
|
||||
* privacyContractName: this.platformContractName || this.$lang(`your.module.defaultContract`),
|
||||
* };
|
||||
* },
|
||||
* }
|
||||
*
|
||||
* // 3) 在需要显示前调 this.prepareI18n()(来自 mixin)
|
||||
* // 此时 Lang.boot() 必然已完成, $lang() 返回真实翻译
|
||||
* popUp() {
|
||||
* this.prepareI18n();
|
||||
* this.showPop = true;
|
||||
* }
|
||||
*
|
||||
* 模板中只读 i18n.xxx:
|
||||
* ```html
|
||||
* <view>{{ i18n.title }}</view>
|
||||
* <view>{{ i18n.descPrefix }}</view>
|
||||
* ```
|
||||
*/
|
||||
export default {
|
||||
methods: {
|
||||
/**
|
||||
* 一次性计算所有 i18n 文案并写入 this.i18n
|
||||
* 关键: 调用时机必须是 boot 完成之后(否则会缓存空串)
|
||||
* 模板中读 this.i18n.xxx 永远拿到字符串
|
||||
*
|
||||
* 业务组件需要实现 i18nPrepareFn() 方法,
|
||||
* 返回一个对象, key 与 data().i18n 字段一一对应
|
||||
*/
|
||||
prepareI18n() {
|
||||
if (typeof this.i18nPrepareFn !== 'function') {
|
||||
console.warn('[i18n-lazy] i18nPrepareFn() not implemented; this.i18n will not be filled');
|
||||
return;
|
||||
}
|
||||
this.i18n = this.i18nPrepareFn();
|
||||
},
|
||||
},
|
||||
};
|
||||
38
common/mixin/image-longpress.js
Normal file
38
common/mixin/image-longpress.js
Normal file
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* 微信小程序图片长按识别二维码 mixin
|
||||
* 自动为页面中的所有 image 组件添加 show-menu-by-longpress 属性
|
||||
*/
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
// 需要排除的图片类名(不需要长按识别的)
|
||||
excludeImageClass: ['no-longpress', 'swiper-image', 'banner-image']
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
// #ifdef MP-WEIXIN
|
||||
this.$nextTick(() => {
|
||||
this.addLongpressToImages()
|
||||
})
|
||||
// #endif
|
||||
},
|
||||
methods: {
|
||||
/**
|
||||
* 为页面中的所有 image 添加长按识别支持
|
||||
*/
|
||||
addLongpressToImages() {
|
||||
// 获取当前页面所有 image 组件
|
||||
const images = document.querySelectorAll && document.querySelectorAll('image')
|
||||
if (images) {
|
||||
images.forEach(img => {
|
||||
// 检查是否需要排除
|
||||
const className = img.className || ''
|
||||
const shouldExclude = this.excludeImageClass.some(cls => className.includes(cls))
|
||||
if (!shouldExclude) {
|
||||
img.setAttribute('show-menu-by-longpress', 'true')
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -17,7 +17,7 @@
|
||||
<view class="fui-audio style3" :style="{ background: value.background }" v-else>
|
||||
<!-- <audio src="/static/audio/bgm.mp3" controls loop></audio> -->
|
||||
<view class="img">
|
||||
<image :src="$util.img(value.imageUrl)"></image>
|
||||
<image :src="$util.img(value.imageUrl)" show-menu-by-longpress></image>
|
||||
</view>
|
||||
<view class="content">
|
||||
<view class="name" :style="{ color: value.textcolor }">{{ value.text }}</view>
|
||||
@@ -98,9 +98,7 @@ export default {
|
||||
uni.setStorageSync('audio_list', audio_list)
|
||||
}
|
||||
}
|
||||
console.log(uni.getStorageSync('audio_list'))
|
||||
var n = this;
|
||||
// console.log(a)
|
||||
a.onPlay(function () {
|
||||
var e = setInterval(function () {
|
||||
var i = a.currentTime / a.duration * 100 + "%", s = Math.floor(Math.ceil(a.currentTime) / 60), o = (Math.ceil(a.currentTime) % 60 / 100).toFixed(2).slice(-2), r = Math.ceil(a.currentTime);
|
||||
@@ -113,13 +111,12 @@ export default {
|
||||
|
||||
var s = n.$util.img(n.value.audioUrl), o = n.audios[n.value.id].seconds || 0, r = 0, u = 1;
|
||||
0 == u && a.onEnded(function (e) {
|
||||
c[t].status = !1, n.status = !1, c[t].seconds = 0, console.log(c), n.audios = c;
|
||||
c[t].status = !1, n.status = !1, c[t].seconds = 0, n.audios = c;
|
||||
});
|
||||
var c = n.audios;
|
||||
c[t] || (c[t] = {}), a.paused && 0 == o ? (a.src = s, a.play(), 1 == u && (a.loop = !0),
|
||||
c[t].status = !0, n.status = !0, n.pauseOther(t)) : a.paused && o > 0 ? (a.play(), 0 == r ? a.seek(o) : a.seek(0),
|
||||
c[t].status = !0, n.status = !0, n.pauseOther(t)) : (a.pause(), c[t].status = !1, n.status = !1), n.audios = c;
|
||||
console.log(n.audios)
|
||||
},
|
||||
pauseOther: function (e) {
|
||||
var t = this;
|
||||
@@ -190,18 +187,14 @@ export default {
|
||||
var u = s + ":" + o, c = that.audios;
|
||||
c[t].audiowidth = i, c[t].Time = e, c[t].audiotime = u, c[t].seconds = r
|
||||
that.audios = c
|
||||
// console.log(c)
|
||||
console.log(that.audios[that.value.id].audiotime)
|
||||
that.audiotime = that.audios[that.value.id].audiotime
|
||||
that.audiowidth = that.audios[that.value.id].audiowidth
|
||||
console.log(i)
|
||||
that.lyg = i
|
||||
}, 1e3);
|
||||
});
|
||||
|
||||
|
||||
this.audioContext.onEnded(() => {
|
||||
console.log('播放结束');
|
||||
this.status = 0
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,9 +10,9 @@
|
||||
:style="{ fontSize: value.titleStyle.fontSize * 2 + 'rpx', color: value.titleStyle.textColor, fontWeight: value.titleStyle.fontWeight ? 'bold' : '' }">
|
||||
{{ value.titleStyle.leftText }}
|
||||
</view>
|
||||
<image v-else class="left-img" :src="$util.img(value.titleStyle.leftImg)" mode="heightFix"></image>
|
||||
<image v-else class="left-img" :src="$util.img(value.titleStyle.leftImg)" mode="heightFix" show-menu-by-longpress></image>
|
||||
<view class="head-content" v-if="value.titleStyle.style == 'style-1'"
|
||||
:style="{ color: value.titleStyle.textColor }">低至0元免费拿</view>
|
||||
:style="{ color: value.titleStyle.textColor }">{{ $lang('components-diy.diy-bargain.freeGet') }}</view>
|
||||
<view class="head-right"
|
||||
:style="{ fontSize: value.titleStyle.moreFontSize * 2 + 'rpx', color: value.titleStyle.moreColor }"
|
||||
@tap.stop="$util.redirectTo('/pages_promotion/bargain/list')">
|
||||
@@ -28,7 +28,7 @@
|
||||
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
|
||||
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
|
||||
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
|
||||
@error="imageError(index)" />
|
||||
@error="imageError(index)" show-menu-by-longpress/>
|
||||
</view>
|
||||
<view class="content"
|
||||
v-if="value.goodsNameStyle.control || value.priceStyle.mainControl || value.btnStyle.control">
|
||||
@@ -41,22 +41,22 @@
|
||||
<view class="bg">
|
||||
<view class="curr" :style="{ width: progress(item) * 2 + 'rpx' }">
|
||||
<image class="progress-bar" mode="widthFix"
|
||||
:src="$util.img('public/uniapp/bargain/progress_bar_01.png')" />
|
||||
:src="$util.img('public/uniapp/bargain/progress_bar_01.png')" show-menu-by-longpress/>
|
||||
</view>
|
||||
</view>
|
||||
<view class="num" v-if="item.is_bargaining">
|
||||
已砍
|
||||
{{ $lang('components-diy.diy-bargain.bargained') }}
|
||||
<text>¥{{ (item.price - item.curr_price).toFixed(2) }}</text>
|
||||
,仅差
|
||||
{{ $lang('components-diy.diy-bargain.onlyDiff') }}
|
||||
<text>¥{{ item.curr_price }}</text>
|
||||
</view>
|
||||
<view class="num" v-else>
|
||||
最低可砍至
|
||||
{{ $lang('components-diy.diy-bargain.minBargainTo') }}
|
||||
<text>¥{{ item.floor_price }}</text>
|
||||
</view>
|
||||
</view>
|
||||
<view class="progress" v-if="value.style == 'style-3'">
|
||||
最低可砍至
|
||||
{{ $lang('components-diy.diy-bargain.minBargainTo') }}
|
||||
<text class="num">¥{{ item.floor_price }}</text>
|
||||
</view>
|
||||
<view class="price-wrap">
|
||||
@@ -75,7 +75,7 @@
|
||||
color: value.btnStyle.theme == 'diy' ? value.btnStyle.textColor : '',
|
||||
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
|
||||
}">
|
||||
{{ item.is_bargaining ? '继续砍价' : value.btnStyle.text }}
|
||||
{{ item.is_bargaining ? $lang('components-diy.diy-bargain.continueBargain') : value.btnStyle.text }}
|
||||
</button>
|
||||
</view>
|
||||
</view>
|
||||
@@ -89,14 +89,14 @@
|
||||
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
|
||||
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
|
||||
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
|
||||
@error="imageError(index)" :lazy-load="true" />
|
||||
@error="imageError(index)" :lazy-load="true" show-menu-by-longpress/>
|
||||
<image class="bg"
|
||||
v-if="value.saleStyle.control && value.template == 'horizontal-slide' && value.style != 'style-2'"
|
||||
:src="$util.img('public/uniapp/bargain/bg.png')" mode="widthFix" />
|
||||
<view class="num"
|
||||
v-if="value.saleStyle.control && value.template == 'horizontal-slide' && value.style != 'style-2'"
|
||||
:style="{ color: value.theme == 'diy' ? value.saleStyle.color : '' }">
|
||||
已砍{{ item.sale_num }}件
|
||||
{{ $lang('components-diy.diy-bargain.soldCount', { num: item.sale_num }) }}
|
||||
</view>
|
||||
</view>
|
||||
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
|
||||
@@ -134,14 +134,14 @@
|
||||
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
|
||||
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
|
||||
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
|
||||
@error="imageError(dataIndex)" :lazy-load="true" />
|
||||
@error="imageError(dataIndex)" :lazy-load="true" show-menu-by-longpress/>
|
||||
<image class="bg"
|
||||
v-if="value.saleStyle.control && value.template == 'horizontal-slide' && value.style != 'style-2'"
|
||||
:src="$util.img('public/uniapp/bargain/bg.png')" mode="widthFix" />
|
||||
<view class="num"
|
||||
v-if="value.saleStyle.control && value.template == 'horizontal-slide' && value.style != 'style-2'"
|
||||
:style="{ color: value.theme == 'diy' ? value.saleStyle.color : '' }">
|
||||
已砍{{ item.sale_num }}件
|
||||
{{ $lang('components-diy.diy-bargain.soldCount', { num: item.sale_num }) }}
|
||||
</view>
|
||||
</view>
|
||||
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
|
||||
@@ -461,7 +461,10 @@ scroll-view ::-webkit-scrollbar {
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 36rpx;
|
||||
background: linear-gradient(270deg, #ffbd5b 0%, #fd882e 100%);
|
||||
// P0: 砍价头渐变 → var(--pintuan-label-grad-start/end) 复用(同色系)
|
||||
// 兼容: 微信小程序 / 鸿蒙元服务 — linear-gradient 嵌套 var() 现代 runtime 支持
|
||||
background: #ffbd5b; // 兜底
|
||||
background: linear-gradient(270deg, var(--pintuan-label-grad-start, #ffbd5b) 0%, var(--pintuan-label-grad-end, #fd882e) 100%);
|
||||
border-radius: 24rpx;
|
||||
padding: 2rpx;
|
||||
|
||||
@@ -474,7 +477,9 @@ scroll-view ::-webkit-scrollbar {
|
||||
text:nth-child(2) {
|
||||
padding: 6rpx 4rpx 4rpx;
|
||||
background-color: #fff;
|
||||
color: #ffbd5b;
|
||||
// P0: 砍价头文字色 → var(--pintuan-label-grad-start) 复用
|
||||
// 兼容: 微信小程序 / 鸿蒙元服务 — color 接受 var() 无问题
|
||||
color: var(--pintuan-label-grad-start, #ffbd5b);
|
||||
border-radius: 50%;
|
||||
transform: scale(0.6);
|
||||
font-weight: bold;
|
||||
@@ -576,7 +581,9 @@ scroll-view ::-webkit-scrollbar {
|
||||
width: auto;
|
||||
height: 20rpx;
|
||||
border-radius: 20rpx;
|
||||
background-color: #ffeadb;
|
||||
// P0: 砍价浅底 → var(--bargain-promo-shallow)
|
||||
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
|
||||
background-color: var(--bargain-promo-shallow, #ffeadb);
|
||||
position: relative;
|
||||
|
||||
&::after {
|
||||
@@ -584,7 +591,9 @@ scroll-view ::-webkit-scrollbar {
|
||||
width: 26rpx;
|
||||
height: 26rpx;
|
||||
border-radius: 50%;
|
||||
background-color: #fa1a1a;
|
||||
// P0: 砍价红圆点 → var(--bargain-promo-color)
|
||||
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
|
||||
background-color: var(--bargain-promo-color, #fa1a1a);
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
@@ -595,7 +604,9 @@ scroll-view ::-webkit-scrollbar {
|
||||
width: 0;
|
||||
height: 20rpx;
|
||||
border-radius: 20rpx;
|
||||
background-color: #fa1a1a;
|
||||
// P0: 砍价红进度条 → var(--bargain-promo-color)
|
||||
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
|
||||
background-color: var(--bargain-promo-color, #fa1a1a);
|
||||
position: relative;
|
||||
|
||||
.progress-bar {
|
||||
@@ -618,7 +629,9 @@ scroll-view ::-webkit-scrollbar {
|
||||
line-height: 1;
|
||||
|
||||
text {
|
||||
color: #fa1a1a;
|
||||
// P0: 砍价数字红 → var(--bargain-promo-color)
|
||||
// 兼容: 微信小程序 / 鸿蒙元服务 — color 接受 var() 无问题
|
||||
color: var(--bargain-promo-color, #fa1a1a);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,65 +1,56 @@
|
||||
<template>
|
||||
<view data-component-name="diy-bottom-nav" v-if="tabBarList && tabBarList.list">
|
||||
<view class="tab-bar" :style="{ backgroundColor: tabBarList.backgroundColor }">
|
||||
<!-- 修复底部 TabBar 频闪:
|
||||
微信小程序等环境下 `shouldShowTabBar` 在 tabBarList 异步加载期间会从 false→true 短暂切换,
|
||||
配合 `v-if` 会让整个 tab 组件树卸载/重建 -> 视觉频闪 + tabBar 占用空间反复占位/释放导致上方内容跳动。
|
||||
改为 `v-show`, 只切换可见性, 内部 tab 始终在 DOM 中(无 tabBarList 时只渲染空壳占位)。 -->
|
||||
<view data-component-name="diy-bottom-nav" v-show="shouldShowTabBar">
|
||||
<!-- tabBarList 未就绪时仍保留 placeholder 占位, 避免上方内容在加载完成后突跳 -->
|
||||
<view v-if="tabBarList && tabBarList.list && tabBarList.list.length" class="tab-bar" :style="{ backgroundColor: tabBarList.backgroundColor }">
|
||||
<view class="tabbar-border"></view>
|
||||
<view class="item" v-for="(item, index) in tabBarList.list" :key="item.id" @tap.stop="redirectTo(item.link)">
|
||||
<view class="bd">
|
||||
<block v-if="item.link.wap_url == '/pages_goods/cart'">
|
||||
<view class="icon" v-if="tabBarList.type == 1 || tabBarList.type == 2"
|
||||
:animation="cartAnimation" id="tabbarCart">
|
||||
<block v-if="verify(item.link)">
|
||||
<image v-if="item.selected_icon_type == 'img'"
|
||||
:src="$util.img(item.selectedIconPath)" />
|
||||
<diy-icon v-if="item.selected_icon_type == 'icon'" :icon="item.selectedIconPath"
|
||||
:value="item.selected_style ? item.selected_style : null"></diy-icon>
|
||||
</block>
|
||||
<block v-else>
|
||||
<image v-if="item.icon_type == 'img'" :src="$util.img(item.iconPath)" />
|
||||
<diy-icon v-if="item.icon_type == 'icon'" :icon="item.iconPath"
|
||||
:value="item.style ? item.style : null"></diy-icon>
|
||||
</block>
|
||||
<view class="cart-count-mark font-size-activity-tag"
|
||||
:class="{ max: item.link.wap_url == '/pages_goods/cart' && cartNumber > 99 }"
|
||||
:style="{ background: 'var(--price-color)' }" v-if="cartNumber > 0">
|
||||
{{ cartNumber > 99 ? '99+' : cartNumber }}
|
||||
</view>
|
||||
<view class="icon" v-if="tabBarList.type == 1 || tabBarList.type == 2"
|
||||
:animation="isCartItem(item.link) ? cartAnimation : null"
|
||||
:id="isCartItem(item.link) ? 'tabbarCart' : null">
|
||||
<block v-if="verify(item.link)">
|
||||
<image v-if="item.selected_icon_type == 'img'"
|
||||
:src="$util.img(item.selectedIconPath)" />
|
||||
<diy-icon v-if="item.selected_icon_type == 'icon'" :icon="item.selectedIconPath"
|
||||
:value="item.selected_style ? item.selected_style : null"></diy-icon>
|
||||
</block>
|
||||
<block v-else>
|
||||
<image v-if="item.icon_type == 'img'" :src="$util.img(item.iconPath)" />
|
||||
<diy-icon v-if="item.icon_type == 'icon'" :icon="item.iconPath"
|
||||
:value="item.style ? item.style : null"></diy-icon>
|
||||
</block>
|
||||
<view class="cart-count-mark font-size-activity-tag"
|
||||
:class="{ max: cartNumber > 99 }"
|
||||
:style="{ background: 'var(--price-color)' }"
|
||||
v-if="isCartItem(item.link) && cartNumber > 0">
|
||||
{{ cartNumber > 99 ? '99+' : cartNumber }}
|
||||
</view>
|
||||
</block>
|
||||
<block v-else>
|
||||
<view class="icon" v-if="tabBarList.type == 1 || tabBarList.type == 2">
|
||||
<block v-if="verify(item.link)">
|
||||
<image v-if="item.selected_icon_type == 'img'"
|
||||
:src="$util.img(item.selectedIconPath)" />
|
||||
<diy-icon v-if="item.selected_icon_type == 'icon'" :icon="item.selectedIconPath"
|
||||
:value="item.selected_style ? item.selected_style : null"></diy-icon>
|
||||
</block>
|
||||
<block v-else>
|
||||
<image v-if="item.icon_type == 'img'" :src="$util.img(item.iconPath)" />
|
||||
<diy-icon v-if="item.icon_type == 'icon'" :icon="item.iconPath"
|
||||
:value="item.style ? item.style : null"></diy-icon>
|
||||
</block>
|
||||
</view>
|
||||
</block>
|
||||
</view>
|
||||
<view class="label"
|
||||
v-if="(tabBarList.type == 1 || tabBarList.type == 3) && tabBarList.theme == 'diy'"
|
||||
:style="{ color: verify(item.link) ? tabBarList.textHoverColor : tabBarList.textColor }">
|
||||
{{ lang == 'en-us' ? item.en_text : item.text }}
|
||||
{{ $langConfig.getField(item, 'text') }}
|
||||
</view>
|
||||
<view class="label"
|
||||
v-if="(tabBarList.type == 1 || tabBarList.type == 3) && tabBarList.theme == 'default'"
|
||||
:style="{ color: verify(item.link) ? 'var(--base-color)' : '#333333' }">
|
||||
{{ lang == 'en-us' ? item.en_text : item.text }}
|
||||
{{ $langConfig.getField(item, 'text') }}
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
<!-- 解决fixed定位后底部导航栏塌陷问题 -->
|
||||
<!-- 解决fixed定位后底部导航栏塌陷问题: 始终保留 placeholder, 避免内容随 tabBar 可见性跳 -->
|
||||
<view class="tab-bar-placeholder"></view>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { adaptSubpackageUrl, checkTabBarActive } from '@/common/js/util.js'
|
||||
import { adaptSubpackageUrl, checkTabBarActive, decodeEntity } from '@/common/js/util.js'
|
||||
import { resolveEntryTab } from '@/common/js/util-tabbar.js'
|
||||
import DiyMinx from './minx.js'
|
||||
// 底部导航栏
|
||||
export default {
|
||||
@@ -76,7 +67,6 @@ export default {
|
||||
mixins: [DiyMinx],
|
||||
data() {
|
||||
return {
|
||||
lang: uni.getStorageSync("lang"),
|
||||
currentRoute: '', //当前页面路径
|
||||
jumpFlag: true, //是否可以跳转,防止重复点击
|
||||
cartAnimation: {}
|
||||
@@ -105,9 +95,25 @@ export default {
|
||||
});
|
||||
},
|
||||
computed: {
|
||||
// 当前语言(响应式):通过 componentRefresh 建立依赖,切语言时自动更新
|
||||
// 不能直接用 uni.getStorageSync 作为 data,因为它不是响应式的
|
||||
currentLang() {
|
||||
// 通过 componentRefresh 建立响应式依赖
|
||||
// 切语言时 store 中的 componentRefresh 会 +1,触发重新计算
|
||||
this.componentRefresh;
|
||||
return uni.getStorageSync("lang") || 'zh-cn';
|
||||
},
|
||||
cartChange() {
|
||||
return this.$store.state.cartChange;
|
||||
}
|
||||
},
|
||||
packageEntryTab() {
|
||||
return this.$store.state.packageEntryTab;
|
||||
},
|
||||
// 响应 tabBarList 异步加载: 后端返回前 updateCurrentRoute 是 no-op,
|
||||
// tabBarList 就绪后必须重跑一次, 否则冷启动+秒点链接会出现"先不高亮→再突然高亮"
|
||||
tabBarReady() {
|
||||
return this.tabBarList && this.tabBarList.list && this.tabBarList.list.length > 0;
|
||||
},
|
||||
},
|
||||
watch: {
|
||||
cartChange: function (nval, oval) {
|
||||
@@ -123,38 +129,148 @@ export default {
|
||||
this.cartAnimation = animation.export();
|
||||
}, 300);
|
||||
}
|
||||
}
|
||||
},
|
||||
// tabBarList 异步加载完成后, 补一次 updateCurrentRoute
|
||||
// 修复: 冷启动时用户在 tabBarList 就绪前点击链接, 第一次 updateCurrentRoute 是 no-op
|
||||
tabBarReady: {
|
||||
handler(ready) {
|
||||
if (ready) {
|
||||
this.updateCurrentRoute();
|
||||
}
|
||||
},
|
||||
immediate: false,
|
||||
},
|
||||
},
|
||||
methods: {
|
||||
// 更新当前路由
|
||||
// 统一归一化路径:currentPage.route 不带前导 '/',但 tab 的 wap_url 带前导 '/'
|
||||
// 统一加前导 '/' 后再 split,确保 parts[1]=分包名、parts[2]=页面名
|
||||
_normalizeRoute(route) {
|
||||
if (!route) return '';
|
||||
return route.startsWith('/') ? route : '/' + route;
|
||||
},
|
||||
// 从归一化路径中提取分包名(parts[1])
|
||||
_getPackageName(normalizedRoute) {
|
||||
const parts = normalizedRoute.split('?')[0].split('/');
|
||||
return parts[1] || '';
|
||||
},
|
||||
// 判断某个链接是否指向购物车页面
|
||||
isCartItem(link) {
|
||||
if (!link || !link.wap_url) return false;
|
||||
return adaptSubpackageUrl(link.wap_url).split('?')[0] === '/pages_goods/cart';
|
||||
},
|
||||
// 更新当前路由,追踪每个分包的入口 tab
|
||||
updateCurrentRoute() {
|
||||
let currentPage = getCurrentPages()[getCurrentPages().length - 1];
|
||||
if (currentPage && currentPage.route) {
|
||||
this.currentRoute = currentPage.route;
|
||||
const currentPages = getCurrentPages();
|
||||
const currentPage = currentPages[currentPages.length - 1];
|
||||
if (!currentPage || !currentPage.route) return;
|
||||
|
||||
// 归一化:补全前导 '/',确保后续 split('/') 后 parts[1]=分包名
|
||||
const newRoute = this._normalizeRoute(currentPage.route);
|
||||
const currentPackageName = newRoute.split('?')[0].split('/')[1] || '';
|
||||
|
||||
if (this.tabBarList && this.tabBarList.list && currentPackageName) {
|
||||
// 收集历史栈路由 (排除当前页, 已 _normalizeRoute)
|
||||
// 注意: 组件里直接传 raw route 给 resolveEntryTab,
|
||||
// 内部 adaptSubpackageUrl 会兜底处理老路径 /pages/member/ 等
|
||||
const historyRoutes = currentPages.length >= 2
|
||||
? currentPages.slice(0, -1).map((p) =>
|
||||
p && p.route ? this._normalizeRoute(p.route) : null)
|
||||
: [];
|
||||
|
||||
// 调用纯函数 resolveEntryTab 完成 4 步查找
|
||||
// 规则: 从哪个 TabBar 出发, 非 tab 页就归属哪个 TabBar 高亮
|
||||
// 修复: home → diy 微页面 等跨分包导航被"同分包第一个 tab"误判的问题
|
||||
const entryTab = resolveEntryTab({
|
||||
currentPageRoute: newRoute,
|
||||
tabBarList: this.tabBarList,
|
||||
historyRoutes,
|
||||
// 传 NO_TAB_PAGES 进去, 让 login/pay/AI 等 modal 页不参与归属判定
|
||||
// 例子: home → login → diy 应算作 home → diy (login 是 modal)
|
||||
noTabPages: this.$util && this.$util.NO_TAB_PAGES ? this.$util.NO_TAB_PAGES : null,
|
||||
});
|
||||
|
||||
if (entryTab) {
|
||||
this.$store.commit('setPackageEntryTab', {
|
||||
...this.packageEntryTab,
|
||||
[currentPackageName]: entryTab
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
this.currentRoute = newRoute;
|
||||
},
|
||||
redirectTo(link) {
|
||||
this.$emit('callback');
|
||||
this.$util.diyRedirectTo(link);
|
||||
const redirectLink = link ? { ...link } : link;
|
||||
|
||||
if (link && link.wap_url) {
|
||||
const decodedUrl = decodeEntity(link.wap_url);
|
||||
const adaptedUrl = adaptSubpackageUrl(decodedUrl);
|
||||
const packageName = this._getPackageName(adaptedUrl);
|
||||
|
||||
if (packageName) {
|
||||
this.$store.commit('setPackageEntryTab', {
|
||||
...this.packageEntryTab,
|
||||
[packageName]: adaptedUrl.split('?')[0]
|
||||
});
|
||||
}
|
||||
|
||||
// 若目标页面不是 TabBar 根页面,追加 from_tab 来源参数,
|
||||
// 用于非 Tab 页面的 TabBar 高亮记忆
|
||||
if (this.tabBarList && this.tabBarList.list) {
|
||||
const tabUrls = this.tabBarList.list
|
||||
.filter(item => item.link && item.link.wap_url)
|
||||
.map(item => adaptSubpackageUrl(decodeEntity(item.link.wap_url)).split('?')[0]);
|
||||
if (!tabUrls.includes(adaptedUrl.split('?')[0])) {
|
||||
const currentPages = getCurrentPages();
|
||||
const currentPage = currentPages[currentPages.length - 1];
|
||||
const currentTab = currentPage && currentPage.route
|
||||
? tabUrls.find(tabUrl => checkTabBarActive(tabUrl, '/' + currentPage.route, this.tabBarList, this.packageEntryTab))
|
||||
: null;
|
||||
if (currentTab) {
|
||||
redirectLink.from_tab = currentTab;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.$util.diyRedirectTo(redirectLink);
|
||||
},
|
||||
verify(link) {
|
||||
if (link == null || link == '' || !link.wap_url) return false;
|
||||
|
||||
// 标准化路径格式,确保比较的一致性
|
||||
let currentPageRoute = this.currentRoute ? '/' + this.currentRoute : '';
|
||||
let linkUrl = link.wap_url;
|
||||
const currentPages = getCurrentPages();
|
||||
const currentPage = currentPages[currentPages.length - 1];
|
||||
const currentPageRoute = currentPage && currentPage.route
|
||||
? this._normalizeRoute(currentPage.route)
|
||||
: '';
|
||||
|
||||
// 首页特殊处理
|
||||
if (linkUrl === this.$util.INDEX_PAGE_URL && this.name === 'DIY_VIEW_INDEX') {
|
||||
return true;
|
||||
// 读取当前页面 query 参数(兼容小程序与 H5)
|
||||
let currentPageQuery = {};
|
||||
if (currentPage) {
|
||||
if (currentPage.options) {
|
||||
currentPageQuery = currentPage.options;
|
||||
} else if (currentPage.$page && currentPage.$page.options) {
|
||||
currentPageQuery = currentPage.$page.options;
|
||||
} else if (currentPage.$route && currentPage.$route.query) {
|
||||
currentPageQuery = currentPage.$route.query;
|
||||
}
|
||||
}
|
||||
|
||||
// 精确匹配当前路径
|
||||
if (adaptSubpackageUrl(linkUrl) === currentPageRoute) {
|
||||
return true;
|
||||
if (this.name === 'DIY_VIEW_INDEX') {
|
||||
// DIY_VIEW_INDEX 短路: 当 name 是 DIY_VIEW_INDEX 时, 任意匹配的 tab 都高亮
|
||||
// 修复前: 只对 HOME (INDEX_PAGE_URL) 生效
|
||||
// 修复后: 适用于所有 tab 页面 (如 merchant DIY 首页、cart DIY 首页 等)
|
||||
// 前提: 当前页面本身就是该 tab 根, 链接 == 当前页 → step 1 早就命中
|
||||
// 这个短路主要兜底: "DIY_VIEW_INDEX 页面 + tab 链接" 的强语义关联
|
||||
const linkUrl = adaptSubpackageUrl(link.wap_url).split('?')[0];
|
||||
const currentUrl = currentPageRoute.split('?')[0];
|
||||
if (linkUrl === currentUrl) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return checkTabBarActive(linkUrl, currentPageRoute);
|
||||
return checkTabBarActive(link.wap_url, currentPageRoute, this.tabBarList, this.packageEntryTab, currentPageQuery);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -178,13 +294,42 @@ export default {
|
||||
.tab-bar {
|
||||
background-color: #fff;
|
||||
box-sizing: border-box;
|
||||
position: fixed;
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
/* ============================================================
|
||||
* 固定在最底端,不能位置漂移(微信小程序 / 鸿蒙元服务 / 快应用 H5)
|
||||
* ------------------------------------------------------------
|
||||
* 现象(只在客户端小程序里复现,浏览器 H5 没事):
|
||||
* 页面带 navigationStyle:custom + 页面内有 scroll-view,
|
||||
* 滚到底部时 .tab-bar 会被微信客户端的页面避让逻辑推上去,
|
||||
* 出现"位置漂移"。
|
||||
*
|
||||
* 根因(微信小程序特性):
|
||||
* 1) 微信小程序里 position:fixed 的 containing block 是 page
|
||||
* 根容器(不是 viewport),可视区变化时 fixed 元素下沿会
|
||||
* 跟着重算,造成漂移。
|
||||
* 2) 父级一旦出现 transform/filter/will-change,fixed 的
|
||||
* containing block 会被进一步改写,fixed 元素行为更不可控。
|
||||
*
|
||||
* 加固措施:
|
||||
* - bottom: 0 !important 钉死下沿
|
||||
* - 提升 z-index 到 2147483647,避免被其他 fixed 元素遮挡
|
||||
* - transform: translateZ(0) 强制提升到独立合成层,降低父级
|
||||
* transform 干扰;will-change:transform 提示浏览器持续合成
|
||||
* - 微信小程序里 #ifdef MP-WEIXIN / #ifdef MP-HARMONY 走原生
|
||||
* tabBar,diy-bottom-nav 通常不会同时存在,但保留兜底
|
||||
* ============================================================ */
|
||||
position: fixed !important;
|
||||
left: 0 !important;
|
||||
right: 0 !important;
|
||||
bottom: 0 !important;
|
||||
top: auto !important;
|
||||
width: 100%;
|
||||
z-index: 998;
|
||||
z-index: 2147483647 !important;
|
||||
display: flex;
|
||||
border-top: 2rpx solid #f5f5f5;
|
||||
/* 强制提升合成层,降低父级 transform/filter 改变 containing block 的概率 */
|
||||
transform: translateZ(0) !important;
|
||||
-webkit-transform: translateZ(0) !important;
|
||||
will-change: transform !important;
|
||||
padding-bottom: 0;
|
||||
padding-bottom: constant(safe-area-inset-bottom);
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -256,7 +256,6 @@ export default {
|
||||
try {
|
||||
// 发送视频被点击播放事件
|
||||
this.$emit('channel-video-click-play', item);
|
||||
console.log('播放视频:', item);
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
// 在微信小程序环境中调用视频播放接口
|
||||
@@ -266,7 +265,7 @@ export default {
|
||||
// #ifndef MP-WEIXIN
|
||||
if (item?.channelType === 'wechat') {
|
||||
uni.showToast({
|
||||
title: '视频号仅支持在微信小程序环境中播放',
|
||||
title: this.$lang('wechatChannel.wechatMpOnly'),
|
||||
icon: 'none',
|
||||
duration: 2000
|
||||
});
|
||||
@@ -289,7 +288,6 @@ export default {
|
||||
*/
|
||||
imgError(index) {
|
||||
// 图片加载失败的处理逻辑
|
||||
console.log('图片加载失败:', index);
|
||||
// 为失败的图片设置默认图片
|
||||
const item = this.value.list[index];
|
||||
if (item) {
|
||||
@@ -306,7 +304,6 @@ export default {
|
||||
addMouseDragScroll() {
|
||||
// 只在Web环境中添加
|
||||
// #ifndef MP
|
||||
console.log('addMouseDragScroll called');
|
||||
|
||||
let isDragging = false;
|
||||
let startX = 0;
|
||||
@@ -329,11 +326,9 @@ export default {
|
||||
const handleMouseDown = (e) => {
|
||||
// 检查是否点击在组件内
|
||||
if (this.$el.contains(e.target)) {
|
||||
console.log('mousedown event in component:', e);
|
||||
// 查找可滚动元素
|
||||
currentScrollElement = findScrollableParent(e.target);
|
||||
if (currentScrollElement) {
|
||||
console.log('Found scrollable element:', currentScrollElement);
|
||||
isDragging = true;
|
||||
startX = e.pageX;
|
||||
startScrollLeft = currentScrollElement.scrollLeft;
|
||||
@@ -345,17 +340,14 @@ export default {
|
||||
// 鼠标移动事件
|
||||
const handleMouseMove = (e) => {
|
||||
if (!isDragging || !currentScrollElement) return;
|
||||
console.log('mousemove event:', e);
|
||||
e.preventDefault();
|
||||
const dx = e.pageX - startX;
|
||||
currentScrollElement.scrollLeft = startScrollLeft - dx;
|
||||
console.log('scrollLeft:', currentScrollElement.scrollLeft);
|
||||
};
|
||||
|
||||
// 鼠标释放事件
|
||||
const handleMouseUp = () => {
|
||||
if (isDragging && currentScrollElement) {
|
||||
console.log('mouseup event');
|
||||
currentScrollElement.style.cursor = 'grab';
|
||||
}
|
||||
isDragging = false;
|
||||
@@ -368,21 +360,17 @@ export default {
|
||||
document.addEventListener('mouseup', handleMouseUp);
|
||||
document.addEventListener('mouseleave', handleMouseUp);
|
||||
|
||||
console.log('Global mouse event listeners added');
|
||||
|
||||
// 组件销毁时移除事件监听器
|
||||
this.$once('hook:beforeDestroy', () => {
|
||||
document.removeEventListener('mousedown', handleMouseDown);
|
||||
document.removeEventListener('mousemove', handleMouseMove);
|
||||
document.removeEventListener('mouseup', handleMouseUp);
|
||||
document.removeEventListener('mouseleave', handleMouseUp);
|
||||
console.log('Global mouse event listeners removed');
|
||||
});
|
||||
|
||||
// 为所有.channel-nav元素添加必要的样式
|
||||
setTimeout(() => {
|
||||
const channelNavs = document.querySelectorAll('.channel-nav');
|
||||
console.log('Found channel-nav elements:', channelNavs.length);
|
||||
channelNavs.forEach(element => {
|
||||
element.style.overflowX = 'auto';
|
||||
element.style.overflowY = 'hidden';
|
||||
@@ -391,11 +379,9 @@ export default {
|
||||
element.style.maxWidth = '100%';
|
||||
element.style.cursor = 'grab';
|
||||
element.style.userSelect = 'none'; // 防止文本选择
|
||||
console.log('Added styles to channel-nav:', element);
|
||||
});
|
||||
}, 100); // 延迟执行,确保DOM已完全渲染
|
||||
|
||||
console.log('Mouse drag scroll setup completed');
|
||||
// #endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,19 +17,19 @@
|
||||
<view class="video-title" :style="[{ '--title-line-clamp': titleLineClamp }]">{{ value.videoTitle }}
|
||||
</view>
|
||||
<!-- 视频统计信息 -->
|
||||
<view class="video-stats" v-if="showViewCount && value.showViewCount">{{ value.viewCount }}次观看</view>
|
||||
<view class="video-stats" v-if="showViewCount && value.showViewCount">{{ $lang('components-diy.diy-channel-video.viewCountSuffix', { count: value.viewCount }) }}</view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<!-- 跳转式视频播放 -->
|
||||
<view v-else @tap.stop="playVideo" class="video-container">
|
||||
<view class="video-cover-wrap" :style="[coverStyle]">
|
||||
<image class="video-cover" :src="$util.img(value.coverUrl)" mode="aspectFill"></image>
|
||||
<image class="video-cover" :src="$util.img(value.coverUrl)" mode="aspectFill" show-menu-by-longpress></image>
|
||||
<view class="channel-play-btn" v-if="showPlayBtn" :style="[playBtnStyle]">
|
||||
<view class="play-icon-css"></view>
|
||||
</view>
|
||||
<view class="video-stats-overlay" v-if="showViewCount && value.showViewCount">
|
||||
{{ value.viewCount }}次观看
|
||||
{{ $lang('components-diy.diy-channel-video.viewCountSuffix', { count: value.viewCount }) }}
|
||||
</view>
|
||||
</view>
|
||||
<view class="video-info">
|
||||
@@ -37,7 +37,7 @@
|
||||
<view class="video-title" :style="[{ '--title-line-clamp': titleLineClamp }]">{{ value.videoTitle }}
|
||||
</view>
|
||||
<!-- 视频统计信息,非列表模式下显示 -->
|
||||
<view class="video-stats" v-if="showViewCount && value.showViewCount && !listMode">{{ value.viewCount }}次观看</view>
|
||||
<view class="video-stats" v-if="showViewCount && value.showViewCount && !listMode">{{ $lang('components-diy.diy-channel-video.viewCountSuffix', { count: value.viewCount }) }}</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -139,7 +139,6 @@ export default {
|
||||
const enableEmbedMode = Boolean(this.value?.embedMode)
|
||||
&& Boolean(this.value?.feedToken)
|
||||
&& wechatChannelUtil.isEmbedModeSupported();
|
||||
console.log('enableEmbedMode', enableEmbedMode);
|
||||
return enableEmbedMode;
|
||||
// #endif
|
||||
return false
|
||||
|
||||
@@ -26,16 +26,16 @@
|
||||
</view>
|
||||
<view class="coupon-num" :style="{ color: value.moneyColor }" v-else>
|
||||
<text class="coupon-size">{{ item.discount | moneyConduct }}</text>
|
||||
<text class="font-size-tag coupon-sign">折</text>
|
||||
<text class="font-size-tag coupon-sign">{{ $lang('components-diy.diy-coupon.discount') }}</text>
|
||||
</view>
|
||||
<view class="coupon-type font-size-tag" :style="{ color: value.limitColor }">
|
||||
{{ item.at_least > 0 ? '满' + Number(item.at_least) + '元可用' : '无门槛优惠券' }}
|
||||
{{ item.at_least > 0 ? $lang('components-diy.diy-coupon.minSpendAvailable', { amount: Number(item.at_least) }) : $lang('components-diy.diy-coupon.noThresholdCoupon') }}
|
||||
</view>
|
||||
</view>
|
||||
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">
|
||||
{{ value.btnStyle.text }}
|
||||
</view>
|
||||
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">去使用</view>
|
||||
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">{{ $lang('components-diy.diy-coupon.goUse') }}</view>
|
||||
</view>
|
||||
|
||||
</swiper-item>
|
||||
@@ -61,16 +61,16 @@
|
||||
</view>
|
||||
<view class="coupon-num" :style="{ color: value.moneyColor }" v-else>
|
||||
<text class="coupon-size">{{ item.discount | moneyConduct }}</text>
|
||||
<text class="font-size-tag coupon-sign">折</text>
|
||||
<text class="font-size-tag coupon-sign">{{ $lang('components-diy.diy-coupon.discount') }}</text>
|
||||
</view>
|
||||
<view class="coupon-type font-size-tag" :style="{ color: value.limitColor }">
|
||||
{{ item.at_least > 0 ? '满' + Number(item.at_least) + '元可用' : '无门槛优惠券' }}
|
||||
{{ item.at_least > 0 ? $lang('components-diy.diy-coupon.minSpendAvailable', { amount: Number(item.at_least) }) : $lang('components-diy.diy-coupon.noThresholdCoupon') }}
|
||||
</view>
|
||||
</view>
|
||||
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">
|
||||
{{ value.btnStyle.text || '领取' }}
|
||||
{{ value.btnStyle.text || $lang('components-diy.diy-coupon.claim') }}
|
||||
</view>
|
||||
<view class="coupon-get use" :style="couponBtnStyle" v-if="parseInt(item.useState)">去使用
|
||||
<view class="coupon-get use" :style="couponBtnStyle" v-if="parseInt(item.useState)">{{ $lang('components-diy.diy-coupon.goUse') }}
|
||||
</view>
|
||||
</view>
|
||||
</swiper-item>
|
||||
@@ -95,20 +95,19 @@
|
||||
</view>
|
||||
<view class="coupon-num" :style="{ color: value.moneyColor }" v-else>
|
||||
<text class="coupon-size">{{ item.discount | moneyConduct }}</text>
|
||||
<text class="font-size-tag coupon-sign">折</text>
|
||||
<text class="font-size-tag coupon-sign">{{ $lang('components-diy.diy-coupon.discount') }}</text>
|
||||
</view>
|
||||
<view class="coupon-type font-size-tag">
|
||||
<text :style="{ color: value.limitColor }">{{ item.at_least > 0 ? '满' +
|
||||
Number(item.at_least) + '元可用' : '无门槛优惠券' }}</text>
|
||||
<view class="item-text" v-if="item.goods_type == 1">所有商品可用</view>
|
||||
<view class="item-text" v-else-if="item.goods_type == 2">指定商品可用</view>
|
||||
<view class="item-text" v-else-if="item.goods_type == 3">指定商品不可用</view>
|
||||
<text :style="{ color: value.limitColor }">{{ item.at_least > 0 ? $lang('components-diy.diy-coupon.minSpendAvailable', { amount: Number(item.at_least) }) : $lang('components-diy.diy-coupon.noThresholdCoupon') }}</text>
|
||||
<view class="item-text" v-if="item.goods_type == 1">{{ $lang('components-diy.diy-coupon.allProductsAvailable') }}</view>
|
||||
<view class="item-text" v-else-if="item.goods_type == 2">{{ $lang('components-diy.diy-coupon.specifiedProductsAvailable') }}</view>
|
||||
<view class="item-text" v-else-if="item.goods_type == 3">{{ $lang('components-diy.diy-coupon.specifiedProductsUnavailable') }}</view>
|
||||
</view>
|
||||
|
||||
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">
|
||||
{{ value.btnStyle.text || '领取' }}
|
||||
{{ value.btnStyle.text || $lang('components-diy.diy-coupon.claim') }}
|
||||
</view>
|
||||
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">去使用</view>
|
||||
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">{{ $lang('components-diy.diy-coupon.goUse') }}</view>
|
||||
</view>
|
||||
</swiper-item>
|
||||
</swiper>
|
||||
@@ -133,16 +132,16 @@
|
||||
</view>
|
||||
<view class="coupon-num" :style="{ color: value.moneyColor }" v-else>
|
||||
<text class="coupon-size">{{ item.discount | moneyConduct }}</text>
|
||||
<text class="font-size-tag coupon-sign">折</text>
|
||||
<text class="font-size-tag coupon-sign">{{ $lang('components-diy.diy-coupon.discount') }}</text>
|
||||
</view>
|
||||
<view class="coupon-type font-size-tag" :style="{ color: value.limitColor }">
|
||||
{{ item.at_least > 0 ? '满' + Number(item.at_least) + '元可用' : '无门槛优惠券' }}
|
||||
{{ item.at_least > 0 ? $lang('components-diy.diy-coupon.minSpendAvailable', { amount: Number(item.at_least) }) : $lang('components-diy.diy-coupon.noThresholdCoupon') }}
|
||||
</view>
|
||||
</view>
|
||||
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">
|
||||
{{ value.btnStyle.text || '立即使用' }}
|
||||
{{ value.btnStyle.text || $lang('components-diy.diy-coupon.useNow') }}
|
||||
</view>
|
||||
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">去使用</view>
|
||||
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">{{ $lang('components-diy.diy-coupon.goUse') }}</view>
|
||||
</view>
|
||||
</swiper-item>
|
||||
</swiper>
|
||||
@@ -160,11 +159,11 @@
|
||||
<view class="coupon-num" v-if="item.discount == '0.00'"
|
||||
:style="{ color: value.moneyColor }">
|
||||
<text class="coupon-size">{{ item.money | moneyConduct }}</text>
|
||||
<text class="font-size-tag coupon-sign">元</text>
|
||||
<text class="font-size-tag coupon-sign">{{ $lang('components-diy.diy-coupon.yuan') }}</text>
|
||||
</view>
|
||||
<view class="coupon-num" v-else :style="{ color: value.moneyColor }">
|
||||
<text class="coupon-size">{{ item.discount | moneyConduct }}</text>
|
||||
<text class="font-size-tag coupon-sign">折</text>
|
||||
<text class="font-size-tag coupon-sign">{{ $lang('components-diy.diy-coupon.discount') }}</text>
|
||||
</view>
|
||||
</view>
|
||||
<view class="coupon-line"></view>
|
||||
@@ -173,14 +172,14 @@
|
||||
<view class="coupon-name" :style="{ color: value.nameColor }">{{
|
||||
item.coupon_name }}</view>
|
||||
<text class="coupon-least" :style="{ color: value.limitColor }"
|
||||
v-if="item.at_least > 0">满{{ Number(item.at_least) }}元可用</text>
|
||||
v-if="item.at_least > 0">{{ $lang('components-diy.diy-coupon.minSpendAvailable', { amount: Number(item.at_least) }) }}</text>
|
||||
<text class="coupon-least" :style="{ color: value.limitColor }"
|
||||
v-else>无门槛优惠券</text>
|
||||
v-else>{{ $lang('components-diy.diy-coupon.noThresholdCoupon') }}</text>
|
||||
</view>
|
||||
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">{{
|
||||
value.btnStyle.text || '立即领取' }}</view>
|
||||
value.btnStyle.text || $lang('components-diy.diy-coupon.claimNow') }}</view>
|
||||
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">
|
||||
去使用</view>
|
||||
{{ $lang('components-diy.diy-coupon.goUse') }}</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -204,9 +203,9 @@
|
||||
<view class="price-wrap">
|
||||
<text class="price" :style="{ color: value.moneyColor }">{{ (item.discount == '0.00'
|
||||
? item.money : item.discount) | moneyConduct }}</text>
|
||||
<text class="unit">{{ item.discount == '0.00' ? '元' : '折' }}</text>
|
||||
<text class="unit">{{ item.discount == '0.00' ? $lang('components-diy.diy-coupon.yuan') : $lang('components-diy.diy-coupon.discount') }}</text>
|
||||
</view>
|
||||
<text class="text">优惠券</text>
|
||||
<text class="text">{{ $lang('components-diy.diy-coupon.coupon') }}</text>
|
||||
</view>
|
||||
<text class="btn" v-if="item.useState == 0" :style="{
|
||||
color: value.btnStyle.textColor,
|
||||
@@ -222,11 +221,11 @@
|
||||
borderTopLeftRadius: value.btnStyle.aroundRadius * 2 + 'rpx',
|
||||
borderBottomLeftRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
|
||||
}">
|
||||
<text class="btn-content">去使用</text>
|
||||
<text class="btn-content">{{ $lang('components-diy.diy-coupon.goUse') }}</text>
|
||||
</text>
|
||||
<text class="limit" :style="{ color: value.limitColor }"
|
||||
v-if="parseFloat(item.at_least) > 0">满{{ item.at_least | moneyConduct }}元使用</text>
|
||||
<text class="limit" :style="{ color: value.limitColor }" v-else>无门槛使用</text>
|
||||
v-if="parseFloat(item.at_least) > 0">{{ $lang('components-diy.diy-coupon.minSpendUse', { amount: item.at_least | moneyConduct }) }}</text>
|
||||
<text class="limit" :style="{ color: value.limitColor }" v-else>{{ $lang('components-diy.diy-coupon.noThresholdUse') }}</text>
|
||||
</view>
|
||||
|
||||
<div v-if="computedCouponList.length <= 2" @tap.stop="$util.redirectTo('/pages_goods/category')"
|
||||
@@ -238,9 +237,9 @@
|
||||
}">
|
||||
<div class="coupon-content" :style="{ color: value.moneyColor }">
|
||||
<span class="price">+</span>
|
||||
<span class="text">暂无优惠券</span>
|
||||
<span class="text">{{ $lang('components-diy.diy-coupon.noCoupons') }}</span>
|
||||
</div>
|
||||
<span class="limit" :style="{ color: value.limitColor }">去逛逛</span>
|
||||
<span class="limit" :style="{ color: value.limitColor }">{{ $lang('components-diy.diy-coupon.goBrowse') }}</span>
|
||||
</div>
|
||||
</swiper-item>
|
||||
</swiper>
|
||||
@@ -257,25 +256,24 @@
|
||||
<view class="coupon-num" v-if="item.discount == '0.00'"
|
||||
:style="{ color: value.moneyColor }">
|
||||
<text class="coupon-size">{{ item.money | moneyConduct }}</text>
|
||||
<text class="font-size-tag coupon-sign">元</text>
|
||||
<text class="font-size-tag coupon-sign">{{ $lang('components-diy.diy-coupon.yuan') }}</text>
|
||||
</view>
|
||||
<view class="coupon-num" v-else :style="{ color: value.moneyColor }">
|
||||
<text class="coupon-size">{{ item.discount | moneyConduct }}</text>
|
||||
<text class="font-size-tag coupon-sign">折</text>
|
||||
<text class="font-size-tag coupon-sign">{{ $lang('components-diy.diy-coupon.discount') }}</text>
|
||||
</view>
|
||||
</view>
|
||||
<view class="coupon-type">
|
||||
<text class="coupon-name" :style="{ color: value.limitColor }"
|
||||
v-if="item.at_least > 0">满{{ Number(item.at_least) }}元可用</text>
|
||||
<text class="coupon-name" :style="{ color: value.limitColor }" v-else>无门槛优惠券</text>
|
||||
<view class="coupon-least" :style="{ color: value.limitColor }">有效期至{{
|
||||
$util.timeStampTurnTime(item.end_time, 'yearmonthday') }}</view>
|
||||
v-if="item.at_least > 0">{{ $lang('components-diy.diy-coupon.minSpendAvailable', { amount: Number(item.at_least) }) }}</text>
|
||||
<text class="coupon-name" :style="{ color: value.limitColor }" v-else>{{ $lang('components-diy.diy-coupon.noThresholdCoupon') }}</text>
|
||||
<view class="coupon-least" :style="{ color: value.limitColor }">{{ $lang('components-diy.diy-coupon.validUntil', { date: $util.timeStampTurnTime(item.end_time, 'yearmonthday') }) }}</view>
|
||||
</view>
|
||||
<view class="coupon-line"></view>
|
||||
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">
|
||||
{{ value.btnStyle.text || '立即领取' }}
|
||||
{{ value.btnStyle.text || $lang('components-diy.diy-coupon.claimNow') }}
|
||||
</view>
|
||||
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">去使用
|
||||
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">{{ $lang('components-diy.diy-coupon.goUse') }}
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -404,7 +402,7 @@ export default {
|
||||
couponTap(item, index) {
|
||||
if (item.count == item.lead_count) {
|
||||
this.$util.showToast({
|
||||
title: '该优惠券已抢光'
|
||||
title: this.$lang('components-diy.diy-coupon.couponSoldOut')
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -427,7 +425,7 @@ export default {
|
||||
var data = res.data;
|
||||
let msg = res.message;
|
||||
if (res.code == 0) {
|
||||
msg = '领取成功';
|
||||
msg = this.$lang('components-diy.diy-coupon.claimSuccess');
|
||||
if (res.data.is_exist == 1) {
|
||||
for (let i = 0; i < that.couponList.length; i++) {
|
||||
if (that.couponList[i].coupon_type_id == item.coupon_type_id) {
|
||||
|
||||
@@ -1,36 +1,25 @@
|
||||
<template>
|
||||
<template>
|
||||
<view :style="componentStyle" data-component-name="diy-digit">
|
||||
<scroll-view :class="['graphic-nav', value.showStyle == 'fixed' ? 'fixed-layout' : value.showStyle]"
|
||||
:scroll-x="value.showStyle == 'singleSlide'">
|
||||
<view class="uni-scroll-view-content">
|
||||
<view v-for="(item, index) in value.list" :key="index"
|
||||
:class="['graphic-nav-item', value.mode, value.mode === 'text' ? 'newright' : '']"
|
||||
:style="{ width: (100 / value.rowCount + '%') + ';' }">
|
||||
<view style="display:flex;">
|
||||
<view :style="{
|
||||
'line-height': '1.2;',
|
||||
'font-size': (value.font.titlesize * 2 + 'rpx') + ';',
|
||||
'font-weight': '600;',
|
||||
'color': value.font.titlecolor + ';'
|
||||
}">
|
||||
:style="itemStyle">
|
||||
<view :style="innerWrapStyle">
|
||||
<view :style="innerRowStyle">
|
||||
<uv-count-to :ref="`countTo-${index}`" :autoplay="true" :startVal="30" :endVal="item.title"
|
||||
:decimals="getvalue(item.title)" decimal="."></uv-count-to>
|
||||
<text :style="{
|
||||
'margin-left': '4rpx;',
|
||||
'font-size': (value.font.unitsize * 2 + 'rpx') + ';',
|
||||
'font-weight': value.font.weight + ';',
|
||||
'color': value.font.unitcolor + ';'
|
||||
}">{{ item.unit }}</text>
|
||||
:decimals="getvalue(item.title)" decimal="."
|
||||
:color="value.font.titlecolor"
|
||||
:fontSize="titleFontSize"
|
||||
:bold="isBold(value.font.weight)"></uv-count-to>
|
||||
<text :style="unitStyle">{{ item.unit }}</text>
|
||||
</view>
|
||||
</view>
|
||||
<view class="graphic-text">
|
||||
<text :style="{
|
||||
'font-size': (value.font.descsize * 2 + 'rpx') + ';',
|
||||
'font-weight': value.font.weight + ';',
|
||||
'color': value.font.desccolor + ';'
|
||||
}">{{ item.desc }}</text>
|
||||
<view class="graphic-text">
|
||||
<text :style="descStyle">{{ item.desc }}</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</scroll-view>
|
||||
<ns-login ref="login"></ns-login>
|
||||
@@ -54,10 +43,20 @@ export default {
|
||||
pageWidth: '',
|
||||
indicatorDots: false,
|
||||
swiperCurrent: 0
|
||||
// #ifndef MP
|
||||
,windowWidth: 375
|
||||
// #endif
|
||||
}
|
||||
},
|
||||
created() {
|
||||
// 组件创建时的逻辑
|
||||
// #ifndef MP
|
||||
try {
|
||||
let info = uni.getSystemInfoSync();
|
||||
this.windowWidth = info.windowWidth || info.screenWidth || 375;
|
||||
if (this.windowWidth > 960) this.windowWidth = 375;
|
||||
} catch (e) { }
|
||||
// #endif
|
||||
},
|
||||
watch: {
|
||||
componentRefresh(newValue) {
|
||||
@@ -65,6 +64,42 @@ export default {
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
// 全部返回字符串:WeChat 小程序的 style="{{obj}}" 对象绑定不会被运行时正确解析为内联 CSS
|
||||
//(参考 diy-graphic-nav.vue:那里同样用字符串拼接 style="{{'width:...%'}}",能正常生效)。
|
||||
// 字符串既能被 MP 直接当 cssText,也能被 H5 的 CSSOM 正确解析。
|
||||
itemStyle() {
|
||||
return 'width:' + (100 / this.value.rowCount) + '%;';
|
||||
},
|
||||
innerWrapStyle() {
|
||||
return 'display:flex;justify-content:center;align-items:center;width:100%;';
|
||||
},
|
||||
innerRowStyle() {
|
||||
return 'display:flex;align-items:baseline;justify-content:center;width:100%;line-height:1.2;';
|
||||
},
|
||||
unitStyle() {
|
||||
// #ifdef MP
|
||||
return 'margin-left:4rpx;font-size:' + (this.value.font.unitsize * 2) + 'rpx;font-weight:' + this.value.font.weight + ';color:' + this.value.font.unitcolor + ';';
|
||||
// #endif
|
||||
// #ifndef MP
|
||||
return 'margin-left:' + this.rpxToPx(4) + 'px;font-size:' + this.rpxToPx((Number(this.value.font.unitsize) || 12) * 2) + 'px;font-weight:' + this.value.font.weight + ';color:' + this.value.font.unitcolor + ';';
|
||||
// #endif
|
||||
},
|
||||
descStyle() {
|
||||
// #ifdef MP
|
||||
return 'font-size:' + (this.value.font.descsize * 2) + 'rpx;font-weight:' + this.value.font.weight + ';color:' + this.value.font.desccolor + ';';
|
||||
// #endif
|
||||
// #ifndef MP
|
||||
return 'font-size:' + this.rpxToPx((Number(this.value.font.descsize) || 12) * 2) + 'px;font-weight:' + this.value.font.weight + ';color:' + this.value.font.desccolor + ';';
|
||||
// #endif
|
||||
},
|
||||
titleFontSize() {
|
||||
// #ifdef MP
|
||||
return this.value.font.titlesize || 22;
|
||||
// #endif
|
||||
// #ifndef MP
|
||||
return this.rpxToPx((Number(this.value.font.titlesize) || 22) * 2);
|
||||
// #endif
|
||||
},
|
||||
componentStyle() {
|
||||
let style = '';
|
||||
style += 'background-image:url(' + this.$util.img(this.value.imageUrl) + ');background-size:100% 100%;';
|
||||
@@ -83,15 +118,28 @@ export default {
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
// #ifndef MP
|
||||
// rpx -> px:H5 行内样式里的 rpx 不生效,统一换算成 px
|
||||
rpxToPx(rpx) {
|
||||
let num = Number(rpx) || 0;
|
||||
if (!num) return 0;
|
||||
return Math.round((num * (this.windowWidth || 375) / 750) * 100) / 100;
|
||||
},
|
||||
// #endif
|
||||
|
||||
// 获取小数位数
|
||||
getvalue(value) {
|
||||
return value % 1 !== 0 ? 2 : 0;
|
||||
},
|
||||
|
||||
// 是否加粗
|
||||
isBold(weight) {
|
||||
return weight === 'bold' || (weight && Number(weight) >= 600);
|
||||
},
|
||||
|
||||
// 页面跳转
|
||||
redirectTo(item) {
|
||||
if (!item.wap_url || this.$util.getCurrRoute() != this.$util.MEMBER_PAGE_URL || this.storeToken) {
|
||||
console.log(item);
|
||||
this.$util.diyRedirectTo(item);
|
||||
} else {
|
||||
this.$refs.login.open(item.wap_url);
|
||||
@@ -258,4 +306,5 @@ export default {
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
</style>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
:class="[value.ornament.type]" :style="goodsItemCss">
|
||||
<view class="goods-img" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
|
||||
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
|
||||
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix" @error="imgError(index)" />
|
||||
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix" @error="imgError(index)" show-menu-by-longpress/>
|
||||
</view>
|
||||
<view class="info-wrap"
|
||||
v-if="value.goodsNameStyle.control || value.priceStyle.mainControl || value.priceStyle.lineControl || value.btnStyle.control">
|
||||
@@ -20,7 +20,7 @@
|
||||
<view class="discount-price">
|
||||
<view class="price-wrap" v-if="value.priceStyle.mainControl">
|
||||
<text class="unit price-style small"
|
||||
:style="{ color: value.theme == 'diy' ? value.priceStyle.mainColor : '' }">赚 ¥</text>
|
||||
:style="{ color: value.theme == 'diy' ? value.priceStyle.mainColor : '' }">{{ $lang('components-diy.diy-fenxiao-goods-list.earnPrefix') }}</text>
|
||||
<text class="price price-style large"
|
||||
:style="{ color: value.theme == 'diy' ? value.priceStyle.mainColor : '' }">{{
|
||||
item.commission_money.split('.')[0] }}</text>
|
||||
@@ -33,14 +33,14 @@
|
||||
color: value.btnStyle.theme == 'diy' ? value.btnStyle.textColor : '',
|
||||
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
|
||||
}" @tap.stop="followGoods(item, index)">
|
||||
关注
|
||||
{{ $lang('components-diy.diy-fenxiao-goods-list.follow') }}
|
||||
</view>
|
||||
<view class="sale-btn" v-if="value.btnStyle.control && item.is_collect == 1" :style="{
|
||||
background: value.btnStyle.theme == 'diy' ? 'linear-gradient(to right,' + value.btnStyle.bgColorStart + ',' + value.btnStyle.bgColorEnd + ')' : '',
|
||||
color: value.btnStyle.theme == 'diy' ? value.btnStyle.textColor : '',
|
||||
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
|
||||
}" @tap.stop="delFollowTip(item, index)">
|
||||
取消关注
|
||||
{{ $lang('components-diy.diy-fenxiao-goods-list.unfollow') }}
|
||||
</view>
|
||||
</view>
|
||||
<view class="delete-price" v-if="value.priceStyle.lineControl"
|
||||
@@ -138,7 +138,7 @@ export default {
|
||||
},
|
||||
success: res => {
|
||||
if (res.code >= 0) {
|
||||
this.$util.showToast({ title: '关注成功' });
|
||||
this.$util.showToast({ title: this.$lang('components-diy.diy-fenxiao-goods-list.followSuccess') });
|
||||
this.list[index].is_collect = 1;
|
||||
this.list[index].collect_id = res.data;
|
||||
}
|
||||
@@ -149,8 +149,8 @@ export default {
|
||||
//取消关注
|
||||
delFollowTip(e, index) {
|
||||
uni.showModal({
|
||||
title: '提示',
|
||||
content: '确认取消关注该商品吗',
|
||||
title: this.$lang('components-diy.diy-fenxiao-goods-list.tip'),
|
||||
content: this.$lang('components-diy.diy-fenxiao-goods-list.confirmUnfollow'),
|
||||
success: res => {
|
||||
if (res.confirm) {
|
||||
this.delFollow(e.collect_id, index);
|
||||
@@ -167,7 +167,7 @@ export default {
|
||||
success: res => {
|
||||
let msg = '';
|
||||
if (res.code == 0) {
|
||||
msg = '取消成功';
|
||||
msg = this.$lang('components-diy.diy-fenxiao-goods-list.cancelSuccess');
|
||||
} else {
|
||||
msg = res.message;
|
||||
}
|
||||
@@ -337,7 +337,7 @@ export default {
|
||||
width: calc(50% - 10rpx);
|
||||
|
||||
&:nth-child(2n + 2) {
|
||||
width: calc(50% - 11rpx);
|
||||
width: calc(50% - 10rpx);
|
||||
margin-right: 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
:class="{ left_top: value.bottomPosition == 1, right_top: value.bottomPosition == 2, left_bottom: value.bottomPosition == 3, right_bottom: value.bottomPosition == 4 }"
|
||||
:style="style">
|
||||
<block v-for="(item, index) in value.list" :key="index">
|
||||
<view class="button-box" @tap.stop="$util.diyRedirectTo(item.link)"
|
||||
<view class="button-box" @tap.stop="onFloatBtnClick(item)"
|
||||
:style="{ width: value.imageSize + 'px', height: value.imageSize + 'px', fontSize: value.imageSize + 'px' }">
|
||||
<image v-if="!item.iconType || item.iconType == 'img'" :src="$util.img(item.imageUrl)" mode="aspectFit"
|
||||
:show-menu-by-longpress="true" />
|
||||
show-menu-by-longpress />
|
||||
<diy-icon v-else-if="item.iconType && item.iconType == 'icon'" :icon="item.icon"
|
||||
:value="item.style ? item.style : null"></diy-icon>
|
||||
</view>
|
||||
@@ -44,7 +44,44 @@ export default {
|
||||
componentRefresh: function (nval) { }
|
||||
},
|
||||
components: {},
|
||||
methods: {},
|
||||
methods: {
|
||||
/**
|
||||
* 浮动按钮点击处理:
|
||||
* 在跳转前给 link 注入 __dyu=FloatBtn 来源标记,
|
||||
* 让目标页面(尤其是 ai-chat)能识别"来自浮动按钮"从而隐藏底部 tabBar,
|
||||
* 与"从底部导航栏点击进入时显示并高亮 tabBar"的场景并存。
|
||||
*
|
||||
* 为什么用 __dyu 这种 3 字符命名:
|
||||
* - 双下划线 __ 前缀 + 3 位字母(dy-ui 框架) 是前端约定俗成的"系统内部保留字段"标志
|
||||
* (如 __proto__, __esModule),业务方配置 link 时几乎不可能使用这种短命名 → 与业务参数零冲突
|
||||
* - URL 中占用空间极小,不污染业务 query 字符串
|
||||
* - 未来如需扩展其他组件的入口来源,可继续使用 __dyu 前缀(如 __dyu=Banner / __dyu=Nav)
|
||||
*
|
||||
* 实现要点:
|
||||
* - 浅拷贝 item.link 避免污染原数据(可能被 v-for 复用)
|
||||
* - 把标记写入 page_params,diyRedirectTo → redirectTo 会自动拼到 URL query,
|
||||
* 目标页 onLoad(options) 可直接读取
|
||||
* - 同时在 wap_url 末尾追加/合并 __dyu=FloatBtn 兜底:某些路径不走 page_params 拼接
|
||||
*/
|
||||
onFloatBtnClick(item) {
|
||||
if (!item || !item.link) return;
|
||||
const link = { ...item.link };
|
||||
link.page_params = Object.assign({}, link.page_params || {}, {
|
||||
__dyu: 'FloatBtn'
|
||||
});
|
||||
|
||||
// 兜底:直接把标记拼到 wap_url query,防止 page_params 在某些分支未被透传
|
||||
if (link.wap_url && typeof link.wap_url === 'string' && link.wap_url.indexOf('http') === -1) {
|
||||
const sep = link.wap_url.indexOf('?') === -1 ? '?' : '&';
|
||||
// 避免重复追加(精确匹配 __dyu= 而不是 __dyu,避免误伤可能的 __dyu_other)
|
||||
if (link.wap_url.indexOf('__dyu=') === -1) {
|
||||
link.wap_url = link.wap_url + sep + '__dyu=FloatBtn';
|
||||
}
|
||||
}
|
||||
|
||||
this.$util.diyRedirectTo(link);
|
||||
},
|
||||
},
|
||||
computed: {
|
||||
style() {
|
||||
let style = {},
|
||||
|
||||
@@ -1,103 +1,745 @@
|
||||
<template>
|
||||
<view data-component-name="diy-form" class="diy-from" :style="style">
|
||||
<view class="fui-cell-group">
|
||||
<view class="fui-cell ">
|
||||
<view class="fui-cell-label ">您的姓名</view>
|
||||
<view class="fui-cell-info">
|
||||
<input v-model="Form.realname" class="fui-input" placeholder="请输入您的姓名" value=""></input>
|
||||
</view>
|
||||
</view>
|
||||
<view class="fui-cell ">
|
||||
<view class="fui-cell-label">手机号码</view>
|
||||
<view class="fui-cell-info">
|
||||
<input v-model="Form.mobile" class="fui-input" maxlength="11" placeholder="请输入您的手机号"
|
||||
type="number"></input>
|
||||
</view>
|
||||
</view>
|
||||
<view class="fui-cell ">
|
||||
<view class="fui-cell-label">您的邮箱</view>
|
||||
<view class="fui-cell-info">
|
||||
<input v-model="Form.mailbox" class="fui-input" placeholder="请输入您的邮箱" type="text"></input>
|
||||
</view>
|
||||
</view>
|
||||
<view class="fui-cell">
|
||||
<view class="fui-cell-label">所在城市</view>
|
||||
<view class="fui-cell-info">
|
||||
<input v-model="Form.citys" class="fui-input" placeholder="请输入您的所在地" value=""></input>
|
||||
</view>
|
||||
</view>
|
||||
<view class="fui-cell">
|
||||
<view class="fui-cell-label">备注</view>
|
||||
<view class="fui-cell-info">
|
||||
<input v-model="Form.remark" class="fui-input" placeholder="请输入备注" value=""></input>
|
||||
<view data-component-name="diy-form" class="diy-from" :style="diyFormStyle">
|
||||
<!-- Banner -->
|
||||
<!-- 鸿蒙元服务运行时在首次 _render 时 value 可能还是 undefined,
|
||||
下面所有 value.xxx 模板表达式都必须用 `value && value.xxx` 守护,
|
||||
否则会触发 MP 编译器注入的 propsToData 观察者(对应编译产物里
|
||||
r=function(){var o=this.value.show_banner...this.$mp.data...})
|
||||
报 "Cannot read properties of undefined (reading 'show_banner')"。 -->
|
||||
<view v-if="value && value.show_banner && value.form_banner" class="form-banner is-card-overlap" :style="bannerStyle + bannerBleedStyle">
|
||||
<!-- Banner 图片高度策略(与商家端预览 .preview-banner height:auto 对齐):
|
||||
默认 mode="widthFix":宽度撑满、高度按图片原始比例自适应,图片完整显示不裁剪;
|
||||
显式配置 bannerHeight/banner_height 或 bannerCropRatio → 切 aspectFill 居中裁剪;
|
||||
显式配置 bannerCropBox → 切 widthFix + image 内联 transform translate/缩放(手动裁栏框);
|
||||
裁剪位置(bannerCropPosition):uni-app image 不支持 object-position,
|
||||
通过 .banner-img-crop 容器的 transform translateY 控制(top/居中/底部)。 -->
|
||||
<view class="banner-img-wrap" :class="bannerImgWrapClass" :style="bannerImgWrapStyle">
|
||||
<view class="banner-img-crop" :class="'crop-' + bannerCropPosition">
|
||||
<image :src="$util.img(value.form_banner)" :mode="bannerImgMode" class="banner-img" :style="bannerImgStyle" />
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
<view @tap.stop="submitform" class="fui-btn btn-danger block mtop">提交信息</view>
|
||||
<!-- 卡片浮起模式:tip / 提交按钮位置可配(仅 card 风格生效)
|
||||
- tip_position: outside(默认)= 独立白卡负 margin 压住 banner 底部;inside = 内容卡内
|
||||
- submit_position: inside(默认)= 提交按钮在内容卡内;outside = 卡片下方独立区域 -->
|
||||
<template v-if="hasBannerMode">
|
||||
<!-- tip 独立卡(outside,默认):负 margin 压 banner + 白底 + 圆角 + 阴影,视觉参照商家端预览 .preview-tip -->
|
||||
<view v-if="value && value.show_tip && value.form_tip && tipPosition === 'outside'" class="form-tip-card" :style="tipCardStyle">{{ value.form_tip }}</view>
|
||||
<!-- 内容卡:tipPosition !== 'outside'(tip 关闭或 tip 在卡内)时由本卡接管负 margin 浮起 -->
|
||||
<view class="form-card" :style="cardWrapStyle">
|
||||
<!-- tip 卡内(inside):无独立卡视觉,用户配置的 bg/border/shadow 仍生效 -->
|
||||
<view v-if="value && value.show_tip && value.form_tip && tipPosition !== 'outside'" class="form-tip" :style="tipStyle">{{ value.form_tip }}</view>
|
||||
<!-- 表单组件 -->
|
||||
<ns-newform
|
||||
:data="formComponents"
|
||||
:customAttr="value"
|
||||
:mode="mergedFormConfig.formLayout || 'vertical'"
|
||||
:formConfig="mergedFormConfig"
|
||||
ref="nsNewform"
|
||||
></ns-newform>
|
||||
<!-- 提交按钮(inside,默认):在内容卡内 -->
|
||||
<view v-if="showSubmit && submitPosition !== 'outside'" class="form-submit-wrap" :style="submitWrapStyle">
|
||||
<view @click.stop="handleSubmit" class="form-submit" :style="submitStyle">{{ submitText }}</view>
|
||||
</view>
|
||||
</view>
|
||||
<!-- 提交按钮独立区(outside):卡片下方,无卡背景 -->
|
||||
<view v-if="showSubmit && submitPosition === 'outside'" class="form-submit-wrap" :style="submitWrapStyle">
|
||||
<view @click.stop="handleSubmit" class="form-submit" :style="submitStyle">{{ submitText }}</view>
|
||||
</view>
|
||||
</template>
|
||||
<!-- 无 banner 时仍按旧布局直接渲染 tip / ns-newform / submit,避免影响其他使用方(diy-group / diy-article 等) -->
|
||||
<template v-else>
|
||||
<!-- 提示语 -->
|
||||
<view v-if="value && value.show_tip && value.form_tip" class="form-tip" :style="tipStyle">{{ value && value.form_tip }}</view>
|
||||
<!-- 表单组件 -->
|
||||
<ns-newform
|
||||
:data="formComponents"
|
||||
:customAttr="value"
|
||||
:mode="mergedFormConfig.formLayout || 'vertical'"
|
||||
:formConfig="mergedFormConfig"
|
||||
ref="nsNewform"
|
||||
></ns-newform>
|
||||
<view v-if="showSubmit" class="form-submit-wrap" :style="submitWrapStyle">
|
||||
<view @click.stop="handleSubmit" class="form-submit" :style="submitStyle">{{ submitText }}</view>
|
||||
</view>
|
||||
</template>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
// 自定义表单
|
||||
// 提交接管三档(不依赖 $listeners / 事件机制,跨 H5 / MP / 鸿蒙一致):
|
||||
// 1) 默认 → showSubmit=true + 不传 onSubmit → 内置按钮 + 内置 defaultSubmit
|
||||
// 2) 复用按钮、自定义逻辑 → showSubmit=true + :onSubmit="fn" → 内置按钮 + 父级 fn
|
||||
// 3) 完全自定义 UI → showSubmit=false + :onSubmit="fn" 或 ref.verify()/getFormData() → 父级全控
|
||||
// 注:type: Function prop 在 uni-app MP 端走 Vue runtime 注入,机制与 ns-navbar.customBack 一致
|
||||
import DiyMinx from './minx.js'
|
||||
import NsNewform from '@/components/ns-newform/ns-newform.vue'
|
||||
|
||||
// 横幅裁剪比例白名单(与后端 form.js syncFormConfigToCSS 保持一致)
|
||||
const BANNER_CROP_RATIOS = { '16:9': 16/9, '4:3': 4/3, '1:1': 1, '3:4': 3/4 }
|
||||
|
||||
export default {
|
||||
name: 'diy-from',
|
||||
components: { NsNewform },
|
||||
props: {
|
||||
value: {
|
||||
type: Object
|
||||
},
|
||||
// 数据源模式:
|
||||
// 'diy'(默认):value.formComponents 是 [{ type, value }],组件内部转换为 ns-newform 期望的 [{ controller, value, val }]
|
||||
// 'raw' :value.jsonData / value.json_data 已经是 ns-newform 期望的格式,直接透传给 ns-newform
|
||||
// 用途:让 formdata 等"已是 ns-newform 格式"的页面也能复用本组件的 banner/tip/样式系统
|
||||
dataMode: {
|
||||
type: String,
|
||||
default: 'diy',
|
||||
validator: (v) => ['diy', 'raw'].includes(v)
|
||||
},
|
||||
// 是否渲染内置提交按钮。false 时由父级调用 ref 上的 verify()/getFormData() 自行实现提交
|
||||
showSubmit: {
|
||||
type: Boolean,
|
||||
default: true
|
||||
},
|
||||
// 父级容器左右内边距(rpx)。卡片模式下让 banner 图片突破这个内边距左右铺满(如 system-form-wrap 的 padding-x)。
|
||||
// 仅在 hasBannerMode=true 时生效;默认 0(不铺满)。
|
||||
// 引入原因:formdata.vue 的 .system-form-wrap 默认 padding: 0 50rpx,banner 图片被左右各 50rpx 收缩,
|
||||
// 后台配 form_banner 后图片应跨越屏幕宽度,而不是被容器内缩。
|
||||
containerInset: {
|
||||
type: Number,
|
||||
default: 0
|
||||
},
|
||||
// 父级可选地接管提交:传入函数 prop 时,verify 通过后由它处理 formData;
|
||||
// 不传时走组件内置 defaultSubmit(兜底)。default 必须是 null,不能写成函数返回 null
|
||||
onSubmit: {
|
||||
type: Function,
|
||||
default: null
|
||||
}
|
||||
},
|
||||
mixins: [DiyMinx],
|
||||
data() {
|
||||
return {
|
||||
loading: true,
|
||||
markers: [],
|
||||
Form: {
|
||||
realname: '',
|
||||
mobile: '',
|
||||
mailbox: '',
|
||||
citys: '',
|
||||
remark: '',
|
||||
}
|
||||
formComponents: [] // 转换后的表单组件
|
||||
};
|
||||
},
|
||||
created() {
|
||||
this.initForm();
|
||||
},
|
||||
watch: {
|
||||
// 组件刷新监听
|
||||
componentRefresh: function (nval) {
|
||||
// this.getDataList();
|
||||
'value': {
|
||||
deep: true,
|
||||
handler() {
|
||||
// raw 模式:formData 由父级透传,跳过重跑 initForm(避免每次父组件 re-render 触发 ns-newform 的深拷贝 initFormData)
|
||||
if (this.dataMode === 'raw') return;
|
||||
this.initForm();
|
||||
}
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
markerst() {
|
||||
return [{
|
||||
id: 1,
|
||||
latitude: this.value.list[0].lat,
|
||||
longitude: this.value.list[0].lng
|
||||
}]
|
||||
},
|
||||
style() {
|
||||
// 鸿蒙元服务运行时首次 _render 时 this.value 可能还是 undefined,必须全程加护
|
||||
var css = '';
|
||||
css += 'background-color:' + this.value.contentBgColor + ';';
|
||||
if (this.value.elementAngle == 'round') {
|
||||
css += 'border-top-left-radius:' + this.value.topElementAroundRadius * 2 + 'rpx;';
|
||||
css += 'border-top-right-radius:' + this.value.topElementAroundRadius * 2 + 'rpx;';
|
||||
css += 'border-bottom-left-radius:' + this.value.bottomElementAroundRadius * 2 + 'rpx;';
|
||||
css += 'border-bottom-right-radius:' + this.value.bottomElementAroundRadius * 2 + 'rpx;';
|
||||
var v = this.value || {};
|
||||
css += 'background-color:' + (v.contentBgColor || '') + ';';
|
||||
if (v.elementAngle === 'round') {
|
||||
css += 'border-top-left-radius:' + (v.topElementAroundRadius || 0) * 2 + 'rpx;';
|
||||
css += 'border-top-right-radius:' + (v.topElementAroundRadius || 0) * 2 + 'rpx;';
|
||||
css += 'border-bottom-left-radius:' + (v.bottomElementAroundRadius || 0) * 2 + 'rpx;';
|
||||
css += 'border-bottom-right-radius:' + (v.bottomElementAroundRadius || 0) * 2 + 'rpx;';
|
||||
}
|
||||
return css;
|
||||
},
|
||||
// 兼容旧 style 别名(部分页面用 :style="style" 引用)
|
||||
diyFormStyle() {
|
||||
return this.style;
|
||||
},
|
||||
// Banner 容器左右内边距(与后端 .form-preview-banner padding-x 对齐)
|
||||
bannerStyle() {
|
||||
return this.$util.objToStyle({
|
||||
padding: `0 ${this._num(this.mergedFormConfig && this.mergedFormConfig.bannerPaddingX, 0)}rpx`
|
||||
});
|
||||
},
|
||||
// Banner 图片高度模式(2026-09-03 对齐商家端预览):
|
||||
// 商家端预览 .preview-banner 是 max-width:100%; height:auto —— 按图片原始比例完整显示。
|
||||
// 此前 H5 固定 180rpx + aspectFill 居中裁剪,导致横幅高度不一/图片内容被裁缺失。
|
||||
// 现在:无显式配置 → widthFix 自适应(与后端 height:auto 等价);
|
||||
// 显式配置 bannerHeight / banner_height → 固定高度 + aspectFill 裁剪(用户主动选择);
|
||||
// 显式配置 bannerCropRatio → 按比例锁高度,比例+高度都设时高度优先(保持数字 rpx 的语义);
|
||||
// 显式配置 bannerCropBox → 手动裁栏框(widthFix + image transform,最高优先级,独享遮罩)。
|
||||
hasBannerHeight() {
|
||||
const cfg = this.mergedFormConfig || {};
|
||||
const raw = cfg.bannerHeight !== undefined ? cfg.bannerHeight : cfg.banner_height;
|
||||
const n = parseInt(raw);
|
||||
return !isNaN(n) && n > 0;
|
||||
},
|
||||
bannerImgMode() {
|
||||
// 手动裁栏框优先(widthFix + transform);
|
||||
// 显式选择比例(16:9/4:3/...)时用 aspectFill 填满比例容器;
|
||||
// 仅配置高度 + 原比例时与商家端预览一致:widthFix 自适应,容器限制最大高度,图片完整显示不裁剪。
|
||||
if (this.hasManualCrop) return 'widthFix';
|
||||
return this.bannerCropRatio ? 'aspectFill' : 'widthFix';
|
||||
},
|
||||
// Banner 图片包裹层高度:
|
||||
// - 比例模式 / 手动框:输出固定 height,配合 aspectFill 裁剪;
|
||||
// - 仅高度 + 原比例:输出 max-height,让图片按原始比例完整显示,高度不超过设定值。
|
||||
bannerImgWrapStyle() {
|
||||
if (!this.hasBannerHeight) return '';
|
||||
let h = parseInt(this.mergedFormConfig.bannerHeight !== undefined ? this.mergedFormConfig.bannerHeight : this.mergedFormConfig.banner_height);
|
||||
if (h < 40) h = 40;
|
||||
if (h > 1200) h = 1200;
|
||||
if (this.bannerCropRatio || this.hasManualCrop) {
|
||||
return this.$util.objToStyle({ height: h + 'rpx' });
|
||||
}
|
||||
return this.$util.objToStyle({ 'max-height': h + 'rpx' });
|
||||
},
|
||||
// 裁剪比例:读双键(camel + snake);合法值 16:9/4:3/1:1/3:4;空 = 不启用
|
||||
bannerCropRatio() {
|
||||
const cfg = this.mergedFormConfig || {};
|
||||
const raw = cfg.bannerCropRatio !== undefined ? cfg.bannerCropRatio : cfg.banner_crop_ratio;
|
||||
return (raw && BANNER_CROP_RATIOS[raw]) ? raw : '';
|
||||
},
|
||||
// 裁剪位置:top/center/bottom(默认 center);通过 CSS object-position 控制(uni-app H5/MP 容器配合 transform 实现)
|
||||
bannerCropPosition() {
|
||||
const cfg = this.mergedFormConfig || {};
|
||||
const raw = cfg.bannerCropPosition !== undefined ? cfg.bannerCropPosition : cfg.banner_crop_position;
|
||||
return (raw === 'top' || raw === 'bottom') ? raw : 'center';
|
||||
},
|
||||
// 手动裁栏框:读双键;返回 {x,y,w,h} 0..1 比例或 null
|
||||
// 三优先级:手动框 > 比例/位置 > 高度/位置(与后端 syncFormConfigToCSS 对齐)
|
||||
bannerCropBox() {
|
||||
const cfg = this.mergedFormConfig || {};
|
||||
const raw = cfg.bannerCropBox !== undefined ? cfg.bannerCropBox : cfg.banner_crop_box;
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const obj = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
||||
if (obj && typeof obj.x === 'number' && typeof obj.y === 'number' && typeof obj.w === 'number' && typeof obj.h === 'number' && obj.w > 0 && obj.h > 0) {
|
||||
return obj;
|
||||
}
|
||||
} catch (e) { return null; }
|
||||
return null;
|
||||
},
|
||||
// 手动裁栏框激活时:渲染模式切 widthFix(保留全图)+ 内层 img 用 transform 移动/缩放显示裁栏区域
|
||||
hasManualCrop() { return !!this.bannerCropBox; },
|
||||
// 手动裁栏框下 image 内联样式:放大到原图尺寸,按 box 坐标 translate 显示
|
||||
// 用 rpx 转换(MP 原生 rpx / H5 换算 px)
|
||||
bannerImgStyle() {
|
||||
if (!this.hasManualCrop) return '';
|
||||
const b = this.bannerCropBox;
|
||||
const scaleX = 1 / b.w;
|
||||
const scaleY = 1 / b.h;
|
||||
const tx = -b.x * 100;
|
||||
const ty = -b.y * 100;
|
||||
return this.$util.objToStyle({
|
||||
position: 'absolute',
|
||||
left: 0,
|
||||
top: 0,
|
||||
width: (scaleX * 100) + '%',
|
||||
height: (scaleY * 100) + '%',
|
||||
maxWidth: 'none',
|
||||
transform: 'translate(' + tx + '%, ' + ty + '%)',
|
||||
});
|
||||
},
|
||||
// 手动裁栏框下容器需要绝对定位 + 隐藏溢出
|
||||
bannerImgWrapClass() {
|
||||
const isAspectFill = this.bannerImgMode === 'aspectFill';
|
||||
return {
|
||||
'is-fixed-height': isAspectFill,
|
||||
'has-crop': isAspectFill,
|
||||
'has-manual-crop': this.hasManualCrop,
|
||||
'has-height-limit': this.hasBannerHeight && !isAspectFill && !this.hasManualCrop
|
||||
};
|
||||
},
|
||||
// 表单风格:优先读显式 form_style(classic / card),未设置时回退到隐式判定(看 show_banner && form_banner)
|
||||
// - classic:经典风格,平铺无 banner 卡片
|
||||
// - card :卡片浮起风格,banner + 卡片浮起 + 容器内缩
|
||||
// 注意:必须读 this.formCfg(原始 formConfig 对象)而不是 mergedFormConfig(白名单组装对象,不含 form_style 键)
|
||||
// 双键兼容:formdata 链路 camel(formStyle,api splitFormConfig 转换);DIY 链路 snake(form_style,design.js 直存)
|
||||
// 老表单无 form_style 字段时 → undefined → 走隐式判定,与原行为完全一致,零迁移风险
|
||||
hasBannerMode() {
|
||||
const v = this.value || {};
|
||||
const fc = this.formCfg || {};
|
||||
const style = fc.formStyle !== undefined ? fc.formStyle : fc.form_style;
|
||||
if (style === 'card') return true;
|
||||
if (style === 'classic') return false;
|
||||
return !!(v.show_banner && v.form_banner);
|
||||
},
|
||||
// tip 提示语位置(仅 card 风格消费;classic 恒 'outside' 维持原结构)
|
||||
// outside=独立白卡浮起压 banner(默认);inside=内容卡内(无独立卡视觉)
|
||||
tipPosition() {
|
||||
if (!this.hasBannerMode) return 'outside';
|
||||
return this.mergedFormConfig.tipPosition === 'inside' ? 'inside' : 'outside';
|
||||
},
|
||||
// 提交按钮位置(仅 card 风格消费;classic 恒 'outside' 维持原结构)
|
||||
// inside=内容卡内(默认);outside=卡片下方独立区域
|
||||
submitPosition() {
|
||||
if (!this.hasBannerMode) return 'outside';
|
||||
return this.mergedFormConfig.submitPosition === 'outside' ? 'outside' : 'inside';
|
||||
},
|
||||
// 卡片容器内联样式:margin-top(负偏移+下移补偿)+ 左右外缩 + border-radius + box-shadow + background + border。
|
||||
// clamp 与默认值对齐后端 form.js syncFormConfigToCSS:overlap 0-200(默认48) / radius 0-40(默认24) / sidePad 0-60(默认30);
|
||||
// margin-top = -overlap + overlap_top(后端 --card-overlap 公式 (-overlap+overlapTop)/2 为 px,rpx 不除 2)
|
||||
// tip 独立卡(outside + showTip)带队浮起时,本卡只留正常间距(后端预览 draggable margin 10px=20rpx)
|
||||
// sidePad 语义(2026-09-03 与后端统一):卡片距屏幕左右距离(对齐后端 --card-side-pad,默认 30rpx=15px)。
|
||||
// formdata 链路(containerInset>0)容器已有 padding,卡片负 margin 破壳后再缩 sidePad(与 banner bleed 同思路);
|
||||
// DIY 链路(无 containerInset)直接 margin = sidePad。
|
||||
// 卡内内容缩进由 ns-newform .form-wrap 的 formPaddingX 承担(与后端 .draggable-wrap padding: form-padding-x 同构)。
|
||||
cardWrapStyle() {
|
||||
const cfg = this.mergedFormConfig || {};
|
||||
const parentInset = this._num(this.containerInset, 0);
|
||||
let sidePad = this._num(cfg.cardSidePad, 30);
|
||||
if (sidePad < 0) sidePad = 0;
|
||||
if (sidePad > 60) sidePad = 60;
|
||||
const sideMargin = parentInset > 0 ? (sidePad - parentInset) : sidePad;
|
||||
// overlap:负值向上压住 banner 底部;overlap_top 为下移补偿(可正可负,叠加生效)
|
||||
let overlap = Math.abs(this._num(cfg.cardOverlap, 48));
|
||||
if (overlap > 200) overlap = 200;
|
||||
const overlapTop = this._num(cfg.cardOverlapTop, 0);
|
||||
// banner 实际渲染时才用负 margin 压住它;banner 被隐藏(如 hideInnerBanner / 配置缺失)时
|
||||
// 负 margin 会把卡片(含 tip)整体推出屏幕顶部,必须收回 0
|
||||
const bannerVisible = !!(this.value && this.value.show_banner && this.value.form_banner);
|
||||
// tip 独立卡存在时由 tip 卡带队压 banner,内容卡只留正常间距(20rpx ≈ 后端预览 10px)
|
||||
const tipLeads = this.tipPosition === 'outside' && !!(this.value && this.value.show_tip && this.value.form_tip);
|
||||
// 卡片圆角:缺省 24rpx(浮起卡片的圆角,比外层卡片的 16rpx 更明显,突出浮起感)
|
||||
let radius = this._num(cfg.cardRadius, 24);
|
||||
if (radius < 0) radius = 0;
|
||||
if (radius > 40) radius = 40;
|
||||
// 阴影:缺省中等阴影(与设计方案一致)—— 由本容器承担浮起感
|
||||
const shadow = cfg.cardShadow || '0 8rpx 24rpx rgba(0,0,0,0.08)';
|
||||
// 卡片底色:纯白,与设计方案一致;可由后台 formConfig.cardBgColor 覆盖
|
||||
const bgColor = cfg.cardBgColor || '#ffffff';
|
||||
// 边框:宽度 rpx(0-20),留空/0 = 无边框
|
||||
let borderWidth = this._num(cfg.cardBorderWidth, 0);
|
||||
if (borderWidth < 0) borderWidth = 0;
|
||||
if (borderWidth > 20) borderWidth = 20;
|
||||
const style = {
|
||||
marginTop: (bannerVisible ? (tipLeads ? 20 : (-overlap + overlapTop)) : 0) + 'rpx',
|
||||
marginLeft: sideMargin + 'rpx',
|
||||
marginRight: sideMargin + 'rpx',
|
||||
borderRadius: radius + 'rpx',
|
||||
boxShadow: shadow,
|
||||
backgroundColor: bgColor
|
||||
};
|
||||
if (borderWidth > 0) {
|
||||
style['border'] = borderWidth + 'rpx ' + (cfg.cardBorderStyle || 'solid') + ' ' + (cfg.cardBorderColor || 'transparent');
|
||||
}
|
||||
return this.$util.objToStyle(style);
|
||||
},
|
||||
// tip 独立卡样式(card + outside):负 margin 压 banner + 左右外缩 + 白底 + 圆角 + 阴影 + 细边框。
|
||||
// 视觉参照后端预览 .form-style-card .preview-tip(margin: var(--card-overlap) var(--card-side-pad) 0;白底 12px 圆角 柔和阴影 左对齐)
|
||||
// 用户配置的 tip 四态属性(bg/border/radius/shadow/padding/align)在此全部生效,仅默认值不同(独立卡默认白底卡视觉)
|
||||
// sidePad 语义与 cardWrapStyle 一致:卡片距屏幕左右距离(默认 30rpx;formdata 链路破壳 sidePad-parentInset)
|
||||
tipCardStyle() {
|
||||
const cfg = this.mergedFormConfig || {};
|
||||
const bannerVisible = !!(this.value && this.value.show_banner && this.value.form_banner);
|
||||
let overlap = Math.abs(this._num(cfg.cardOverlap, 48));
|
||||
if (overlap > 200) overlap = 200;
|
||||
const overlapTop = this._num(cfg.cardOverlapTop, 0);
|
||||
const parentInset = this._num(this.containerInset, 0);
|
||||
let sidePad = this._num(cfg.cardSidePad, 30);
|
||||
if (sidePad < 0) sidePad = 0;
|
||||
if (sidePad > 60) sidePad = 60;
|
||||
const sideMargin = parentInset > 0 ? (sidePad - parentInset) : sidePad;
|
||||
const padT = this._num(cfg.tipPaddingTop, 32);
|
||||
const padR = this._num(cfg.tipPaddingRight, 32);
|
||||
const padB = this._num(cfg.tipPaddingBottom, 32);
|
||||
const padL = this._num(cfg.tipPaddingLeft, 32);
|
||||
const style = {
|
||||
marginTop: (bannerVisible ? (-overlap + overlapTop) : 0) + 'rpx',
|
||||
marginLeft: sideMargin + 'rpx',
|
||||
marginRight: sideMargin + 'rpx',
|
||||
padding: `${padT}rpx ${padR}rpx ${padB}rpx ${padL}rpx`,
|
||||
'font-size': `${this._num(cfg.tipFontSize, 32)}rpx`,
|
||||
'color': cfg.tipColor || '#1f2937',
|
||||
'background-color': cfg.tipBgColor || '#ffffff',
|
||||
'border-radius': `${this._num(cfg.tipRadius, 24)}rpx`,
|
||||
'box-shadow': cfg.tipShadow || '0 8rpx 24rpx rgba(0,0,0,0.08)',
|
||||
'text-align': cfg.tipAlign || 'left'
|
||||
};
|
||||
// 边框:独立卡默认细边框(2rpx ≈ 后端预览 1px);配置 0 = 无边框
|
||||
const bw = this._num(cfg.tipBorderWidth, 2);
|
||||
if (bw > 0) {
|
||||
style['border'] = `${bw}rpx ${cfg.tipBorderStyle || 'solid'} ${cfg.tipBorderColor || 'rgba(0,0,0,0.06)'}`;
|
||||
}
|
||||
return this.$util.objToStyle(style);
|
||||
},
|
||||
// Banner 容器破壳样式:仅在卡片模式下 + 父级传了 containerInset>0 时启用,让 banner 突破父容器 padding 跨越屏幕宽度。
|
||||
// 计算逻辑:负 margin-left/right + 等量扩宽 width,使 banner 元素左/右边界对齐到屏幕边缘。
|
||||
// 父级未传 containerInset 或传 0 时返回空样式,banner 保持原尺寸(零外溢)。
|
||||
bannerBleedStyle() {
|
||||
const inset = this._num(this.containerInset, 0);
|
||||
if (!this.hasBannerMode || inset <= 0) return '';
|
||||
const expand = inset * 2;
|
||||
return this.$util.objToStyle({
|
||||
marginLeft: -inset + 'rpx',
|
||||
marginRight: -inset + 'rpx',
|
||||
width: 'calc(100% + ' + expand + 'rpx)'
|
||||
});
|
||||
},
|
||||
// 提示语样式(classic 平铺 / card+inside 卡内共用):与后端 edit.html 内联 .preview-tip 对齐
|
||||
// - 四边内边距:未配置时经典态 上/下=rowPaddingY(4) 左右=tipPaddingX(14);卡片态统一 32rpx
|
||||
// - 边框:classic 用 border-bottom(宽度默认 0;旧数据仅配 color → 2rpx 底边);
|
||||
// card 用全边框(配置宽度才输出)
|
||||
// - 圆角 / 阴影(rpx 字符串) / 对齐(card 态默认左对齐,经典态居中)
|
||||
// - 背景色:''=未配置 → 透明(独立卡白底兜底已挪到 tipCardStyle,卡内 tip 无独立卡视觉)
|
||||
tipStyle() {
|
||||
const cfg = this.mergedFormConfig || {};
|
||||
const card = this.hasBannerMode;
|
||||
const padT = this._num(cfg.tipPaddingTop, card ? 32 : this._num(cfg.rowPaddingY, 4));
|
||||
const padR = this._num(cfg.tipPaddingRight, card ? 32 : this._num(cfg.tipPaddingX, 14));
|
||||
const padB = this._num(cfg.tipPaddingBottom, card ? 32 : this._num(cfg.rowPaddingY, 4));
|
||||
const padL = this._num(cfg.tipPaddingLeft, card ? 32 : this._num(cfg.tipPaddingX, 14));
|
||||
const style = {
|
||||
padding: `${padT}rpx ${padR}rpx ${padB}rpx ${padL}rpx`,
|
||||
'font-size': `${this._num(cfg.tipFontSize, 32)}rpx`,
|
||||
'color': cfg.tipColor || (card ? '#1f2937' : '#000000'),
|
||||
'background-color': cfg.tipBgColor || 'transparent',
|
||||
'text-align': cfg.tipAlign || (card ? 'left' : 'center')
|
||||
};
|
||||
// 边框:配置了宽度(>0)输出;未配宽度但配了颜色 → 旧数据兼容,2rpx 底边(仅经典态)
|
||||
const bw = this._num(cfg.tipBorderWidth, 0);
|
||||
if (bw > 0) {
|
||||
const bs = cfg.tipBorderStyle || 'solid';
|
||||
const bc = cfg.tipBorderColor || 'rgba(0,0,0,0.06)';
|
||||
if (card) {
|
||||
style['border'] = `${bw}rpx ${bs} ${bc}`;
|
||||
} else {
|
||||
style['border-bottom'] = `${bw}rpx ${bs} ${bc}`;
|
||||
}
|
||||
} else if (!card && cfg.tipBorderColor) {
|
||||
style['border-bottom'] = `2rpx solid ${cfg.tipBorderColor}`;
|
||||
}
|
||||
// 圆角(rpx)
|
||||
if (cfg.tipRadius !== undefined && cfg.tipRadius !== null && cfg.tipRadius !== '') {
|
||||
style['border-radius'] = `${this._num(cfg.tipRadius, 0)}rpx`;
|
||||
}
|
||||
// 阴影:后端存 rpx 单位字符串(如 '0 4rpx 12rpx rgba(...)'),uniapp H5/MP 运行时支持 rpx
|
||||
if (cfg.tipShadow) {
|
||||
style['box-shadow'] = cfg.tipShadow;
|
||||
}
|
||||
return this.$util.objToStyle(style);
|
||||
},
|
||||
// 提交按钮外层:与后端 .form-preview-submit 对齐(margin-top + padding: row-padding-y form-padding-x;background: form-bg-color)
|
||||
// card + inside(默认)时按钮已在内容卡内:padding 收窄为卡内边距(≈后端预览 14px 12px 20px),不设独立背景(继承卡白底)
|
||||
submitWrapStyle() {
|
||||
const cfg = this.mergedFormConfig || {};
|
||||
if (this.hasBannerMode && this.submitPosition !== 'outside') {
|
||||
return this.$util.objToStyle({
|
||||
marginTop: `${this._num(cfg.submitMarginTop, 0)}rpx`,
|
||||
padding: `24rpx 24rpx 40rpx`
|
||||
});
|
||||
}
|
||||
if (this.hasBannerMode) {
|
||||
// card + outside:卡片下方独立区域 —— 与后端 .preview-submit-wrap(card 模式)同构:
|
||||
// 左右破壳对齐卡片缩进(sidePad - parentInset),水平内缩 formPaddingX,
|
||||
// 上下 padding 36rpx/48rpx(后端 18px/24px),背景白底(后端 .preview-submit-wrap 亦为白底)
|
||||
const parentInset = this._num(this.containerInset, 0);
|
||||
let sidePad = this._num(cfg.cardSidePad, 30);
|
||||
if (sidePad < 0) sidePad = 0;
|
||||
if (sidePad > 60) sidePad = 60;
|
||||
const sideMargin = parentInset > 0 ? (sidePad - parentInset) : 0;
|
||||
return this.$util.objToStyle({
|
||||
marginTop: `${this._num(cfg.submitMarginTop, 0)}rpx`,
|
||||
marginLeft: sideMargin + 'rpx',
|
||||
marginRight: sideMargin + 'rpx',
|
||||
padding: `36rpx ${this._num(cfg.formPaddingX, 14)}rpx 48rpx`,
|
||||
'background-color': cfg.formBgColor || '#ffffff'
|
||||
});
|
||||
}
|
||||
return this.$util.objToStyle({
|
||||
marginTop: `${this._num(cfg.submitMarginTop, 0)}rpx`,
|
||||
padding: `${this._num(cfg.rowPaddingY, 4)}rpx ${this._num(cfg.formPaddingX, 14)}rpx`,
|
||||
'background-color': cfg.formBgColor || '#ffffff'
|
||||
});
|
||||
},
|
||||
// 提交按钮样式:颜色 / 背景色 / 宽度(百分比)/ 上下内边距(控制高度)/ 圆角 / 字号
|
||||
// 与后端 design.css .form-preview-submit button 对齐:
|
||||
// - 高度由 --submit-padding-y + 字号决定,避免硬编码 line-height
|
||||
// - 宽度由 --submit-width-percent 控制(10-100,clamp)
|
||||
submitStyle() {
|
||||
const cfg = this.mergedFormConfig || {};
|
||||
// 宽度百分比:clamp 到 10-100
|
||||
const widthPct = Math.min(100, Math.max(10, this._num(cfg.submitWidthPercent, 100)));
|
||||
// 上下内边距:与后端 design.js submitSizeMap 对齐(mini/small/medium/large/huge → 0/4/12/24/40 rpx)
|
||||
const submitPaddingMap = { mini: 0, small: 4, medium: 12, large: 24, huge: 40 };
|
||||
const submitPaddingY = submitPaddingMap[cfg.submitSize] != null
|
||||
? submitPaddingMap[cfg.submitSize]
|
||||
: submitPaddingMap.medium;
|
||||
return this.$util.objToStyle({
|
||||
width: widthPct + '%',
|
||||
padding: `${submitPaddingY}rpx 0`,
|
||||
color: cfg.submitColor || '#ffffff',
|
||||
'background-color': cfg.submitBgColor || '#3b82f6',
|
||||
'border-radius': `${this._num(cfg.inputRadius, 10)}rpx`,
|
||||
'font-size': `${this._num(cfg.labelFontSize, 28)}rpx`
|
||||
});
|
||||
},
|
||||
// 提交按钮文字:与后端 design.html <button>提交</button> 默认对齐,开放给 formConfig 覆盖
|
||||
// 走 mergedFormConfig(兼容 camelCase / snake_case),让 formConfig.submitText 能正确覆盖
|
||||
submitText() {
|
||||
return this.mergedFormConfig.submitText || '提交';
|
||||
},
|
||||
// 父级是否接管提交(集中判断,便于以后替换机制;避免多个调用点各自 typeof 校验)
|
||||
hasCustomSubmit() {
|
||||
return typeof this.onSubmit === 'function';
|
||||
},
|
||||
// 后端把表单样式配置统一存放在 data.formConfig 子对象中(与后端 design.js getDefaultFormData().formConfig 字段名一致)。
|
||||
// 这里做一次归一化:优先取 formConfig;如果历史数据是扁平结构(直接挂在 value 上),也做兼容。
|
||||
formCfg() {
|
||||
const v = this.value || {};
|
||||
if (v.formConfig && typeof v.formConfig === 'object') {
|
||||
return v.formConfig;
|
||||
}
|
||||
return v;
|
||||
},
|
||||
// 合并后的表单配置(支持平台差异化)
|
||||
mergedFormConfig() {
|
||||
const v = this.value || {};
|
||||
const fc = this.formCfg;
|
||||
// 后端实际返回 camelCase(如 formPaddingX / formBgColor / labelFontSize),
|
||||
// 但旧版 design.js / 部分序列化路径可能用 snake_case(form_padding_x)。这里同时读两种写法,camelCase 优先
|
||||
const self = this;
|
||||
const pick = function(camel, snake) {
|
||||
var v1 = fc[camel];
|
||||
if (v1 !== undefined && v1 !== null && v1 !== '') return v1;
|
||||
return fc[snake];
|
||||
};
|
||||
// 多别名取值:后台不同版本 / 不同序列化路径对同一配置项可能用不同键名,
|
||||
// 这里按优先级取第一个有效值,避免白名单裁剪时把后台配置丢掉(丢了下层永远读不到)
|
||||
const pickAny = function(keys) {
|
||||
for (var i = 0; i < keys.length; i++) {
|
||||
var kv = fc[keys[i]];
|
||||
if (kv !== undefined && kv !== null && kv !== '') return kv;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
// 通用全局配置(与后端 design.js getDefaultFormData().formConfig 字段名一致)
|
||||
const base = {
|
||||
formPaddingX: pick('formPaddingX', 'form_padding_x'),
|
||||
// Banner 高度(rpx)。后台可配,默认 180rpx ≈ 页面 1/8 高度(适配主流手机屏高)
|
||||
// 配合 mode="aspectFill" 居中裁剪,保证横幅只占页面八分之一左右
|
||||
bannerHeight: pick('bannerHeight', 'banner_height'),
|
||||
bannerPaddingX: pick('bannerPaddingX', 'banner_padding_x'),
|
||||
// 横幅裁剪位置(top/center/bottom)+ 比例(16:9/4:3/1:1/3:4)+ 手动裁栏框 JSON(2026-09-04 方案 C 抽屉配套)
|
||||
bannerCropPosition: pick('bannerCropPosition', 'banner_crop_position'),
|
||||
bannerCropRatio: pick('bannerCropRatio', 'banner_crop_ratio'),
|
||||
bannerCropBox: pick('bannerCropBox', 'banner_crop_box'),
|
||||
tipPaddingX: pick('tipPaddingX', 'tip_padding_x'),
|
||||
// 行内上下边距:兼容 row_padding_y / rowPaddingY / row_padding / rowPadding 等键名
|
||||
rowPaddingY: (function() {
|
||||
var v = pick('rowPaddingY', 'row_padding_y');
|
||||
if (v !== undefined && v !== null && v !== '') return v;
|
||||
return pickAny(['rowPadding', 'row_padding', 'rowPaddingVertical', 'row_padding_vertical', 'row_padding_top', 'rowPaddingTop']);
|
||||
})(),
|
||||
rowMinHeight: pick('rowMinHeight', 'row_min_height'),
|
||||
labelGap: pick('labelGap', 'label_gap'),
|
||||
formBgColor: pick('formBgColor', 'form_bg_color'),
|
||||
rowDividerColor: pick('rowDividerColor', 'row_divider_color'),
|
||||
showRowDivider: self._coerceBool(pick('showRowDivider', 'show_row_divider')),
|
||||
inputHeight: pick('inputHeight', 'input_height'),
|
||||
inputRadius: pick('inputRadius', 'input_radius'),
|
||||
formLayout: pick('formLayout', 'form_layout'),
|
||||
labelWidthMode: pick('labelWidthMode', 'label_width_mode'),
|
||||
labelFixedWidth: pick('labelFixedWidth', 'label_fixed_width'),
|
||||
labelFontSize: pick('labelFontSize', 'label_font_size'),
|
||||
labelColor: pick('labelColor', 'label_color'),
|
||||
labelFontWeight: pick('labelFontWeight', 'label_font_weight'),
|
||||
labelAutoMaxWidth: pick('labelAutoMaxWidth', 'label_auto_max_width'),
|
||||
requiredColor: pick('requiredColor', 'required_color'),
|
||||
// 必填星号位置:before=标签前(默认)/ after=标签后(终端无关,存 base 层)
|
||||
requiredPosition: pick('requiredPosition', 'required_position'),
|
||||
checkedColor: pick('checkedColor', 'checked_color'),
|
||||
// 占位符:遗漏会被 ns-newform SCSS 默认值回退覆盖
|
||||
placeholderColor: pick('placeholderColor', 'placeholder_color'),
|
||||
placeholderFontSize: pick('placeholderFontSize', 'placeholder_font_size'),
|
||||
// textarea 显示行数 / 行高(透传给 ns-newform,与 ns-form 保持一致)
|
||||
// 不传时 ns-newform 走自己的默认 4 行 / 44rpx
|
||||
textareaRows: pick('textareaRows', 'textarea_rows'),
|
||||
textareaLineHeight: pick('textareaLineHeight', 'textarea_line_height'),
|
||||
// 输入框视觉增强(与 ns-newform 对齐)
|
||||
inputBorderColor: pick('inputBorderColor', 'input_border_color'),
|
||||
inputBgColor: pick('inputBgColor', 'input_bg_color'),
|
||||
inputFocusBorderColor: pick('inputFocusBorderColor', 'input_focus_border_color'),
|
||||
inputFocusBgColor: pick('inputFocusBgColor', 'input_focus_bg_color'),
|
||||
submitText: pick('submitText', 'submit_text'),
|
||||
submitColor: pick('submitColor', 'submit_color'),
|
||||
submitBgColor: pick('submitBgColor', 'submit_bg_color'),
|
||||
// 提交按钮尺寸:宽度百分比 + 尺寸预设(与后端 design.js 对齐)
|
||||
submitWidthPercent: pick('submitWidthPercent', 'submit_width_percent'),
|
||||
submitSize: pick('submitSize', 'submit_size'),
|
||||
submitMarginTop: pick('submitMarginTop', 'submit_margin_top'),
|
||||
// 提示语(与后端 form.js syncFormConfigToCSS 的 --tip-* 变量一一对应)
|
||||
tipFontSize: pick('tipFontSize', 'tip_font_size'),
|
||||
tipColor: pick('tipColor', 'tip_color'),
|
||||
tipBgColor: pick('tipBgColor', 'tip_bg_color'),
|
||||
tipBorderColor: pick('tipBorderColor', 'tip_border_color'),
|
||||
// 边框:宽度(rpx)/线型;未配置宽度时保留旧逻辑(仅 color 配置 → 底边 2rpx)
|
||||
tipBorderWidth: pick('tipBorderWidth', 'tip_border_width'),
|
||||
tipBorderStyle: pick('tipBorderStyle', 'tip_border_style'),
|
||||
// 独立样式:圆角 / 四边内边距 / 阴影 / 对齐('' 与 null 均走 delete → 用各自态的兜底默认)
|
||||
tipRadius: pick('tipRadius', 'tip_radius'),
|
||||
tipPaddingTop: pick('tipPaddingTop', 'tip_padding_top'),
|
||||
tipPaddingRight: pick('tipPaddingRight', 'tip_padding_right'),
|
||||
tipPaddingBottom: pick('tipPaddingBottom', 'tip_padding_bottom'),
|
||||
tipPaddingLeft: pick('tipPaddingLeft', 'tip_padding_left'),
|
||||
tipShadow: pick('tipShadow', 'tip_shadow'),
|
||||
tipAlign: pick('tipAlign', 'tip_align'),
|
||||
// 卡片浮起(仅 show_banner && form_banner 启用)
|
||||
cardOverlap: pick('cardOverlap', 'card_overlap'),
|
||||
// 额外下移补偿(rpx,可正可负,与 overlap 叠加:margin-top = -overlap + overlap_top)
|
||||
cardOverlapTop: pick('cardOverlapTop', 'card_overlap_top'),
|
||||
cardRadius: pick('cardRadius', 'card_radius'),
|
||||
cardShadow: pick('cardShadow', 'card_shadow'),
|
||||
cardSidePad: pick('cardSidePad', 'card_side_pad'),
|
||||
cardBgColor: pick('cardBgColor', 'card_bg_color'),
|
||||
// 卡片边框(宽度 rpx / CSS 线型 / 颜色;留空 = 无边框)
|
||||
cardBorderWidth: pick('cardBorderWidth', 'card_border_width'),
|
||||
cardBorderStyle: pick('cardBorderStyle', 'card_border_style'),
|
||||
cardBorderColor: pick('cardBorderColor', 'card_border_color'),
|
||||
// 位置控制(仅 card 风格生效;outside/inside 见 tipPosition/submitPosition computed)
|
||||
tipPosition: pick('tipPosition', 'tip_position'),
|
||||
submitPosition: pick('submitPosition', 'submit_position')
|
||||
};
|
||||
// 移除 undefined / 空字符串(保留 0/false)
|
||||
Object.keys(base).forEach(function(k) {
|
||||
if (base[k] === undefined || base[k] === null || base[k] === '') {
|
||||
delete base[k];
|
||||
}
|
||||
});
|
||||
// 前端视觉默认:仅作兜底(后端未配置的字段才生效)。
|
||||
// 注意合并顺序:base 在后 —— 后台 formConfig 显式配置的值(如 submit_bg_color / input_radius)
|
||||
// 必须覆盖前端默认,否则商家端样式配置完全不生效(曾因此导致提交按钮恒为蓝色)。
|
||||
const styleDefaults = {
|
||||
formLayout: 'vertical',
|
||||
formPaddingX: 28,
|
||||
rowPaddingY: 24,
|
||||
labelGap: 20,
|
||||
labelFontSize: 32,
|
||||
labelFontWeight: 700,
|
||||
labelColor: '#1f2937',
|
||||
inputHeight: 84,
|
||||
inputRadius: 16,
|
||||
inputBgColor: '#ffffff',
|
||||
inputBorderColor: '#e5e7eb',
|
||||
inputFocusBorderColor: '#3b82f6',
|
||||
inputFocusBgColor: '#ffffff',
|
||||
placeholderColor: '#9ca3af',
|
||||
placeholderFontSize: 28,
|
||||
checkedColor: '#3b82f6',
|
||||
showRowDivider: false,
|
||||
submitColor: '#ffffff',
|
||||
submitBgColor: '#3b82f6'
|
||||
};
|
||||
// 平台差异化配置(terminal 块在 formConfig 子对象内)
|
||||
// 优先级:v.formConfig.terminal > v.form_config_terminal > v.terminal > v.form_config_platform
|
||||
const result = Object.assign({}, styleDefaults, base);
|
||||
const termBlock = (v.formConfig && v.formConfig.terminal) || v.form_config_terminal || v.terminal || v.form_config_platform;
|
||||
if (termBlock && typeof termBlock === 'object') {
|
||||
Object.keys(termBlock).forEach(function(platform) {
|
||||
var src = termBlock[platform];
|
||||
if (!src) return;
|
||||
// 嵌套值若为 snake_case(部分序列化路径),在此统一转 camelCase
|
||||
var translated = {};
|
||||
Object.keys(src).forEach(function(k) {
|
||||
translated[self.$util.snakeToCamel(k)] = src[k];
|
||||
});
|
||||
result[platform] = translated;
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
submitform() {
|
||||
// 初始化表单 - 将 diy-form 的数据格式转换成 ns-newform 的格式
|
||||
initForm() {
|
||||
if (!this.value) {
|
||||
this.formComponents = [];
|
||||
return;
|
||||
}
|
||||
// raw 模式:value.jsonData / value.json_data 已经是 ns-newform 期望的 [{ controller, value, val }],直接透传
|
||||
if (this.dataMode === 'raw') {
|
||||
this.formComponents = this.value.jsonData || this.value.json_data || [];
|
||||
return;
|
||||
}
|
||||
var components = this.value.formComponents || this.value.form_components || [];
|
||||
// 转换格式:type -> controller
|
||||
this.formComponents = (components || []).map(function(item) {
|
||||
return {
|
||||
controller: item.type,
|
||||
value: item.value || {},
|
||||
val: (item.value && item.value.default) ? item.value.default : '' // 添加初始值
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
// 暴露给父级:触发 ns-newform 校验。校验失败时 ns-newform 内部会 toast;返回 false 表示失败,返回 formData 数组表示成功
|
||||
verify() {
|
||||
if (this.$refs.nsNewform && this.$refs.nsNewform.verify) {
|
||||
return this.$refs.nsNewform.verify();
|
||||
}
|
||||
return false;
|
||||
},
|
||||
// 暴露给父级:获取 ns-newform 当前的 formData 数组(含 val / option_lists / img_lists 等全部字段)
|
||||
getFormData() {
|
||||
return (this.$refs.nsNewform && this.$refs.nsNewform.formData) || [];
|
||||
},
|
||||
|
||||
// 数字保底:undefined/空串/非数字时返回兜底值
|
||||
_num(v, fb) {
|
||||
if (v === '' || v === null || v === undefined) return fb;
|
||||
var n = parseInt(v);
|
||||
return isNaN(n) ? fb : n;
|
||||
},
|
||||
// 布尔保底:0/false/'0'/'false' → false;其它有值 → true
|
||||
_coerceBool(v) {
|
||||
if (v === false || v === 0 || v === '0' || v === 'false' || v === null || v === undefined) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
|
||||
// 统一提交入口:内置按钮 / 父级 ref 调用都走这里
|
||||
// 不依赖 $listeners / 事件机制(MP 端 $listeners 为 undefined),跨端一致
|
||||
handleSubmit() {
|
||||
// 校验(同时返回 formData 数组;校验失败时 ns-newform 内部 toast 提示)
|
||||
if (!this.verify()) {
|
||||
return;
|
||||
}
|
||||
const formData = this.getFormData();
|
||||
// 父级显式接管:function prop 在 H5 / MP / 鸿蒙一致可用
|
||||
if (this.hasCustomSubmit) {
|
||||
return this.onSubmit(formData);
|
||||
}
|
||||
// 兜底:内置 sendRequest 流程
|
||||
this.defaultSubmit(formData);
|
||||
},
|
||||
|
||||
// 公共兜底实现:默认的 /form/api/form/create 流程;
|
||||
// 父级若需"先自定义、失败回退",可经 ref.defaultSubmit(formData) 调用
|
||||
defaultSubmit(submitFormData) {
|
||||
var self = this;
|
||||
this.$api.sendRequest({
|
||||
url: '/api/member/information',
|
||||
data: this.Form,
|
||||
success: res => {
|
||||
this.$util.showToast({
|
||||
title: res.message
|
||||
});
|
||||
url: '/form/api/form/create',
|
||||
data: {
|
||||
form_id: this.value.form_id || 0,
|
||||
form_data: typeof submitFormData === 'string' ? submitFormData : JSON.stringify(submitFormData),
|
||||
component_id: this.value.id || '',
|
||||
form_name: this.value.form_name || '默认表单'
|
||||
},
|
||||
success: function(res) {
|
||||
if (res.code === 0) {
|
||||
uni.showToast({
|
||||
title: self.$lang('submitSuccess'),
|
||||
icon: 'success'
|
||||
});
|
||||
// 重置表单
|
||||
if (self.$refs.nsNewform && self.$refs.nsNewform.setFormData) {
|
||||
self.$refs.nsNewform.setFormData();
|
||||
}
|
||||
} else {
|
||||
uni.showToast({
|
||||
title: res.message || self.$lang('submitFail'),
|
||||
icon: 'none'
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -108,7 +750,181 @@ export default {
|
||||
<style lang="scss">
|
||||
.diy-from {
|
||||
background: #fff;
|
||||
padding-bottom: 20rpx;
|
||||
padding: 0;
|
||||
border-radius: 10rpx;
|
||||
|
||||
.form-banner {
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
// 默认左右无边距(与后端 --banner-padding-x 对齐;由内联 bannerStyle 覆盖)
|
||||
margin: 0;
|
||||
|
||||
// banner 图片作为卡片上方的"底图":建立层叠上下文,让 .form-card 通过 z-index 浮在其上。
|
||||
// 仅在卡片浮起模式(.is-card-overlap)启用,不影响其它使用方(diy-group 等)的旧布局。
|
||||
&.is-card-overlap {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
// 横幅图片容器:默认高度由 image widthFix 按图片比例自适应(与商家端预览 height:auto 对齐);
|
||||
// .is-fixed-height(显式配置 bannerHeight)时高度由 bannerImgWrapStyle 内联写入,
|
||||
// 配合 mode="aspectFill" 居中裁剪填充。
|
||||
.banner-img-wrap {
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
|
||||
// 默认作为 flex 容器,支持 widthFix + max-height 模式下的顶部/居中/底部对齐
|
||||
.banner-img-crop {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: flex-start;
|
||||
overflow: hidden;
|
||||
|
||||
&.crop-center {
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
&.crop-bottom {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
}
|
||||
|
||||
&.is-fixed-height {
|
||||
.banner-img {
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
// 启用 aspectFill 裁剪时,包装一层 .banner-img-crop 承接裁剪位置。
|
||||
// 重要:uni-app image 在 H5 端固定转译为 <div style="background-image:url; background-size:cover; background-position:center center;"></div>,
|
||||
// 内层 div 的 background-position 是运行时生成的 inline 样式,普通 CSS 覆盖不了,必须 !important;
|
||||
// (不能用 .banner-img 的 translateY 实现位置:image 高度被钉死为容器 100% 后 transform 一去一回相互抵消,是零位移)
|
||||
// - crop-top → background-position: center top(显示图片顶部区域)
|
||||
// - crop-center → 默认 center center(不覆盖)
|
||||
// - crop-bottom → background-position: center bottom(显示图片底部区域)
|
||||
&.has-crop {
|
||||
.banner-img-crop {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
.banner-img {
|
||||
// 撑满 wrap,让内层 background-image div 拿到确定高度(uni-image H5 端转译依赖)
|
||||
height: 100%;
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
}
|
||||
// uni-app H5 编译器会给样式追加 [data-v-xxx](即使未写 scoped),
|
||||
// 而 uni-image 运行时 JS 生成的内层 div 没有该属性 → 必须 ::v-deep 把属性选择器挪到 .banner-img 上
|
||||
.banner-img-crop.crop-top .banner-img ::v-deep div {
|
||||
background-position: center top !important;
|
||||
}
|
||||
.banner-img-crop.crop-bottom .banner-img ::v-deep div {
|
||||
background-position: center bottom !important;
|
||||
}
|
||||
}
|
||||
|
||||
// 启用手动裁栏框(bannerCropBox 非空)时:image 用 transform 显示裁栏部分,原图按 box 缩放 + 平移
|
||||
&.has-manual-crop {
|
||||
.banner-img-crop {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
.banner-img {
|
||||
// 手动框下由 bannerImgStyle 内联 width/height/transform 驱动,不固定 100%
|
||||
height: auto;
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.banner-img {
|
||||
width: 100%;
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
// 卡片容器:浮在 banner 图片上方(参考设计左图)。
|
||||
// 仅在 hasBannerMode=true 时渲染(见 template v-if);
|
||||
// 阴影 + margin-top(负偏移)+ 圆角 + 白底 全部由 cardWrapStyle 内联写入(读取后台 formConfig.card*)。
|
||||
// 关键:卡片必须自带白底并 z-index 高于 banner,才能真正"盖住"banner 图片底部形成浮起;
|
||||
// 父级容器(formdata.vue 的 .system-form-wrap)虽也是白底,但它是 banner 的祖先、背景会被 banner 覆盖,
|
||||
// 因此本容器的白底不可省略(与 .system-form-wrap 同色,视觉上从卡片向下自然延续到页面底部)。
|
||||
.form-card {
|
||||
// 定位上下文 + 高于 banner 的层级:让卡片盖住 banner 底部(banner z-index:1)
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
// 兜底白底 / 圆角 / 阴影:与后端未配置时内联写入的默认值一致;后台配置时由内联 cardWrapStyle 覆盖
|
||||
background-color: #ffffff;
|
||||
border-radius: 24rpx;
|
||||
box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
|
||||
// 关键:裁剪卡内子元素(ns-newform 白底 / submit 区)到圆角内。
|
||||
// tip 关闭时本卡带队负 margin 压 banner,若无 overflow:hidden,
|
||||
// 卡内第一个子元素的方形背景会盖住卡片上圆角(banner 图片在圆角外的部分被遮)。
|
||||
// 商家端预览 .draggable-wrap 同样有 overflow:hidden(form.css 两处同步)。
|
||||
overflow: hidden;
|
||||
// 兜底 padding-bottom:让卡片与后面内容(如推荐码、其它 diy 组件)有间距
|
||||
padding-bottom: 24rpx;
|
||||
}
|
||||
|
||||
// tip 独立卡(card + tip_position=outside):浮在 banner 上方的独立白卡。
|
||||
// margin/padding/白底/圆角/阴影/边框 全部由 tipCardStyle 内联写入;
|
||||
// 必须自带 z-index 高于 banner(z-index:1)才能真正"盖住"banner 底部形成浮起。
|
||||
.form-tip-card {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
box-sizing: border-box;
|
||||
line-height: 1.5;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.form-tip {
|
||||
// 提示语:上下内边距 / 左右内边距 / 字号 / 颜色 / 背景 全部由 tipStyle 内联写入
|
||||
padding: 0;
|
||||
text-align: center;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.form-submit-wrap {
|
||||
// 外层:与后端 .form-preview-submit 对齐(margin-top + padding-y + form-padding-x + form-bg-color + flex 居中)
|
||||
// margin-top/padding/background 由 submitWrapStyle 内联写入
|
||||
// display: flex + justify-content: center 是让宽度小于 100% 的按钮水平居中的关键
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.form-submit {
|
||||
// 提交按钮:颜色 / 背景色 / 宽度(百分比)/ 上下内边距(控制高度)/ 圆角 / 字号
|
||||
// 全部由 submitStyle 内联写入
|
||||
// 宽度不再写死 100%,由内联 style 的 width: <pct>% 决定;max-width: 100% 防止溢出
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
max-width: 100%;
|
||||
font-weight: 500;
|
||||
letter-spacing: 1rpx;
|
||||
transition: opacity 0.2s ease;
|
||||
box-sizing: border-box;
|
||||
|
||||
&:active {
|
||||
opacity: 0.85;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</style>
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
<view class="li-item" v-for="(item, index) in list" :key="index">
|
||||
<image class="brand-pic" :src="$util.img(item.image_url)" mode="aspectFit"
|
||||
@tap.stop="handlerClick(item)" @error="imgError(index)"
|
||||
:style="itemCss" />
|
||||
:style="itemCss" show-menu-by-longpress/>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
@@ -7,8 +7,9 @@
|
||||
<view class="goods-img-wrap">
|
||||
<image class="goods-img"
|
||||
:src="$util.img(item.goods_image, { size: goodsValue.template == 'large-mode' ? 'big' : 'mid' })"
|
||||
mode="widthFix" @error="imgError(index)"
|
||||
:style="{ borderRadius: goodsValue.imgAroundRadius * 2 + 'rpx' }" />
|
||||
:mode="imgMode" @error="imgError(index)"
|
||||
:style="{ borderRadius: goodsValue.imgAroundRadius * 2 + 'rpx' }"
|
||||
show-menu-by-longpress />
|
||||
<view class="sell-out" v-if="item.stock <= 0">
|
||||
<text class="iconfont icon-shuqing"></text>
|
||||
</view>
|
||||
@@ -48,9 +49,9 @@
|
||||
<view class="member-price"
|
||||
v-if="(item.member_price && item.member_price == showPrice(item)) || item.promotion_type == 1">
|
||||
<image v-if="item.member_price && item.member_price == showPrice(item)"
|
||||
:src="$util.img('public/uniapp/index/VIP.png')" />
|
||||
:src="$util.img('public/uniapp/index/VIP.png')" show-menu-by-longpress />
|
||||
<image v-else-if="item.promotion_type == 1"
|
||||
:src="$util.img('public/uniapp/index/discount.png')" />
|
||||
:src="$util.img('public/uniapp/index/discount.png')" show-menu-by-longpress />
|
||||
</view>
|
||||
<view v-if="goodsValue.priceStyle.lineControl && showMarketPrice(item)"
|
||||
class="delete-price price-font"
|
||||
@@ -59,7 +60,7 @@
|
||||
</view>
|
||||
<view class="sale" v-if="goodsValue.saleStyle.control"
|
||||
:style="{ color: goodsValue.theme == 'diy' ? goodsValue.saleStyle.color : '' }">
|
||||
已售{{ item.sale_num }}{{ item.unit ? item.unit : '件' }}
|
||||
{{ $lang('components-diy.diy-goods-list.soldCount', { count: item.sale_num, unit: item.unit || $lang('components-diy.diy-goods-list.soldUnit') }) }}
|
||||
</view>
|
||||
</view>
|
||||
|
||||
@@ -116,8 +117,8 @@
|
||||
:class="[goodsValue.ornament.type]" :style="goodsItemCss">
|
||||
<view class="goods-img-wrap">
|
||||
<image class="goods-img" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
|
||||
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix" @error="imgError(index)"
|
||||
:lazy-load="true" />
|
||||
:src="$util.img(item.goods_image, { size: 'mid' })" :mode="imgMode" @error="imgError(index)"
|
||||
:lazy-load="true" show-menu-by-longpress />
|
||||
<view class="sell-out" v-if="item.stock <= 0">
|
||||
<text class="iconfont icon-shuqing"></text>
|
||||
</view>
|
||||
@@ -156,9 +157,9 @@
|
||||
<view class="member-price"
|
||||
v-if="(item.member_price && item.member_price == showPrice(item)) || item.promotion_type == 1">
|
||||
<image v-if="item.member_price && item.member_price == showPrice(item)"
|
||||
:src="$util.img('public/uniapp/index/VIP.png')" />
|
||||
:src="$util.img('public/uniapp/index/VIP.png')" show-menu-by-longpress />
|
||||
<image v-else-if="item.promotion_type == 1"
|
||||
:src="$util.img('public/uniapp/index/discount.png')" />
|
||||
:src="$util.img('public/uniapp/index/discount.png')" show-menu-by-longpress />
|
||||
</view>
|
||||
<view v-if="goodsValue.priceStyle.lineControl && showMarketPrice(item)"
|
||||
class="delete-price price-font"
|
||||
@@ -167,7 +168,7 @@
|
||||
</view>
|
||||
<view class="sale" v-if="goodsValue.saleStyle.control"
|
||||
:style="{ color: goodsValue.theme == 'diy' ? goodsValue.saleStyle.color : '' }">
|
||||
已售{{ item.sale_num }}{{ item.unit ? item.unit : '件' }}
|
||||
{{ $lang('components-diy.diy-goods-list.soldCount', { count: item.sale_num, unit: item.unit || $lang('components-diy.diy-goods-list.soldUnit') }) }}
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -183,8 +184,8 @@
|
||||
:class="[goodsValue.ornament.type]" :style="goodsItemCss">
|
||||
<view class="goods-img-wrap">
|
||||
<image class="goods-img" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
|
||||
:src="$util.img(dataItem.goods_image, { size: 'mid' })" mode="widthFix"
|
||||
@error="imgError(dataIndex)" :lazy-load="true" />
|
||||
:src="$util.img(dataItem.goods_image, { size: 'mid' })" :mode="imgMode"
|
||||
@error="imgError(dataIndex)" :lazy-load="true" show-menu-by-longpress />
|
||||
<view class="sell-out" v-if="dataItem.stock <= 0">
|
||||
<text class="iconfont icon-shuqing"></text>
|
||||
</view>
|
||||
@@ -226,9 +227,9 @@
|
||||
v-if="(dataItem.member_price && dataItem.member_price == showPrice(dataItem)) || dataItem.promotion_type == 1">
|
||||
<image
|
||||
v-if="dataItem.member_price && dataItem.member_price == showPrice(dataItem)"
|
||||
:src="$util.img('public/uniapp/index/VIP.png')" />
|
||||
:src="$util.img('public/uniapp/index/VIP.png')" show-menu-by-longpress />
|
||||
<image v-else-if="dataItem.promotion_type == 1"
|
||||
:src="$util.img('public/uniapp/index/discount.png')" />
|
||||
:src="$util.img('public/uniapp/index/discount.png')" show-menu-by-longpress />
|
||||
</view>
|
||||
<view v-if="goodsValue.priceStyle.lineControl && showMarketPrice(dataItem)"
|
||||
class="delete-price"
|
||||
@@ -237,7 +238,7 @@
|
||||
</view>
|
||||
<view class="sale" v-if="goodsValue.saleStyle.control"
|
||||
:style="{ color: goodsValue.theme == 'diy' ? goodsValue.saleStyle.color : '' }">
|
||||
已售{{ dataItem.sale_num }}{{ dataItem.unit ? dataItem.unit : '件' }}
|
||||
{{ $lang('components-diy.diy-goods-list.soldCount', { count: dataItem.sale_num, unit: dataItem.unit || $lang('components-diy.diy-goods-list.soldUnit') }) }}
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -301,6 +302,19 @@ export default {
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
// 商品图 image 的 mode 模式:
|
||||
// - 大图模式(large-mode):容器高度由图片决定,固定使用 widthFix 保持原比例
|
||||
// - 鸿蒙元服务:其他模板下 image 的 widthFix 模式异常(图片被裁剪/显示不全),改用 aspectFill 填满固定容器
|
||||
// - H5、微信小程序等其他环境:保持 widthFix 行为不变
|
||||
imgMode() {
|
||||
if (this.goodsValue.template == 'large-mode') return 'widthFix';
|
||||
// #ifdef MP-HARMONY
|
||||
return 'aspectFill';
|
||||
// #endif
|
||||
// #ifndef MP-HARMONY
|
||||
return 'widthFix';
|
||||
// #endif
|
||||
},
|
||||
goodsListWarpCss() {
|
||||
var obj = '';
|
||||
obj += 'background-color:' + this.goodsValue.componentBgColor + ';';
|
||||
@@ -1017,10 +1031,6 @@ export default {
|
||||
width: calc(33.3333333% - 14rpx);
|
||||
box-sizing: border-box;
|
||||
|
||||
&:nth-child(3n + 3) {
|
||||
width: calc(33.33% - 15rpx);
|
||||
}
|
||||
|
||||
&:nth-of-type(1),
|
||||
&:nth-of-type(2),
|
||||
&:nth-of-type(3) {
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
<div class="goods-img-wrap">
|
||||
<image class="goods-img" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
|
||||
:src="$util.img(dataItem.goods_image, { size: 'mid' })" mode="widthFix"
|
||||
@error="imgError(index, dataIndex)" :lazy-load="true" />
|
||||
@error="imgError(index, dataIndex)" :lazy-load="true" show-menu-by-longpress />
|
||||
<view class="sell-out" v-if="dataItem.stock <= 0">
|
||||
<text class="iconfont icon-shuqing"></text>
|
||||
</view>
|
||||
@@ -33,7 +33,7 @@
|
||||
<view class="label-wrap" v-if="goodsValue.labelStyle.support"
|
||||
:style="{ background: goodsValue.labelStyle.bgColor, color: goodsValue.labelStyle.color }">
|
||||
<image :src="$util.img('app/component/view/goods_recommend/img/label.png')"
|
||||
mode="widthFix" />
|
||||
mode="widthFix" show-menu-by-longpress />
|
||||
<text>{{ goodsValue.labelStyle.title }}</text>
|
||||
</view>
|
||||
<view class="discount-price">
|
||||
@@ -53,7 +53,7 @@
|
||||
¥{{ showMarketPrice(dataItem) }}</view>
|
||||
<view class="sale" v-if="goodsValue.saleStyle.control"
|
||||
:style="{ color: goodsValue.theme == 'diy' ? goodsValue.saleStyle.color : '' }">
|
||||
售{{ dataItem.sale_num }}{{ dataItem.unit ? dataItem.unit : '件' }}
|
||||
{{ $lang('components-diy.diy-goods-recommend.soldPrefix') }}{{ dataItem.sale_num }}{{ dataItem.unit ? dataItem.unit : $lang('unit.piece') }}
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
:src="$util.img(item.imageUrl) || $util.img('public/uniapp/default_img/goods.png')"
|
||||
mode="aspectFill"
|
||||
:style="{ maxWidth: value.imageSize * 2 + 'rpx', maxHeight: value.imageSize * 2 + 'rpx', borderRadius: value.aroundRadius * 2 + 'rpx' }"
|
||||
:show-menu-by-longpress="true" />
|
||||
show-menu-by-longpress />
|
||||
|
||||
<diy-icon v-if="item.iconType == 'icon'" :icon="item.icon"
|
||||
:value="item.style ? item.style : null"
|
||||
@@ -69,7 +69,7 @@
|
||||
:src="$util.img(item.imageUrl) || $util.img('public/uniapp/default_img/goods.png')"
|
||||
mode="aspectFill"
|
||||
:style="{ maxWidth: value.imageSize * 2 + 'rpx', maxHeight: value.imageSize * 2 + 'rpx', borderRadius: value.aroundRadius * 2 + 'rpx' }"
|
||||
:show-menu-by-longpress="true" />
|
||||
show-menu-by-longpress />
|
||||
<diy-icon v-if="item.iconType == 'icon'" :icon="item.icon"
|
||||
:value="item.style ? item.style : null"
|
||||
:style="{ maxWidth: value.imageSize * 2 + 'rpx', maxHeight: value.imageSize * 2 + 'rpx', width: '100%', height: '100%' }"></diy-icon>
|
||||
@@ -164,7 +164,6 @@ export default {
|
||||
return;
|
||||
}
|
||||
}
|
||||
console.log(link)
|
||||
this.$util.diyRedirectTo(link);
|
||||
},
|
||||
swiperChange(e) {
|
||||
|
||||
@@ -64,6 +64,13 @@
|
||||
<diy-rich-text :value="item"></diy-rich-text>
|
||||
</template>
|
||||
|
||||
<!-- #ifdef H5 -->
|
||||
<template v-if="['Webview', 'WebView'].includes(item.componentName)">
|
||||
<!-- 网页容器 -->
|
||||
<diy-webview :value="item"></diy-webview>
|
||||
</template>
|
||||
<!-- #endif -->
|
||||
|
||||
<template v-if="item.componentName == 'HorzLine'">
|
||||
<!-- 辅助线 -->
|
||||
<diy-horz-line :value="item"></diy-horz-line>
|
||||
@@ -159,7 +166,10 @@
|
||||
<!-- 商品推荐 -->
|
||||
<diy-goods-recommend :value="item"></diy-goods-recommend>
|
||||
</template>
|
||||
|
||||
<template v-if="item.componentName == 'DiyRecommendCode'">
|
||||
<!-- 自定义推荐码组件 -->
|
||||
<diy-recommend-code :value="item"></diy-recommend-code>
|
||||
</template>
|
||||
<template v-if="item.componentName == 'GoodsBrand'">
|
||||
<!-- 商品品牌 -->
|
||||
<diy-goods-brand :value="item"></diy-goods-brand>
|
||||
@@ -291,82 +301,130 @@ export default {
|
||||
mixins: [DiyMinx],
|
||||
data() {
|
||||
return {
|
||||
diyGlobalData: null
|
||||
diyGlobalData: this.diyData ? this.$util.deepClone(this.diyData) : null,
|
||||
processedData: null
|
||||
};
|
||||
},
|
||||
watch: {
|
||||
diyData: {
|
||||
handler() {
|
||||
this.diyGlobalData = this.diyData ? this.$util.deepClone(this.diyData) : null;
|
||||
this.processData();
|
||||
this._notifyLoaded();
|
||||
},
|
||||
deep: true
|
||||
}
|
||||
},
|
||||
created() {
|
||||
this.diyGlobalData = JSON.parse(JSON.stringify(this.diyData));
|
||||
console.log('[DIY-GROUP][created] hasDiyData=', !!this.diyData, 'valueLen=', this.diyData && this.diyData.value && this.diyData.value.length);
|
||||
this.processData();
|
||||
},
|
||||
mounted() {
|
||||
console.log('[DIY-GROUP][mounted] hasDiyData=', !!this.diyData, 'valueLen=', this.diyData && this.diyData.value && this.diyData.value.length);
|
||||
if (this.diyData && this.diyData.value) {
|
||||
this._notifyLoaded();
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
topNavColor() {
|
||||
var color = '';
|
||||
if (this.diyData.global.topNavBg) {
|
||||
color = 'transparent';
|
||||
if (this.scrollTop > 20) {
|
||||
color = this.diyData.global.topNavColor;
|
||||
} else {
|
||||
color = 'transparent';
|
||||
}
|
||||
} else {
|
||||
color = this.diyData.global.topNavColor;
|
||||
if (!this.diyData?.global) return '';
|
||||
|
||||
const { topNavBg, topNavColor } = this.diyData.global;
|
||||
|
||||
if (topNavBg) {
|
||||
return this.scrollTop > 20 ? topNavColor : 'transparent';
|
||||
}
|
||||
return color;
|
||||
|
||||
return topNavColor;
|
||||
},
|
||||
// 修改属性样式
|
||||
setPagestyle() {
|
||||
this.diyGlobalData.value.forEach((item, index) => {
|
||||
item.pageStyle = '';
|
||||
// 给每个组件增加位置属性,用于定位,搜索、分类导航等定位
|
||||
// 如果是Tab组件内部的子组件,添加tabIndex前缀避免moduleIndex冲突
|
||||
if (this.diyData.tabIndex !== undefined) {
|
||||
item.moduleIndex = `${this.diyData.tabIndex}-${index + 1}`;
|
||||
} else {
|
||||
item.moduleIndex = index + 1;
|
||||
}
|
||||
|
||||
// 特殊处理搜索框 当显示位置为滚动至顶部固定时,只设置背景颜色
|
||||
if (item.componentName == 'Search' && item.positionWay == 'fixed') {
|
||||
// item.pageStyle = 'background-color:' + item.pageBgColor + ';';
|
||||
return false;
|
||||
}
|
||||
|
||||
item.pageStyle += 'background-color:' + item.pageBgColor + ';';
|
||||
if (item.margin) {
|
||||
item.pageStyle += 'padding-top:' + item.margin.top * 2 + 'rpx' + ';';
|
||||
item.pageStyle += 'padding-bottom:' + item.margin.bottom * 2 + 'rpx' + ';';
|
||||
item.pageStyle += 'padding-right:' + item.margin.both * 2 + 'rpx' + ';';
|
||||
item.pageStyle += 'padding-left:' + item.margin.both * 2 + 'rpx' + ';';
|
||||
}
|
||||
});
|
||||
|
||||
return this.diyGlobalData.value;
|
||||
},
|
||||
// 过滤组件的渲染
|
||||
diyDataArray() {
|
||||
let data = [],
|
||||
showModuleData = this.$store.state.diyGroupShowModule ? JSON.parse(this.$store.state
|
||||
.diyGroupShowModule) : '';
|
||||
if (!this.processedData) {
|
||||
this.processData();
|
||||
}
|
||||
|
||||
const showModuleData = this.$store.state.diyGroupShowModule
|
||||
? JSON.parse(this.$store.state.diyGroupShowModule)
|
||||
: null;
|
||||
|
||||
if (showModuleData.length) {
|
||||
if (showModuleData.includes('null')) return [];
|
||||
if (!showModuleData || !showModuleData.length) {
|
||||
return this.processedData || [];
|
||||
}
|
||||
|
||||
let diyDataArr = this.setPagestyle;
|
||||
diyDataArr.forEach((item, index) => {
|
||||
if (showModuleData.includes(item.componentName)) {
|
||||
data.push(item);
|
||||
}
|
||||
});
|
||||
} else data = this.setPagestyle;
|
||||
if (showModuleData.includes('null')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
console.log(`diy-group ['diyDataArray'] = `, {
|
||||
data: data,
|
||||
diyData: this.diyData,
|
||||
diyGlobalData: this.diyGlobalData,
|
||||
})
|
||||
return data;
|
||||
return (this.processedData || []).filter(item =>
|
||||
showModuleData.includes(item.componentName)
|
||||
);
|
||||
}
|
||||
},
|
||||
methods: {}
|
||||
methods: {
|
||||
_notifyLoaded() {
|
||||
console.log('[DIY-GROUP][_notifyLoaded] enter, will emit loaded in 300ms');
|
||||
if (this._loadedTimer) clearTimeout(this._loadedTimer);
|
||||
this._loadedTimer = setTimeout(() => {
|
||||
console.log('[DIY-GROUP][_notifyLoaded] emit loaded');
|
||||
this.$emit('loaded');
|
||||
}, 300);
|
||||
},
|
||||
processData() {
|
||||
if (!this.diyGlobalData || !this.diyGlobalData.value) {
|
||||
this.processedData = [];
|
||||
return;
|
||||
}
|
||||
|
||||
this.processedData = this.diyGlobalData.value.map((item, index) => {
|
||||
const newItem = this.$util.deepClone(item);
|
||||
|
||||
newItem.pageStyle = '';
|
||||
|
||||
newItem.moduleIndex = this.diyData.tabIndex !== undefined
|
||||
? `${this.diyData.tabIndex}-${index + 1}`
|
||||
: index + 1;
|
||||
|
||||
if (newItem.componentName !== 'Search' || newItem.positionWay !== 'fixed') {
|
||||
// PR-DIY-SEARCH-MARGIN-COLOR (2026-09-17): 搜索组件的上下左右边距区域颜色
|
||||
// 与搜索框背景色(componentBgColor, 后台自定义)保持一致, 使边距和搜索框融为一体;
|
||||
// 兼容旧数据: 未配置 componentBgColor 时回退 pageBgColor。其余组件仍用 pageBgColor。
|
||||
const wrapBgColor = (newItem.componentName === 'Search' && newItem.componentBgColor)
|
||||
? newItem.componentBgColor
|
||||
: newItem.pageBgColor;
|
||||
newItem.pageStyle = `background-color:${wrapBgColor};`;
|
||||
|
||||
// 边距归一化: 兼容后台两种数据结构(否则边距不生效)
|
||||
// ① 标准对象形态 margin = { top, bottom, both } —— 大多数组件
|
||||
// ② 扁平字段形态 marginTop / marginBottom / marginBoth
|
||||
// —— 如"滑动图片"(ImageNav), 其 margin 是空数组 [], 左右边距存在 marginBoth 里
|
||||
// both / marginBoth 表示"左右边距"; 数值 → rpx 统一 × 2 (与其它组件一致)
|
||||
const rawMargin = newItem.margin;
|
||||
const objMargin = (rawMargin && typeof rawMargin === 'object' && !Array.isArray(rawMargin)) ? rawMargin : null;
|
||||
const toMarginNum = (v) => { const n = Number(v); return isNaN(n) ? 0 : n; };
|
||||
const pickMargin = (objKey, flatKey) => {
|
||||
if (objMargin && objMargin[objKey] !== undefined && objMargin[objKey] !== null && objMargin[objKey] !== '') {
|
||||
return toMarginNum(objMargin[objKey]);
|
||||
}
|
||||
return toMarginNum(newItem[flatKey]);
|
||||
};
|
||||
const marginTopNum = pickMargin('top', 'marginTop');
|
||||
const marginBottomNum = pickMargin('bottom', 'marginBottom');
|
||||
const marginBothNum = pickMargin('both', 'marginBoth');
|
||||
// 左右: 若有独立的 left/right 字段则优先, 否则用 both(左右一致)
|
||||
const marginLeftNum = (objMargin && objMargin.left !== undefined) ? toMarginNum(objMargin.left)
|
||||
: (newItem.marginLeft !== undefined ? toMarginNum(newItem.marginLeft) : marginBothNum);
|
||||
const marginRightNum = (objMargin && objMargin.right !== undefined) ? toMarginNum(objMargin.right)
|
||||
: (newItem.marginRight !== undefined ? toMarginNum(newItem.marginRight) : marginBothNum);
|
||||
|
||||
newItem.pageStyle += `padding-top:${marginTopNum * 2}rpx;`;
|
||||
newItem.pageStyle += `padding-bottom:${marginBottomNum * 2}rpx;`;
|
||||
newItem.pageStyle += `padding-left:${marginLeftNum * 2}rpx;`;
|
||||
newItem.pageStyle += `padding-right:${marginRightNum * 2}rpx;`;
|
||||
}
|
||||
|
||||
return newItem;
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
|
||||
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
|
||||
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
|
||||
@error="imageError(index)">
|
||||
@error="imageError(index)" show-menu-by-longpress>
|
||||
</image>
|
||||
</view>
|
||||
<view class="content"
|
||||
@@ -44,7 +44,7 @@
|
||||
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
|
||||
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
|
||||
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
|
||||
@error="imageError(index)" />
|
||||
@error="imageError(index)" show-menu-by-longpress/>
|
||||
<image class="bg" v-if="value.saleStyle.control"
|
||||
:src="$util.img('public/uniapp/groupbuy/bg.png')" mode="widthFix" />
|
||||
<view class="num" v-if="value.saleStyle.control"
|
||||
@@ -85,7 +85,7 @@
|
||||
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
|
||||
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
|
||||
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
|
||||
@error="imageError(dataIndex)" />
|
||||
@error="imageError(dataIndex)" show-menu-by-longpress/>
|
||||
<image class="bg" v-if="value.saleStyle.control"
|
||||
:src="$util.img('public/uniapp/groupbuy/bg.png')" mode="widthFix" />
|
||||
<view class="num" v-if="value.saleStyle.control"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<view data-component-name="diy-hot-area" :style="hotAreaWarp" class="hot-area-box">
|
||||
<view class="simple-graph-wrap">
|
||||
<image :style="{ height: value.imgHeight }" :src="$util.img(value.imageUrl)" mode="widthFix"
|
||||
:show-menu-by-longpress="true" />
|
||||
show-menu-by-longpress />
|
||||
<!-- 热区功能 -->
|
||||
<view class="heat-map" v-for="(mapItem, mapIndex) in value.heatMapData" :key="mapIndex" :style="{
|
||||
width: mapItem.width + '%',
|
||||
|
||||
@@ -1,38 +1,52 @@
|
||||
<template>
|
||||
<view :style="componentStyle">
|
||||
<scroll-view :class="['image-nav', value.showStyle == 'fixed' ? 'fixed-layout' : value.showStyle]"
|
||||
:scroll-x="value.showStyle == 'singleSlide'">
|
||||
<view class="uni-scroll-view-content">
|
||||
<view v-for="(item, index) in value.list" :key="index" :class="['image-nav-item', value.mode]"
|
||||
style="margin-right: 28rpx;">
|
||||
<!-- 图片部分 -->
|
||||
<view v-if="value.mode != 'text'" class="image-img" :style="{
|
||||
'font-size': (value.imageSize * 2 + 'rpx') + ';',
|
||||
'width': (item.imgWidth / 2 + 'rpx') + ';',
|
||||
'height': (item.imgHeight / 2 + 'rpx') + ';'
|
||||
}">
|
||||
<image v-if="item.link.wap_url" :style="{
|
||||
'width': (item.imgWidth / 2 + 'rpx') + ';',
|
||||
'height': (item.imgHeight / 2 + 'rpx') + ';'
|
||||
}" :src="$util.img(item.imageUrl) || $util.img('public/uniapp/default_img/goods.png')"
|
||||
:show-menu-by-longpress="true" @tap.stop="redirectTo(item.link)"></image>
|
||||
<image v-else :style="{
|
||||
'width': (item.imgWidth / 2 + 'rpx') + ';',
|
||||
'height': (item.imgHeight / 2 + 'rpx') + ';'
|
||||
}" :src="$util.img(item.imageUrl) || $util.img('public/uniapp/default_img/goods.png')"
|
||||
:show-menu-by-longpress="true" @tap.stop="previewImg(item.imageUrl)"></image>
|
||||
</view>
|
||||
<view :style="componentStyle" data-component-name="diy-image-nav">
|
||||
<!-- PR-FRONTEND-DIY-SCROLLBAR (2026-09-18): 水平滚动条显隐三态(后台配置)
|
||||
slide=滑动时显示(默认) / always=始终显示 / never=永不显示
|
||||
注意: 微信小程序端原生 show-scrollbar 属性被忽略(仅在 App 端生效),
|
||||
无法保证"始终显示/滑动时显示", 因此小程序端改用【自定义滚动条】(.img-nav-scrollbar),
|
||||
H5 端用 CSS 伪元素(见下方 #ifdef H5 样式) —— 两端视觉/逻辑保持一致。
|
||||
fix (2026-09-22): 小程序端"始终显示"失效 —— 见 measureScrollbar() 注释(内容宽度测错)。 -->
|
||||
<view class="image-nav-wrap">
|
||||
<scroll-view :class="['image-nav', value.showStyle == 'fixed' ? 'fixed-layout' : value.showStyle, scrollBarClass]"
|
||||
:style="imageSpacingStyle"
|
||||
:scroll-x="value.showStyle == 'singleSlide'"
|
||||
:show-scrollbar="showScrollbarAttr"
|
||||
:enhanced="enhancedScrollbar"
|
||||
@scroll="onSlideScroll">
|
||||
<view class="uni-scroll-view-content">
|
||||
<view v-for="(item, index) in value.list" :key="index" :class="['image-nav-item', value.mode]"
|
||||
:style="imageItemStyle">
|
||||
<!-- 图片部分 -->
|
||||
<!-- PR-FRONTEND-DIY-IMAGE-NAV-IMG-SIZE (2026-09-22):
|
||||
图片按后台上传/配置的尺寸渲染,避免 uni <image> 取不到尺寸时
|
||||
回退到浏览器默认 320x240 而被"撑到最大";mode=aspectFit 保证不拉伸变形 -->
|
||||
<view v-if="value.mode != 'text'" class="image-img" :style="imageBoxStyle(item)">
|
||||
<image v-if="item.link.wap_url" class="image-content" :style="imageInnerStyle(item)"
|
||||
mode="aspectFit"
|
||||
:src="$util.img(item.imageUrl) || $util.img('public/uniapp/default_img/goods.png')"
|
||||
show-menu-by-longpress @tap.stop="redirectTo(item.link)"></image>
|
||||
<image v-else class="image-content" :style="imageInnerStyle(item)" mode="aspectFit"
|
||||
:src="$util.img(item.imageUrl) || $util.img('public/uniapp/default_img/goods.png')"
|
||||
show-menu-by-longpress @tap.stop="previewImg(item.imageUrl)"></image>
|
||||
</view>
|
||||
|
||||
<!-- 文字部分 -->
|
||||
<text class="image-text" :style="{
|
||||
'width': (item.imgWidth / 2 + 'rpx') + ';',
|
||||
'font-size': (value.font.size * 2 + 'rpx') + ';',
|
||||
'font-weight': value.font.weight + ';',
|
||||
'color': value.font.color + ';'
|
||||
}">{{ item.title }}</text>
|
||||
<!-- 文字部分 -->
|
||||
<text class="image-text" :style="{
|
||||
'width': (item.imgWidth / 2 + 'rpx') + ';',
|
||||
'font-size': (value.font.size * 2 + 'rpx') + ';',
|
||||
'font-weight': value.font.weight + ';',
|
||||
'color': value.font.color + ';'
|
||||
}">{{ item.title }}</text>
|
||||
</view>
|
||||
</view>
|
||||
</scroll-view>
|
||||
<!-- #ifdef MP -->
|
||||
<!-- 小程序端自定义水平滚动条: 原生 show-scrollbar 被忽略, 这里自绘以对齐后台/ H5 -->
|
||||
<view v-if="showCustomScrollbar" class="img-nav-scrollbar">
|
||||
<view class="img-nav-scrollbar-thumb" :style="scrollbarThumbStyle"></view>
|
||||
</view>
|
||||
</scroll-view>
|
||||
<!-- #endif -->
|
||||
</view>
|
||||
<ns-login ref="login"></ns-login>
|
||||
</view>
|
||||
</template>
|
||||
@@ -54,21 +68,120 @@ export default {
|
||||
return {
|
||||
pageWidth: '',
|
||||
indicatorDots: false,
|
||||
swiperCurrent: 0
|
||||
swiperCurrent: 0,
|
||||
// H5 鼠标拖拽状态(singleSlide 模式专用)
|
||||
slideIsDragging: false,
|
||||
slideDidDrag: false, // 5px 阈值后置 true,用于判断 mouseup 后是否拦截 click
|
||||
slideStartX: 0,
|
||||
slideStartScrollLeft: 0,
|
||||
_suppressNextClick: false, // 拖拽结束后拦截一次 click,防止误触发跳转
|
||||
// PR-FRONTEND-DIY-SCROLLBAR (2026-09-18): "滑动时显示"模式专用
|
||||
// 滚动中为 true → 给 scroll-view 加 is-scrolling 类展示滚动条, 停止 800ms 后隐藏
|
||||
slideScrolling: false,
|
||||
// 小程序端自定义滚动条度量(原生 show-scrollbar 被忽略, 改用自绘)
|
||||
mpScroll: { viewW: 0, contentW: 0, left: 0 }
|
||||
}
|
||||
},
|
||||
created() {
|
||||
// 组件创建时的逻辑
|
||||
},
|
||||
mounted() {
|
||||
// H5 端:为 singleSlide 模式的 scroll-view 手动绑定 mouse/wheel 事件
|
||||
// 原因:模板里写 @mousedown/@wheel 在小程序/鸿蒙端会产生"未知事件"警告,
|
||||
// 所以 H5 专属事件全部在 mounted 中通过 addEventListener 绑定。
|
||||
// $nextTick 是为了确保 ref 在 DOM 中已就绪(滚动容器总是存在的,无 v-if)。
|
||||
// #ifdef H5
|
||||
var self = this;
|
||||
this.$nextTick(function() {
|
||||
self.bindSlideMouseEvents();
|
||||
self.bindSlideScrollbar();
|
||||
});
|
||||
// #endif
|
||||
// 小程序端:测量滚动条所需的视口/内容宽度(图片尺寸由内联样式决定, 渲染后稳定)
|
||||
// 多次(0/300/1000ms)重测: 首次渲染时节点可能尚未布局完成, 单次测量容易拿不到宽度
|
||||
// → 滚动条不显示; 之后的测量只覆盖有效值, 不会把已测得的宽度清零。
|
||||
// #ifdef MP
|
||||
var selfMp = this;
|
||||
this.$nextTick(function() {
|
||||
selfMp.measureScrollbar();
|
||||
});
|
||||
this._mpMeasureTimers = [300, 1000].map(function(delay) {
|
||||
return setTimeout(function() {
|
||||
selfMp.measureScrollbar();
|
||||
}, delay);
|
||||
});
|
||||
// #endif
|
||||
},
|
||||
beforeDestroy() {
|
||||
// #ifdef H5
|
||||
this.unbindSlideMouseEvents();
|
||||
this.unbindSlideScrollbar();
|
||||
// #endif
|
||||
// #ifdef MP
|
||||
if (this._mpMeasureTimers) {
|
||||
this._mpMeasureTimers.forEach(function(t) { clearTimeout(t); });
|
||||
this._mpMeasureTimers = null;
|
||||
}
|
||||
// #endif
|
||||
},
|
||||
watch: {
|
||||
componentRefresh(newValue) {
|
||||
// 监听组件刷新
|
||||
},
|
||||
// 小程序端: 列表/数量变化后, 内容宽度会变, 重新测量自定义滚动条
|
||||
'value.list'(newVal, oldVal) {
|
||||
// #ifdef MP
|
||||
if (newVal !== oldVal) {
|
||||
var self = this;
|
||||
this.$nextTick(function() {
|
||||
self.measureScrollbar();
|
||||
});
|
||||
}
|
||||
// #endif
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
// PR-FRONTEND-DIY-IMAGE-NAV-SPACING (2026-09-18): 组件背景色
|
||||
// 后台"组件背景"面板下发的字段是 componentBgColor(与图片轮播/搜索等组件一致);
|
||||
// 兼容别名/数组形态/嵌套容器(避免后台换名或存成数组时前端读不到而完全不上色),
|
||||
// 最后兜底组件级 pageBgColor(部分组件后台把组件背景存在这里)。
|
||||
// 空值/非法值(图片URL等)返回空串, 此时不输出 background-color, 保持历史透明视觉。
|
||||
componentBgColor() {
|
||||
const v = this.value || {};
|
||||
const norm = k => String(k).toLowerCase().replace(/[\s_-]/g, '');
|
||||
const asColor = val => {
|
||||
if (Array.isArray(val)) val = val[0];
|
||||
if (typeof val !== 'string') return '';
|
||||
const s = val.trim();
|
||||
if (!s) return '';
|
||||
// 排除图片/URL 等非颜色值
|
||||
if (/^(url\(|https?:|data:|upload\/|addon\/|\/)/i.test(s)) return '';
|
||||
return s;
|
||||
};
|
||||
const sources = [v];
|
||||
['style', 'config', 'setting', 'data'].forEach(k => {
|
||||
if (v[k] && typeof v[k] === 'object' && !Array.isArray(v[k])) sources.push(v[k]);
|
||||
});
|
||||
const candidates = [
|
||||
'componentbgcolor', 'componentbackgroundcolor', 'componentcolor', 'componentbg',
|
||||
'bgcolor', 'backgroundcolor', 'background',
|
||||
'pagebgcolor'
|
||||
];
|
||||
for (let c = 0; c < candidates.length; c++) {
|
||||
for (let s = 0; s < sources.length; s++) {
|
||||
for (const key in sources[s]) {
|
||||
if (norm(key) === candidates[c]) {
|
||||
const color = asColor(sources[s][key]);
|
||||
if (color) return color;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return '';
|
||||
},
|
||||
componentStyle() {
|
||||
let style = '';
|
||||
style += 'background-color:' + this.value.componentBgColor + ';';
|
||||
if (this.componentBgColor) style += 'background-color:' + this.componentBgColor + ';';
|
||||
|
||||
if (this.value.componentAngle == 'round') {
|
||||
style += 'border-top-left-radius:' + (2 * this.value.topAroundRadius) + 'rpx;';
|
||||
@@ -100,9 +213,446 @@ export default {
|
||||
isIndicatorDots() {
|
||||
return this.value.carousel.type != 'hide' &&
|
||||
1 != Math.ceil(this.value.list.length / (this.value.pageCount * this.value.rowCount));
|
||||
},
|
||||
|
||||
// ========== PR-FRONTEND-DIY-SCROLLBAR (2026-09-18): 水平滚动条显隐三态 ==========
|
||||
// 后台"水平滚动条"配置: 滑动时显示 / 始终显示 / 永不显示 → 归一化为 slide / always / never
|
||||
// 字段名兼容: scrollBar / scrollbar / scrollBarType / horizontalScrollBar / horizontalScrollbar
|
||||
// (忽略大小写/下划线/中划线差异, 并向下探测 value.scrollBar / value.style 等嵌套容器)
|
||||
// 值兼容: 英文枚举(slide/auto/always/never/none...) / 中文枚举(滑动时显示/始终显示/永不显示)
|
||||
// / 数字(0=滑动时显示 1=始终显示 2=永不显示) / 布尔(true=始终显示 false=永不显示)
|
||||
// 兜底: 未下发或无法识别 → 'slide' (滑动时显示, 与历史行为一致)
|
||||
scrollBarMode() {
|
||||
const v = this.value || {};
|
||||
const norm = k => String(k).toLowerCase().replace(/[\s_-]/g, '');
|
||||
// 从配置对象中取"滚动条"字段的原始值
|
||||
const pickRaw = obj => {
|
||||
if (!obj || typeof obj != 'object') return undefined;
|
||||
for (const key in obj) {
|
||||
const k = norm(key);
|
||||
if (k.indexOf('scrollbar') != -1 || k.indexOf('scrolltype') != -1) {
|
||||
const val = obj[key];
|
||||
if (val && typeof val === 'object') {
|
||||
// 子配置对象形态: { scrollBar: { type: 'always' } }
|
||||
return val.type !== undefined ? val.type : (val.value !== undefined ? val.value : val.mode);
|
||||
}
|
||||
if (val !== undefined && val !== null && val !== '') return val;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
let raw = pickRaw(v);
|
||||
// 嵌套容器兜底
|
||||
if (raw === undefined) {
|
||||
const containers = ['scrollBar', 'scrollbar', 'style', 'config', 'setting', 'data'];
|
||||
for (let i = 0; i < containers.length; i++) {
|
||||
if (v[containers[i]] && typeof v[containers[i]] === 'object') {
|
||||
raw = pickRaw(v[containers[i]]);
|
||||
if (raw !== undefined) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (raw === undefined || raw === null || raw === '') return 'slide';
|
||||
if (typeof raw === 'boolean') return raw ? 'always' : 'never';
|
||||
if (raw === 0 || raw === '0') return 'slide';
|
||||
if (raw === 1 || raw === '1') return 'always';
|
||||
if (raw === 2 || raw === '2') return 'never';
|
||||
|
||||
const map = {
|
||||
slide: 'slide', scroll: 'slide', auto: 'slide', scrolling: 'slide', whilescrolling: 'slide', moveslide: 'slide',
|
||||
always: 'always', alwaysdisplay: 'always', show: 'always',
|
||||
never: 'never', none: 'never', hidden: 'never', hide: 'never',
|
||||
// 后台直出中文枚举时兜底
|
||||
'滑动时显示': 'slide', '滑动时': 'slide', '滚动时显示': 'slide',
|
||||
'始终显示': 'always', '一直显示': 'always', '永久显示': 'always',
|
||||
'永不显示': 'never', '从不显示': 'never', '不显示': 'never'
|
||||
};
|
||||
const hit = map[String(raw).toLowerCase().trim()] || map[norm(raw)];
|
||||
return hit || 'slide';
|
||||
},
|
||||
|
||||
// scroll-view 上的滚动条显隐 class: scrollbar-slide / scrollbar-always / scrollbar-never
|
||||
// "滑动时显示"在滚动中追加 is-scrolling (由 scroll 监听维护)
|
||||
scrollBarClass() {
|
||||
const cls = ['scrollbar-' + this.scrollBarMode];
|
||||
if (this.scrollBarMode == 'slide' && this.slideScrolling) cls.push('is-scrolling');
|
||||
return cls;
|
||||
},
|
||||
|
||||
// 原生 show-scrollbar / enhanced 仅在 App 端生效, 小程序端被忽略且会干扰原生行为,
|
||||
// 故小程序端一律关闭, 改用自定义滚动条; H5 端这两个属性为 no-op, 不影响。
|
||||
enhancedScrollbar() {
|
||||
// #ifndef MP
|
||||
return this.scrollBarMode != 'never';
|
||||
// #endif
|
||||
// #ifdef MP
|
||||
return false;
|
||||
// #endif
|
||||
},
|
||||
showScrollbarAttr() {
|
||||
// #ifndef MP
|
||||
return this.scrollBarMode != 'never';
|
||||
// #endif
|
||||
// #ifdef MP
|
||||
return false;
|
||||
// #endif
|
||||
},
|
||||
|
||||
// 小程序端自定义滚动条的"是否显示"
|
||||
showCustomScrollbar() {
|
||||
// #ifdef MP
|
||||
if (this.scrollBarMode === 'never') return false;
|
||||
// 只有 singleSlide(横向可滚动)才有滚动条, 与 H5 的 .singleSlide 样式作用域保持一致
|
||||
if (this.value.showStyle != 'singleSlide') return false;
|
||||
// 内容没有溢出(无需横向滚动)则不显示
|
||||
if (!(this.mpScroll.contentW > this.mpScroll.viewW)) return false;
|
||||
// 滑动时显示: 仅在滚动中显示
|
||||
if (this.scrollBarMode === 'slide') return this.slideScrolling;
|
||||
// 始终显示: 一直显示
|
||||
return true;
|
||||
// #endif
|
||||
},
|
||||
|
||||
// 小程序端自定义滚动条 thumb 的内联样式(width + 位移)
|
||||
scrollbarThumbStyle() {
|
||||
// #ifdef MP
|
||||
const viewW = this.mpScroll.viewW;
|
||||
const contentW = this.mpScroll.contentW;
|
||||
const left = this.mpScroll.left;
|
||||
if (!viewW || !contentW || contentW <= viewW) return 'display:none;';
|
||||
const thumbW = Math.max(20, Math.floor(viewW * viewW / contentW));
|
||||
const maxLeft = contentW - viewW;
|
||||
const ratio = maxLeft > 0 ? Math.min(1, Math.max(0, left / maxLeft)) : 0;
|
||||
const thumbLeft = ratio * (viewW - thumbW);
|
||||
return 'width:' + thumbW + 'px;transform:translateX(' + thumbLeft + 'px);';
|
||||
// #endif
|
||||
},
|
||||
|
||||
// ========== PR-FRONTEND-DIY-IMAGE-NAV-SPACING (2026-09-18): 图片自定义间距 ==========
|
||||
// 后台"滑动图片"组件(componentName = ImageNav)的 3 项间距配置。
|
||||
// 字段名已用线上接口 POST /api/diyview/info(uniacid=312, DIY_VIEW_INDEX) 核对, 实际为:
|
||||
// imageSpacing 图片横向间距: 相邻图片项之间的横向间隔
|
||||
// imageSpacingTop 图片上间距 : 图片区域内侧的上内边距
|
||||
// imageSpacingBottom 图片下间距 : 图片区域内侧的下内边距
|
||||
// 单位: 按项目惯例(与 diy-group 的 margin.top、图片轮播的 margin.both 一致)换算 rpx = 后台数值 × 2
|
||||
// 容错: 除后台现用命名外, 仍按归一化(忽略大小写/下划线/中划线)兼容其它命名,
|
||||
// 并向下探测 value.imageSpacing / value.margin / value.padding 等嵌套容器。
|
||||
// 兜底: 字段缺失/非法时返回 null, 由 imageSpacingStyle / imageItemStyle 回退历史视觉
|
||||
// (横向 28rpx, 上/下沿用 CSS 的 16rpx), 老装修数据不受影响。
|
||||
imageSpacingConfig() {
|
||||
const v = this.value || {};
|
||||
const RATIO = 2; // 后台数值 → rpx 换算比例
|
||||
|
||||
const norm = k => String(k).toLowerCase().replace(/[\s_-]/g, '');
|
||||
// 非数字(如 'diy'/枚举)或空值 → null, 交给兜底
|
||||
const toRpx = val => {
|
||||
if (val === undefined || val === null || val === '') return null;
|
||||
const n = Number(val);
|
||||
if (isNaN(n)) return null;
|
||||
return Math.max(0, n) * RATIO;
|
||||
};
|
||||
|
||||
// 查找源: value 自身 + 常见嵌套容器(顶层优先)
|
||||
// 注意: 后端偶发把 margin 存成数组(线上该组件 margin: []), 数组不能当容器取裸键, 直接跳过
|
||||
const sources = [v];
|
||||
['imageSpacing', 'imageSpace', 'spacing', 'space', 'margin', 'padding', 'style', 'config', 'setting']
|
||||
.forEach(k => {
|
||||
if (v[k] && typeof v[k] === 'object' && !Array.isArray(v[k])) sources.push(v[k]);
|
||||
});
|
||||
|
||||
// 三级查找: ① 全源精确名 → ② 全源模糊包含名 → ③ 嵌套容器内的裸键
|
||||
// (如 imageSpacing: { horizontal: 3, top: 0, bottom: 0 })
|
||||
const pick = (exact, fuzzy, nested) => {
|
||||
for (let s = 0; s < sources.length; s++) {
|
||||
const src = sources[s];
|
||||
for (const key in src) {
|
||||
if (exact.indexOf(norm(key)) != -1) {
|
||||
const rpx = toRpx(src[key]);
|
||||
if (rpx !== null) return rpx;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (let s = 0; s < sources.length; s++) {
|
||||
const src = sources[s];
|
||||
for (const key in src) {
|
||||
const k = norm(key);
|
||||
if (fuzzy.some(f => k.indexOf(f) != -1)) {
|
||||
const rpx = toRpx(src[key]);
|
||||
if (rpx !== null) return rpx;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 裸键(top/bottom/both...)只在嵌套容器内解释, 避免误取顶层同名字段
|
||||
for (let s = 1; s < sources.length; s++) {
|
||||
const src = sources[s];
|
||||
for (const key in src) {
|
||||
if (nested.indexOf(norm(key)) != -1) {
|
||||
const rpx = toRpx(src[key]);
|
||||
if (rpx !== null) return rpx;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
return {
|
||||
// 图片横向间距 —— 后台现用命名 imageSpacing(首项命中即可, 后面都是兼容别名)
|
||||
horizontal: pick(
|
||||
['imagespacing', 'imagespacinghorizontal', 'imagehorizontalspacing', 'imagespacingboth', 'imagespacenum',
|
||||
'imagemargin', 'imagemarginnum', 'imagespace', 'horizontalspacing', 'horizontalspacenum', 'imagegap',
|
||||
'spacenum', 'marginnum', 'imageverticalspace', 'space', 'gap'],
|
||||
['horizontalspacing', 'imagespacing', 'imagespace', 'imagemargin', 'spacenum', 'marginnum', 'imagegap', 'gap'],
|
||||
['horizontal', 'horizontalnum', 'lr', 'leftright', 'both', 'bothnum', 'imagespacing', 'num', 'margin', 'space', 'gap']
|
||||
),
|
||||
// 图片上间距 —— 后台现用命名 imageSpacingTop
|
||||
paddingTop: pick(
|
||||
['imagespacingtop', 'imagetopspacing', 'imagespacetop', 'imagetopspace', 'imagepaddingtop',
|
||||
'paddingtop', 'spacingtop', 'topspace', 'margintop'],
|
||||
['imagespacingtop', 'paddingtop', 'spacingtop', 'topspacing', 'topspace', 'margintop'],
|
||||
['top', 'topnum', 'paddingtop', 'margintop', 'spacetop', 'spacingtop']
|
||||
),
|
||||
// 图片下间距 —— 后台现用命名 imageSpacingBottom
|
||||
paddingBottom: pick(
|
||||
['imagespacingbottom', 'imagebottomspacing', 'imagespacebottom', 'imagebottomspace', 'imagepaddingbottom',
|
||||
'paddingbottom', 'spacingbottom', 'bottomspace', 'marginbottom'],
|
||||
['imagespacingbottom', 'paddingbottom', 'spacingbottom', 'bottomspacing', 'bottomspace', 'marginbottom'],
|
||||
['bottom', 'bottomnum', 'paddingbottom', 'marginbottom', 'spacebottom', 'spacingbottom']
|
||||
)
|
||||
};
|
||||
},
|
||||
|
||||
// 图片区域上/下内边距(作用在滚动容器上); 未配置时不输出内联样式, 沿用 CSS padding
|
||||
imageSpacingStyle() {
|
||||
const cfg = this.imageSpacingConfig;
|
||||
let style = '';
|
||||
if (cfg.paddingTop !== null) style += 'padding-top:' + cfg.paddingTop + 'rpx;';
|
||||
if (cfg.paddingBottom !== null) style += 'padding-bottom:' + cfg.paddingBottom + 'rpx;';
|
||||
return style;
|
||||
},
|
||||
|
||||
// 图片项之间的横向间距; 未配置时回退原写死的 28rpx
|
||||
imageItemStyle() {
|
||||
const horizontal = this.imageSpacingConfig.horizontal;
|
||||
return 'margin-right:' + (horizontal === null ? 28 : horizontal) + 'rpx;';
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
// ========== PR-FRONTEND-DIY-IMAGE-NAV-IMG-SIZE (2026-09-22): 图片展示尺寸 ==========
|
||||
// 目标: 图片按后台"上传/配置的尺寸"渲染, 不再被撑到最大(小程序/H5 表现一致)。
|
||||
// 背景: 原写法直接把 item.imgWidth / item.imgHeight(每项字段)当成内联尺寸,
|
||||
// 后台往往不下发这两个字段(或下发 "") → 生成 'NaNrpx' 这类非法值被忽略,
|
||||
// <image> 于是回退到 uni-app 默认尺寸 320px x 240px, 视觉上就是"被撑到最大"。
|
||||
// 取值优先级(后台数值单位按 rpx 约定, 经 $util.rpx() 转成当前端可用单位):
|
||||
// ① 每一项下发的 imgWidth / imgHeight —— 沿用历史约定: 数值 ÷ 2
|
||||
// ② 组件级 imgWidth / imgHeight —— 兜底, 同样 ÷ 2
|
||||
// ③ 组件级"图片尺寸"imageSize —— 与 diy-graphic-nav / diy-merch-list 一致, × 2
|
||||
// ④ 都没有 → 120 正方形, 只做最小安全兜底(远小于 320x240 默认值)
|
||||
//
|
||||
// 落地结构: 外层 .image-img(view) 与 <image> 都按解析出的尺寸渲染, 两端一致;
|
||||
// 样式统一由下面的方法输出"字符串"(见 imageBoxStyle 的说明, 对象在小程序端会失效)。
|
||||
rpxVal(val) {
|
||||
// 项目约定: 小程序/App 输出 'Nrpx', H5 输出 'Npx'(uni.upx2px)
|
||||
if (this.$util && typeof this.$util.rpx === 'function') return this.$util.rpx(val);
|
||||
return val + 'rpx';
|
||||
},
|
||||
resolveItemImgSize(item) {
|
||||
const valid = v => {
|
||||
if (v === undefined || v === null || v === '') return null;
|
||||
const n = Number(v);
|
||||
return (!isNaN(n) && n > 0) ? n : null;
|
||||
};
|
||||
// ① 每一项图片自身尺寸
|
||||
const iw = valid(item && item.imgWidth);
|
||||
const ih = valid(item && item.imgHeight);
|
||||
if (iw !== null && ih !== null) return { width: iw / 2, height: ih / 2 };
|
||||
if (iw !== null) return { width: iw / 2, height: iw / 2 };
|
||||
if (ih !== null) return { width: ih / 2, height: ih / 2 };
|
||||
// ② 组件级 imgWidth / imgHeight
|
||||
const v = this.value || {};
|
||||
const ciw = valid(v.imgWidth);
|
||||
const cih = valid(v.imgHeight);
|
||||
if (ciw !== null && cih !== null) return { width: ciw / 2, height: cih / 2 };
|
||||
if (ciw !== null) return { width: ciw / 2, height: ciw / 2 };
|
||||
if (cih !== null) return { width: cih / 2, height: cih / 2 };
|
||||
// ③ 组件级"图片尺寸"
|
||||
const is = valid(v.imageSize);
|
||||
if (is !== null) return { width: is * 2, height: is * 2 };
|
||||
// ④ 安全兜底
|
||||
return { width: 120, height: 120 };
|
||||
},
|
||||
// 图片外层占位盒样式(决定图片最终尺寸)
|
||||
//
|
||||
// ⚠️ 必须返回"样式字符串", 不能返回对象!
|
||||
// 返回对象时 mp-weixin 的编译产物是 `style="{{(item.m0)}}"`(m0 是对象),
|
||||
// 小程序 WXML 不能把对象转成 style 字符串 → 整条样式直接失效:
|
||||
// · 只有 <image> 时 → 图片回退到默认 320x240(看起来"被撑到最大")
|
||||
// · 外层盒没尺寸 + 图片 width:100% 时 → 高度塌成 0(图片完全不显示)
|
||||
// diy-graphic-nav.vue 能在小程序正常显示, 正是因为它的 style 编译出来是字符串。
|
||||
imageBoxStyle(item) {
|
||||
const size = this.resolveItemImgSize(item);
|
||||
const imageSize = Number(this.value && this.value.imageSize);
|
||||
const font = (!isNaN(imageSize) && imageSize > 0) ? imageSize * 2 : size.height;
|
||||
return 'font-size:' + this.rpxVal(font) + ';'
|
||||
+ 'width:' + this.rpxVal(size.width) + ';'
|
||||
+ 'height:' + this.rpxVal(size.height) + ';';
|
||||
},
|
||||
// 图片自身样式(与占位盒同尺寸, 配合 mode="aspectFit" 等比完整显示)
|
||||
// max-width / max-height 与 diy-graphic-nav 的写法保持一致, 用于兜底夹住尺寸,
|
||||
// 保证图片不会超出后台配置的大小。
|
||||
imageInnerStyle(item) {
|
||||
const size = this.resolveItemImgSize(item);
|
||||
const w = this.rpxVal(size.width);
|
||||
const h = this.rpxVal(size.height);
|
||||
return 'width:' + w + ';height:' + h + ';max-width:' + w + ';max-height:' + h + ';';
|
||||
},
|
||||
|
||||
// ========== PR-FRONTEND-DIY-SCROLLBAR (2026-09-18): H5 "滑动时显示"滚动条控制 ==========
|
||||
// 背景: H5 端 scroll-view 的横向滚动条默认被 CSS 隐藏; "滑动时显示"需要监听 scroll,
|
||||
// 滚动中给容器加 is-scrolling 类展示滚动条, 停止滚动 800ms 后移除类再隐藏。
|
||||
// "始终显示/永不显示"为纯 CSS 类控制(scrollbar-always/scrollbar-never), 无需 JS。
|
||||
bindSlideScrollbar() {
|
||||
// #ifdef H5
|
||||
if (this._slideScrollBound) return;
|
||||
// 挂载瞬间若还没拿到滚动容器,直接 return 不标记已绑定;
|
||||
// ensureSlideEls() 会在用户首次交互时重试(见 emit 处),不会永久失效。
|
||||
var el = this.getSlideContainer();
|
||||
if (!el) return;
|
||||
this._slideScrollEl = el;
|
||||
this._slideScrollBound = true;
|
||||
var self = this;
|
||||
this._onSlideScroll = function() {
|
||||
if (self.scrollBarMode != 'slide') return;
|
||||
if (!self.slideScrolling) self.slideScrolling = true;
|
||||
clearTimeout(self._slideScrollTimer);
|
||||
self._slideScrollTimer = setTimeout(function() {
|
||||
self.slideScrolling = false;
|
||||
}, 800);
|
||||
};
|
||||
el.addEventListener('scroll', this._onSlideScroll, { passive: true });
|
||||
// #endif
|
||||
},
|
||||
unbindSlideScrollbar() {
|
||||
// #ifdef H5
|
||||
if (this._slideScrollEl && this._onSlideScroll) {
|
||||
this._slideScrollEl.removeEventListener('scroll', this._onSlideScroll);
|
||||
}
|
||||
clearTimeout(this._slideScrollTimer);
|
||||
this._slideScrollEl = null;
|
||||
this._onSlideScroll = null;
|
||||
this._slideScrollBound = false;
|
||||
this.slideScrolling = false;
|
||||
// #endif
|
||||
},
|
||||
|
||||
// 统一的 scroll 事件处理(模板 @scroll 绑定, 小程序/H5 共用)
|
||||
// · 两端:"滑动时显示"模式 → 维护 slideScrolling(滚动中标记, H5 用于 is-scrolling 类)
|
||||
// · 小程序端: 驱动自定义滚动条 thumb 位置(原生 show-scrollbar 被忽略, 改用自绘)
|
||||
onSlideScroll(e) {
|
||||
if (this.scrollBarMode === 'slide') {
|
||||
if (!this.slideScrolling) this.slideScrolling = true;
|
||||
clearTimeout(this._slideScrollTimer);
|
||||
this._slideScrollTimer = setTimeout(() => {
|
||||
this.slideScrolling = false;
|
||||
}, 800);
|
||||
}
|
||||
// #ifdef MP
|
||||
// 首次滚动时若还没拿到尺寸, 先测量一次(图片尺寸由内联样式决定, 渲染后即稳定)
|
||||
if (!this.mpScroll.viewW || !this.mpScroll.contentW) this.measureScrollbar();
|
||||
// scroll-view 的 scroll 事件 detail 自带真实 scrollWidth(小程序原生返回),
|
||||
// 只要它比当前记录的更大(内容更长), 就更新 —— 保证滚动条长度比例准确
|
||||
if (e && e.detail && typeof e.detail.scrollWidth === 'number'
|
||||
&& e.detail.scrollWidth > this.mpScroll.contentW) {
|
||||
this.mpScroll.contentW = e.detail.scrollWidth;
|
||||
}
|
||||
let left = 0;
|
||||
if (e && e.detail && typeof e.detail.scrollLeft === 'number') left = e.detail.scrollLeft;
|
||||
this.mpScroll.left = left;
|
||||
// #endif
|
||||
},
|
||||
|
||||
// 小程序端: 测量 scroll-view 视口宽度与内容宽度(供自定义滚动条计算 thumb)
|
||||
//
|
||||
// ⚠️ fix (2026-09-22) 「始终显示水平滚动条」在小程序端不生效的根因:
|
||||
// 原实现只取 .uni-scroll-view-content 的 width 当"内容宽度"。但在 mp-weixin 中,
|
||||
// 该 view 是块级/flex 容器, 宽度恒等于 scroll-view 宽度(子项只是溢出它而不是撑开它),
|
||||
// 于是 contentW 永远 == viewW → showCustomScrollbar / scrollbarThumbStyle 判定
|
||||
// "内容没有溢出" → 滚动条永不渲染(后台选"始终显示"也无效)。
|
||||
// 现改为三级取样, 取到即可用, 且已被测得的有效值不会被后续空测量覆盖:
|
||||
// ① scroll-view 的 scrollOffset.scrollWidth —— WeChat 原生返回的真实滚动区宽度(首选, 含内边距)
|
||||
// ② 全部 .image-nav-item 的 rect 跨度 max(right) - min(left) + 左右内边距 —— 最可靠的 DOM 兜底
|
||||
// ③ 按后台下发的图片/文本尺寸累加推算(rpx → px) —— 极端情况(查询全部失败)下兜底
|
||||
measureScrollbar() {
|
||||
// #ifdef MP
|
||||
if (!uni || !uni.createSelectorQuery) return;
|
||||
var self = this;
|
||||
var query = uni.createSelectorQuery().in(this);
|
||||
query.select('.image-nav').fields({ size: true, scrollOffset: true });
|
||||
query.selectAll('.image-nav-item').boundingClientRect();
|
||||
query.exec(function(res) {
|
||||
var view = res && res[0];
|
||||
if (!view) return;
|
||||
var viewW = view.width || 0;
|
||||
var items = res && res[1];
|
||||
|
||||
// ① 原生 scrollWidth
|
||||
var contentW = view.scrollWidth || 0;
|
||||
|
||||
// ② 首尾 item 的 rect 跨度(与当前滚动位置无关: 两端同步平移, 差值稳定)
|
||||
if (contentW <= viewW && items && items.length) {
|
||||
var minLeft = Infinity;
|
||||
var maxRight = -Infinity;
|
||||
for (var i = 0; i < items.length; i++) {
|
||||
var r = items[i];
|
||||
if (!r) continue;
|
||||
if (r.left < minLeft) minLeft = r.left;
|
||||
if (r.right > maxRight) maxRight = r.right;
|
||||
}
|
||||
if (maxRight > minLeft) {
|
||||
var padPx = (uni.upx2px ? uni.upx2px(16) : 8) * 2; // .image-nav 左右各 16rpx
|
||||
var spanW = (maxRight - minLeft) + padPx;
|
||||
if (spanW > contentW) contentW = spanW;
|
||||
}
|
||||
}
|
||||
|
||||
// ③ 数据推算兜底
|
||||
if (!contentW) contentW = self.estimateContentWidthPx();
|
||||
|
||||
self.mpScroll.viewW = viewW;
|
||||
// 有效值只增不减: 避免后一次空测量把已测得的宽度清零(会导致滚动条突然消失)
|
||||
if (contentW > 0) self.mpScroll.contentW = contentW;
|
||||
else if (!self.mpScroll.contentW) self.mpScroll.contentW = 0;
|
||||
self.mpScroll.left = view.scrollLeft || 0;
|
||||
});
|
||||
// #endif
|
||||
},
|
||||
|
||||
// 小程序端: 按后台下发的尺寸推算内容总宽度(rpx → px), 仅在 DOM 测量失败时兜底
|
||||
estimateContentWidthPx() {
|
||||
// #ifdef MP
|
||||
const list = (this.value && this.value.list) || [];
|
||||
if (!list.length) return 0;
|
||||
const cfg = this.imageSpacingConfig;
|
||||
const gap = cfg.horizontal === null ? 28 : cfg.horizontal;
|
||||
let totalRpx = 32; // 容器左右 padding(16rpx × 2)
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
if (this.value.mode == 'text') {
|
||||
const w = Number(list[i] && list[i].imgWidth);
|
||||
totalRpx += (!isNaN(w) && w > 0) ? w / 2 : 0;
|
||||
} else {
|
||||
totalRpx += this.resolveItemImgSize(list[i]).width;
|
||||
}
|
||||
totalRpx += gap;
|
||||
}
|
||||
let winW = 375;
|
||||
try {
|
||||
if (uni && uni.getSystemInfoSync) winW = uni.getSystemInfoSync().windowWidth || 375;
|
||||
} catch (e) {}
|
||||
return totalRpx * winW / 750;
|
||||
// #endif
|
||||
},
|
||||
|
||||
// 页面跳转
|
||||
redirectTo(link) {
|
||||
if (!link.wap_url || this.$util.getCurrRoute() != this.$util.MEMBER_PAGE_URL || this.storeToken) {
|
||||
@@ -115,12 +665,224 @@ export default {
|
||||
// 轮播切换
|
||||
swiperChange(event) {
|
||||
this.swiperCurrent = event.detail.current;
|
||||
},
|
||||
|
||||
// ========== H5 singleSlide 鼠标拖拽支持 ==========
|
||||
// 背景:uni-app 的 scroll-view 在 H5 端被编译为 div,虽然 overflow-x: auto 可让
|
||||
// 浏览器渲染横向滚动条,但 scrollLeft 不响应鼠标拖拽(uni 的滚动逻辑不监听 mouse)。
|
||||
// 因此 H5 下需要手动绑定 mousedown/mousemove/mouseup,模拟拖拽改变 scrollLeft。
|
||||
// 同时绑定 wheel,让鼠标滚轮也能横向滚动(浏览器默认滚轮是垂直,需 preventDefault 后手动改 scrollLeft)。
|
||||
// 仅在 singleSlide 模式下生效;fixed / pageSlide 走原逻辑。
|
||||
//
|
||||
// 关键设计:H5 专属事件全部在 mounted 中通过 addEventListener 绑定,而不是写在模板上,
|
||||
// 避免小程序/鸿蒙端产生"未知事件"编译警告。所有端共用同一份模板。
|
||||
bindSlideMouseEvents() {
|
||||
// #ifdef H5
|
||||
// 防止重复绑定
|
||||
if (this._slideEventsBound) return;
|
||||
// 注意:这里不再要求"挂载那一刻就能拿到滚动容器"再去绑定监听。
|
||||
// 之前只要 getSlideContainer() 返回 null(mounted 时 DOM/样式尚未就绪就会发生),
|
||||
// 就直接 return 且不再重试 → 整个拖拽能力静默失效(鼠标怎么拖都不动)。
|
||||
// 现在:监听一律先绑上,元素在每次事件里按需解析(见 ensureSlideEls)。
|
||||
this._slideEventsBound = true;
|
||||
// document 级别 capture 阶段,先于 uni-app 内部的滚动库触发
|
||||
document.addEventListener('mousedown', this.onSlideMouseDown, true);
|
||||
document.addEventListener('wheel', this.onSlideWheel, { passive: false, capture: true });
|
||||
// click 拦截:如果在 mousemove 中真的拖动了容器(mousedown 后 deltaX > 5),
|
||||
// mouseup 时进入"忽略接下来一次 click"状态,防止拖拽结束后误触发跳转。
|
||||
document.addEventListener('click', this.onSlideMaybeClick, true);
|
||||
window.addEventListener('mousemove', this.onSlideMouseMove);
|
||||
window.addEventListener('mouseup', this.onSlideMouseUp);
|
||||
// #endif
|
||||
},
|
||||
unbindSlideMouseEvents() {
|
||||
// #ifdef H5
|
||||
document.removeEventListener('mousedown', this.onSlideMouseDown, true);
|
||||
document.removeEventListener('wheel', this.onSlideWheel, true);
|
||||
document.removeEventListener('click', this.onSlideMaybeClick, true);
|
||||
window.removeEventListener('mousemove', this.onSlideMouseMove);
|
||||
window.removeEventListener('mouseup', this.onSlideMouseUp);
|
||||
this._slideOuterEl = null;
|
||||
this._slideEventsBound = false;
|
||||
// #endif
|
||||
},
|
||||
// 本组件实例的根元素(<view data-component-name="diy-image-nav">)
|
||||
//
|
||||
// ⚠️ 必须用 this.$el 限定在"本实例"内查找元素!
|
||||
// 历史实现用 document.querySelector('[data-component-name="diy-image-nav"]'),
|
||||
// 而同一个页面可以放多个滑动图组件(如 首页的 合作伙伴 + 证书资质 + 服务资质),
|
||||
// document.querySelector 永远只返回页面上的**第一个**实例 ——
|
||||
// 于是拖拽/滚轮第 2、3 个组件时,"指针是否在容器内"用的是第 1 个组件的位置,
|
||||
// 判断不通过直接 return → 表现就是"鼠标拖不动、滚轮也没反应"。
|
||||
getSlideRootEl() {
|
||||
// #ifdef H5
|
||||
var el = this.$el;
|
||||
if (el && el.nodeType === 1) return el;
|
||||
return null;
|
||||
// #endif
|
||||
},
|
||||
// 用于判断 mousedown/wheel 是否落在容器内(bounding box)
|
||||
getSlideOuterEl() {
|
||||
// #ifdef H5
|
||||
return this.getSlideRootEl();
|
||||
// #endif
|
||||
},
|
||||
getSlideContainer() {
|
||||
// #ifdef H5
|
||||
// uni-app 的 scroll-view 在 H5 端编译为 <uni-scroll-view> 自定义元素,
|
||||
// 真正的滚动 div 是内部的 .uni-scroll-view。这里在**本实例范围内**查找:
|
||||
// ① 优先"内容宽度 > 可视宽度"判定真滚动容器(与 overflow 写法无关, 最可靠)
|
||||
// ② 其次 overflow-x: auto/scroll
|
||||
// ③ 再退化为最后一个 .uni-scroll-view
|
||||
// ④ 最后退化到 .uni-scroll-view-content 的父元素
|
||||
var root = this.getSlideRootEl();
|
||||
if (!root) return null;
|
||||
var candidates = root.querySelectorAll('.uni-scroll-view');
|
||||
var i;
|
||||
for (i = 0; i < candidates.length; i++) {
|
||||
if (candidates[i].scrollWidth > candidates[i].clientWidth + 1) return candidates[i];
|
||||
}
|
||||
for (i = 0; i < candidates.length; i++) {
|
||||
var s = getComputedStyle(candidates[i]).overflowX;
|
||||
if (s === 'auto' || s === 'scroll') return candidates[i];
|
||||
}
|
||||
if (candidates.length > 0) return candidates[candidates.length - 1];
|
||||
var content = root.querySelector('.uni-scroll-view-content');
|
||||
if (content && content.parentElement) return content.parentElement;
|
||||
return root.querySelector('uni-scroll-view');
|
||||
// #endif
|
||||
},
|
||||
// 按需解析本实例的"根元素 + 真滚动容器"(挂载时机不确定, 统一走这里)
|
||||
ensureSlideEls() {
|
||||
// #ifdef H5
|
||||
var root = this.getSlideRootEl();
|
||||
if (!root) return false;
|
||||
this._slideOuterEl = root;
|
||||
var el = this.getSlideContainer();
|
||||
if (!el) return false;
|
||||
this._slideEl = el;
|
||||
// 滚动条显隐依赖真滚动容器的 scroll 事件:mounted 时若还没拿到容器,
|
||||
// 这里补绑一次(否则"滑动时显示滚动条"也会失效)。
|
||||
if (!this._slideScrollBound) this.bindSlideScrollbar();
|
||||
return true;
|
||||
// #endif
|
||||
},
|
||||
onSlideMouseDown(e) {
|
||||
// #ifdef H5
|
||||
if (this.value.showStyle != 'singleSlide') return;
|
||||
// document 级别监听,只处理落在"本实例"容器内的事件
|
||||
// 关键:e.target 可能是 HTML 本身(uni 内部事件重定向导致),
|
||||
// 所以用 clientX/clientY 判断是否落在容器 bounding box 内。
|
||||
if (!this.ensureSlideEls()) return;
|
||||
var rect = this._slideOuterEl.getBoundingClientRect();
|
||||
if (!rect) return;
|
||||
var x = e.clientX, y = e.clientY;
|
||||
if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) return;
|
||||
var el = this._slideEl;
|
||||
if (!el) return;
|
||||
this.slideIsDragging = true;
|
||||
this.slideStartX = x;
|
||||
this.slideStartScrollLeft = el.scrollLeft;
|
||||
this.slideDidDrag = false; // mousedown 时清零:5px 阈值后才置 true
|
||||
this._suppressNextClick = false;
|
||||
if (e.preventDefault) e.preventDefault();
|
||||
// 注意:这里不调 stopPropagation,否则纯点击也不能触发 click/tap → 跳转
|
||||
// #endif
|
||||
},
|
||||
onSlideMouseMove(e) {
|
||||
// #ifdef H5
|
||||
if (!this.slideIsDragging) return;
|
||||
var el = this._slideEl;
|
||||
if (!el) return;
|
||||
var x = (e.clientX != null) ? e.clientX : 0;
|
||||
var deltaX = x - this.slideStartX;
|
||||
// 5px 阈值:超过后标记已经拖动,后续 mouseup 会忽略接下来一次 click
|
||||
if (!this.slideDidDrag && Math.abs(deltaX) >= 5) {
|
||||
this.slideDidDrag = true;
|
||||
}
|
||||
// 反向:手指/鼠标往右拖 → 内容向右滚 → scrollLeft 减小
|
||||
el.scrollLeft = this.slideStartScrollLeft - deltaX;
|
||||
if (e.preventDefault) e.preventDefault();
|
||||
// #endif
|
||||
},
|
||||
onSlideMouseUp() {
|
||||
// #ifdef H5
|
||||
this.slideIsDragging = false;
|
||||
// 如果确实拖动过,标记接下来一次 click 应当被拦截(防止拖拽结束后误触发跳转)
|
||||
if (this.slideDidDrag) {
|
||||
this._suppressNextClick = true;
|
||||
}
|
||||
// #endif
|
||||
},
|
||||
// click 拦截:如果 mouseup 时设置了 _suppressNextClick,就拦截这一次 click 并清除标记
|
||||
onSlideMaybeClick(e) {
|
||||
// #ifdef H5
|
||||
if (!this._suppressNextClick) return;
|
||||
if (!e.target) return;
|
||||
var outer = this._slideOuterEl || this.getSlideOuterEl();
|
||||
if (!outer || !outer.contains(e.target)) return;
|
||||
this._suppressNextClick = false;
|
||||
if (e.preventDefault) e.preventDefault();
|
||||
if (e.stopPropagation) e.stopPropagation();
|
||||
if (e.stopImmediatePropagation) e.stopImmediatePropagation();
|
||||
// #endif
|
||||
},
|
||||
onSlideWheel(e) {
|
||||
// #ifdef H5
|
||||
if (this.value.showStyle != 'singleSlide') return;
|
||||
// 同 mouseDown:用 clientX/clientY 判断 wheel 是否落在"本实例"容器内
|
||||
if (!this.ensureSlideEls()) return;
|
||||
var rect = this._slideOuterEl.getBoundingClientRect();
|
||||
if (!rect) return;
|
||||
var x = e.clientX, y = e.clientY;
|
||||
if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) return;
|
||||
var el = this._slideEl;
|
||||
if (!el) return;
|
||||
// 浏览器 wheel 事件的 deltaY 是垂直方向;此处把垂直滚轮映射到横向滚动
|
||||
var dx = e.deltaX || 0;
|
||||
var dy = e.deltaY || 0;
|
||||
// 优先用 deltaX(触控板横向 / Shift+滚轮),否则用 deltaY(普通滚轮 → 转横向)
|
||||
var step = dx !== 0 ? dx : dy;
|
||||
el.scrollLeft += step;
|
||||
if (e.preventDefault) e.preventDefault();
|
||||
if (e.stopPropagation) e.stopPropagation();
|
||||
// #endif
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
// 包裹 scroll-view 的容器(相对定位, 自定义滚动条绝对定位于其底部)
|
||||
.image-nav-wrap {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
// 小程序端自定义水平滚动条(MP 原生 show-scrollbar 被忽略, 改用自绘,
|
||||
// 与 H5 的 CSS 伪元素滚动条视觉一致; 元素仅在 #ifdef MP 下渲染)
|
||||
.img-nav-scrollbar {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 2rpx;
|
||||
height: 4rpx;
|
||||
background-color: rgba(0, 0, 0, 0.12);
|
||||
border-radius: 2rpx;
|
||||
z-index: 2;
|
||||
pointer-events: none;
|
||||
overflow: hidden;
|
||||
}
|
||||
.img-nav-scrollbar-thumb {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
height: 4rpx;
|
||||
background-color: rgba(0, 0, 0, 0.4);
|
||||
border-radius: 2rpx;
|
||||
transition: transform 0.08s linear;
|
||||
}
|
||||
|
||||
.image-nav {
|
||||
padding: 16rpx;
|
||||
box-sizing: border-box;
|
||||
@@ -140,6 +902,80 @@ export default {
|
||||
.image-nav-item {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
// ========== H5 singleSlide 鼠标拖拽支持:横向滚动 ==========
|
||||
// uni-app 在 H5 端会把 scroll-view 编译为 div,但默认样式不一定是
|
||||
// overflow-x:auto → 横向内容溢出后无法滚动。需要显式声明。
|
||||
// #ifdef H5
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
// 拖拽手势提示(桌面端鼠标用户能看出这一行是可以拖动的)
|
||||
cursor: grab;
|
||||
&:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
// 本行是 <uni-scroll-view> 自定义元素,真正产生滚动的是内部 div.uni-scroll-view,
|
||||
// 这里同步声明,保证内层容器一定是"可横向滚动"的(鼠标拖拽/滚轮/触屏滑动都依赖它)
|
||||
::v-deep .uni-scroll-view {
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
}
|
||||
// 禁止鼠标选中文字(拖拽时选中会显得很别扭)
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
// 拖拽时关闭过渡,避免 Chrome 的惯性滚动与 JS 抢控制权
|
||||
-webkit-overflow-scrolling: touch;
|
||||
|
||||
// ========== PR-FRONTEND-DIY-SCROLLBAR (2026-09-18): 水平滚动条显隐三态 ==========
|
||||
// 默认态(滑动时显示的静止态 / 永不显示): 隐藏滚动条,视觉上仍保持单页布局;
|
||||
// 用户用鼠标拖拽/滚轮即可滚动(滚动能力不受滚动条显隐影响)
|
||||
scrollbar-width: none; // Firefox
|
||||
-ms-overflow-style: none; // IE/Edge legacy
|
||||
&::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
// uni scroll-view 在 H5 编译后真滚动容器是内层 .uni-scroll-view, 同步隐藏
|
||||
::v-deep .uni-scroll-view {
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
}
|
||||
::v-deep .uni-scroll-view::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
// "始终显示" 与 "滑动时显示"(滚动中, 由 is-scrolling 类驱动): 展示细滚动条
|
||||
&.scrollbar-always,
|
||||
&.scrollbar-slide.is-scrolling {
|
||||
scrollbar-width: thin; // Firefox
|
||||
scrollbar-color: rgba(0, 0, 0, 0.25) transparent;
|
||||
&::-webkit-scrollbar {
|
||||
display: block;
|
||||
height: 4px;
|
||||
}
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background-color: rgba(0, 0, 0, 0.25);
|
||||
border-radius: 2px;
|
||||
}
|
||||
&::-webkit-scrollbar-track {
|
||||
background-color: transparent;
|
||||
}
|
||||
::v-deep .uni-scroll-view {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: rgba(0, 0, 0, 0.25) transparent;
|
||||
}
|
||||
::v-deep .uni-scroll-view::-webkit-scrollbar {
|
||||
display: block;
|
||||
height: 4px;
|
||||
}
|
||||
::v-deep .uni-scroll-view::-webkit-scrollbar-thumb {
|
||||
background-color: rgba(0, 0, 0, 0.25);
|
||||
border-radius: 2px;
|
||||
}
|
||||
::v-deep .uni-scroll-view::-webkit-scrollbar-track {
|
||||
background-color: transparent;
|
||||
}
|
||||
}
|
||||
// #endif
|
||||
}
|
||||
|
||||
&.pageSlide {
|
||||
@@ -203,6 +1039,15 @@ export default {
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 90rpx;
|
||||
overflow: hidden;
|
||||
|
||||
// PR-FRONTEND-DIY-IMAGE-NAV-IMG-SIZE (2026-09-22):
|
||||
// 兜底夹住图片尺寸(不设 width/height:100%, 避免外层盒尺寸异常时高度塌成 0
|
||||
// 导致图片完全不显示)。正常尺寸由 imageInnerStyle 输出的内联样式决定。
|
||||
.image-content {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
}
|
||||
|
||||
.tag {
|
||||
position: absolute;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<block v-if="imgAdsValue.list.length == 1">
|
||||
<view class="simple-graph-wrap" :style="imgAdsSwiper" @tap.stop="handlerClick(imgAdsValue.list[0].link)">
|
||||
<image :style="{ height: imgAdsValue.list[0].imgHeight }"
|
||||
:src="$util.img(imgAdsValue.list[0].imageUrl)" mode="widthFix" :show-menu-by-longpress="true" />
|
||||
:src="$util.img(imgAdsValue.list[0].imageUrl)" mode="widthFix" show-menu-by-longpress />
|
||||
</view>
|
||||
</block>
|
||||
<swiper v-else class="swiper" :style="{ height: swiperHeight }" :class="{
|
||||
@@ -18,7 +18,7 @@
|
||||
:key="index" v-if="item.imageUrl" @tap.stop="handlerClick(item.link)">
|
||||
<view class="item" :style="imgAdsSwiper + 'height: ' + item.imgHeight">
|
||||
<image :src="$util.img(item.imageUrl)" :mode="item.imageMode || 'scaleToFill'"
|
||||
:show-menu-by-longpress="true" />
|
||||
show-menu-by-longpress />
|
||||
</view>
|
||||
</swiper-item>
|
||||
</swiper>
|
||||
|
||||
@@ -58,9 +58,9 @@
|
||||
:key="index" @tap.stop="toCateGoodsList(item.category_id_2, 2)">
|
||||
<view class="item-box">
|
||||
<image :src="$util.img(item.image)" v-if="item.image"
|
||||
mode="aspectFill" />
|
||||
mode="aspectFill" show-menu-by-longpress/>
|
||||
<image :src="$util.getDefaultImage().goods" v-else
|
||||
mode="aspectFill" />
|
||||
mode="aspectFill" show-menu-by-longpress/>
|
||||
<view>{{ item.category_name }}</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -73,9 +73,9 @@
|
||||
:key="index" @tap.stop="toCateGoodsList(item.category_id_2, 2)">
|
||||
<view class="item-box">
|
||||
<image :src="$util.img(item.image)" v-if="item.image"
|
||||
mode="aspectFill" />
|
||||
mode="aspectFill" show-menu-by-longpress/>
|
||||
<image :src="$util.getDefaultImage().goods" v-else
|
||||
mode="aspectFill" />
|
||||
mode="aspectFill" show-menu-by-longpress/>
|
||||
<view>{{ item.category_name }}</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -88,7 +88,7 @@
|
||||
:key="index" v-if="index >= (page - 1) * 10 && index < page * 10"
|
||||
@tap.stop="toCateGoodsList(item.category_id_2, 2)">
|
||||
<view class="item-box">
|
||||
<image :src="item.image" mode="aspectFill" />
|
||||
<image :src="item.image" mode="aspectFill" show-menu-by-longpress/>
|
||||
<view>{{ item.category_name }}</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -104,19 +104,19 @@
|
||||
|
||||
<!-- 分类广告 -->
|
||||
<image class="category_adv" v-if="cateList[pageIndex].image_adv"
|
||||
:src="$util.img(cateList[pageIndex].image_adv)" mode="widthFix" />
|
||||
:src="$util.img(cateList[pageIndex].image_adv)" mode="widthFix" show-menu-by-longpress/>
|
||||
|
||||
<view class="goods-list double-column" v-if="goodsList[pageIndex].list.length">
|
||||
<view class="goods-item" v-for="(item, index) in goodsList[pageIndex].list"
|
||||
:key="index" @tap.stop="toDetail(item)">
|
||||
<view class="goods-img">
|
||||
<image :src="goodsImg(item.goods_image)" mode="widthFix"
|
||||
@error="imgError(index)" />
|
||||
@error="imgError(index)" show-menu-by-longpress/>
|
||||
<view class="color-base-bg goods-tag"
|
||||
v-if="value.goodsTag == 'default' && goodsTag(item) != ''">{{
|
||||
goodsTag(item) }}</view>
|
||||
<view class="goods-tag-img" v-if="value.goodsTag == 'diy'">
|
||||
<image :src="$util.img(value.tagImg.imageUrl)" />
|
||||
<image :src="$util.img(value.tagImg.imageUrl)" show-menu-by-longpress/>
|
||||
</view>
|
||||
</view>
|
||||
<view class="info-wrap">
|
||||
@@ -133,11 +133,11 @@
|
||||
<view class="member-price-tag"
|
||||
v-if="item.member_price && item.member_price == showPrice(item)">
|
||||
<image :src="$util.img('public/uniapp/index/VIP.png')"
|
||||
mode="widthFix" />
|
||||
mode="widthFix" show-menu-by-longpress/>
|
||||
</view>
|
||||
<view class="member-price-tag" v-else-if="item.promotion_type == 1">
|
||||
<image :src="$util.img('public/uniapp/index/discount.png')"
|
||||
mode="widthFix" />
|
||||
mode="widthFix" show-menu-by-longpress/>
|
||||
</view>
|
||||
</view>
|
||||
<view class="pro-info">
|
||||
@@ -146,14 +146,14 @@
|
||||
<text class="unit">{{ $lang('common.currencySymbol') }}</text>
|
||||
<text>{{ showMarketPrice(item) }}</text>
|
||||
</view>
|
||||
<view class="sale font-size-activity-tag color-tip">已售{{
|
||||
item.sale_num }}{{ item.unit ? item.unit : '件' }}</view>
|
||||
<view class="sale font-size-activity-tag color-tip">{{
|
||||
$lang('components-diy.diy-index-page.soldCount', { count: item.sale_num, unit: item.unit || $lang('components-diy.diy-index-page.soldUnit') }) }}</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
<view v-if="!isloading && goodsList[pageIndex].list.length == 0">
|
||||
<ns-empty text="该分类下暂无商品" :isIndex="false"></ns-empty>
|
||||
<ns-empty :text="$lang('components-diy.diy-index-page.noGoodsInCategory')" :isIndex="false"></ns-empty>
|
||||
</view>
|
||||
</block>
|
||||
</mescroll-uni>
|
||||
@@ -193,7 +193,7 @@ export default {
|
||||
pageIndex: 0, //当前选中分类id
|
||||
cateList: [{
|
||||
//header分类
|
||||
category_name: '首页'
|
||||
category_name: ''
|
||||
}],
|
||||
twoCategorylist: [], //二级分类
|
||||
twoCategorylistId: 0, //二级分类所在的swiper
|
||||
@@ -258,6 +258,9 @@ export default {
|
||||
return data;
|
||||
}
|
||||
},
|
||||
created() {
|
||||
this.cateList[0].category_name = this.$lang('components-diy.diy-index-page.home');
|
||||
},
|
||||
watch: {
|
||||
type(newVal, oldVal) {
|
||||
if (newVal) {
|
||||
@@ -323,7 +326,7 @@ export default {
|
||||
let obj = {
|
||||
list: []
|
||||
};
|
||||
obj.category_name = this.value.title ? this.value.title : '首页';
|
||||
obj.category_name = this.value.title ? this.value.title : this.$lang('components-diy.diy-index-page.home');
|
||||
arr.push(obj);
|
||||
this.cateList = arr.concat(res.data);
|
||||
Object.keys(this.cateList).forEach((key, index) => {
|
||||
|
||||
@@ -3,18 +3,23 @@
|
||||
<view class="fui-list-group merchgroup" v-for="(item, index) in value.list" :key="index">
|
||||
<view class="fui-list jump" v-if="index == 0">
|
||||
<view class="fui-list-media">
|
||||
<image class="round" :src="$util.img(item.imageUrl)" style="border-radius:6rpx"></image>
|
||||
<image class="round" :src="$util.img(item.imageUrl)" style="border-radius:6rpx" show-menu-by-longpress></image>
|
||||
</view>
|
||||
<view class="fui-list-inner">
|
||||
<view class="title" style="height: 75rpx;">
|
||||
<text style="font-weight:600" :style="{ color: item.textColor }">{{ item.title }}</text>
|
||||
<view class="subtitle" style="font-size:24rpx" :style="{ color: item.textColor }">{{ item.desc }}
|
||||
</view>
|
||||
<view class="title">
|
||||
<text class="title-text" :style="titleStyle(item)">{{ item.title }}</text>
|
||||
<view class="subtitle" :style="descStyle(item)">{{ item.desc }}</view>
|
||||
<!-- #ifndef H5 -->
|
||||
<!-- PR-DIY-KEFU-ONE-LINE (2026-09-17): 小程序端隐藏测量节点, 以默认字号实测文本宽度, 反推一行能放下的最大字号 -->
|
||||
<text class="measure-text measure-title" style="font-size:28rpx;">{{ item.title }}</text>
|
||||
<text class="measure-text measure-desc" style="font-size:24rpx;">{{ item.desc }}</text>
|
||||
<!-- #endif -->
|
||||
</view>
|
||||
</view>
|
||||
<view class="fui-remark jump" style="padding-right: 20rpx; text-align: center; line-height: 140rpx;">
|
||||
<!-- PR-DIY-KEFU-ONE-LINE (2026-09-17): 按钮颜色未配置时不再渲染/占位, 避免透明按钮挤窄文字区 -->
|
||||
<view class="fui-remark jump" v-if="item.BtBgColor || item.BtColor" style="padding-right: 20rpx; text-align: center; line-height: 140rpx;">
|
||||
<span style="font-size:24rpx;padding: 14rpx 18rpx;border-radius:8rpx"
|
||||
:style="{ background: item.BtBgColor, color: item.BtColor }" @tap.stop="previewSqs()">立即添加</span>
|
||||
:style="{ background: item.BtBgColor, color: item.BtColor }" @tap.stop="previewSqs()">{{ $lang('components-diy.diy-kefu.addNow') }}</span>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -35,15 +40,31 @@ export default {
|
||||
data() {
|
||||
return {
|
||||
loading: true,
|
||||
// PR-DIY-KEFU-ONE-LINE (2026-09-17): 小程序端实测得出的一行自适应字号(rpx), 0 表示用默认字号
|
||||
mpTitleSize: 0,
|
||||
mpDescSize: 0
|
||||
};
|
||||
},
|
||||
created() {
|
||||
// this.getDataList();
|
||||
},
|
||||
// PR-DIY-KEFU-ONE-LINE (2026-09-17): 英文公司名等长标题一行完整展示(不换行、不省略)
|
||||
// H5: 挂载/数据变化后实测每个文本的溢出宽度, 逐级缩小 font-size 直到恰好一行放下 —— 保证无省略号;
|
||||
// 小程序端无法测 DOM, 用字符宽度估算兜底(CJK 1em / 其他 0.6em), 极端超长时仍有省略号兜底
|
||||
mounted() {
|
||||
this.$nextTick(this.fitOneLineText)
|
||||
},
|
||||
watch: {
|
||||
// 组件刷新监听
|
||||
componentRefresh: function (nval) {
|
||||
// this.getDataList();
|
||||
this.$nextTick(this.fitOneLineText)
|
||||
},
|
||||
value: {
|
||||
deep: true,
|
||||
handler() {
|
||||
this.$nextTick(this.fitOneLineText)
|
||||
}
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
@@ -66,9 +87,130 @@ export default {
|
||||
current: img,
|
||||
urls: [img]
|
||||
})
|
||||
},
|
||||
// PR-DIY-KEFU-ONE-LINE (2026-09-17): 单行自适应 —— 标题/描述一行完整展示(不换行), 字号取一行能放下的最大值
|
||||
// #ifdef H5
|
||||
fitOneLineText() {
|
||||
this.$nextTick(() => {
|
||||
const root = this.$el && this.$el.querySelectorAll ? this.$el : null
|
||||
if (!root) return
|
||||
const nodes = root.querySelectorAll('.title-text, .subtitle')
|
||||
nodes.forEach((el) => {
|
||||
// 先还原 CSS 默认字号, 再实测是否溢出; 目标宽度留 3px 右侧空隙, 不贴边
|
||||
el.style.fontSize = ''
|
||||
let size = parseFloat(window.getComputedStyle(el).fontSize)
|
||||
const MIN_PX = 10 // 下限 10px, 再小可读性太差
|
||||
const target = el.clientWidth - 3
|
||||
let guard = 0
|
||||
while (el.scrollWidth > target && size > MIN_PX && guard < 60) {
|
||||
size -= 0.5
|
||||
el.style.fontSize = size + 'px'
|
||||
guard++
|
||||
}
|
||||
})
|
||||
})
|
||||
},
|
||||
// #endif
|
||||
// #ifndef H5
|
||||
// 小程序端: 隐藏测量节点以默认字号实测文本宽度, 宽度与字号成线性关系, 反推一行能放下的最大字号
|
||||
fitOneLineText() {
|
||||
uni.createSelectorQuery().in(this)
|
||||
.select('.fui-list-inner').boundingClientRect()
|
||||
.select('.measure-title').boundingClientRect()
|
||||
.select('.measure-desc').boundingClientRect()
|
||||
.exec((rects) => {
|
||||
if (!rects || !rects[0]) return
|
||||
const sys = uni.getSystemInfoSync()
|
||||
const pxPerRpx = (sys.windowWidth || 375) / 750
|
||||
// 可用宽度 = 文字区宽度 - 容器右内边距(8rpx) - 与右侧元素(按钮)之间留 8rpx 空隙
|
||||
const avail = rects[0].width - 16 * pxPerRpx
|
||||
if (avail <= 0) return
|
||||
// 标题: 默认 28rpx, 最小 16rpx
|
||||
if (rects[1] && rects[1].width > avail) {
|
||||
this.mpTitleSize = Math.max(16, Math.floor(28 * avail / rects[1].width))
|
||||
} else {
|
||||
this.mpTitleSize = 0
|
||||
}
|
||||
// 描述: 默认 24rpx, 最小 16rpx
|
||||
if (rects[2] && rects[2].width > avail) {
|
||||
this.mpDescSize = Math.max(16, Math.floor(24 * avail / rects[2].width))
|
||||
} else {
|
||||
this.mpDescSize = 0
|
||||
}
|
||||
})
|
||||
},
|
||||
// #endif
|
||||
titleStyle() {
|
||||
// #ifndef H5
|
||||
return this.mpTitleSize ? 'font-size:' + this.mpTitleSize + 'rpx;' : ''
|
||||
// #endif
|
||||
// #ifdef H5
|
||||
return ''
|
||||
// #endif
|
||||
},
|
||||
descStyle() {
|
||||
// #ifndef H5
|
||||
return this.mpDescSize ? 'font-size:' + this.mpDescSize + 'rpx;' : ''
|
||||
// #endif
|
||||
// #ifdef H5
|
||||
return ''
|
||||
// #endif
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="scss"></style>
|
||||
<style lang="scss">
|
||||
// 客服展示:标题/描述需要完整展示(中英文均不截断)
|
||||
// 全局 .fui-list-inner .title 有 nowrap + ellipsis + overflow:hidden,这里用更高优先级的选择器覆盖
|
||||
// PR-DIY-KEFU-ONE-LINE (2026-09-17): 标题/描述强制单行(配合 JS 自适应字号保证一行放得下), 超长省略号兜底
|
||||
.diy-kefu {
|
||||
.fui-list-group {
|
||||
.fui-list {
|
||||
align-items: center;
|
||||
|
||||
.fui-list-inner {
|
||||
overflow: hidden;
|
||||
min-width: 0;
|
||||
// 右侧留少量空隙, 避免单行文本贴着容器右边缘, 又能尽量铺满到按钮旁
|
||||
padding-right: 8rpx;
|
||||
box-sizing: border-box;
|
||||
|
||||
.title {
|
||||
height: auto;
|
||||
line-height: 1.4;
|
||||
|
||||
.title-text {
|
||||
display: block;
|
||||
font-size: 28rpx;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
display: block;
|
||||
margin-top: 6rpx;
|
||||
font-size: 24rpx;
|
||||
line-height: 1.4;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
}
|
||||
|
||||
// PR-DIY-KEFU-ONE-LINE (2026-09-17): 小程序端隐藏测量节点(不占布局、不可见)
|
||||
.measure-text {
|
||||
position: absolute;
|
||||
left: -9999rpx;
|
||||
top: 0;
|
||||
white-space: nowrap;
|
||||
visibility: hidden;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<view data-component-name="diy-listmenu" class="diy-listmenu" :style="style">
|
||||
<view class="fui-cell-group">
|
||||
<!-- <image mode="widthFix" style="width: 100%;" :src="$util.img(item.imageUrl)"></image> -->
|
||||
<!-- <image mode="widthFix" style="width: 100%;" :src="$util.img(item.imageUrl)" show-menu-by-longpress></image> -->
|
||||
|
||||
<view v-for="(item, index) in value.list" @tap.stop="redirectTo(item.link)" class="fui-cell"
|
||||
:class="item.iconType == 'img' ? 'img-cell' : ''">
|
||||
@@ -12,9 +12,10 @@
|
||||
style="border-radius:6rpx;width: 60rpx;"></image>
|
||||
</view>
|
||||
<view class="fui-cell-text" style="color:#333;">{{ item.title }}</view>
|
||||
<view class="fui-cell-remark" style="font-size: 24rpx;">{{ lang == 'en-us' ? 'view' : '查看' }}</view>
|
||||
<view class="fui-cell-remark" @tap.stop="redirectTo(item.link)" style="font-size: 24rpx;">{{ $lang('components-diy.diy-listmenu.view') }}</view>
|
||||
</view>
|
||||
</view>
|
||||
<ns-login ref="login"></ns-login>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
@@ -32,7 +33,6 @@ export default {
|
||||
data() {
|
||||
return {
|
||||
loading: true,
|
||||
lang: uni.getStorageSync("lang")//en-us 英文
|
||||
};
|
||||
},
|
||||
created() {
|
||||
@@ -63,7 +63,7 @@ export default {
|
||||
redirectTo(link) {
|
||||
if (link.wap_url) {
|
||||
if (this.$util.getCurrRoute() == this.$util.MEMBER_PAGE_URL && !this.storeToken) {
|
||||
this.$refs?.login?.open(link.wap_url);
|
||||
this.redirectTologin(link.wap_url)
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,12 +25,12 @@
|
||||
<block v-if="value.isShowAnchorInfo">
|
||||
<image
|
||||
:src="liveInfo.anchor_img != '' ? $util.img(liveInfo.anchor_img) : $util.getDefaultImage().head"
|
||||
class="anchor-img" @error="liveInfo.anchor_img = $util.getDefaultImage().head" />
|
||||
<text class="anchor-name">主播:{{ liveInfo.anchor_name }}</text>
|
||||
class="anchor-img" @error="liveInfo.anchor_img = $util.getDefaultImage().head" show-menu-by-longpress/>
|
||||
<text class="anchor-name">{{ $lang('components-diy.diy-live.anchorPrefix') }}{{ liveInfo.anchor_name }}</text>
|
||||
</block>
|
||||
<text class="separate" v-if="value.isShowAnchorInfo && value.isShowLiveGood">|</text>
|
||||
<block v-if="value.isShowLiveGood">
|
||||
<text class="goods-text">直播商品:{{ liveInfo.goods.length }}</text>
|
||||
<text class="goods-text">{{ $lang('components-diy.diy-live.goodsPrefix') }}{{ liveInfo.goods.length }}</text>
|
||||
</block>
|
||||
</view>
|
||||
</view>
|
||||
@@ -109,7 +109,6 @@ export default {
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
console.log('get live status', err);
|
||||
});
|
||||
|
||||
// 往后间隔1分钟或更慢的频率去轮询获取直播状态
|
||||
@@ -127,8 +126,7 @@ export default {
|
||||
clearInterval(timer);
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
console.log('get live status', err);
|
||||
.catch(err => {
|
||||
});
|
||||
}, 60000);
|
||||
// #endif
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
<div
|
||||
style="position:absolute;right:12rpx;bottom:48rpx;z-index:1;background:#4390FF;padding:0rpx 20rpx;border-radius:8rpx;color: #fff;"
|
||||
@tap.stop="handlerClick(item)">
|
||||
<span style="font-size:24rpx;color: #fff;">一键导航</span>
|
||||
<span style="font-size:24rpx;color: #fff;">{{ $lang('components-diy.diy-map.navigate') }}</span>
|
||||
</div>
|
||||
</map>
|
||||
</view>
|
||||
@@ -71,7 +71,7 @@ export default {
|
||||
uni.openLocation({
|
||||
latitude: parseFloat(item.lat),
|
||||
longitude: parseFloat(item.lng),
|
||||
name: "一键导航",
|
||||
name: this.$lang('components-diy.diy-map.navigate'),
|
||||
})
|
||||
},
|
||||
async handlerClick(item) {
|
||||
|
||||
@@ -6,16 +6,16 @@
|
||||
<view class="info-wrap" :style="infoStyle" v-if="memberInfo">
|
||||
<view class="headimg" @tap.stop="getWxAuth">
|
||||
<image :src="memberInfo.headimg ? $util.img(memberInfo.headimg) : $util.getDefaultImage().head"
|
||||
mode="widthFix" @error="memberInfo.headimg = $util.getDefaultImage().head" />
|
||||
mode="widthFix" @error="memberInfo.headimg = $util.getDefaultImage().head" show-menu-by-longpress/>
|
||||
</view>
|
||||
<view class="info">
|
||||
<!-- #ifdef MP -->
|
||||
<block
|
||||
v-if="(memberInfo.nickname.indexOf('u_') != -1 && memberInfo.nickname == memberInfo.username) || memberInfo.nickname == memberInfo.mobile">
|
||||
<view class="nickname"><text class="name" @tap.stop="getWxAuth">点击授权头像昵称</text></view>
|
||||
<view class="nickname"><text class="name" :style="nameStyle" @tap.stop="getWxAuth">{{ $lang('components-diy.diy-member-info.clickToAuthorizeAvatarNickname') }}</text></view>
|
||||
</block>
|
||||
<view class="nickname" v-else>
|
||||
<text class="name" @tap.stop="getWxAuth">{{ memberInfo.nickname }}</text>
|
||||
<text class="name" :style="nameStyle" @tap.stop="getWxAuth">{{ memberInfo.nickname }}</text>
|
||||
<view class="member-level"
|
||||
v-if="(value.style == 1 || value.style == 2) && memberInfo.member_level">
|
||||
<!-- <text class="icondiy icon-system-huangguan"></text> -->
|
||||
@@ -36,10 +36,10 @@
|
||||
<!-- #ifdef H5 -->
|
||||
<block
|
||||
v-if="$util.isWeiXin() && ((memberInfo.nickname.indexOf('u_') != -1 && memberInfo.nickname == memberInfo.username) || memberInfo.nickname == memberInfo.mobile)">
|
||||
<view class="nickname"><text class="name" @tap.stop="getWxAuth">点击获取微信头像</text></view>
|
||||
<view class="nickname"><text class="name" @tap.stop="getWxAuth">{{ $lang('components-diy.diy-member-info.clickToGetWechatAvatar') }}</text></view>
|
||||
</block>
|
||||
<view class="nickname" v-else>
|
||||
<text class="name" @tap.stop="redirect('/pages_tool/member/info')">{{ memberInfo.nickname
|
||||
<text class="name" :style="nameStyle" @tap.stop="redirect('/pages_tool/member/info')">{{ memberInfo.nickname
|
||||
}}</text>
|
||||
<view class="member-level"
|
||||
v-if="(value.style == 1 || value.style == 2) && memberInfo.member_level">
|
||||
@@ -66,11 +66,11 @@
|
||||
|
||||
<view class="info-wrap" v-else :style="infoStyle" @tap.stop="redirect($util.MEMBER_PAGE_URL)">
|
||||
<view class="headimg">
|
||||
<image :src="$util.getDefaultImage().head" mode="widthFix"></image>
|
||||
<image :src="$util.getDefaultImage().head" mode="widthFix" show-menu-by-longpress></image>
|
||||
</view>
|
||||
<view class="info">
|
||||
<view class="nickname"><text class="name">{{ $lang('login') }}</text></view>
|
||||
<view class="desc">{{ $lang('loginTpis') }}</view>
|
||||
<view class="nickname"><text class="name" :style="nameStyle">{{ $lang('member.index.login') }}</text></view>
|
||||
<view class="desc">{{ $lang('member.index.loginTips') }}</view>
|
||||
</view>
|
||||
|
||||
<view v-if="ischina == 1"
|
||||
@@ -85,19 +85,19 @@
|
||||
{{ memberInfo ? (parseFloat(memberInfo.balance) +
|
||||
parseFloat(memberInfo.balance_money)).toFixed(2) : '--' }}
|
||||
</view>
|
||||
<view class="title">{{ $lang('balance') }}</view>
|
||||
<view class="title">{{ $lang('member.index.balance') }}</view>
|
||||
</view>
|
||||
<view class="solid"></view>
|
||||
<view class="account-item" @tap.stop="redirect('/pages_tool/member/point_detail')">
|
||||
<view class="value price-font">{{ memberInfo ? parseFloat(memberInfo.point) : '--' }}</view>
|
||||
<view class="title">{{ $lang('point') }}</view>
|
||||
<view class="title">{{ $lang('member.index.point') }}</view>
|
||||
</view>
|
||||
<view class="solid"></view>
|
||||
<view class="account-item" @tap.stop="redirect('/pages_tool/member/coupon')">
|
||||
<view class="value price-font">
|
||||
{{ memberInfo && memberInfo.coupon_num != undefined ? memberInfo.coupon_num : '--' }}
|
||||
</view>
|
||||
<view class="title">{{ $lang('coupon') }}</view>
|
||||
<view class="title">{{ $lang('member.index.coupon') }}</view>
|
||||
</view>
|
||||
</view>
|
||||
<!--
|
||||
@@ -117,7 +117,7 @@
|
||||
</block>
|
||||
<block v-if="value.style == 3">
|
||||
<view class="super-info">
|
||||
<image :src="$util.img('public/uniapp/member/open_member.png')" class="title" mode="heightFix" />
|
||||
<image :src="$util.img('public/uniapp/member/open_member.png')" class="title" mode="heightFix" show-menu-by-longpress/>
|
||||
<view class="desc">开通可享更多权益</view>
|
||||
</view>
|
||||
<view class="super-text">
|
||||
@@ -130,7 +130,7 @@
|
||||
<view class="member-info-style4" v-show="value.style == 4">
|
||||
<view class="super-member" v-if="superMember" :style="superMemberStyle">
|
||||
<view class="super-info">
|
||||
<image :src="$util.img('app/component/view/member_info/img/style_4_vip_huangguan.png')" class="title" mode="widthFix" />
|
||||
<image :src="$util.img('app/component/view/member_info/img/style_4_vip_huangguan.png')" class="title" mode="widthFix" show-menu-by-longpress/>
|
||||
<view class="desc">开通可享更多权益</view>
|
||||
</view>
|
||||
<view class="super-text" :class="{ 'more' : memberInfo && memberInfo.member_level_type }">
|
||||
@@ -172,19 +172,19 @@
|
||||
<view class="account-item" @tap.stop="redirect('/pages_tool/member/balance')">
|
||||
<view class="value price-font">{{ memberInfo ? (parseFloat(memberInfo.balance) +
|
||||
parseFloat(memberInfo.balance_money)).toFixed(2) : '--' }}</view>
|
||||
<view class="title">{{ $lang('balance') }}</view>
|
||||
<view class="title">{{ $lang('member.index.balance') }}</view>
|
||||
</view>
|
||||
<view class="solid"></view>
|
||||
<view class="account-item" @tap.stop="redirect('/pages_tool/member/point_detail')">
|
||||
<view class="value price-font">{{ memberInfo ? parseFloat(memberInfo.point) : '--' }}</view>
|
||||
<view class="title">{{ $lang('point') }}</view>
|
||||
<view class="title">{{ $lang('member.index.point') }}</view>
|
||||
</view>
|
||||
<view class="solid"></view>
|
||||
<view class="account-item" @tap.stop="redirect('/pages_tool/member/coupon')">
|
||||
<view class="value price-font">
|
||||
{{ memberInfo && memberInfo.coupon_num != undefined ? memberInfo.coupon_num : '--' }}
|
||||
</view>
|
||||
<view class="title">{{ $lang('coupon') }}</view>
|
||||
<view class="title">{{ $lang('member.index.coupon') }}</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -194,40 +194,40 @@
|
||||
<uni-popup ref="completeInfoPopup" type="bottom" :maskClick="false">
|
||||
<view class="complete-info-wrap">
|
||||
<view class="head">
|
||||
<text class="title">获取您的昵称、头像</text>
|
||||
<text class="color-tip tips">获取用户头像、昵称完善个人资料,主要用于向用户提供具有辨识度的用户中心界面</text>
|
||||
<text class="title">{{ $lang('components-diy.diy-member-info.completeInfoTitle') }}</text>
|
||||
<text class="color-tip tips">{{ $lang('components-diy.diy-member-info.completeInfoTip') }}</text>
|
||||
<text class="iconfont icon-close color-tip" @tap.stop="cancelCompleteInfo"></text>
|
||||
</view>
|
||||
<!-- #ifdef MP-WEIXIN -->
|
||||
<view class="item-wrap">
|
||||
<text class="label">头像</text>
|
||||
<text class="label">{{ $lang('components-diy.diy-member-info.avatarLabel') }}</text>
|
||||
<button open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
|
||||
<image :src="avatarUrl ? avatarUrl : $util.getDefaultImage().head"
|
||||
@error="avatarUrl = $util.getDefaultImage().head" mode="aspectFill" />
|
||||
@error="avatarUrl = $util.getDefaultImage().head" mode="aspectFill" show-menu-by-longpress/>
|
||||
<text class="iconfont icon-right color-tip"></text>
|
||||
</button>
|
||||
</view>
|
||||
<view class="item-wrap">
|
||||
<text class="label">昵称</text>
|
||||
<input type="nickname" placeholder="请输入昵称" v-model="nickName" @blur="blurNickName" />
|
||||
<text class="label">{{ $lang('components-diy.diy-member-info.nicknameLabel') }}</text>
|
||||
<input type="nickname" :placeholder="$lang('components-diy.diy-member-info.nicknamePlaceholder')" v-model="nickName" @blur="blurNickName" />
|
||||
</view>
|
||||
<!-- #endif -->
|
||||
<!-- #ifdef MP-ALIPAY -->
|
||||
<view class="item-wrap">
|
||||
<text class="label">头像</text>
|
||||
<text class="label">{{ $lang('components-diy.diy-member-info.avatarLabel') }}</text>
|
||||
<button open-type="getAuthorize" scope="userInfo" @getAuthorize="aliappGetUserinfo"
|
||||
:plain="true" class="border-0">
|
||||
<image :src="avatarUrl ? avatarUrl : $util.getDefaultImage().head"
|
||||
@error="avatarUrl = $util.getDefaultImage().head" mode="aspectFill" />
|
||||
@error="avatarUrl = $util.getDefaultImage().head" mode="aspectFill" show-menu-by-longpress/>
|
||||
<text class="iconfont icon-right color-tip"></text>
|
||||
</button>
|
||||
</view>
|
||||
<view class="item-wrap">
|
||||
<text class="label">昵称</text>
|
||||
<input type="nickname" placeholder="请输入昵称" v-model="nickName" @blur="blurNickName" />
|
||||
<text class="label">{{ $lang('components-diy.diy-member-info.nicknameLabel') }}</text>
|
||||
<input type="nickname" :placeholder="$lang('components-diy.diy-member-info.nicknamePlaceholder')" v-model="nickName" @blur="blurNickName" />
|
||||
</view>
|
||||
<!-- #endif -->
|
||||
<button type="default" class="save-btn" @tap.stop="saveCompleteInfo" :disabled="isDisabled">保存</button>
|
||||
<button type="default" class="save-btn" @tap.stop="saveCompleteInfo" :disabled="isDisabled">{{ $lang('components-diy.diy-member-info.save') }}</button>
|
||||
</view>
|
||||
</uni-popup>
|
||||
</view>
|
||||
@@ -367,6 +367,26 @@ export default {
|
||||
isDisabled() {
|
||||
if (this.nickName.length > 0) return false;
|
||||
return true;
|
||||
},
|
||||
// PR-DIY-MEMBER-INFO-NAME-FIT (2026-09-17): 英文公司名等长标题自动缩小字号保证一行放下(像后台预览一样一排)
|
||||
// 标题来源: 已登录取昵称, 未登录取 $lang('member.index.login') 文案(英文包里配置的是公司全称)
|
||||
// 估算宽度: CJK/全角字符按 1em, 其余(英文/数字/空格)按 0.55em; 标题可用宽度约 470rpx
|
||||
// 最小 20rpx, 超长时仍有 .name 的省略号兜底
|
||||
nameStyle() {
|
||||
let name = '';
|
||||
if (this.memberInfo && this.memberInfo.nickname) {
|
||||
name = this.memberInfo.nickname;
|
||||
} else {
|
||||
try { name = this.$lang('member.index.login') || ''; } catch (e) { name = ''; }
|
||||
}
|
||||
if (!name) return '';
|
||||
let units = 0;
|
||||
for (let i = 0; i < name.length; i++) {
|
||||
units += /[\u2e80-\u9fff\uac00-\ud7af\u3000-\u303f\uff01-\uff60]/.test(name[i]) ? 1 : 0.55;
|
||||
}
|
||||
if (units <= 10) return ''; // 短标题走默认 38rpx
|
||||
const size = Math.max(20, Math.min(34, Math.floor(470 / units)));
|
||||
return 'font-size:' + size + 'rpx;';
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
@@ -493,8 +513,8 @@ export default {
|
||||
showMemberQrcode() {
|
||||
if (!this.memberInfo.mobile && !this.memberInfo.member_code) {
|
||||
uni.showModal({
|
||||
title: '提示',
|
||||
content: '使用会员码需先绑定手机号,是否绑定手机号?',
|
||||
title: this.$lang('components-diy.diy-member-info.tip'),
|
||||
content: this.$lang('components-diy.diy-member-info.bindMobileTip'),
|
||||
success: res => {
|
||||
if (res.confirm) {
|
||||
// #ifdef MP-WEIXIN
|
||||
@@ -566,6 +586,10 @@ export default {
|
||||
this.$util.redirectTo(url);
|
||||
}
|
||||
// #endif
|
||||
|
||||
// #ifndef MP || H5
|
||||
this.$util.redirectTo(url);
|
||||
// #endif
|
||||
},
|
||||
/**
|
||||
* 获取微信授权
|
||||
@@ -630,16 +654,19 @@ export default {
|
||||
});
|
||||
},
|
||||
openCompleteInfoPop(callback) {
|
||||
this.$refs.completeInfoPopup.open(() => {
|
||||
this.$store.commit('setBottomNavHidden', false); //显示底部导航
|
||||
});
|
||||
this.$store.commit('setBottomNavHidden', true); // 隐藏底部导航
|
||||
this.$refs.completeInfoPopup.open();
|
||||
// 关闭时(setBottomNavHidden=false)由 saveCompleteInfo / cancelCompleteInfo 显式处理,
|
||||
// 不在 open 回调里写 — 回调在"弹窗被销毁/页面被卸载"等异常路径下不保证触发,会卡住 TabBar 隐藏态
|
||||
// TabBar 根页面(如会员中心)不能藏 TabBar — 否则会被自己藏起来
|
||||
if (!this.$util.isCurrentPageTabBarRoot()) {
|
||||
this.$store.commit('setBottomNavHidden', true); // 隐藏底部导航
|
||||
}
|
||||
this.completeInfoCallback = callback;
|
||||
},
|
||||
saveCompleteInfo() {
|
||||
if (this.nickName.length == 0) {
|
||||
this.$util.showToast({
|
||||
title: '请输入昵称'
|
||||
title: this.$lang('components-diy.diy-member-info.pleaseEnterNickname')
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -678,7 +705,7 @@ export default {
|
||||
},
|
||||
fail: () => {
|
||||
this.$util.showToast({
|
||||
title: '上传失败'
|
||||
title: this.$lang('components-diy.diy-member-info.uploadFailed')
|
||||
});
|
||||
}
|
||||
})
|
||||
@@ -709,7 +736,7 @@ export default {
|
||||
},
|
||||
fail: () => {
|
||||
this.$util.showToast({
|
||||
title: '头像拉取失败'
|
||||
title: this.$lang('components-diy.diy-member-info.avatarPullFailed')
|
||||
});
|
||||
}
|
||||
})
|
||||
@@ -858,7 +885,11 @@ export default {
|
||||
height: 120rpx;
|
||||
border-top-left-radius: 10rpx;
|
||||
border-top-right-radius: 10rpx;
|
||||
background: linear-gradient(107deg, #7c7878 0%, #201a18 100%);
|
||||
// P0: 用现有 token,主题切换时会员卡背景跟着变
|
||||
// 旧字面: #7c7878 / #201a18(默认 preset 值) → 现在由 token 决定
|
||||
// 兼容: 微信小程序 / 鸿蒙元服务 — var() 在 linear-gradient 中现代 runtime 均支持
|
||||
background: #7c7878; // 兜底(微信小程序老 runtime 无 var() 兜底)
|
||||
background: linear-gradient(107deg, var(--super-member-start-bg) 0%, var(--super-member-end-bg) 100%);
|
||||
padding: 30rpx 40rpx;
|
||||
box-sizing: border-box;
|
||||
|
||||
@@ -939,7 +970,12 @@ export default {
|
||||
}
|
||||
|
||||
.super-text {
|
||||
background-image: linear-gradient(90deg, #ffdba6 0%, #ffebca 49%, #f7c774 100%);
|
||||
// P0: 3 停渐变 → 2 停(start + end),token 化
|
||||
// 旧字面: #ffdba6 / #ffebca (默认 preset 文字色) + 中间色 #f7c774
|
||||
// 中间色 #f7c774 不在 token 系统中,合并为 start→end 渐变(视觉差异可接受)
|
||||
// 兼容: -webkit-background-clip: text 在微信小程序 / 鸿蒙元服务均支持
|
||||
background: #ffdba6; // 兜底
|
||||
background-image: linear-gradient(90deg, var(--super-member-start-text-color) 0%, var(--super-member-end-text-color) 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
display: flex;
|
||||
@@ -989,7 +1025,11 @@ export default {
|
||||
|
||||
.super-member {
|
||||
color: #8d4b16;
|
||||
background: linear-gradient(107deg, #fadcb5 0%, #f6bd74 100%);
|
||||
// P0 注释 A 修复: 之前这个渐变是 black preset 的字面,导致 data-style-2 在 default 主题下显示错误
|
||||
// 现在用 var() 让主题切换时自动跟着变(无论 data-style-1 还是 data-style-2)
|
||||
// 兼容: 同 865 行,微信小程序 / 鸿蒙元服务均 OK
|
||||
background: #fadcb5; // 兜底
|
||||
background: linear-gradient(107deg, var(--super-member-start-bg) 0%, var(--super-member-end-bg) 100%);
|
||||
border-top-left-radius: 18rpx;
|
||||
border-top-right-radius: 18rpx;
|
||||
|
||||
@@ -1489,4 +1529,4 @@ export default {
|
||||
border-top-left-radius: 30rpx !important;
|
||||
border-top-right-radius: 30rpx !important;
|
||||
}
|
||||
</style>
|
||||
</style>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
style="margin-right: 10rpx;">
|
||||
<view class="icon-block">
|
||||
<template v-if="value.style == 3">
|
||||
<image :src="$util.img('public/uniapp/member/order/wait_pay.png')" mode="widthFix" />
|
||||
<image :src="$util.img('public/uniapp/member/order/wait_pay.png')" mode="widthFix" show-menu-by-longpress/>
|
||||
<view class="icon-shade"
|
||||
:style="'-webkit-mask-image: url(' + $util.img('public/uniapp/member/order/wait_pay_shade.png') + ')'">
|
||||
</view>
|
||||
@@ -25,7 +25,7 @@
|
||||
style="margin-right: 10rpx;">
|
||||
<view class="icon-block">
|
||||
<template v-if="value.style == 3">
|
||||
<image :src="$util.img('public/uniapp/member/order/wait_send.png')" mode="widthFix"></image>
|
||||
<image :src="$util.img('public/uniapp/member/order/wait_send.png')" mode="widthFix" show-menu-by-longpress></image>
|
||||
<view class="icon-shade"
|
||||
:style="'-webkit-mask-image: url(' + $util.img('public/uniapp/member/order/wait_send_shade.png') + ')'">
|
||||
</view>
|
||||
@@ -44,7 +44,7 @@
|
||||
style="margin-right: 10rpx;">
|
||||
<view class="icon-block">
|
||||
<template v-if="value.style == 3">
|
||||
<image :src="$util.img('public/uniapp/member/order/wait_confirm.png')" mode="widthFix" />
|
||||
<image :src="$util.img('public/uniapp/member/order/wait_confirm.png')" mode="widthFix" show-menu-by-longpress/>
|
||||
<view class="icon-shade"
|
||||
:style="'-webkit-mask-image: url(' + $util.img('public/uniapp/member/order/wait_confirm_shade.png') + ')'">
|
||||
</view>
|
||||
@@ -63,7 +63,7 @@
|
||||
style="margin-right: 10rpx;">
|
||||
<view class="icon-block">
|
||||
<template v-if="value.style == 3">
|
||||
<image :src="$util.img('public/uniapp/member/order/wait_use.png')" mode="widthFix" />
|
||||
<image :src="$util.img('public/uniapp/member/order/wait_use.png')" mode="widthFix" show-menu-by-longpress/>
|
||||
<view class="icon-shade"
|
||||
:style="'-webkit-mask-image: url(' + $util.img('public/uniapp/member/order/wait_rate_shade.png') + ')'">
|
||||
</view>
|
||||
@@ -79,7 +79,7 @@
|
||||
<view class="item-wrap" @tap.stop="redirect('/pages_tool/order/activist')">
|
||||
<view class="icon-block">
|
||||
<template v-if="value.style == 3">
|
||||
<image :src="$util.img('public/uniapp/member/order/refunding.png')" mode="widthFix" />
|
||||
<image :src="$util.img('public/uniapp/member/order/refunding.png')" mode="widthFix" show-menu-by-longpress/>
|
||||
<view class="icon-shade"
|
||||
:style="'-webkit-mask-image: url(' + $util.img('public/uniapp/member/order/refunding_shade.png') + ')'">
|
||||
</view>
|
||||
@@ -137,8 +137,8 @@ export default {
|
||||
},
|
||||
computed: {
|
||||
warpCss() {
|
||||
var obj = '';
|
||||
obj += 'background-color:' + this.value.componentBgColor + ';';
|
||||
var obj = '';
|
||||
obj += 'background-color:' + this.value.componentBgColor + ';';
|
||||
if (this.value.componentAngle == 'round') {
|
||||
obj += 'border-top-left-radius:' + this.value.topAroundRadius * 2 + 'rpx;';
|
||||
obj += 'border-top-right-radius:' + this.value.topAroundRadius * 2 + 'rpx;';
|
||||
|
||||
@@ -5,15 +5,15 @@
|
||||
<view :class="['list-wrap', value.style]" :style="warpCss">
|
||||
<view :class="['item', value.ornament.type]" v-for="(item, index) in list" :key="index"
|
||||
:style="itemCss" @tap.stop="handlerClick(item)">
|
||||
<view class="merch-img">
|
||||
<view class="merch-img" @tap.stop="handlerClick(item)">
|
||||
<image class="cover-img" :src="$util.img(item.merch_image)" mode="widthFix"
|
||||
@error="imgError(index)" />
|
||||
@error="imgError(index)" show-menu-by-longpress />
|
||||
</view>
|
||||
<view class="info-wrap">
|
||||
<text class="title">{{ item.merch_name }}</text>
|
||||
<text class="desc">{{ item.desc }}</text>
|
||||
<view class="read-wrap"></view>
|
||||
</view>
|
||||
<text class="title" :style="titleStyle(item)" @tap.stop="handlerClick(item)">{{ item.merch_name }}</text>
|
||||
<text class="desc" :style="descStyle(item)">{{ item.desc }}</text>
|
||||
<view class="read-wrap"></view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -27,14 +27,16 @@
|
||||
<view class="merch-nav-item graphic" v-for="(item, index) in list" :key="index"
|
||||
:style="{ width: 100 / 4 + '%' }" @tap.stop="handlerClick(item)">
|
||||
<view class="graphic-img" v-if="value.mode != 'text'"
|
||||
:style="{ fontSize: value.imageSize * 2 + 'rpx', width: value.imageSize * 2 + 'rpx', height: value.imageSize * 2 + 'rpx' }">
|
||||
:style="{ fontSize: value.imageSize * 2 + 'rpx', width: value.imageSize * 2 + 'rpx', height: value.imageSize * 2 + 'rpx' }"
|
||||
@tap.stop="handlerClick(item)">
|
||||
<image
|
||||
:src="$util.img(item.merch_image) || $util.img('public/uniapp/default_img/goods.png')"
|
||||
mode="aspectFill" :show-menu-by-longpress="true"
|
||||
mode="aspectFill" show-menu-by-longpress
|
||||
style="max-width: 80rpx; max-height: 80rpx; border-radius: 50rpx;" />
|
||||
</view>
|
||||
<text class="graphic-text"
|
||||
style="font-size: 28rpx; font-weight: normal; color: rgb(48, 49, 51);">
|
||||
style="font-size: 28rpx; font-weight: normal; color: rgb(48, 49, 51);"
|
||||
@tap.stop="handlerClick(item)">
|
||||
{{ item.merch_name }}
|
||||
</text>
|
||||
</view>
|
||||
@@ -62,31 +64,31 @@ export default {
|
||||
list: [
|
||||
/*{
|
||||
merch_name:'品牌',
|
||||
merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
|
||||
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
|
||||
},
|
||||
{
|
||||
merch_name:'品牌',
|
||||
merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
|
||||
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
|
||||
},
|
||||
{
|
||||
merch_name:'品牌',
|
||||
merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
|
||||
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
|
||||
},
|
||||
{
|
||||
merch_name:'品牌',
|
||||
merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
|
||||
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
|
||||
},
|
||||
{
|
||||
merch_name:'品牌',
|
||||
merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
|
||||
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
|
||||
},
|
||||
{
|
||||
merch_name:'品牌',
|
||||
merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
|
||||
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
|
||||
},
|
||||
{
|
||||
merch_name:'品牌',
|
||||
merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
|
||||
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
|
||||
}*/
|
||||
],
|
||||
loading: true,
|
||||
@@ -119,7 +121,6 @@ export default {
|
||||
obj += 'border-bottom-left-radius:' + this.value.bottomAroundRadius * 2 + 'rpx;';
|
||||
obj += 'border-bottom-right-radius:' + this.value.bottomAroundRadius * 2 + 'rpx;';
|
||||
}
|
||||
console.log(obj)
|
||||
return obj;
|
||||
},
|
||||
// 子项样式
|
||||
@@ -140,14 +141,12 @@ export default {
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
},
|
||||
},
|
||||
methods: {
|
||||
getList() {
|
||||
console.log(121)
|
||||
var data = {
|
||||
num: this.value.count
|
||||
};
|
||||
console.log(this.value)
|
||||
if (this.value.sources == 'diy') {
|
||||
data.num = 0;
|
||||
data.merch_id_arr = this.value.merchIds.toString();
|
||||
@@ -180,6 +179,25 @@ export default {
|
||||
this.toDetail(item);
|
||||
}
|
||||
})
|
||||
},
|
||||
// PR-DIY-MERCH-LIST-ONE-LINE (2026-09-17): 英文公司名等长标题/描述自动缩小字号, 保证单行显示(像后台预览一样一排)
|
||||
// 估算宽度: CJK/全角字符按 1em, 其余(英文/数字/空格)按 0.55em; 文字区可用宽度约 500rpx
|
||||
// 短文本走 CSS 默认字号, 极端超长时仍有省略号兜底
|
||||
oneLineFontStyle(text, defaultSize, minSize) {
|
||||
if (!text) return '';
|
||||
let units = 0;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
units += /[\u2e80-\u9fff\uac00-\ud7af\u3000-\u303f\uff01-\uff60]/.test(text[i]) ? 1 : 0.55;
|
||||
}
|
||||
if (units <= 12) return '';
|
||||
const size = Math.max(minSize, Math.min(defaultSize, Math.floor(500 / units)));
|
||||
return 'font-size:' + size + 'rpx;';
|
||||
},
|
||||
titleStyle(item) {
|
||||
return this.oneLineFontStyle(item.merch_name, 30, 20);
|
||||
},
|
||||
descStyle(item) {
|
||||
return this.oneLineFontStyle(item.desc, 24, 20);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -297,13 +315,19 @@ export default {
|
||||
}
|
||||
|
||||
.info-wrap {
|
||||
flex: 1;
|
||||
min-width: 0; /* PR-DIY-MERCH-LIST-ONE-LINE: 约束宽度让单行省略号生效 */
|
||||
|
||||
// flex: 1;
|
||||
// display: flex;
|
||||
// flex-direction: column;
|
||||
// justify-content: space-between;
|
||||
.desc {
|
||||
color: #888
|
||||
color: #888;
|
||||
/* PR-DIY-MERCH-LIST-ONE-LINE: 描述单行, 超出省略 */
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.title {
|
||||
@@ -312,8 +336,9 @@ export default {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-line-clamp: 1; /* PR-DIY-MERCH-LIST-ONE-LINE: 标题一行(原为2行), 配合自适应字号保证放得下 */
|
||||
-webkit-box-orient: vertical;
|
||||
white-space: nowrap;
|
||||
font-size: 30rpx;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
@@ -25,10 +25,10 @@
|
||||
|
||||
<view class="notes-img-wrap" :class="{ 'notes-img-wrap-list': item.cover_type == 1 }">
|
||||
<image v-if="item.cover_type == 0" :src="$util.img(item.img)" @error="imageError(i)"
|
||||
mode="aspectFill" class="notes-item-image" />
|
||||
mode="aspectFill" class="notes-item-image" show-menu-by-longpress/>
|
||||
<image v-else v-for="(imgItem, imgIndex) in item.img" :key="imgIndex"
|
||||
:src="$util.img(imgItem)" @error="imageError(i)" mode="aspectFit"
|
||||
class="notes-item-image-li" />
|
||||
class="notes-item-image-li" show-menu-by-longpress/>
|
||||
</view>
|
||||
|
||||
<view class="notes-item-con">
|
||||
@@ -39,14 +39,14 @@
|
||||
item.update_time_day }}</text>
|
||||
</view>
|
||||
<view class="notes-num">
|
||||
<text v-show="value.readNum == 1 && item.is_show_read_num == 1">阅读 {{
|
||||
item.initial_read_num + item.read_num }}</text>
|
||||
</view>
|
||||
<text v-show="value.readNum == 1 && item.is_show_read_num == 1">{{ $lang('components-diy.diy-notes.readPrefix') }} {{
|
||||
item.initial_read_num + item.read_num }}</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</scroll-view>
|
||||
</view>
|
||||
</scroll-view>
|
||||
|
||||
<ns-login ref="login"></ns-login>
|
||||
</view>
|
||||
|
||||
@@ -9,7 +9,8 @@
|
||||
<view class="notice-xian"></view>
|
||||
<view class="main-wrap">
|
||||
<!-- 横向滚动 -->
|
||||
<view class="horizontal-wrap" v-if="value.scrollWay == 'horizontal'">
|
||||
<view class="horizontal-wrap" v-if="value.scrollWay == 'horizontal'"
|
||||
@tap="toLink(list[0])">
|
||||
<view class="marquee-wrap">
|
||||
<view class="marquee" :style="marqueeStyle">
|
||||
<text v-for="(item, index) in list" :key="index"
|
||||
@@ -27,7 +28,8 @@
|
||||
<!-- 上下滚动 -->
|
||||
<template v-if="value.scrollWay == 'upDown'">
|
||||
<swiper :vertical="true" :duration="500" autoplay="true" circular="true">
|
||||
<swiper-item v-for="(item, index) in list" :key="index" @touchmove.prevent.stop>
|
||||
<swiper-item v-for="(item, index) in list" :key="index"
|
||||
@touchmove.prevent.stop @tap="toLink(item)">
|
||||
<text class="beyond-hiding using-hidden"
|
||||
:style="{ color: value.textColor, fontSize: value.fontSize * 2 + 'rpx', fontWeight: value.fontWeight }">
|
||||
{{ item.title }}
|
||||
@@ -42,11 +44,11 @@
|
||||
<uni-popup ref="noticePopup" type="center">
|
||||
<view class="notice-popup">
|
||||
<view class="head-wrap" @tap.stop="closeNoticePopup">
|
||||
<text>公告</text>
|
||||
<text>{{ $lang('components-diy.diy-notice.notice') }}</text>
|
||||
<text class="iconfont icon-close"></text>
|
||||
</view>
|
||||
<view class="content-wrap">{{ notice }}</view>
|
||||
<button type="primary" @tap.stop="closeNoticePopup">我知道了</button>
|
||||
<button type="primary" @tap.stop="closeNoticePopup">{{ $lang('components-diy.diy-notice.gotIt') }}</button>
|
||||
</view>
|
||||
</uni-popup>
|
||||
</view>
|
||||
@@ -136,11 +138,11 @@ export default {
|
||||
});
|
||||
} else if (!item) {
|
||||
this.$util.redirectTo('/pages_tool/notice/list');
|
||||
} else if (Object.keys(item.link).length > 1) {
|
||||
} else if (item.link && (item.link.wap_url || item.link.appid || item.link.name)) {
|
||||
this.$util.diyRedirectTo(item.link);
|
||||
} else {
|
||||
// 如果不设置跳转链接,则点击弹框展示
|
||||
this.notice = item.title;
|
||||
this.notice = item.content || item.title || '';
|
||||
this.$refs.noticePopup.open();
|
||||
}
|
||||
},
|
||||
|
||||
@@ -3,23 +3,23 @@
|
||||
<view class="payment-qrocde-box">
|
||||
<view class="qrocde-left">
|
||||
<view class="qrocde-desc">
|
||||
<text>门店消费时使用,支付时点击下方展示付款码</text>
|
||||
<text>{{ $lang('components-diy.diy-payment-qrcode.description') }}</text>
|
||||
<!-- <text class="iconfont icon-shuaxin"></text> -->
|
||||
</view>
|
||||
<view class="qrocde-action">
|
||||
<button type="primary" @tap.stop="toLink">
|
||||
<text class="iconfont icon-fukuanma"></text>
|
||||
<text class="action-name">付款码</text>
|
||||
<text class="action-name">{{ $lang('components-diy.diy-payment-qrcode.paymentCode') }}</text>
|
||||
</button>
|
||||
<button type="primary" @tap.stop="openPaymentPopup">
|
||||
<text class="iconfont icon-saomafu"></text>
|
||||
<text class="action-name">扫码付</text>
|
||||
<text class="action-name">{{ $lang('components-diy.diy-payment-qrcode.scanToPay') }}</text>
|
||||
</button>
|
||||
</view>
|
||||
</view>
|
||||
<view class="qrocde-right">
|
||||
<text class="iconfont icon-zhifu"></text>
|
||||
<text class="name">门店支付</text>
|
||||
<text class="name">{{ $lang('components-diy.diy-payment-qrcode.storePayment') }}</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
@@ -27,11 +27,11 @@
|
||||
<uni-popup ref="paymentPopup" type="center">
|
||||
<view class="payment-popup">
|
||||
<view class="head-wrap" @tap.stop="closePaymentPopup">
|
||||
<text>提示</text>
|
||||
<text>{{ $lang('components-diy.diy-payment-qrcode.popupTipTitle') }}</text>
|
||||
<text class="iconfont icon-close"></text>
|
||||
</view>
|
||||
<view class="content-wrap">扫码付请退出程序后直接使用微信扫一扫或返回上一页使用付款码进行支付</view>
|
||||
<button type="primary" @tap.stop="closePaymentPopup">我知道了</button>
|
||||
<view class="content-wrap">{{ $lang('components-diy.diy-payment-qrcode.scanToPayTip') }}</view>
|
||||
<button type="primary" @tap.stop="closePaymentPopup">{{ $lang('components-diy.diy-payment-qrcode.gotIt') }}</button>
|
||||
</view>
|
||||
</uni-popup>
|
||||
</view>
|
||||
@@ -75,8 +75,6 @@ export default {
|
||||
// 允许从相机和相册扫码,h5端不起作用
|
||||
uni.scanCode({
|
||||
success: function (res) {
|
||||
console.log('条码类型:' + res.scanType);
|
||||
console.log('条码内容:' + res.result);
|
||||
}
|
||||
});
|
||||
// #endif
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
<template>
|
||||
<view data-component-name="diy-picture" class="diy-picture" :style="style">
|
||||
<view class="fui-picture">
|
||||
<view v-for="(item, index) in value.list" style="line-height: 0;">
|
||||
<view v-for="(item, index) in value.list" :key="index" style="line-height: 0;">
|
||||
<image mode="widthFix" style="width: 100%;height:auto" :src="$util.img(item.imageUrl)"
|
||||
v-if="item.link.wap_url" @tap.stop="handlerClick(item)"></image>
|
||||
v-if="item.link.wap_url" @tap.stop="handlerClick(item)" show-menu-by-longpress></image>
|
||||
<image mode="widthFix" style="width: 100%;height:auto" :src="$util.img(item.imageUrl)" v-else
|
||||
@tap.stop="handlerClick(item)"></image>
|
||||
@tap.stop="handlerClick(item)" show-menu-by-longpress></image>
|
||||
</view>
|
||||
<!-- <view wx:if="{{!childitem.linkurl}}" bindtap="previewImg" data-src="{{childitem.imgurl}}" style="padding:{{diyitem.style.paddingtop==0?0:diyitem.style.paddingtop+'rpx'}} {{diyitem.style.paddingleft==0?0:diyitem.style.paddingleft+'rpx'}}" wx:for="{{diyitem.data}}" wx:for-index="childid" wx:for-item="childitem" wx:key="{{childid}}">
|
||||
<image mode="widthFix" src="{{childitem.imgurl}}" style="{{bannerheight?'height:'+bannerheight+'px':'height:auto'}}"></image>
|
||||
</view> -->
|
||||
</view>
|
||||
<ns-login ref="login"></ns-login>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
|
||||
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
|
||||
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
|
||||
@error="imageError(index)" />
|
||||
@error="imageError(index)" show-menu-by-longpress/>
|
||||
</view>
|
||||
<view class="content"
|
||||
v-if="value.goodsNameStyle.control || value.priceStyle.mainControl || value.priceStyle.lineControl || value.btnStyle.control">
|
||||
@@ -21,11 +21,11 @@
|
||||
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '', borderColor: value.theme == 'diy' ? value.groupStyle.bgColor : '' }">
|
||||
<text class="iconfont icon-yonghu3"
|
||||
:style="{ backgroundColor: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"></text>
|
||||
<text>{{ item.pintuan_num }}人团</text>
|
||||
<text>{{ $lang('components-diy.diy-pinfan.peopleGroup', { num: item.pintuan_num }) }}</text>
|
||||
</view>
|
||||
<view v-if="value.saleStyle.control"
|
||||
:style="{ color: value.theme == 'diy' ? value.saleStyle.color : '', borderColor: value.theme == 'diy' ? value.saleStyle.color : '' }">
|
||||
<text>已拼{{ item.order_num }}件</text>
|
||||
<text>{{ $lang('components-diy.diy-pinfan.soldCount', { num: item.order_num }) }}</text>
|
||||
</view>
|
||||
</view>
|
||||
<view class="price-wrap">
|
||||
@@ -49,10 +49,9 @@
|
||||
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
|
||||
}">
|
||||
<text class="text">{{ value.btnStyle.text }}</text>
|
||||
<text class="fan" v-if="item.reward_type == 4">返{{ item.reward_type_num }}积分</text>
|
||||
<text class="fan" v-if="item.reward_type == 1 || item.reward_type == 2">返¥{{
|
||||
item.reward_type_num }}</text>
|
||||
<text class="fan" v-if="item.reward_type == 3">返优惠券</text>
|
||||
<text class="fan" v-if="item.reward_type == 4">{{ $lang('components-diy.diy-pinfan.backPoints', { num: item.reward_type_num }) }}</text>
|
||||
<text class="fan" v-if="item.reward_type == 1 || item.reward_type == 2">{{ $lang('components-diy.diy-pinfan.backCash', { num: item.reward_type_num }) }}</text>
|
||||
<text class="fan" v-if="item.reward_type == 3">{{ $lang('components-diy.diy-pinfan.backCoupon') }}</text>
|
||||
</button>
|
||||
</view>
|
||||
</view>
|
||||
@@ -66,7 +65,7 @@
|
||||
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
|
||||
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
|
||||
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
|
||||
@error="imageError(index)" />
|
||||
@error="imageError(index)" show-menu-by-longpress/>
|
||||
</view>
|
||||
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
|
||||
v-if="value.goodsNameStyle.control || value.priceStyle.mainControl">
|
||||
@@ -78,21 +77,21 @@
|
||||
<view v-if="value.groupStyle.control" class="num">
|
||||
<text class="content-tuan-box"
|
||||
:style="{ color: value.theme == 'diy' ? value.groupStyle.color : '', backgroundColor: value.theme == 'diy' ? value.groupStyle.bgColor : '' }">
|
||||
{{ item.pintuan_num }}人团
|
||||
{{ $lang('components-diy.diy-pinfan.peopleGroup', { num: item.pintuan_num }) }}
|
||||
</text>
|
||||
<text class="content-tuan-price"
|
||||
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
|
||||
v-if="item.reward_type == 4">
|
||||
返{{ item.reward_type_num }}积分
|
||||
{{ $lang('components-diy.diy-pinfan.backPoints', { num: item.reward_type_num }) }}
|
||||
</text>
|
||||
<text class="content-tuan-price"
|
||||
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
|
||||
v-if="item.reward_type == 1 || item.reward_type == 2">
|
||||
返¥{{ item.reward_type_num }}
|
||||
{{ $lang('components-diy.diy-pinfan.backCash', { num: item.reward_type_num }) }}
|
||||
</text>
|
||||
<text class="content-tuan-price"
|
||||
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
|
||||
v-if="item.reward_type == 3">返优惠券</text>
|
||||
v-if="item.reward_type == 3">{{ $lang('components-diy.diy-pinfan.backCoupon') }}</text>
|
||||
</view>
|
||||
<view class="price-wrap" v-if="value.priceStyle.mainControl">
|
||||
<text class="unit price-style small"
|
||||
@@ -117,7 +116,7 @@
|
||||
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
|
||||
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
|
||||
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
|
||||
@error="imageError(dataIndex)" />
|
||||
@error="imageError(dataIndex)" show-menu-by-longpress/>
|
||||
</view>
|
||||
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
|
||||
v-if="value.goodsNameStyle.control || value.priceStyle.mainControl">
|
||||
@@ -129,22 +128,22 @@
|
||||
<view v-if="value.groupStyle.control" class="num">
|
||||
<text class="content-tuan-box"
|
||||
:style="{ color: value.theme == 'diy' ? value.groupStyle.color : '', backgroundColor: value.theme == 'diy' ? value.groupStyle.bgColor : '' }">
|
||||
{{ item.pintuan_num }}人团
|
||||
{{ $lang('components-diy.diy-pinfan.peopleGroup', { num: item.pintuan_num }) }}
|
||||
</text>
|
||||
<text class="content-tuan-price"
|
||||
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
|
||||
v-if="item.reward_type == 4">
|
||||
返{{ item.reward_type_num }}积分
|
||||
{{ $lang('components-diy.diy-pinfan.backPoints', { num: item.reward_type_num }) }}
|
||||
</text>
|
||||
<text class="content-tuan-price"
|
||||
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
|
||||
v-if="item.reward_type == 1 || item.reward_type == 2">
|
||||
返¥{{ item.reward_type_num }}
|
||||
{{ $lang('components-diy.diy-pinfan.backCash', { num: item.reward_type_num }) }}
|
||||
</text>
|
||||
<text class="content-tuan-price"
|
||||
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
|
||||
v-if="item.reward_type == 3">
|
||||
返优惠券
|
||||
{{ $lang('components-diy.diy-pinfan.backCoupon') }}
|
||||
</text>
|
||||
</view>
|
||||
<view class="price-wrap" v-if="value.priceStyle.mainControl">
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user