Commit b94305bc authored by haiyoucuv's avatar haiyoucuv

init

parents
# 顶部的EditorConfig文件
root = true
# unix风格的换行符,每个文件都以换行符结尾
[*]
end_of_line = lf
insert_final_newline = true
# 设置默认字符集
charset = utf-8
# 去除行尾空白字符
trim_trailing_whitespace = true
# 使用空格缩进,设置2个空格缩进
indent_style = space
indent_size = 2
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
tmp.txt
dist/*/*
!dist/index.html
# NO SPARK !!!!!
# 为了消除疯火台影响,特地做此框架,建设中,未完工
UPLOAD_DIR=db_games/spark/v3
\ No newline at end of file
# .env.production
CDN_DOMAIN=https://yun.duiba.com.cn
OSS_REGION=oss-cn-hangzhou
OSS_BUCKET=duiba
OSS_ACCESS_KEY_ID=LTAI5tPUSSxgkEmKPAfVXUQQ
OSS_ACCESS_SECRET=6sk3EDd1BYrXlAUoh8maMuN7hOMkh1
import {exec, execSync} from 'child_process';
import * as path from "path";
import {promises as fs} from "fs";
import * as Os from "os";
import * as fsSync from "fs";
/** 压缩引擎路径表 */
const enginePathMap = {
/** macOS */
'darwin': 'pngquant/macos/pngquant',
/** Windows */
'win32': 'pngquant/windows/pngquant'
}
export async function compressAllImage(
paths = [],
onProgress: (cur?: number, total?: number) => void = () => void 0,
) {
const platform = Os.platform();
const pngquantPath = path.join(__dirname, "./", enginePathMap[platform]);
// 设置引擎文件的执行权限(仅 macOS)
if (pngquantPath && platform === 'darwin') {
if ((await fs.stat(pngquantPath)).mode != 33261) {
// 默认为 33188
await fs.chmod(pngquantPath, 33261);
}
}
const qualityParam = `--quality 0-99`,
speedParam = `--speed 4`,
skipParam = platform == "win32" ? "" : '--skip-if-larger',
outputParam = '--ext=.png',
writeParam = '--force',
// colorsParam = config.colors,
// compressOptions = `${qualityParam} ${speedParam} ${skipParam} ${outputParam} ${writeParam} ${colorsParam}`;
compressOptions = `${qualityParam} ${speedParam} ${skipParam} ${outputParam} ${writeParam}`;
let completed = 0;
if (platform == "win32") {
const now = Date.now();
const tempDir = `C:\\Temp\\duiba\\${now}`;
if (!fsSync.existsSync("C:\\Temp")) await fs.mkdir("C:\\Temp");
if (!fsSync.existsSync("C:\\Temp\\duiba")) await fs.mkdir("C:\\Temp\\duiba");
if (!fsSync.existsSync(tempDir)) await fs.mkdir(tempDir);
const ps = paths.map(async (imgPath, idx) => {
const tempName = `${tempDir}/${idx}.png`;
await fs.copyFile(imgPath, tempName);
execSync(`"${pngquantPath}" ${compressOptions} "${tempName}"`);
await fs.copyFile(tempName, imgPath);
completed++;
onProgress(completed, paths.length);
});
await Promise.all(ps);
await fs.rm(tempDir, {recursive: true});
} else {
const chunkSize = 20;
const totalBatches = Math.ceil(paths.length / chunkSize);
// 批次执行
for (let i = 0; i < paths.length; i += chunkSize) {
const currentBatch = Math.floor(i / chunkSize) + 1;
console.log(`正在处理第 ${currentBatch}/${totalBatches} 批图片压缩...`);
const chunk = paths.slice(i, i + chunkSize);
let command = "";
chunk.forEach((imgPath) => {
command += `"${pngquantPath}" ${compressOptions} "${imgPath}" &`; // 使用分号替代&实现串行
});
await new Promise<void>((resolve) => {
exec(command, (error, stdout, stderr) => {
if (error) {
// console.error(error);
}
completed += chunk.length;
onProgress(completed, paths.length);
resolve();
});
});
}
}
}
import {promises as fs} from "fs";
import SvgaDescriptor from "./SvgaDescriptor";
import {compressAllImage} from "./ImageCompress";
import * as pako from "pako";
import protobuf from "protobufjs";
import chalk from "chalk";
import * as Os from "node:os";
import * as path from "node:path";
const ProtoMovieEntity = protobuf.Root
.fromJSON(SvgaDescriptor)
.lookupType('com.opensource.svga.MovieEntity');
/**
* 压缩Svga
* @author haiyoucuv
* @param {string}svga
* @return {Promise<boolean|ArrayBuffer>}
*/
export async function compressSvga(svga: string): Promise<Uint8Array> {
try {
const buffer = await fs.readFile(svga);
// 解析svga
const data = ProtoMovieEntity.decode(pako.inflate(buffer)).toJSON();
const {images} = data;
let tempDir = svga.replace(/\.svga/, '') + "__temp__/";
// if (Os.platform() == "win32") {
// const now = Date.now();
// tempDir = `C:\\Temp\\duiba\\${now}`
//
// if (!fs.existsSync("C:\\Temp")) fs.mkdirSync("C:\\Temp");
// if (!fs.existsSync("C:\\Temp\\duiba")) fs.mkdirSync("C:\\Temp\\duiba");
// if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir);
// }
await fs.mkdir(tempDir);
const ps1 = Object.keys(images).map(async (name) => {
const path = `${tempDir}${name}.png`;
await fs.writeFile(path, Buffer.from(images[name], 'base64'));
return path;
});
// 保存图片
const imgPaths = await Promise.all(ps1);
// 压缩图片
await compressAllImage(imgPaths);
// 读取图片,还原到data
const ps2 = Object.keys(images).map(async (name) => {
const path = `${tempDir}${name}.png`;
const buffer = await fs.readFile(path);
data.images[name] = buffer.toString('base64');
});
await Promise.all(ps2);
await fs.rm(tempDir, {recursive: true});
// 压缩buffer
return pako.deflate(ProtoMovieEntity.encode(data).finish());
} catch (e) {
console.log(e);
return null;
}
}
export async function compressAllSvga(
paths = [],
onProgress: (cur?: number, total?: number) => void = () => void 0,
) {
for (let i = 0; i < paths.length; i++) {
const svga = paths[i];
const fileName = path.basename(svga);
try {
const sizePre = (await fs.stat(svga)).size;
const result = await compressSvga(svga);
if (result) {
await fs.writeFile(svga, result);
const sizeOp = (await fs.stat(svga)).size;
const radio = ((1 - sizeOp / sizePre) * 100).toFixed(2);
console.log(chalk.green("压缩Svga成功:" + fileName, `,压缩率:${radio}`));
}
} catch (e) {
console.log(chalk.red("压缩Svga失败:" + fileName));
}
onProgress(i + 1, paths.length);
}
// let completed = 0;
// const svgaPArr = paths.map((svga) => {
// return (async () => {
// const fileName = path.basename(svga);
// try {
// const sizePre = (await fs.stat(svga)).size;
// const result = await compressSvga(svga);
// if (result) {
// await fs.writeFile(svga, result);
// const sizeOp = (await fs.stat(svga)).size;
// const radio = ((1 - sizeOp / sizePre) * 100).toFixed(2);
// console.log(chalk.green("压缩Svga成功:" + fileName, `,压缩率:${radio}`));
// }
// } catch (e) {
// console.log(chalk.red("压缩Svga失败:" + fileName));
// }
//
// onProgress(completed++, paths.length);
// })();
// });
//
// await Promise.all(svgaPArr);
}
// protobuf读取svga配置
export default {
nested: {
com: {
nested: {
opensource: {
nested: {
svga: {
options: {
objc_class_prefix: 'SVGAProto',
java_package: 'com.opensource.svgaplayer.proto'
},
nested: {
MovieParams: {
fields: {
viewBoxWidth: {
type: 'float',
id: 1
},
viewBoxHeight: {
type: 'float',
id: 2
},
fps: {
type: 'int32',
id: 3
},
frames: {
type: 'int32',
id: 4
}
}
},
SpriteEntity: {
fields: {
imageKey: {
type: 'string',
id: 1
},
frames: {
rule: 'repeated',
type: 'FrameEntity',
id: 2
},
matteKey: {
type: 'string',
id: 3
}
}
},
AudioEntity: {
fields: {
audioKey: {
type: 'string',
id: 1
},
startFrame: {
type: 'int32',
id: 2
},
endFrame: {
type: 'int32',
id: 3
},
startTime: {
type: 'int32',
id: 4
},
totalTime: {
type: 'int32',
id: 5
}
}
},
Layout: {
fields: {
x: {
type: 'float',
id: 1
},
y: {
type: 'float',
id: 2
},
width: {
type: 'float',
id: 3
},
height: {
type: 'float',
id: 4
}
}
},
Transform: {
fields: {
a: {
type: 'float',
id: 1
},
b: {
type: 'float',
id: 2
},
c: {
type: 'float',
id: 3
},
d: {
type: 'float',
id: 4
},
tx: {
type: 'float',
id: 5
},
ty: {
type: 'float',
id: 6
}
}
},
ShapeEntity: {
oneofs: {
args: {
oneof: ['shape', 'rect', 'ellipse']
}
},
fields: {
type: {
type: 'ShapeType',
id: 1
},
shape: {
type: 'ShapeArgs',
id: 2
},
rect: {
type: 'RectArgs',
id: 3
},
ellipse: {
type: 'EllipseArgs',
id: 4
},
styles: {
type: 'ShapeStyle',
id: 10
},
transform: {
type: 'Transform',
id: 11
}
},
nested: {
ShapeType: {
values: {
SHAPE: 0,
RECT: 1,
ELLIPSE: 2,
KEEP: 3
}
},
ShapeArgs: {
fields: {
d: {
type: 'string',
id: 1
}
}
},
RectArgs: {
fields: {
x: {
type: 'float',
id: 1
},
y: {
type: 'float',
id: 2
},
width: {
type: 'float',
id: 3
},
height: {
type: 'float',
id: 4
},
cornerRadius: {
type: 'float',
id: 5
}
}
},
EllipseArgs: {
fields: {
x: {
type: 'float',
id: 1
},
y: {
type: 'float',
id: 2
},
radiusX: {
type: 'float',
id: 3
},
radiusY: {
type: 'float',
id: 4
}
}
},
ShapeStyle: {
fields: {
fill: {
type: 'RGBAColor',
id: 1
},
stroke: {
type: 'RGBAColor',
id: 2
},
strokeWidth: {
type: 'float',
id: 3
},
lineCap: {
type: 'LineCap',
id: 4
},
lineJoin: {
type: 'LineJoin',
id: 5
},
miterLimit: {
type: 'float',
id: 6
},
lineDashI: {
type: 'float',
id: 7
},
lineDashII: {
type: 'float',
id: 8
},
lineDashIII: {
type: 'float',
id: 9
}
},
nested: {
RGBAColor: {
fields: {
r: {
type: 'float',
id: 1
},
g: {
type: 'float',
id: 2
},
b: {
type: 'float',
id: 3
},
a: {
type: 'float',
id: 4
}
}
},
LineCap: {
values: {
LineCap_BUTT: 0,
LineCap_ROUND: 1,
LineCap_SQUARE: 2
}
},
LineJoin: {
values: {
LineJoin_MITER: 0,
LineJoin_ROUND: 1,
LineJoin_BEVEL: 2
}
}
}
}
}
},
FrameEntity: {
fields: {
alpha: {
type: 'float',
id: 1
},
layout: {
type: 'Layout',
id: 2
},
transform: {
type: 'Transform',
id: 3
},
clipPath: {
type: 'string',
id: 4
},
shapes: {
rule: 'repeated',
type: 'ShapeEntity',
id: 5
}
}
},
MovieEntity: {
fields: {
version: {
type: 'string',
id: 1
},
params: {
type: 'MovieParams',
id: 2
},
images: {
keyType: 'string',
type: 'bytes',
id: 3
},
sprites: {
rule: 'repeated',
type: 'SpriteEntity',
id: 4
},
audios: {
rule: 'repeated',
type: 'AudioEntity',
id: 5
}
}
}
}
}
}
}
}
}
}
};
pngquant and libimagequant are derived from code by Jef Poskanzer and Greg Roelofs
licensed under pngquant's original licenses (near the end of this file),
and contain extensive changes and additions by Kornel Lesiński
licensed under GPL v3 or later.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pngquant © 2009-2018 by Kornel Lesiński.
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The quantization and dithering code in pngquant is lifted from Jef Poskanzer's
'ppmquant', part of his wonderful PBMPLUS tool suite.
Greg Roelofs hacked it into a (in his words) "slightly cheesy" 'pamquant' back
in 1997 (see http://pobox.com/~newt/greg_rgba.html) and finally he ripped out
the cheesy file-I/O parts and replaced them with nice PNG code in December
2000. The PNG reading and writing code is a merged and slightly simplified
version of readpng, readpng2, and writepng from his book "PNG: The Definitive
Guide."
In 2014 Greg has relicensed the code under the simplified BSD license.
Note that both licenses are basically BSD-like; that is, use the code however
you like, as long as you acknowledge its origins.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pngquant.c:
© 1989, 1991 by Jef Poskanzer.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted, provided
that the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation. This software is provided "as is" without express or
implied warranty.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pngquant.c and rwpng.c/h:
© 1997-2002 by Greg Roelofs; based on an idea by Stefan Schneider.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# pngquant 3 [![CI](https://github.com/kornelski/pngquant/actions/workflows/ci.yml/badge.svg)](https://github.com/kornelski/pngquant/actions/workflows/ci.yml)
[pngquant](https://pngquant.org) is a PNG compressor that significantly reduces file sizes by converting images to a more efficient 8-bit PNG format *with alpha channel* (often 60-80% smaller than 24/32-bit PNG files). Compressed images are fully standards-compliant and are supported by all web browsers and operating systems.
[This](https://github.com/kornelski/pngquant) is the official `pngquant` repository. The compression engine is also available [as an embeddable library](https://github.com/ImageOptim/libimagequant).
## Usage
- batch conversion of multiple files: `pngquant *.png`
- Unix-style stdin/stdout chaining: `… | pngquant - | …`
To further reduce file size, try [oxipng](https://lib.rs/oxipng), [ImageOptim](https://imageoptim.com), or [zopflipng](https://github.com/google/zopfli).
## Features
* High-quality palette generation
- advanced quantization algorithm with support for gamma correction and premultiplied alpha
- unique dithering algorithm that does not add unnecessary noise to the image
* Configurable quality level
- automatically finds required number of colors and can skip images which can't be converted with the desired quality
* Fast, modern code
- based on a portable [libimagequant library](https://github.com/ImageOptim/libimagequant)
- C99 with no workarounds for legacy systems or compilers ([apart from Visual Studio](https://github.com/kornelski/pngquant/tree/msvc))
- multicore support (via OpenMP) and Intel SSE optimizations
## Options
See `pngquant -h` for full list.
### `--quality min-max`
`min` and `max` are numbers in range 0 (worst) to 100 (perfect), similar to JPEG. pngquant will use the least amount of colors required to meet or exceed the `max` quality. If conversion results in quality below the `min` quality the image won't be saved (if outputting to stdin, 24-bit original will be output) and pngquant will exit with status code 99.
pngquant --quality=65-80 image.png
### `--ext new.png`
Set custom extension (suffix) for output filename. By default `-or8.png` or `-fs8.png` is used. If you use `--ext=.png --force` options pngquant will overwrite input files in place (use with caution).
### `-o out.png` or `--output out.png`
Writes converted file to the given path. When this option is used only single input file is allowed.
### `--skip-if-larger`
Don't write converted files if the conversion isn't worth it.
### `--speed N`
Speed/quality trade-off from 1 (slowest, highest quality, smallest files) to 11 (fastest, less consistent quality, light comperssion). The default is 4. It's recommended to keep the default, unless you need to generate images in real time (e.g. map tiles). Higher speeds are fine with 256 colors, but don't handle lower number of colors well.
### `--nofs`
Disables Floyd-Steinberg dithering.
### `--floyd=0.5`
Controls level of dithering (0 = none, 1 = full). Note that the `=` character is required.
### `--posterize bits`
Reduce precision of the palette by number of bits. Use when the image will be displayed on low-depth screens (e.g. 16-bit displays or compressed textures in ARGB444 format).
### `--strip`
Don't copy optional PNG chunks. Metadata is always removed on Mac (when using Cocoa reader).
See [man page](https://github.com/kornelski/pngquant/blob/master/pngquant.1) (`man pngquant`) for the full list of options.
## License
pngquant is dual-licensed:
* Under **GPL v3** or later with an additional [copyright notice](https://github.com/kornelski/pngquant/blob/master/COPYRIGHT) that must be kept for the older parts of the code.
* Or [a **commercial license**](https://supso.org/projects/pngquant) for use in non-GPL software (e.g. closed-source or App Store distribution). You can [get the license via Super Source](https://supso.org/projects/pngquant). Email kornel@pngquant.org if you have any questions.
Apple's Notarization is a control-freak mess, and I don't have enough patience to deal with their tooling. 'brew install pngquant' may work too
pngquant and libimagequant are derived from code by Jef Poskanzer and Greg Roelofs
licensed under pngquant's original licenses (near the end of this file),
and contain extensive changes and additions by Kornel Lesiński
licensed under GPL v3 or later.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pngquant © 2009-2018 by Kornel Lesiński.
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The quantization and dithering code in pngquant is lifted from Jef Poskanzer's
'ppmquant', part of his wonderful PBMPLUS tool suite.
Greg Roelofs hacked it into a (in his words) "slightly cheesy" 'pamquant' back
in 1997 (see http://pobox.com/~newt/greg_rgba.html) and finally he ripped out
the cheesy file-I/O parts and replaced them with nice PNG code in December
2000. The PNG reading and writing code is a merged and slightly simplified
version of readpng, readpng2, and writepng from his book "PNG: The Definitive
Guide."
In 2014 Greg has relicensed the code under the simplified BSD license.
Note that both licenses are basically BSD-like; that is, use the code however
you like, as long as you acknowledge its origins.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pngquant.c:
© 1989, 1991 by Jef Poskanzer.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted, provided
that the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation. This software is provided "as is" without express or
implied warranty.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pngquant.c and rwpng.c/h:
© 1997-2002 by Greg Roelofs; based on an idea by Stefan Schneider.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@echo off
set path=%~d0%~p0
:start
"%path%pngquant.exe" --force --verbose --quality=45-85 %1
"%path%pngquant.exe" --force --verbose --ordered --speed=1 --quality=50-90 %1
shift
if NOT x%1==x goto start
@echo off
set path=%~d0%~p0
:start
"%path%pngquant.exe" --force --verbose 256 %1
shift
if NOT x%1==x goto start
# pngquant 2
[pngquant](https://pngquant.org) is a PNG compresor that significantly reduces file sizes by converting images to a more efficient 8-bit PNG format *with alpha channel* (often 60-80% smaller than 24/32-bit PNG files). Compressed images are fully standards-compliant and are supported by all web browsers and operating systems.
[This](https://github.com/kornelski/pngquant) is the official `pngquant` repository. The compression engine is also available [as an embeddable library](https://github.com/ImageOptim/libimagequant).
## Usage
- batch conversion of multiple files: `pngquant *.png`
- Unix-style stdin/stdout chaining: `… | pngquant - | …`
To further reduce file size, try [optipng](http://optipng.sourceforge.net), [ImageOptim](https://imageoptim.com), or [zopflipng](https://github.com/google/zopfli).
## Features
* High-quality palette generation
- advanced quantization algorithm with support for gamma correction and premultiplied alpha
- unique dithering algorithm that does not add unnecessary noise to the image
* Configurable quality level
- automatically finds required number of colors and can skip images which can't be converted with the desired quality
* Fast, modern code
- based on a portable [libimagequant library](https://github.com/ImageOptim/libimagequant)
- C99 with no workarounds for legacy systems or compilers ([apart from Visual Studio](https://github.com/kornelski/pngquant/tree/msvc))
- multicore support (via OpenMP) and Intel SSE optimizations
## Options
See `pngquant -h` for full list.
### `--quality min-max`
`min` and `max` are numbers in range 0 (worst) to 100 (perfect), similar to JPEG. pngquant will use the least amount of colors required to meet or exceed the `max` quality. If conversion results in quality below the `min` quality the image won't be saved (if outputting to stdin, 24-bit original will be output) and pngquant will exit with status code 99.
pngquant --quality=65-80 image.png
### `--ext new.png`
Set custom extension (suffix) for output filename. By default `-or8.png` or `-fs8.png` is used. If you use `--ext=.png --force` options pngquant will overwrite input files in place (use with caution).
### `-o out.png` or `--output out.png`
Writes converted file to the given path. When this option is used only single input file is allowed.
### `--skip-if-larger`
Don't write converted files if the conversion isn't worth it.
### `--speed N`
Speed/quality trade-off from 1 (slowest, highest quality, smallest files) to 11 (fastest, less consistent quality, light comperssion). The default is 3. It's recommended to keep the default, unless you need to generate images in real time (e.g. map tiles). Higher speeds are fine with 256 colors, but don't handle lower number of colors well.
### `--nofs`
Disables Floyd-Steinberg dithering.
### `--floyd=0.5`
Controls level of dithering (0 = none, 1 = full). Note that the `=` character is required.
### `--posterize bits`
Reduce precision of the palette by number of bits. Use when the image will be displayed on low-depth screens (e.g. 16-bit displays or compressed textures in ARGB444 format).
### `--strip`
Don't copy optional PNG chunks. Metadata is always removed on Mac (when using Cocoa reader).
See [man page](https://github.com/kornelski/pngquant/blob/master/pngquant.1) (`man pngquant`) for the full list of options.
## License
pngquant is dual-licensed:
* Under **GPL v3** or later with an additional [copyright notice](https://github.com/kornelski/pngquant/blob/master/COPYRIGHT) that must be kept for the older parts of the code.
* Or [a **commercial license**](https://supportedsource.org/projects/pngquant) for use in non-GPL software (e.g. closed-source or App Store distribution). You can [get the license via Supported Source](https://supportedsource.org/projects/pngquant/purchase). Email kornel@pngquant.org if you have any questions.
import chalk from "chalk";
import AutoUpload from "../Uploader/Uploader.ts";
import * as path from "path";
import {findFiles} from "../commom/helper.ts";
import {compressAllImage} from "../AssetsMin/ImageCompress.ts";
import {compressAllSvga} from "../AssetsMin/SvgaCompress.ts";
interface IDuibaPublishOptions {
buildVersion: string | number,
uploadDir: string,
accessKeySecret: string,
accessKeyId: string,
bucket: string,
region: string,
}
export default function DuibaPublish(options: IDuibaPublishOptions) {
const {
buildVersion,
uploadDir,
accessKeySecret,
accessKeyId,
bucket,
region,
} = options;
return {
name: 'duiba-publish',
async closeBundle() {
// 资源压缩
console.log(chalk.green("开始资源压缩了"));
console.log(chalk.green("开始压缩图片了"));
const imgPaths = findFiles(path.resolve("dist"), /\.png$/);
process.stdout.write(chalk.green(`\r压缩图片进度:${0}/${imgPaths.length}`));
await compressAllImage(imgPaths, (cur, total) => {
// process.stdout.write("\r");
process.stdout.write(chalk.green(`\r压缩图片进度:${cur}/${total}`));
});
console.log(chalk.green("\n压缩图片结束了\n"));
// 资源压缩
console.log(chalk.green("开始压缩Svga了"));
const svgaPaths = findFiles(path.resolve("dist"), /\.svga$/);
await compressAllSvga(svgaPaths, (cur, total) => {
// process.stdout.write(chalk.green(`\r压缩Svga进度:${cur}/${total}`));
});
console.log(chalk.green("\n压缩Svga结束了\n"));
console.log(chalk.green("开始上传了"));
const autoUpload = new AutoUpload({
dir: path.resolve("dist"),
originDir: `/${uploadDir}/${buildVersion}/`,
accessKeySecret, accessKeyId, bucket, region,
});
await autoUpload.start();
console.log(`${chalk.green(`上传成功,版本号: ${buildVersion}`)}`);
}
}
}
import * as path from "path";
import * as fs from "fs";
import ProgressBar from "progress";
import OSS from "ali-oss";
interface IAutoUploadOptions {
dir: string,
originDir: string,
bucket: string,
accessKeyId: string,
accessKeySecret: string,
region: string,
}
export default class AutoUpload {
options: IAutoUploadOptions = {
dir: "",
originDir: "",
region: "oss-cn-hangzhou",
accessKeyId: "",
accessKeySecret: "",
bucket: ""
};
client = null;
bar = null;
private _files: any[];
private existFiles: number = 0;
private uploadFiles: number = 0;
private errorFiles: number = 0;
constructor(props: IAutoUploadOptions) {
this.options = Object.assign({}, this.options, props);
const checkOptions = [
"dir", "originDir",
"bucket", "region",
"accessKeySecret", "accessKeyId",
];
for (const optionKey of checkOptions) {
if (!this.options[optionKey]) {
throw new Error(`AutoUpload: required option "${optionKey}"`);
}
}
this.init();
}
init() {
const {accessKeyId, accessKeySecret, bucket, region} = this.options;
this.client = new OSS({region, accessKeyId, accessKeySecret, bucket});
this.bar = new ProgressBar(`文件上传中 [:bar] :current/${this.files().length} :percent :elapseds`, {
complete: "●",
incomplete: "○",
width: 20,
total: this.files().length,
callback: () => {
console.log("%cAll complete.", "color: green");
console.log(`%c本次队列文件共${this.files().length}个,已存在文件${this.existFiles}个,上传文件${this.uploadFiles}个,上传失败文件${this.errorFiles}个`, "color: green");
}
})
return this;
}
files() {
if (this._files) return this._files;
this._files = [];
/**
* 文件遍历方法
* @param filePath 需要遍历的文件路径
*/
const fileDisplay = (filePath) => {
//根据文件路径读取文件,返回文件列表
const files = fs.readdirSync(filePath);
files.forEach((filename) => {
//获取当前文件的绝对路径
const fileDir = path.join(filePath, filename);
//根据文件路径获取文件信息,返回一个fs.Stats对象
const stats = fs.statSync(fileDir);
const isFile = stats.isFile();//是文件
const isDir = stats.isDirectory();//是文件夹
if (isFile) {
this._files.push(fileDir);
} else if (isDir) {
fileDisplay(fileDir);//递归,如果是文件夹,就继续遍历该文件夹下面的文件
}
});
}
//调用文件遍历方法
fileDisplay(this.options.dir);
return this._files;
}
async start() {
const ps = this.files().map((file) => {
const relativePath = path.relative(this.options.dir, file)
.replace(path.sep, "/");
this.existFiles = 0;
this.uploadFiles = 0;
this.errorFiles = 0;
const originPath = `${this.options.originDir}${relativePath}`;
return (async () => {
let originFile = null;
originFile = await this.client.head(originPath)
.catch((error: Error) => originFile = error);
try {
if (originFile.status === 404) {
await this.client.put(originPath, file);
this.uploadFiles += 1;
} else {
this.existFiles += 1;
}
} catch (error) {
this.errorFiles += 1;
}
this.bar.tick();
})();
});
await Promise.all(ps).catch((err) => {
console.error("上传错误", err);
});
}
}
import * as fs from "node:fs";
export function findFiles(dir: string, regExp: RegExp) {
let fileArr = [];
if (fs.existsSync(dir)) {
const files = fs.readdirSync(dir);
files.forEach((file) => {
const fpath = dir + '/' + file;
const stat = fs.lstatSync(fpath);
if (stat.isFile() && regExp.test(file)) {
fileArr.push(fpath);
} else if (stat.isDirectory()) {
fileArr.push(...findFiles(fpath, regExp));
}
})
}
return fileArr;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="dns-prefetch" href="//yun.duiba.com.cn" />
<link rel="preconnect" href="//embedlog.duiba.com.cn">
<title>守护权益对对碰</title>
<script type="text/javascript">
if (localStorage && localStorage.isWebp) {
document
.getElementsByTagName('html')[0]
.setAttribute('duiba-webp', 'true');
}
</script>
<script src="//yun.duiba.com.cn/js-libs/rem/1.1.3/rem.min.js"></script>
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script>
var CFG = CFG || {};
CFG.projectId = location.pathname.split('/')[2] || '1';
function getUrlParam(name) {
var search = window.location.search;
var matched = search
.slice(1)
.match(new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'));
return search.length ? matched && matched[2] : null;
}
CFG.appID = '${APPID}';
if (!getUrlParam("appID")) {
// alert("【警告】检测到活动url中没有appID参数\n缺少该参数会导致埋点、分享、app信息获取错误。")
}
</script>
<script type="module" crossorigin src="https://yun.duiba.com.cn/db_games/spark/v3/1746968226438/assets/index-58DNo98O.js"></script>
<link rel="modulepreload" crossorigin href="https://yun.duiba.com.cn/db_games/spark/v3/1746968226438/assets/vendor-BcaFA3fM.js">
<link rel="stylesheet" crossorigin href="https://yun.duiba.com.cn/db_games/spark/v3/1746968226438/assets/vendor-CWeaUrOh.css">
<link rel="stylesheet" crossorigin href="https://yun.duiba.com.cn/db_games/spark/v3/1746968226438/assets/index-DeWsH3SG.css">
<script type="module">import.meta.url;import("_").catch(()=>1);(async function*(){})().next();if(location.protocol!="file:"){window.__vite_is_modern_browser=true}</script>
<script type="module">!function(){if(window.__vite_is_modern_browser)return;console.warn("vite: loading legacy chunks, syntax error above and the same error below should be ignored");var e=document.getElementById("vite-legacy-polyfill"),n=document.createElement("script");n.src=e.src,n.onload=function(){System.import(document.getElementById('vite-legacy-entry').getAttribute('data-src'))},document.body.appendChild(n)}();</script>
</head>
<body>
<div id="root"></div>
<script nomodule>!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",(function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()}),!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();</script>
<script nomodule crossorigin id="vite-legacy-polyfill" src="https://yun.duiba.com.cn/db_games/spark/v3/1746968226438/assets/polyfills-legacy-C2MhNPfJ.js"></script>
<script nomodule crossorigin id="vite-legacy-entry" data-src="https://yun.duiba.com.cn/db_games/spark/v3/1746968226438/assets/index-legacy-D09RGcIT.js">System.import(document.getElementById('vite-legacy-entry').getAttribute('data-src'))</script>
</body>
</html>
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
export default tseslint.config(
{ ignores: ['dist'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/ban-ts-comment": "off",
"@typescript-eslint/no-unused-expressions": "off",
"prefer-rest-params": "off",
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
},
)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="dns-prefetch" href="//yun.duiba.com.cn" />
<link rel="preconnect" href="//embedlog.duiba.com.cn">
<title>天天领积分</title>
<script type="text/javascript">
if (localStorage && localStorage.isWebp) {
document
.getElementsByTagName('html')[0]
.setAttribute('duiba-webp', 'true');
}
</script>
<script src="//yun.duiba.com.cn/js-libs/rem/1.1.3/rem.min.js"></script>
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script>
var CFG = CFG || {};
CFG.projectId = location.pathname.split('/')[2] || '1';
function getUrlParam(name) {
var search = window.location.search;
var matched = search
.slice(1)
.match(new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'));
return search.length ? matched && matched[2] : null;
}
CFG.appID = '${APPID}';
if (!getUrlParam("appID")) {
// alert("【警告】检测到活动url中没有appID参数\n缺少该参数会导致埋点、分享、app信息获取错误。")
}
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/App.tsx"></script>
</body>
</html>
import CryptoJS from 'crypto-js';
const { mode, pad, enc, AES } = CryptoJS;
const getOptions = (iv: string) => {
return {
iv: enc.Utf8.parse(iv),
mode: mode.CBC,
padding: pad.ZeroPadding,
};
}
/** 加密 */
export function AESEncrypt(str: string, key: string, iv: string) {
const options = getOptions(iv);
return AES.encrypt(str, enc.Utf8.parse(key), options).toString();
}
/** 解密 */
export function AESDecrypt(cipherText: string, key: string, iv: string) {
const options = getOptions(iv);
return AES.decrypt(cipherText, enc.Utf8.parse(key), options)
.toString(enc.Utf8)
.trim()
.replace(//g, '')
.replace(//g, '')
.replace(/\v/g, '')
.replace(/\x00/g, '');
}
import { AESDecrypt, AESEncrypt } from "./Crypto";
export default [
{
url: '/tcs/index.do',
response: ({ query }) => {
return {
"success": true,
"code": "",
"message": "",
"timeStamp": Date.now(),
"data": {
"startTime": Date.now() - 1000000,
"endTime": Date.now() + 1000000,
"remainTimes": 12,
"uid": "uiduiduiduiduiduiduid",
}
}
},
},
{
url: '/tcs/start.do',
response: ({ query }) => {
return {
"success": true,
"code": "",
"message": "",
"data": AESEncrypt(JSON.stringify({
recordId: "recordId",
countdownSeconds: 120,
guide: true,
}), "3C8C48E792E9241B", "cDOiBC1n2QrkAY2P"),
}
},
},
{
url: '/tcs/submit.do',
response: ({ query }) => {
return {
success: true,
code: "",
message: "",
data: {
score: 888,
rank: 1,
prizeName: "一等奖",
reachTargetScore: 666,
drawChance: 10,
}
}
},
},
{
url: '/tcs/guide.do',
response: ({ query }) => {
return {
success: true,
code: "",
message: "",
data: null,
}
},
},
{
url: "/gaw/address/getChildrenByParentCode",
response: ({ query }) => {
return {
"success": true,
"code": "0000000000",
"desc": "OK",
"timestamp": 1736580360076,
"data": [{
"name": "东华门街道",
"adCode": "110101001",
"level": 4
},
{
"name": "景山街道",
"adCode": "110101002",
"level": 4
},
{
"name": "交道口街道",
"adCode": "110101003",
"level": 4
},
{
"name": "安定门街道",
"adCode": "110101004",
"level": 4
},
{
"name": "北新桥街道",
"adCode": "110101005",
"level": 4
},
{
"name": "东四街道",
"adCode": "110101006",
"level": 4
},
{
"name": "朝阳门街道",
"adCode": "110101007",
"level": 4
},
{
"name": "建国门街道",
"adCode": "110101008",
"level": 4
},
{
"name": "东直门街道",
"adCode": "110101009",
"level": 4
},
{
"name": "和平里街道",
"adCode": "110101010",
"level": 4
},
{
"name": "前门街道",
"adCode": "110101011",
"level": 4
},
{
"name": "崇文门外街道",
"adCode": "110101012",
"level": 4
},
{
"name": "东花市街道",
"adCode": "110101013",
"level": 4
},
{
"name": "龙潭街道",
"adCode": "110101014",
"level": 4
},
{
"name": "体育馆路街道",
"adCode": "110101015",
"level": 4
},
{
"name": "天坛街道",
"adCode": "110101016",
"level": 4
},
{
"name": "永定门外街道",
"adCode": "110101017",
"level": 4
}
]
}
},
},
{
url: '/draw/myPrizeRecord.do',
response: ({ query }) => {
return {
"success": true,
"code": "",
"message": "",
"data": [
{
extra: {
name: "一等奖",
icon: 'https://yun.duiba.com.cn/polaris/shareImg.721503d9417b09af6346ae018493aec558ca31af.png',
},
needFillAddress: true,
prizeId: '',
boolThirdObject: true
},
{
extra: {
name: "一等奖",
icon: 'https://yun.duiba.com.cn/polaris/shareImg.721503d9417b09af6346ae018493aec558ca31af.png',
},
needFillAddress: true,
prizeId: '',
boolThirdObject: false
},
{
extra: {
name: "一等奖",
icon: 'https://yun.duiba.com.cn/polaris/shareImg.721503d9417b09af6346ae018493aec558ca31af.png',
},
needFillAddress: false,
prizeId: '',
boolThirdObject: true
},
{
extra: {
name: "一等奖",
icon: 'https://yun.duiba.com.cn/polaris/shareImg.721503d9417b09af6346ae018493aec558ca31af.png',
},
needFillAddress: true,
prizeId: ''
},
{
extra: {
name: "一等奖",
icon: 'https://yun.duiba.com.cn/polaris/shareImg.721503d9417b09af6346ae018493aec558ca31af.png',
},
needFillAddress: true,
prizeId: ''
},
{
extra: {
name: "一等奖",
icon: 'https://yun.duiba.com.cn/polaris/shareImg.721503d9417b09af6346ae018493aec558ca31af.png',
},
needFillAddress: true,
prizeId: ''
},
{
extra: {
name: "一等奖",
icon: 'https://yun.duiba.com.cn/polaris/shareImg.721503d9417b09af6346ae018493aec558ca31af.png',
},
needFillAddress: true,
prizeId: ''
},
{
extra: {
name: "一等奖",
icon: 'https://yun.duiba.com.cn/polaris/shareImg.721503d9417b09af6346ae018493aec558ca31af.png',
},
needFillAddress: true,
prizeId: ''
},
{
extra: {
name: "一等奖",
icon: 'https://yun.duiba.com.cn/polaris/shareImg.721503d9417b09af6346ae018493aec558ca31af.png',
},
needFillAddress: true,
prizeId: ''
},
{
extra: {
name: "一等奖",
icon: 'https://yun.duiba.com.cn/polaris/shareImg.721503d9417b09af6346ae018493aec558ca31af.png',
},
needFillAddress: true,
prizeId: ''
},
{
extra: {
name: "一等奖",
icon: 'https://yun.duiba.com.cn/polaris/shareImg.721503d9417b09af6346ae018493aec558ca31af.png',
},
needFillAddress: true,
prizeId: ''
},
{
extra: {
name: "一等奖",
icon: 'https://yun.duiba.com.cn/polaris/shareImg.721503d9417b09af6346ae018493aec558ca31af.png',
},
needFillAddress: true,
prizeId: ''
},
{
extra: {
name: "一等奖",
icon: 'https://yun.duiba.com.cn/polaris/shareImg.721503d9417b09af6346ae018493aec558ca31af.png',
},
needFillAddress: true,
prizeId: ''
},
{
extra: {
name: "一等奖",
icon: 'https://yun.duiba.com.cn/polaris/shareImg.721503d9417b09af6346ae018493aec558ca31af.png',
},
needFillAddress: true,
prizeId: ''
},
{
extra: {
name: "四等奖",
icon: 'https://yun.duiba.com.cn/polaris/shareImg.721503d9417b09af6346ae018493aec558ca31af.png',
},
needFillAddress: true,
prizeId: ''
}
]
}
}
},
{
url: '/inviteAssist_1/getInviteCode.do',
response: ({ query }) => {
return {
"code": null,
"data": {
"dueTime": null,
"extra": null,
"inviteCode": "ZHHUJS",
"timestamp": 1746965897230
},
"message": null,
"success": true,
"timeStamp": 1746965897241
}
}
}
]
import {AESEncrypt} from "./Crypto";
export default [
{
url: '/projectRule.query',
method: 'get',
response: ({query}) => {
return {
"data": "<p>以下是游戏规则:手速要快,点击红包雨。。333。。。。。。。。。。。。。。。。。。。。11111111111111sadasdadadsad5555555557777777777799999999999911111111111111111111111222222222222222222222222222222222222222222222222222222222222222333333333333333333333333333333333333333333333333333333333333311111111111111111111111111111111111111111111111111111111111111122222222222222222222222222222222222222222222222222222222222222233333333333333333333333333333333333333333333333333333333333331111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222223333333333333333333333333333333333333333333333333333333333333</p>",
"success": true
}
},
},
{
url: '/coop_frontVariable.query',
method: 'get',
response: ({query}) => {
return {
"success": true,
"message": "报错了~",
"code": null,
"data": {
"privacyTxt": "privacyTxtprivacyTxtprivacyTxtprivacyTxtprivacyTxtprivacyTxtprivacyTxtprivacyTxt",
"prizeInfoAuthTxt": "prizeInfoAuthTxtprizeInfoAuthTxtprizeInfoAuthTxtprizeInfoAuthTxtprizeInfoAuthTxtprizeInfoAuthTxtprizeInfoAuthTxtprizeInfoAuthTxt",
"test_config_02": "111",
shareInfo: {
"title": '守护权益对对碰',
"desc": '2025年“3·15”金融消费者权益保护教育宣传活动',
"imgUrl": 'https://yun.duiba.com.cn/polaris/shareImg.721503d9417b09af6346ae018493aec558ca31af.png'
},
shopUrl:'https://'
}
}
},
},
{
url: '/join.do',
response: ({query}) => {
return {
"code": "code",
"success": true,
"message": "message",
"timeStamp": Date.now(),
"data": AESEncrypt(JSON.stringify({
"startId": "officia",
"countDown": 30
}), "1696BD3E5BB915A0", "cDOiBC1n2QrkAY2P"),
}
},
},
{
url: '/records.query',
response: ({query}) => {
return {
"code": "code",
"success": true,
"message": "message",
"timeStamp": Date.now(),
"data": [
{
"extra": {
"name": "优惠券-大转盘02优惠券-大转盘02优惠券-大转盘02",
"icon": "//yun.dui88.com/images/201907/tua0um9jjp.jpg",
"refType": "coupon",
"refId": "49354",
"type": 2
},
"strategyId": 11,
"gmtCreate": 1565213353000,
"id": 331,
"prizeId": "g4c4c3edd"
},
{
"extra": {
"name": "优惠券-大转盘03",
"icon": "//yun.duiba.com.cn/polaris/%E6%95%B0%E6%8D%AE%E5%86%B3%E7%AD%96%E5%B7%A5%E5%85%B7.531c2dae250ab379fd6216eb038e60bc12ab9dd6.png",
"refType": "coupon",
"refId": "49354",
"type": 2
},
"strategyId": 11,
"gmtCreate": 1565213116000,
"id": 330,
"prizeId": "g0e432eeb"
},
{
"extra": {
"name": "优惠券-大转盘05",
"icon": "//yun.dui88.com/images/201907/tua0um9jjp.jpg",
"refType": "coupon",
"refId": "49354",
"type": 2
},
"strategyId": 11,
"gmtCreate": 1565212826000,
"id": 329,
"prizeId": "g900c8442"
},
{
"extra": {
"name": "优惠券-大转盘01",
"icon": "//yun.dui88.com/images/201907/tua0um9jjp.jpg",
"refType": "coupon",
"refId": "49354",
"type": 2
},
"gmtCreate": 1565205625000,
"id": 328,
"strategyId": 11,
"prizeId": "g4c7ba888"
},
{
"extra": {
"name": "优惠券-大转盘05",
"icon": "//yun.dui88.com/images/201907/tua0um9jjp.jpg",
"refType": "coupon",
"refId": "49354",
"type": 2
},
"strategyId": 11,
"gmtCreate": 1565203101000,
"id": 327,
"prizeId": "g900c8442"
},
{
"extra": {
"name": "优惠券-大转盘03",
"icon": "//yun.dui88.com/images/201907/tua0um9jjp.jpg",
"refType": "coupon",
"refId": "49354",
"type": 2
},
"strategyId": 11,
"gmtCreate": 1565203040000,
"id": 326,
"prizeId": "g0e432eeb"
},
{
"extra": {
"name": "优惠券-大转盘04",
"icon": "//yun.dui88.com/images/201907/tua0um9jjp.jpg",
"refType": "coupon",
"refId": "49354",
"type": 2
},
"gmtCreate": 1565197386000,
"id": 325,
"prizeId": "gc1a8c03c"
},
{
"extra": {
"name": "优惠券-大转盘02",
"icon": "//yun.dui88.com/images/201907/tua0um9jjp.jpg",
"refType": "coupon",
"refId": "49354",
"type": 2
},
"gmtCreate": 1565197080000,
"id": 324,
"strategyId": 11,
"prizeId": "g0e432eeb"
}
],
}
},
},
]
export default [
{
url: '/log/click',
method: 'get',
response: 1,
},
{
url: '/exposure/standard',
method: 'get',
response: 1,
},
]
export default [
{
url: '/getTokenKey',
method: 'get',
response: ({query}) => {
return `/*kAYom*/var/*r09wG8etE2C0Ww*/__znEpIi/*NQu8hjl0pN*/=\u0053\u0074\u0072\u0069\u006e\u0067
/*oOKm61nGC*/./*azF3poNNY*/\u0066r\u006fm\u0043ha\u0072C\u006fde/*p0scllAOdTIKgCQ*/;
var/*SSGyGa*/_x_PHl = [/*TI3296OxdeL5hVix2TN*/346,2778,2017,2853,3444,/*bkKvcNtSusbemP*/];//zEYRSemnjOjcNUASL
var/*xJMAbB8iLg4*/_$RgZD/*Alev912F2ayU*/=/*jizy4Pza*/function(/*kNI7evNH1dIHLufJv0*/){
/*HmnkIUTfKeeCmuEn6xR*/return/*wdrdF07*/arguments[/*kOUA65F5kmJ6*/0]^/*QliZg*/
/*re6sAsWJiS*/_x_PHl[/*wf4GYRqD7T8*/0];/*EY9BrOknLI4375Ud9*/}/*pjXbjfZ2UttwrBw4*/;
var/*39PJNjIs9b*/_$RJWM/*5AYrCD*/=/*KnY6EjF*/function(/*20AS3Cfv27IbE*/){
/*tNi9OM9o8PhYR2Qk9A*/return/*5pQG605eyTAiTmSweDU*/arguments[/*Krq2tosh3WT6xkxXG*/0]^/*FZUfTGZuYOo079NkKS*/
/*rm4tfrO*/_x_PHl[/*XmxOAUw2BOZare2Dxo*/1];/*5BKxUEwuPMRIoey1*/}/*z5roQy*/;
var/*JgLqC*/_$Hel/*066zrrTHOtkj*/=/*XjCHxPiHiw0xa9*/function(/*QdWUahPa1PgQU3E*/){
/*eyl74GIRr00aGr*/return/*lthXN*/arguments[/*f7XIfP7DLrtDxVhF*/0]^/*tdwAoDV4Pr5xTlbjp*/
/*Ma3P6Vq8I3oiJNCM*/_x_PHl[/*YfxdG2GGzCghna*/2];/*2wv3PI45f5naj*/}/*n0yn7C6o*/;
var/*v5ff4kULiZ*/_$xdxE/*VkgDK*/=/*IfqMFT603dWRb8*/function(/*tvUkbhr25H0bh*/){
/*RCOsZr5YRuv0niCgH*/return/*7oNgjaPNqc2u87FVC*/arguments[/*TGEa25U*/0]^/*abBFrEnlM*/
/*n7omf9N9Y3Bnn3*/_x_PHl[/*cw2io3ClYuq2GfNOK*/3];/*Sno31ANmfqhMODz44Th*/}/*W3gMs3FA*/;
var/*3glOFLO8b*/_$l0Y/*tOL91xBzN9B*/=/*bmowclP6m1X*/function(/*s0VWPJbv*/){
/*EEPm0gV*/return/*2hpbcGZzoYjX75g5u*/arguments[/*GfJl5uMVC*/0]^/*hDkAt8*/
/*0wwp2A7OhWi*/_x_PHl[/*7d2SgQQtQ36HcL9*/4];/*GkBLnGxuRNZsosmgHUi*/}/*1HcGytDTmhVleoGeR4*/;
/*Dwy6qN9hWfj*/\u0065\u0076\u0061\u006c/*BWHcn35SzW*/(__znEpIi(32)
+/*BFmqKuXP*/__znEpIi(102,0x0|0x75,0x0|0x6e,Math.abs(99)&-1,1161/0xA,105,0157,~(0x6e^/*qb*/-1),0x2044>>/*WctgaYWOuAekzs2*/4>>4,1115/0xA,
104/*4I*/,_$Hel(1931),97,-1-~/*nJx*/(0x69^0),0x0|0x6f,0x6899/0400,100,0x6651/0400,0x2866/0400,_$RJWM(0xaf3),
32&(-1^0x00),123,0x2069/0400,118,-1-~/*VY*/(0x61^0),-1-~/*S4n*/(0x72^0),322/0xA,107&(-1^0x00),~/*EpM4E1prAHz*/~/*EeYbvDsSQi521*/101,0x0|0x79,
~/*aOIjG92cKa*/~/*US53CXA*/32,614/0xA,32,_$l0Y(0xd5316/0400),_$RJWM(0x0|0xaaa),~/*2Ev3SdyxvK0mla*/~/*Up4UosavA58ChUz0I*/54,0x3648>>/*eAly5st4amtH*/4>>4,~(0x37^/*pZ*/-1),Math.abs(98)&-1,49,
39,0x3b64>>/*N3FPTpQvLsOddndAbTU*/4>>4,0x7691>>/*isQ6wKT*/4>>4,97,0x7285>>/*zIHppJKQ5VUmkD*/4>>4,0x0|0x20,1161/0xA,32,_$l0Y(0xd4916>>/*mrvi8e*/4>>4),Math.abs(32)&-1,
_$xdxE(05522),_$Hel(19281/0xA),110,0144,Math.abs(111)&-1,0x77,91,107,1015/0xA,121,
Math.abs(93)&-1,590/0xA,-1-~/*Zk4G*/(0x64^0),101,0x0|0x6c,101,0x0|0x74,101/*ni*/,322/0xA,0167,
105,_$Hel(1935),100,111,0x7755/0400,~/*S2SGLLl*/~/*zos5DpQNBy*/91,-1-~/*1WRk*/(0x6b^0),0x0|0x65,_$l0Y(33414/0xA),93&(-1^0x00),
0x0|0x3b,~/*5b3IEtb8fywFrveCRMr*/~/*Q6QxkUid*/32,114,Math.abs(101)&-1,_$RJWM(2734),-1-~/*UbZA*/(0x75^0),114&(-1^0x00),0x6e07/0400,32,~/*rDz4Z2hP0b3viUg*/~/*rUDIyDIW*/116,
_$xdxE(0x0|0xb1e),_$Hel(03634)/*KhGbUVwyZRLYya*/));/*qSvuXGoAFMLnuM7BiqR*/`
},
},
{
url: '/getToken',
method: 'get',
response: ({query}) => {
return {
"success": true,
"message": null,
"code": null,
"timeStamp": 1740109120049,
"data": "/*1rDOzce8YRSb1D*/var/*M3ur3k7KCh3MFN4UK6*/__9yHjP/*Y0w2w*/=\\u0053\\u0074\\u0072\\u0069\\u006e\\u0067\n/*Ens2laCwC8YWQP49*/./*0RndL*/\\u0066r\\u006fm\\u0043ha\\u0072C\\u006fde/*QrSM7OteX*/;\nvar/*ezfJOf*/_x_NGr = [/*VBDIEu*/3790,2234,95,2728,50,/*40MVTLjbG*/];//PVuy2MGSYhmlw\nvar/*STxEm*/_$3fYC/*fmtnZXIV8w1*/=/*3nLvAw3KYkU1Wg*/function(/*VZAWif*/){\n/*qTgV3rN5XFD0keiipI*/return/*7jXapEK2UW2mk9pr*/arguments[/*OasNvLaiuznu*/0]^/*VsX4BqaNzZvZYUbqHg*/\n/*tyt3PMaME4oC8RPbD*/_x_NGr[/*3LSwCA04*/0];/*bsAWvG*/}/*mtoGwrxRKHBwzUS5*/;\nvar/*JFgdwru4ztXSqvCfG*/_$jE8/*axt6G6f4MShTrVmBvs*/=/*GLtAZGXJv4EwdlUOGsb*/function(/*HqLWcKj9Z8e*/){\n/*JzxOXYOHQcZx*/return/*GSWq1nrtGAPnh5WC1H*/arguments[/*EzUMRneiBt9l*/0]^/*oFZ0vztKy7m6ZBAzWQd*/\n/*A3T7OkI*/_x_NGr[/*9RzD4TIneLm02kL*/1];/*DQ2egbUI*/}/*dJg8lx*/;\nvar/*j8u2yL7KgEq4xe*/_$PQvh/*kBWJIqDSMPhgRsej*/=/*mbzoH5mDuD0CUOZQ*/function(/*bE8JIL9kDEaVJyugA*/){\n/*Ns0thIYSuRY0*/return/*IB4qe4obQ5Kf*/arguments[/*VA2Gw*/0]^/*hvGJtzK5TL*/\n/*ZtEFj*/_x_NGr[/*yVDp3LAfM4qHWnzz*/2];/*BEi0oikvf*/}/*Umn8xc*/;\nvar/*UG397EX9BFgrsp*/_$2QNa/*ExBb0LqtVWckJOWs*/=/*l5NLCuoaqqvznTRARM*/function(/*gLOKeuK0C*/){\n/*hj2QebUBrRTrd*/return/*MLl4s2Mtne*/arguments[/*k9EQjBp8NZyW3*/0]^/*I1EZouy0Ty*/\n/*k8kADa*/_x_NGr[/*pyUnGrf3*/3];/*iNYbtsaOkkrL*/}/*oLTvnv*/;\nvar/*vUvMotp0f1VOb7n9b*/_$ykcM/*JeUVpoULqM5N*/=/*slAP4OYRH6NeP*/function(/*MbtyTfCFqg6afTg*/){\n/*52888FSrcva*/return/*ootuTH9X02JgDNeC4f2*/arguments[/*J2vHlch4EJbaH*/0]^/*TO5T0u41f5H*/\n/*DecC2mARFMRDK8hS56m*/_x_NGr[/*ecWbig*/4];/*48K8sjGV*/}/*aYJnfnAu*/;\n/*c8d6D*/\\u0065\\u0076\\u0061\\u006c/*jlVGRPsn4W4vcimcf2w*/(__9yHjP(32)\n+/*oWhxgaFBYHjA7N*/__9yHjP(1194/0xA,1054/0xA,_$jE8(0x0|0x8d4),100&(-1^0x00),~/*FyEW99yb6*/~/*tR4YOHfPelE3EiL*/111,119,-1-~/*lf0h*/(0x5b^0),047,112,_$2QNa(2715),\n98&(-1^0x00),102/*bD*/,Math.abs(97)&-1,99,39&(-1^0x00),93/*JT*/,61,34,0160,~/*rtcl9k*/~/*c5qAxIRkP2eRnkFxq*/51,\n0x0|0x63,Math.abs(57)&-1,0x0|0x32,0x0|0x61,_$2QNa(0xace),98,~/*ai9YfRq*/~/*8plD3warLQW3XHslHf*/34,59,0x0|0x77,105,\n0x6e01>>/*pXWIST6AD4WoZSg*/4>>4,-1-~/*L7*/(0x64^0),111,119,91,395/0xA,112/*Ze*/,~/*DkkUlLo*/~/*6GVezxv*/56,56,-1-~/*t2*/(0x36^0),\n0x3336>>/*IofNKQmyxBuEd*/4>>4,100,393/0xA,932/0xA,~/*EwztjN4KD01myh2*/~/*dhtX0PkTKy7*/61,_$ykcM(0x1061>>/*gKqrVpkS*/4>>4),0x0|0x70,-1-~/*1QC1*/(0x64^0),Math.abs(54)&-1,511/0xA,\n_$ykcM(0x347/0400),Math.abs(99)&-1,519/0xA,~/*8iVqOz0Owd7Y73*/~/*xEZKPcxMx*/50,~/*IEuBPVOcAik*/~/*xQth23iL6v*/34,-1-~/*uwiy*/(0x3b^0),0x77,Math.abs(105)&-1,110,100&(-1^0x00),\n111&(-1^0x00),119/*7j*/,91,~(0x27^/*2E*/-1),0x0|0x70,97,_$3fYC(0xeab33>>/*8ugWNZw*/4>>4),070,0x0|0x61,101,\nMath.abs(39)&-1,93,~/*aHitFgQEkl0*/~/*Z0hamVirzKlAa7ocU*/61,~(0x22^/*XN*/-1),-1-~/*9u*/(0x70^0),54/*rz*/,100,0144,0x6637>>/*HpxBcVTX9eS171Gie*/4>>4,065,\n0x63,_$3fYC(~/*bdjzR8*/~/*1OzRf*/3757),34,0x3b65>>/*f5EcUOqPvF70UuCejFH*/4>>4,0x7762>>/*LjT3McweLcIzh*/4>>4,0151,110,100,0x6f02>>/*9NOOjEiLsnw7L7XDW*/4>>4,119,\n_$ykcM(105&(-1^0x00)),39&(-1^0x00),0x7002>>/*4yi1KDV8wUDZiHo4xb*/4>>4,-1-~/*DA*/(0x39^0),-1-~/*a0*/(0x64^0),52,57/*fh*/,~/*iFFagg5Vy*/~/*Wk6Lh7S0lo*/57,39&(-1^0x00),-1-~/*AwmH*/(0x5d^0))\n+/*kJxhIcbeiUcvU9ywXt*/__9yHjP(~/*PmwiWVgG9NEPJiLKOZ*/~/*9XEawbPlYzYYiTs*/61,34/*hN*/,Math.abs(112)&-1,985/0xA,~(0x62^/*O5*/-1),~(0x66^/*vUe*/-1),~/*YAAXVhhhYiwV9DqvZLJ*/~/*fxBNdY7b*/56,_$jE8(21794/0xA),0x3014>>/*4PvBjzjZb*/4>>4,~(0x30^/*dm*/-1),\n~/*Mt1DrolyttRUPF9H*/~/*MW4RIN2VFPEWT5dBgHc*/34,597/0xA,_$jE8(Math.abs(2253)&-1),105,110,100/*xZ*/,~(0x6f^/*xVG*/-1),119,-1-~/*ua4*/(0x5b^0),_$2QNa(2703),\n-1-~/*12P6*/(0x70^0),0x3041>>/*ljZsY32*/4>>4,-1-~/*Zxn*/(0x65^0),567/0xA,~(0x33^/*z2T*/-1),100,0x2790>>/*u8qQKkoqgY8eMUJDwl*/4>>4,_$jE8(0x8e713/0400),Math.abs(61)&-1,34,\n112,101&(-1^0x00),54,511/0xA,55,Math.abs(54)&-1,97/*9T*/,0144,34&(-1^0x00),0x3b32/0400,\n0x7784>>/*5dXaPpTGbhL4*/4>>4,0x0|0x69,110,Math.abs(100)&-1,~/*Mw6uyiUbgfN516ntsS*/~/*tuplYzaYIb*/111,119,Math.abs(91)&-1,047,112,54,\n0x3669/0400,55,98/*id*/,Math.abs(49)&-1,~(0x27^/*RqZM*/-1),93&(-1^0x00),61/*ob*/,Math.abs(34)&-1,112,~(0x33^/*1vn*/-1),\n~/*uqge9FC9hzHeXglx3vP*/~/*gB1TWr9cmvhbKTlYor9*/51,~/*5hKO3Ixv*/~/*YkVcr*/52,55,_$PQvh(108),54,~/*MhhPJzQD*/~/*jXdPeL0NNMacTqf4dqs*/54,0x22,0x0|0x3b,0x7736/0400,105,\n110,0144,111,119&(-1^0x00),Math.abs(91)&-1,39,0160,_$jE8(Math.abs(2264)&-1),~/*ctRgGewmh*/~/*PgLlilwb*/53,064,\n0x3905>>/*Tv1sWCDF*/4>>4,_$3fYC(3759),_$jE8(2205/*pi*/),~/*XMe6krVbOWctX5*/~/*dlS2sSdNID*/93,610/0xA,_$ykcM(16),112,53,Math.abs(56)&-1,_$2QNa(0xa9b),\n554/0xA,Math.abs(49)&-1,0x6120>>/*1vs8pDqpLiV12gSFS3y*/4>>4,0x6259/0400,342/0xA,59&(-1^0x00),~(0x77^/*ZE6*/-1),_$jE8(0x8d324/0400),110,Math.abs(100)&-1)\n+/*UNNoMiO*/__9yHjP(-1-~/*wpck*/(0x6f^0),1195/0xA,91,~(0x27^/*VdXB*/-1),_$2QNa(Math.abs(2776)&-1),50,97,060,99,98,\n0x2750/0400,0x5d35/0400,61,_$PQvh(125/*Gt*/),0x7065>>/*yN2B1A2gKxq*/4>>4,_$ykcM(-1-~/*mX*/(0x54^0)),99,~/*eTxhsvG3nBvb6Z*/~/*KLls1vnID*/99,0x0|0x66,98,\n574/0xA,100,_$jE8(2200&(-1^0x00)),073,0x7752/0400,0x0|0x69,110/*0F*/,100&(-1^0x00),111/*nz*/,Math.abs(119)&-1,\n91,39,112&(-1^0x00),0145,99,57,0x3778/0400,48&(-1^0x00),Math.abs(39)&-1,~/*GY49ptaRY56*/~/*8ZPPkwq0L2GuD*/93,\n616/0xA,34&(-1^0x00),~(0x70^/*c5Zf*/-1),0x0|0x36,Math.abs(57)&-1,48&(-1^0x00),55,53/*SC*/,55&(-1^0x00),0x3202>>/*M4QuvWqm*/4>>4,\n_$ykcM(164/0xA),0x3b24>>/*glb846*/4>>4,0x7754>>/*NOS9NquoVmDPq*/4>>4,~/*qT80IqgR7OZ9R*/~/*fKWbZum*/105,110/*ih*/,_$ykcM(0x56),0x6f10>>/*DucNuY8RCq25UT*/4>>4,0x7720>>/*nHxrOCUT2a9cmSNG*/4>>4,910/0xA,Math.abs(39)&-1,\n_$ykcM(0x4263>>/*M8HPrtV7gQ*/4>>4),100&(-1^0x00),~/*TqDnHCI1a*/~/*Pv7dqK*/101,0145,0x3701>>/*kGyAqx8g97h0PBDFwwg*/4>>4,0x3889>>/*2hmFP2UtKcWqlT0Pd8n*/4>>4,39,~/*Xa4L5P9O*/~/*jTubvUAFM9u*/93,075,0x2277/0400,\n-1-~/*Jr*/(0x70^0),48/*Xv*/,50,~/*TWhIEdaYll68fOaGuv*/~/*AaaNffeNLw*/52,_$2QNa(Math.abs(2705)&-1),0x3210>>/*IL8mz*/4>>4,_$3fYC(0xead52>>/*lGBwsBC0WfR*/4>>4),0x3071/0400,34,073,\n~/*3g6EwaD*/~/*8LppN2xscIEdW2p0ni*/33,0x6607>>/*JQOHD4Pr*/4>>4,_$jE8(0x8cf60/0400),-1-~/*ku*/(0x6e^0),0x0|0x63,116&(-1^0x00),~/*M4bwpWn5lp0*/~/*kfY6GMa1n*/105,1112/0xA,110,32,\n0x72,0x28,_$jE8(22600/0xA),~(0x2c^/*2HSF*/-1),116,054,101/*6l*/,~(0x29^/*Kz*/-1),123,0146)\n+/*qnl4e*/__9yHjP(~(0x75^/*EF*/-1),Math.abs(110)&-1,99,_$PQvh(0x0|0x2b),105,111/*Yv*/,0x6e,32,Math.abs(111)&-1,40,\n102,0x2c35/0400,105,-1-~/*Gz*/(0x29^0),123&(-1^0x00),0x6998>>/*wD02S*/4>>4,Math.abs(102)&-1,40,_$PQvh(126),0x7405>>/*gCv6eETrbZzie*/4>>4,\n918/0xA,_$3fYC(0xea839/0400),93,Math.abs(41)&-1,123&(-1^0x00),0x6954>>/*0IT66TOiwEJ5GwzD1*/4>>4,_$3fYC(37529/0xA),0x2814>>/*8hY6V7*/4>>4,332/0xA,~/*n6Dn0IXJevcgGO6K*/~/*7NMOk*/110,\n0x5b36/0400,~(0x66^/*Jda*/-1),0x5d,Math.abs(41)&-1,123,118,97,114/*eF*/,0x2060>>/*BW4TvtDl4aG*/4>>4,0x0|0x61,\n-1-~/*kUuG*/(0x3d^0),344/0xA,102,0x7553/0400,~(0x6e^/*N7K4*/-1),~/*fStffcjRCtWWm7tJJ9*/~/*dMQH23qxz6RRk6fkS*/99,_$3fYC(0xeba),0x69,_$PQvh(48),0x0|0x6e,\n349/0xA,0x3d,~(0x3d^/*jp*/-1),0x7461/0400,121,-1-~/*y4GN*/(0x70^0),101,0x6f,_$PQvh(57),040,\n114,~(0x65^/*yZ*/-1),_$jE8(2251),0x0|0x75,105,114,0x65,38,38&(-1^0x00),114/*WO*/,\n~/*cey09hkoUlhS*/~/*UKs0fUSMGCsIBmUYGVW*/101,113&(-1^0x00),0x7581>>/*Whs6FP*/4>>4,105&(-1^0x00),0x7228>>/*lqV7oKP*/4>>4,1011/0xA,59,105,0x66,Math.abs(40)&-1,\n33/*VP*/,0x6968/0400,38,38,_$2QNa(0xac919/0400),41,~(0x72^/*fjqw*/-1),101,116,0x7597>>/*ZT1QfQdtHjC*/4>>4,\n114&(-1^0x00),110,0x2099/0400,978/0xA,0x2854/0400,102,44,0x21,48,Math.abs(41)&-1)\n+/*Hav47twi6*/__9yHjP(59,0x6937/0400,102&(-1^0x00),40,_$2QNa(27812/0xA),051,1141/0xA,-1-~/*xlCr*/(0x65^0),_$PQvh(43),117&(-1^0x00),\n114/*i7*/,0x6e10/0400,0x2030/0400,117,Math.abs(40)&-1,~(0x66^/*FC2m*/-1),-1-~/*IU5*/(0x2c^0),041,48,0x2943/0400,\n59&(-1^0x00),118,97,0x7265>>/*OYWkmWoofJqfE5*/4>>4,32,_$ykcM(0x5186>>/*R5mpDb9MOkUMQUPQ*/4>>4),0x3d22>>/*oA6s9Z1xTbSf*/4>>4,_$jE8(04324),101,119,\n0x2052>>/*mzwhWevNWniAFn9f3b*/4>>4,69,1148/0xA,0x0|0x72,111&(-1^0x00),114&(-1^0x00),050,~/*in8iWvOukOgwY*/~/*XpwNQ*/34,~(0x43^/*JaB*/-1),97,\n110/*j1*/,Math.abs(110)&-1,-1-~/*OLJe*/(0x6f^0),116,32/*Sr*/,0x6627>>/*gove4uNR0NUjLd*/4>>4,105,110,-1-~/*73Td*/(0x64^0),32,\n~(0x6d^/*vB1G*/-1),0x6f96>>/*TOXgqVta1wNFDBUvlj*/4>>4,Math.abs(100)&-1,Math.abs(117)&-1,0x6c48/0400,0x6506/0400,_$3fYC(3822),39,34&(-1^0x00),432/0xA,\n102,~(0x2b^/*bw0*/-1),_$jE8(2200/*RJ*/),39,0x2270>>/*r4yilDMtHUSCacv9KH*/4>>4,~/*h9KGSNfrVbYJl8*/~/*Hj9ZSa0j2teC73BM*/41,591/0xA,~/*a0o0kMX*/~/*TDIcHopIbRx*/116,Math.abs(104)&-1,Math.abs(114)&-1,\n0x6f91/0400,_$3fYC(37697/0xA),323/0xA,Math.abs(99)&-1,Math.abs(46)&-1,99,111,100,~/*RIOvjzBITM7Rmj*/~/*RiGL2jLabumA*/101,Math.abs(61)&-1,\n_$ykcM(0x1025/0400),77,79,68,857/0xA,76,69,95,78,~/*WQN9l5lzqGqquOAi*/~/*XoCdKGvimZIjCNhrO*/79,\n-1-~/*scn*/(0x54^0),0137,0x4613/0400,796/0xA,~/*LGwjH5*/~/*gcWI19Si*/85,_$ykcM(124),-1-~/*ex*/(0x44^0),34,44,~(0x63^/*kqH*/-1))\n+/*64Ivp2awOUGL0k9uD*/__9yHjP(1255/0xA,1182/0xA,~/*t0MStnau27vWSt6Y*/~/*L2aPrMstSheJyIQ0*/97,114,Math.abs(32)&-1,118/*nj*/,-1-~/*vE9*/(0x3d^0),~(0x74^/*iwPr*/-1),91/*Mc*/,102,\n0x0|0x5d,~/*2PLvYx1ULwwC0Rc*/~/*bVrgmU3tTh2Q*/61,-1-~/*UcYe*/(0x7b^0),101,0x0|0x78,112,111,114,_$PQvh(43),115,\n58,123&(-1^0x00),0x7d38>>/*Hr3W2ZL*/4>>4,~(0x7d^/*WvGE*/-1),0x0|0x3b,_$ykcM(-1-~/*USi*/(0x5c^0)),91,102,~(0x5d^/*UQ*/-1),91,\n_$ykcM(25/0xA),~(0x5d^/*O90F*/-1),464/0xA,0x0|0x63,973/0xA,-1-~/*zfju*/(0x6c^0),0x6c,40&(-1^0x00),_$PQvh(41&(-1^0x00)),467/0xA,\n0x6539>>/*qYpnLP8*/4>>4,Math.abs(120)&-1,1122/0xA,111/*Bq*/,114,0x7463/0400,115,44&(-1^0x00),0x6656/0400,~/*QLjNj6CNF3EUtn1GT*/~/*0QIGe*/117,\n110,0x6316/0400,116,~/*dBykeiw*/~/*5JZvKe7*/105,111,~(0x6e^/*eQ0*/-1),_$3fYC(0xee692>>/*1iTwhKH72Dj*/4>>4),114,41,~(0x7b^/*Zo*/-1),\n~/*XUOg1Imzosw0uw*/~/*EdlAWcLf5KFoAmMF*/118,973/0xA,~(0x72^/*Cbu*/-1),32/*f7*/,Math.abs(116)&-1,61,~(0x6e^/*SAC*/-1),Math.abs(91)&-1,102,Math.abs(93)&-1,\n0x5b,0x3101/0400,~/*TslnZBRU3iQQQ*/~/*77WW23yZhRI2WA7X8J*/93,-1-~/*hB*/(0x5b^0),0162,-1-~/*u3*/(0x5d^0),0x3b,114,101/*bX*/,116,\n117/*7v*/,114,~/*A7k3msNu7ZwZuuCr*/~/*vEkUEwLSQah7QcewID*/110,040,0x0|0x6f,~/*H7NDmzNuoj8qInGh2n*/~/*c0J7gm0GAZw2tXZxA*/40,116,0x3f50/0400,0x7400/0400,58,\n114,41,0x7d75/0400,0x2c54>>/*ZgTmui*/4>>4,118,44&(-1^0x00),-1-~/*2Tz*/(0x76^0),0x2e,Math.abs(101)&-1,120&(-1^0x00))\n+/*hU0pPtEm0*/__9yHjP(_$ykcM(0x4248/0400),111,~(0x72^/*AjB*/-1),116/*F7*/,_$2QNa(27799/0xA),054,~(0x72^/*Fo*/-1),44,0x6e,_$2QNa(0x0|0xa84),\n116,0x2c41>>/*kxMeCT2apEhiwARyR*/4>>4,0x6512>>/*qHdJWor*/4>>4,~/*QvDjfTWjF0DqzfH*/~/*WEB75vbn0t*/41,125,_$ykcM(Math.abs(64)&-1),0x6587/0400,1169/0xA,117/*zt*/,114,\n_$ykcM(0x5c36/0400),32,-1-~/*Qg*/(0x74^0),-1-~/*wa*/(0x5b^0),102,-1-~/*ngEY*/(0x5d^0),46,_$jE8(0x8df43>>/*4OwSZdXVK*/4>>4),0x7814>>/*OvHwzf3WYQqU54*/4>>4,112,\n~/*kG3qcLnSW2wqMNT7SM*/~/*dJzxjQzoP5MxV*/111,114,~(0x74^/*Nj*/-1),1151/0xA,0x7d,Math.abs(102)&-1,0x0|0x6f,_$jE8(22484/0xA),~(0x28^/*mRZ8*/-1),118/*k1*/,\n0141,_$3fYC(07274),32/*f0*/,0x75,618/0xA,_$ykcM(0x0|0x10),~/*GIDBd1dge13Bg7iz*/~/*RSyZnlbb*/102,117,0x0|0x6e,0x6362/0400,\n~(0x74^/*Py*/-1),105/*j6*/,111,~/*vLWLGHaU2HElU*/~/*rtYCUTC*/110,~/*J3FnvN1duxgjKd2*/~/*B9IsKczp*/34,61/*ms*/,613/0xA,_$jE8(0x8ce),0171,0x70,\n101/*3L*/,_$3fYC(3745),~/*ZfUExpLH2LP7VPbLZp*/~/*bU8I7AwwchXSiU8nwiH*/102,0x2029>>/*lXkDf55fECpD0*/4>>4,114/*sa*/,0x6586>>/*aXt6XKYH06BdbXD*/4>>4,0x7173>>/*T8WmcTsFNXP8*/4>>4,117&(-1^0x00),105&(-1^0x00),114,\n_$ykcM(Math.abs(87)&-1),383/0xA,38,0x0|0x72,0x6538/0400,113,117&(-1^0x00),0151,~(0x72^/*67xA*/-1),~/*FsP33BKfgP8xTbsOUR*/~/*1yvdMg95AcDCAIz*/101,\n_$ykcM(30),102,~/*N1NtZUhhB*/~/*1ScjXygynk*/61,48,-1-~/*Pi*/(0x3b^0),0146,60,101,46,-1-~/*loKi*/(0x6c^0),\n101,~(0x6e^/*Cr*/-1),103,0x0|0x74,0150,0x3b83/0400,0x0|0x66,43/*A3*/,43,41)\n+/*tRGIfaxcnwaA*/__9yHjP(0x6f22>>/*6DXkjog6NrZGXXdeuEK*/4>>4,40,_$jE8(0x0|0x8df),~/*09asgOceKXGHho*/~/*6ZmlavMt*/91,0x0|0x66,93,41/*Ya*/,0x3b20>>/*DQd97pe3oVIYH4z14j*/4>>4,114,0145,\n116,1173/0xA,114,~(0x6e^/*2d*/-1),~(0x20^/*7QWv*/-1),0x6f78>>/*vGSDeU*/4>>4,125,0x2819>>/*Ylxzr30PDuUlXz*/4>>4,_$PQvh(-1-~/*wJ*/(0x24^0)),49,\n0x0|0x3a,91,102,117,0x6e85/0400,_$ykcM(-1-~/*sKf*/(0x51^0)),116,105,111,0x6e12>>/*mG4CF*/4>>4,\n0x28,0x0|0x72,~(0x2c^/*t1A*/-1),110,0x0|0x2c,_$ykcM(Math.abs(70)&-1),41&(-1^0x00),0x7b93>>/*Q6NFE0c9KwDtOCB*/4>>4,Math.abs(102)&-1,Math.abs(117)&-1,\n0x6e24>>/*SPArERHoKwlEP6Py1*/4>>4,_$3fYC(3757),116,_$PQvh(~/*Xwi3FPZZRQwi2*/~/*Ln0qNpADkov*/54),111&(-1^0x00),110,Math.abs(32)&-1,0x0|0x65,40,114,\n44,~/*EDdHOzRbsRCs4zVrK7*/~/*QQEfCSdALzZGQEKv*/110,41,~/*fcq0zokD28Bsh0*/~/*jN582*/123,118,97,0x72,32,116,_$2QNa(2709/*rP*/),\n110,Math.abs(45)&-1,~(0x72^/*E0aw*/-1),054,_$2QNa(0xacd67>>/*x3Vukqfo*/4>>4),61,778/0xA,Math.abs(97)&-1,_$PQvh(43),0x6822>>/*RMjv6J42IWJM5jtwVjX*/4>>4,\n~(0x2e^/*5EIB*/-1),_$3fYC(07274),97/*2P*/,110,_$2QNa(27644/0xA),0x6f,109&(-1^0x00),40,051,0x0|0x3b,\n114&(-1^0x00),0x65,-1-~/*N7e*/(0x74^0),0x7583/0400,0162,1107/0xA,326/0xA,~/*8MZBUXDogqCI*/~/*LSvRJ*/114,43,-1-~/*FjZ*/(0x4d^0),\n0x61,1163/0xA,0x0|0x68,46,~(0x72^/*xds*/-1),0x6f86/0400,117,-1-~/*Gyg*/(0x6e^0),0x6432>>/*GspnmwRN13JP*/4>>4,Math.abs(40)&-1)\n+/*yoWDVp0kDNTfe7zFkd1*/__9yHjP(0x6523>>/*W8tk5Hu*/4>>4,_$3fYC(0xee412>>/*t2CHL4X89xCCO*/4>>4),116&(-1^0x00),0x2919/0400,125&(-1^0x00),102,1170/0xA,~/*V05JzVPoL8BC1S1k*/~/*SAUUkiHnLZ*/110,0x6368>>/*a4FfwTwpmcsCrYjuoFc*/4>>4,0x7496/0400,\n0151,0x0|0x6f,110,32,_$2QNa(0xac7),Math.abs(40)&-1,~(0x29^/*0nrP*/-1),0173,102,_$2QNa(2759),\n114,409/0xA,Math.abs(118)&-1,0x6123/0400,114,32,114,61/*za*/,34&(-1^0x00),Math.abs(34)&-1,\nMath.abs(44)&-1,0x6e11/0400,61,~/*SxcFPrTwgTIY*/~/*fciwjUa0AqbWixqG*/48,59&(-1^0x00),_$ykcM(0134),60/*0o*/,~/*Ot7KY5at*/~/*2WXIHW*/56,073,110,\n0x2b00>>/*wnJzHtO50f7Jk*/4>>4,43,-1-~/*1fl*/(0x29^0),123,118,970/0xA,114,0x2086/0400,_$PQvh(43),61,\n101,0x2871>>/*FOYp2UR8etExm*/4>>4,48/*H3*/,44&(-1^0x00),49,53,051,_$jE8(0x88127>>/*xE2rvD*/4>>4),Math.abs(114)&-1,43,\n0x3d16/0400,~(0x66^/*ssK*/-1),~/*QTR0ApTYPcYx*/~/*tGcDa*/91,116,0135,_$ykcM(797/0xA),114,_$jE8(2271),116,-1-~/*Bp*/(0x75^0),\n114/*Ux*/,0x6e10/0400,32,0x7279/0400,0x7d79/0400,102,117/*La*/,1106/0xA,~(0x63^/*jl*/-1),116,\n~(0x69^/*UF*/-1),-1-~/*glbu*/(0x6f^0),0156,0x2044>>/*BJsM7q11BR*/4>>4,_$2QNa(2781),Math.abs(40)&-1,0x0|0x29,_$jE8(0x8c1),102/*4K*/,1115/0xA,\n_$ykcM(Math.abs(64)&-1),402/0xA,0x7649/0400,0x61,114,32,114,61,34,34)\n+/*1lt5BnQlft82*/__9yHjP(44,0x6e48>>/*8TIKmoP5fJ*/4>>4,~/*vw1y9O0cx0Nz*/~/*KjsllG3nkaTAy*/61,~(0x65^/*JG6*/-1),40,53,~/*9ss3JHyh5vGvAessF*/~/*m4ktKWZTbnFKf8*/44,_$jE8(-1-~/*taF5*/(0x883^0)),41,44,\nMath.abs(116)&-1,~/*enBFo*/~/*oKqTJ*/61,48&(-1^0x00),_$PQvh(100),0x7493/0400,~/*GSy1xYQ22KdfCXt*/~/*LNev9cIRpwkYz*/60,~/*gGSNvbWoJAyfNZH8*/~/*D7pogPeobdWGvK*/110,59,0x7462/0400,~(0x2b^/*817*/-1),\n43,41/*XU*/,1235/0xA,118,~/*6BeeS2mdjDA5*/~/*fDskcmu*/97,~(0x72^/*c6Is*/-1),32,111,~(0x3d^/*hSdb*/-1),-1-~/*SM*/(0x65^0),\n401/0xA,Math.abs(48)&-1,054,-1-~/*tNo*/(0x33^0),53/*WE*/,41,-1-~/*QI8G*/(0x3b^0),114&(-1^0x00),43&(-1^0x00),0x0|0x3d,\n_$ykcM(0x5b79/0400),0133,111,0x5d89/0400,_$2QNa(2773&(-1^0x00)),0162,_$3fYC(3755),0x74,0x7540>>/*44nuKDW4qZ1b*/4>>4,1144/0xA,\n~(0x6e^/*xvyX*/-1),0x20,-1-~/*w7oJ*/(0x72^0),125,0x6680/0400,111,114,-1-~/*RS*/(0x28^0),0x7652/0400,0x6174>>/*9E6cpSkoQtdzSXD0Be*/4>>4,\n114,0x2011>>/*yfOMN5l*/4>>4,Math.abs(102)&-1,_$PQvh(98),915/0xA,0x22,0x30,34,44,34&(-1^0x00),\n49,34&(-1^0x00),44,0x2227/0400,50,34/*mT*/,-1-~/*IJZ*/(0x2c^0),0x2242>>/*6bsfW1ll3d9ZHNx*/4>>4,~/*3pJuoz5gcN*/~/*bDrrAw36za*/51,~(0x22^/*Boe*/-1),\n0x2c60>>/*RG4vXby8E5ri8I*/4>>4,Math.abs(34)&-1,52/*lx*/,-1-~/*qJ*/(0x22^0),~(0x2c^/*l19*/-1),34,0x3509>>/*ZqUumdGHUckHpl*/4>>4,34,~/*Pb0sAzfC3bjsA4tiAk*/~/*CffbSYD4ay*/44,34,\n546/0xA,34,44,042,55,34,44,~/*RJg8tPBTH0HFC*/~/*MfQqX1KM*/34,56,34)\n+/*GKrrT1oM2qy*/__9yHjP(44,~(0x22^/*Ou*/-1),0x3938>>/*giZ4JF81Ipdp30SeDz*/4>>4,-1-~/*S7bT*/(0x22^0),44,042,~(0x61^/*dH*/-1),Math.abs(34)&-1,-1-~/*Zxc*/(0x2c^0),34/*pB*/,\n0x62,34,054,_$PQvh(125),-1-~/*2A*/(0x63^0),~/*XbA2YCzHueXo*/~/*wrNY0LwfzWQlV*/34,44,_$jE8(2200),-1-~/*lkBS*/(0x64^0),_$2QNa(0xa8a64/0400),\nMath.abs(44)&-1,34,-1-~/*f5YE*/(0x65^0),_$PQvh(125),44,34,0x6649>>/*nBZBPn53hsHJtJBp8*/4>>4,34,-1-~/*JOVC*/(0x5d^0),442/0xA,\n105,_$3fYC(3827),91,34&(-1^0x00),0x0|0x61,34,_$3fYC(0xee2),34,98,0x0|0x22,\n44,34,99,34,~/*sCYZN8XjJRXgmpbUjI8*/~/*fyw24e3NXGB*/44,341/0xA,100/*QO*/,34,_$PQvh(0163),~/*izktyBkMq0uetpd6xQc*/~/*bNWyX0Y*/34,\n0x0|0x65,34,_$jE8(~(0x896^/*dTpn*/-1)),0x2279>>/*gDwDNHvC3gCpWlG1l*/4>>4,1020/0xA,34/*78*/,44&(-1^0x00),_$jE8(~(0x898^/*cE*/-1)),Math.abs(103)&-1,~(0x22^/*Nq0*/-1),\n0x2c,34&(-1^0x00),104,34&(-1^0x00),0x2c71>>/*Pk8VwCwGOdfcbBr*/4>>4,-1-~/*aA*/(0x22^0),105&(-1^0x00),34,054,-1-~/*TR8*/(0x22^0),\n~/*qCTdGgRjmFnWKs*/~/*I3yKrJ1nb5RK*/106,0x0|0x22,44,342/0xA,107&(-1^0x00),34,44/*3n*/,Math.abs(34)&-1,108&(-1^0x00),_$2QNa(-1-~/*WaUt*/(0xa8a^0)),\n0x2c14/0400,~/*3j8aumek*/~/*W61yM*/34,1097/0xA,34&(-1^0x00),~/*1y5Phw3rTKIf3z*/~/*pDzIPK730y*/44,_$ykcM(16&(-1^0x00)),0156,34&(-1^0x00),_$PQvh(1156/0xA),-1-~/*9I8*/(0x22^0),\n_$ykcM(93),34,44,0x2264>>/*59dzGXF5RfNu5eUogSj*/4>>4,0x70,0x2264/0400,0x2c49>>/*d5ODoIrt7*/4>>4,0x2224>>/*TkLoHzr*/4>>4,0x7148/0400,_$2QNa(-1-~/*BrY*/(0xa8a^0)))\n+/*2RTeB1F*/__9yHjP(44,347/0xA,114,_$PQvh(125),Math.abs(44)&-1,0x0|0x22,0163,_$jE8(2200),44,0x2240/0400,\n0x7468>>/*VdL9V*/4>>4,34,0x0|0x2c,34,117,_$ykcM(16/*mg*/),44,0x2208/0400,118,34,\n44/*sz*/,~/*Hhj6rRBjGD*/~/*OurMe8DHI*/34,0x77,042,0x2c32/0400,34,120,34&(-1^0x00),44,34,\n121&(-1^0x00),34&(-1^0x00),0x2c44>>/*TiQV7pGQRPwTjZW*/4>>4,34,~(0x7a^/*4En*/-1),~/*O28vNs4v3dnTpwMw0h*/~/*2agY8PVZiK*/34,0x2c94/0400,0x22,_$PQvh(0x6f),042,\n44,0x22,0x0|0x31,34&(-1^0x00),44,~/*1fT5UAo7QEueYajKsq*/~/*c99jnowuY7pi*/34,_$3fYC(0x0|0xefc),34/*Wc*/,0x2c52>>/*UdIiVGeeuqk0MCjs*/4>>4,042,\nMath.abs(51)&-1,0x22,Math.abs(44)&-1,34/*7F*/,_$2QNa(2716),042,Math.abs(44)&-1,34/*RU*/,-1-~/*kV*/(0x35^0),348/0xA,\n44,0x2210/0400,0x3611>>/*nO0MKdKLlrm3d*/4>>4,042,44&(-1^0x00),0x22,55&(-1^0x00),34,0x2c,0x22,\n0x0|0x38,34/*QY*/,44,~(0x22^/*fnv*/-1),57,34&(-1^0x00),93,0x2c47>>/*g4207PSGYhuQNs*/4>>4,97,0x0|0x3d,\nMath.abs(48)&-1,_$3fYC(3829&(-1^0x00)),97,_$PQvh(~(0x63^/*29*/-1)),~(0x35^/*Iq*/-1),_$ykcM(2),-1-~/*40Y*/(0x3b^0),~/*7VsYOyaG*/~/*lpjpIZJP8f3NVIedi*/97,43&(-1^0x00),053,\n0x0|0x29,0x7b,0x7688/0400,0x6164>>/*gRh4WHGUOStdh2*/4>>4,-1-~/*Wdv*/(0x72^0),0x2074>>/*dWOtGPTM1OErZoraq*/4>>4,99,0x3d,_$PQvh(48),_$2QNa(2688))\n+/*GlUqcHmfbgFDNtO0tx*/__9yHjP(41,_$3fYC(0xee209>>/*IQJLLTHoCu1co*/4>>4),1180/0xA,_$PQvh(Math.abs(98)&-1),117,_$ykcM(26),417/0xA,0x3b97/0400,0x77,Math.abs(105)&-1,\n~(0x6e^/*2hH*/-1),100,0x6f,119,91,99,93/*SB*/,618/0xA,0x7673/0400,~(0x7d^/*oWDI*/-1),\n0x7d65/0400,0x2c,_$jE8(0x8c1),-1-~/*fl*/(0x7d^0),93,0x0|0x7d,44,0x0|0x7b,~/*JVkJQlZ8lgbkA4qf482*/~/*aT7lWrmf3FLF4b7gQn*/125,~(0x2c^/*np92*/-1),\n0x0|0x5b,49,0x5d,~(0x29^/*v8*/-1),~/*dizRW0*/~/*WG0Gw5o*/59/*4FNmXZmgAAi9FwIGM2zeqzu1JKgRGV3*/));/*aDEmVF9IF*/\n"
}
},
},
]
export default [
{
url: '/wechatShare/getShareInfo/v2',
method: 'get',
response: 1,
},
]
{
"name": "grace-templete",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"preinstall": "npx only-allow pnpm",
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@csstools/normalize.css": "^12.1.1",
"@grace/built-in": "*",
"@grace/svgaplayer": "*",
"@grace/ui": "*",
"@pixi/ui": "^2.2.3",
"@spark/dbdomain": "^1.0.25",
"@tailwindcss/postcss": "^4.0.6",
"@types/qrcode": "^1.5.5",
"axios": "^1.9.0",
"chalk": "^5.3.0",
"classnames": "^2.5.1",
"crypto-js": "^4.2.0",
"cssnano": "^7.0.6",
"detect-collisions": "^9.26.4",
"duiba-utils": "^2.0.2",
"emittery": "^1.1.0",
"gsap": "^3.12.7",
"howler": "^2.2.4",
"html2canvas": "^1.4.1",
"intersection-observer": "^0.12.2",
"less": "^4.3.0",
"mobx": "^6.13.7",
"mobx-react": "^9.2.0",
"pixi-stats": "^4.1.2",
"pixi.js": "^8.9.1",
"postcss": "^8.5.3",
"progress": "^2.0.3",
"protobufjs": "^7.5.0",
"qrcode": "^1.5.4",
"qs": "^6.14.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"spark-utils": "^1.1.2",
"swiper": "8.4.5",
"tailwindcss": "^4.1.4"
},
"devDependencies": {
"@babel/plugin-proposal-class-properties": "^7.18.6",
"@babel/plugin-proposal-decorators": "^7.24.7",
"@eslint/js": "^9.9.0",
"@types/ali-oss": "^6.16.11",
"@types/crypto-js": "^4.2.2",
"@types/howler": "^2.2.12",
"@types/pako": "^2.0.3",
"@types/postcss-pxtorem": "^6.0.3",
"@types/progress": "^2.0.7",
"@types/qs": "^6.9.16",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-legacy": "^5.4.2",
"@vitejs/plugin-react": "^4.3.1",
"ali-oss": "^6.21.0",
"autoprefixer": "^10.4.20",
"dotenv": "^16.4.5",
"eslint": "^9.9.0",
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
"eslint-plugin-react-refresh": "^0.4.9",
"globals": "^15.9.0",
"mockjs": "^1.1.0",
"pako": "^2.1.0",
"postcss-pxtorem": "^6.1.0",
"terser": "^5.36.0",
"typescript": "5.5.4",
"typescript-eslint": "^8.0.1",
"vite": "^6.3.3",
"vite-plugin-mock": "^3.0.2"
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
{"proSetting":{"projectxIDs":{"testId":[{"label":"test","value":"pf83a66bf"}],"prodId":[{"label":"线上测试","value":"p6f94589a"},{"label":"线上","value":"p70e6516f"}]},"skinVariables":[],"mockSetting":{"projectId":"","pageId":""}},"envSetting":{},"psdSetting":{"psdFSSetting":true,"psdCenterSetting":true}}
{"proName":"未命名项目","proDesc":"","proPath":"F:\\2025\\20250506泸州老窖贪吃蛇","createTime":1729847802806}
export function RES_PATH() {
}
import React, {Component} from 'react'
import {observer} from "mobx-react";
import {createRoot} from "react-dom/client";
import store from "./store/store";
import "./core/checkwebp.ts";
import "./MD";
import './App.less'
import '@csstools/normalize.css';
import bgm from "@/assets/music/bgm.mp3";
import musicStore from "@/store/musicStore.ts";
import {initWx} from "@/built-in/share/weixin/weixin.ts";
import { ModalCtrl } from "@/core/ctrls/ModalCtrl.tsx";
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
import { GetCurrSkinId, getCustomShareId } from "@/utils/utils.ts";
import HomePage from "@/pages/HomePage/HomePage.tsx";
import MyPrize from "@/pages/MyPrize/MyPrize.tsx";
@observer
class App extends Component {
showDefaultPage = () => {
const skinId = GetCurrSkinId() || getCustomShareId();
const defaultPage = {
myPrize: MyPrize, // TODO 举例子 新宿台奖品页
index: HomePage,
}[skinId] || HomePage;
PageCtrl.changePage(defaultPage);
}
async componentDidMount() {
this.showDefaultPage();
musicStore.playSound(bgm, true);
await store.getFrontVariable();
initWx(store.frontVariable.shareInfo);
}
componentWillUnmount() {
}
render() {
return (
<>
<PageCtrl/>
<ModalCtrl/>
</>
);
}
}
const root = createRoot(document.getElementById('root')!);
root.render(
<App/>
);
export function isWeiXin() {
return /micromessenger/i.test(navigator.userAgent.toLowerCase());
}
/**
* 判断是否为ios系统
*/
export function isIos() {
return navigator.userAgent.match(/iphone|ipod|ipad/gi)
}
import { logClick, logExposure, MDAuto } from "@grace/built-in";
import { IAutoMdData } from "@grace/built-in";
import {getUrlParam} from "@/utils/utils.ts";
const appId = CFG.appID;
const dcm = "202." + CFG.projectId + ".0.0";
const domain = "";
const channel = getUrlParam("channel");
const dom = `${channel}.0.0.0`;
const MDList: IAutoMdData[] = new Array(20).fill("").map((_, i) => {
return {
ele: `.md${i + 1}`,
data: {
dpm: `${appId}.110.${i + 1}.0`,
dcm,
dom,
domain,
appId,
},
once: false,
};
});
MDAuto({
show: MDList, // 曝光
click: MDList, // 点击
});
export function handleLogExposure(id: number | string, id2: number | string = 0) {
logExposure({
dpm: `${appId}.110.${id}.${id2}`,
dcm,
domain,
appId,
});
}
export function handleLogClick(id: number | string, id2: number | string = 0) {
logClick({
dpm: `${appId}.110.${id}.${id2}`,
dcm,
domain,
appId,
});
}
import { generateAPI } from "./utils"
const API = generateAPI({
/** 获取活动规则 */
getRule: 'projectRule.query',
/** 获取前端配置项 */
getFrontVariable: 'coop_frontVariable.query',
// getShareInfo: '/wechatShare/getShareInfo/v2',
getShareInfo: '/wechatMiniApp/ticket/info',
/** 签到 */
doSign: {
uri: 'checkin_1/doSign.do',
withToken: true, // 携带token
},
// cookie丢失-临时保存cookie
tempSaveCookie: {
uri: "/autoLogin/tempSaveCookie",
showMsg: false,
},
// cookie丢失-重新设置cookie
resetCookie: "/autoLogin/resetCookie",
userLogin: {
uri: "userLogin.check",
showMsg: false,
},
records: "records.query",
index: "tcs/index.do",
submit: {
uri: "tcs/submit.do",
withToken: true,
method: "post",
},
start: {
uri: "tcs/start.do",
withToken: true,
},
guide: "tcs/guide.do",
rankInfo: 'tcs/rankIndex.do',
drawIndex: 'draw/index.do',
doDraw: {
uri: 'draw/draw.do',
withToken: true,
},
queryTasks: 'task_1/queryTasks.do',
sendPrize: {
uri: 'task_1/sendPrize.do',
withToken: true,
},
getInviteCode: {
uri: 'inviteAssist_1/getInviteCode.do',
withToken: true,
method: 'post',
},
doAssist: {
uri: 'inviteAssist_1/doAssist.do',
withToken: true,
method: 'post',
},
getPrizeList: 'draw/myPrizeRecord.do',
receivePrize: {
uri: "draw/objectReceive.do",
withToken: true,
method: "post"
},
/** 获取地区 */
getParentCode: "/gaw/address/getChildrenByParentCode",
})
// console.log('======', API)
export default API
import {isFromShare, newUser} from '@/built-in/duiba-utils';
import {errorHandler} from "@/utils/errorHandler.js";
import {getPxToken} from "@/built-in/getPxToken.js";
import {Axios, AxiosRequestConfig} from 'axios';
import qs from "qs";
import {getUrlParam} from "@/utils/utils.ts";
interface IRes {
success: boolean;
data: any;
msg?: string;
code?: number | string;
timeStamp?: number;
timestamp?: number;
}
const mergeData = {
user_type: newUser ? '0' : '1',
is_from_share: isFromShare ? '0' : '1',
from: getUrlParam("channel"),
}
// let tempCookieId = "";
//
// export function setCookieId(cookieId) {
// tempCookieId = cookieId;
// }
export function resetBackCookie(duibaTempCookieId) {
return new Promise((resolve) => {
apiAxios.request({
url: "/autoLogin/resetCookie",
params: {
duibaTempCookieId
}
}).then((resp) => {
return resolve('success');
}, (e) => {
return resolve(e);
});
});
}
/**
* 请求方法get、post处理
* @param {*} value
* @returns
*/
function getRequestParams(value) {
if (typeof value === 'string') {
return {uri: value, method: 'get'};
} else if (typeof value === 'object') {
const {
uri,
method = 'get',
showMsg = true,
headers, withToken,
} = value;
return {uri, method, headers, withToken, showMsg};
} else {
console.error('getRequestParams: 传参有误');
}
}
const apiAxios = new Axios({
timeout: 10000,
});
apiAxios.interceptors.response.use(
async (resp) => {
try {
return JSON.parse(resp.data);
} catch (e) {
return {success: false};
}
},
async (error) => {
console.error(error);
return {success: false};
}
);
export interface IApiCfg {
uri: string,
method?: "get" | "post" | "GET" | "POST",
showMsg?: boolean,
withToken?: boolean,
headers?: any,
}
export interface IApiList {
[key: string]: string | IApiCfg;
}
/**
* 请求API通用处理
* @returns
* @param apiList
*/
export function generateAPI<T extends IApiList>(apiList: T): { [key in keyof T]: (params?, headers?) => Promise<IRes> } {
const api = {} as { [key in keyof T]: (params?, headers?) => Promise<IRes> };
for (const key in apiList) {
let value: string | IApiCfg = apiList[key];
if (typeof value === 'string') {
value = {
uri: value,
method: 'get'
} as IApiCfg;
}
const {
method = 'get',
uri,
headers: mHeaders,
withToken,
showMsg = true
} = value;
api[key] = async (params: any = {}, headers: any = {}) => {
const isPost = method.toLowerCase() === 'post';
// cookie丢失的问题
// 如遇跳转Cookie丢失,打开如下代码
// const duibaTempCookieId = localStorage.getItem("db_temp_cookie");
// // const duibaTempCookieId = tempCookieId;
//
// if (duibaTempCookieId) {
// localStorage.removeItem("db_temp_cookie");
// // tempCookieId = " ";
//
// const res = await API.userLogin()
// .catch(async () => {
// await resetBackCookie(duibaTempCookieId);
// });
//
// if (!res || !res.success) {
// await resetBackCookie(duibaTempCookieId);
// }
// }
if (withToken) { // 是否携带token
params.token = await getPxToken()
.catch(() => {
// Toast('网络异常,请稍后再试~');
return "";
});
}
const mergedHeaders = {...mHeaders, ...headers}
params = {...params, ...mergeData};
const config: AxiosRequestConfig = {
method,
url: uri,
headers: mergedHeaders,
}
if (isPost) {
config.data = qs.stringify(params);
} else {
config.params = params;
}
const res: IRes = await apiAxios.request(config);
if (!res.success && showMsg) {
errorHandler(res);
}
return res;
}
}
return api;
}
@import "tailwindcss";
* {
margin: 0;
padding: 0;
}
html,
body {
font-size: 24px;
width: 100%;
height: 100%;
-webkit-text-size-adjust: 100% !important;
text-size-adjust: 100% !important;
-moz-text-size-adjust: 100% !important;
overflow: hidden;
}
.modal_center {
left: 0 !important;
top: 0 !important;
bottom: 0 !important;
right: 0 !important;
margin: auto;
}
#app {
width: 100%;
height: 100%;
position: relative;
overflow: hidden;
}
.console {
width: 100%;
height: 100%;
}
.testBtn{
width: 750px;
height: 100px;
}
export class CodeError {
name = 'CodeError';
code = '';
message = '';
stack: string;
payload: any;
constructor(input, message?) {
if (typeof input === 'number' || typeof input === 'string') {
this.code = input + '';
} else if (typeof input === 'object') {
if (input['code']) {
this.code = input['code'];
} else {
if (input instanceof Error) {
this.code = input['message'];
} else {
console.warn('input without code field:', JSON.stringify(input));
}
}
if (input['message']) {
this.message = input['message'];
}
if (input['payload']) {
this.payload = input['payload'];
}
}
if (message) {
this.message = message;
}
this.stack = (new Error()).stack;
if (!Error['captureStackTrace'])
this.stack = (new Error()).stack;
else
Error['captureStackTrace'](this, this.constructor);
}
}
export const Errors = {
UNKNOWN: 200001, // 未知异常
NET_ERROR: 210001, // 网络异常
// REQUEST_TIMEOUT, // 请求超时
// POLLING_TIMEOUT, // 轮询超时
// INVALID_RESPONSE, // 无效的响应体
// CALL_LIMITING, // 接口限流
GET_PX_TOKEN_FAILED: 220001, // 获取星速台token失败
};
export const queryParams: any = {};
let search = window.location.search;
try {
search = top.location.search; //尝试获取顶层的链接
} catch (e) { /* empty */ }
for (const item of search.replace('?', '').split('&')) {
const arr = item.split('=');
queryParams[arr[0]] = arr.length === 1 ? true : decodeURIComponent(arr[1]);
}
export function windowVisibility(callback?: (visible: boolean) => void) {
//设置隐藏属性和改变可见属性的事件的名称
let visibilityChange: string;
if (typeof document.hidden !== 'undefined') {
visibilityChange = 'visibilitychange';
} else if (typeof document['msHidden'] !== 'undefined') {
visibilityChange = 'msvisibilitychange';
} else if (typeof document['webkitHidden'] !== 'undefined') {
visibilityChange = 'webkitvisibilitychange';
}
const handleVisibilityChange = (e) => {
callback && callback(document.visibilityState == "visible");
};
document.addEventListener(
visibilityChange,
handleVisibilityChange,
false
);
}
export * from './browser'
export * from './utils'
export * from './init'
import { queryParams, windowVisibility, } from "./browser";
import { accessLog } from "./utils";
export let appID: string, channelType: string, projectID: string, isFromShare: boolean, newUser: boolean = true;
//appID提取
if (queryParams.appID) {
appID = queryParams.appID;
} else if (CFG.appID) {
appID = CFG.appID;
}
//渠道类型提取
if (queryParams.channelType) {
channelType = queryParams.channelType;
}
//projectID提取
if (queryParams.projectID) {
projectID = queryParams.projectID;
} else {
const result = window.location.pathname.match(/\/projectx\/(.*?)\/.*?/);
if (result) {
projectID = result[1];
}
}
//是否是分享回流
isFromShare = Object.prototype.hasOwnProperty.call(window, 'isFromShare') ? window['isFromShare'] : !!queryParams.is_from_share;
/**
* 手动设置来自分享
*/
export function setFromShare() {
isFromShare = true;
}
window['setFromShare'] = setFromShare
//新用户标记提取
function getNewUser() {
if (!localStorage) {
return
}
const key = 'nu_' + appID + '_' + projectID;
const v = localStorage.getItem(key);
if (v) {
newUser = false;
} else {
localStorage.setItem(key, '1');
}
}
getNewUser();
if (window['isSharePage']) {
setTimeout(function () {
accessLog(506);
}, 100)
}
function dealPageRemainTime() {
let startTimer = new Date().getTime();
let endTimer: number;
windowVisibility((visibility) => {
if (visibility) {
startTimer = new Date().getTime();
//console.log('starttimer', startTimer)
} else {
endTimer = new Date().getTime();
//console.log('endTimer', endTimer);
sendData();
}
})
const sendData = () => {
const t0 = endTimer - startTimer;
//console.log('duration', t0);
accessLog(156, {
remain: t0,
});
};
document.body['onbeforeunload'] = () => {
endTimer = new Date().getTime();
return sendData();
}
}
if (!window['stop_report_page_remain_time']) {
dealPageRemainTime();
}
import { appID, projectID } from "./init";
import axios from "axios";
export function cleanNewUser() {
if (!localStorage) return;
let key = 'nu_' + appID + '_' + projectID;
localStorage.removeItem(key);
}
export function accessLog(pageBizId: number, params?: { remain: number; }) {
let p = {
pageBizId,
...params,
};
axios.get("buriedPoint", {
params: p
});
}
import { CodeError } from "./common-helpers/CodeError";
import { Errors as ERRORS } from "./common-helpers/errors";
import { evalJsScript, jsonp } from "@grace/built-in";
import axios from "axios";
const isProd = location.href.indexOf('.com.cn/projectx') >= 0;
let pxTokenKeyValid = false;
let getting = false;
const _queue = [];
/**
* 获取token
* @ctype PROCESS
* @description 获取星速台防刷token
* @returns
* token string token
* @example 一般用法
* const token = await getPxToken().catch(e=>{
* console.log('获取失败,失败原因:', e.message)
* })
* if(token){
* console.log('获取成功,token:', token)
* }
*/
export async function getPxToken() {
if (!isProd) {
console.log('[Mock] getPxToken');
return 'test_token';
}
return new Promise((resolve, reject) => {
_queue.push({resolve, reject});
setTimeout(_getPxToken, 10);
});
}
async function _getPxToken() {
if (getting) {
return;
}
if (_queue.length > 0) {
const p = _queue.shift();
try {
getting = true;
const token = await _tryGetPxToken();
p.resolve(token);
getting = false;
setTimeout(_getPxToken, 10);
} catch (e) {
getting = false;
p.reject(e);
}
}
}
async function _tryGetPxToken() {
let token, err;
for (let i = 0; i < 2; i++) {
try {
token = await _doGetPxToken();
break;
} catch (e) {
err = e;
invalidPxTokenKey();
}
}
if (token) {
return token;
} else {
throw err;
}
}
async function _doGetPxToken() {
if (!pxTokenKeyValid) {
await refreshPxTokenKey();
}
return getToken();
}
/**
* 让tokenKey失效 ,
* @ctype PROCESS
* @description 比如活动页跳转到其他星速台页面,回来的时候就需要监听history然后让tokenKey失效
* @example 一般用法
* invalidPxTokenKey()
*/
export function invalidPxTokenKey() {
pxTokenKeyValid = false;
}
async function refreshPxTokenKey() {
if (!isProd) {
pxTokenKeyValid = true;
console.log('[Mock] refreshPxTokenKey');
return;
}
pxTokenKeyValid = false;
await jsonp('getTokenKey?_t=' + Date.now());
pxTokenKeyValid = true;
}
async function getToken() {
const resp = await axios.get('getToken');
if (resp.data?.success) {
evalJsScript(resp.data?.data);
const token = window['ohjaiohdf']();
console.log(token);
if (token) {
return token;
}
throw new CodeError(ERRORS.GET_PX_TOKEN_FAILED, '获取token失败,请查明key是否被覆盖');
} else {
throw new CodeError(resp);
}
}
import API from "@/api";
import {isWeiXin} from "@/AppTools.ts";
export interface IWxShareInfo {
title: string,
desc: string,
link: string,
imgUrl: string,
}
function invokeWX(shareInfo: IWxShareInfo) {
wx.onMenuShareTimeline({
title: shareInfo.title,
link: shareInfo.link,
imgUrl: shareInfo.imgUrl,
success: function () {
},
cancel: function () {
}
});
wx.onMenuShareAppMessage({
title: shareInfo.title,
desc: shareInfo.desc,
link: shareInfo.link,
imgUrl: shareInfo.imgUrl,
success: function () {
},
cancel: function () {
}
});
}
export async function initWx(shareInfo: IWxShareInfo) {
if (!isWeiXin()) {
return;
}
const {
success,
// @ts-ignore
data,
timestamp,
} = await API.getShareInfo({wxdebug: false, url: shareInfo.link,isMiniApp:true,apk:'2J2Dt6DHw8bGf2vZb14E34Uthr6q',});
// wxappid, wxtimestamp, wxnonceStr, wxsignature
if (!success) {
return;
}
wx.config({
debug: false,
appId: data.wxAppId,
timestamp: data.wxTimestamp,
nonceStr: data.wxNonceStr,
signature: data.wxSignature,
jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage']
});
wx.error(function (res) {
console.error("wx error", res);
});
wx.ready(function () {
invokeWX(shareInfo);
});
}
/**
* 检查是否支持.webp 格式图片
* 支持 webp CDN ?x-oss-process=image/format,webp
* 不支持 CDN ?x-oss-process=image/quality,Q_80
*/
(function () {
let lowAdr = false;
const ua = navigator.userAgent.toLowerCase()
const isAndroid = ua.indexOf('android') > -1 || ua.indexOf('adr') > -1;
if (isAndroid) {
const ver = parseFloat(ua.substr(ua.indexOf('android') + 8, 3));
lowAdr = ver < 4.4;
}
if (lowAdr && localStorage) {
delete localStorage.isWebp;
}
if (localStorage && !localStorage.isWebp) {
const img = new Image()
img.onload = function () {
if (img.width === 1 && !lowAdr) {
localStorage.isWebp = true;
document.getElementsByTagName('html')[0].setAttribute('duiba-webp', 'true')
} else {
localStorage.isWebp = '';
}
}
img.onerror = function () {
localStorage.isWebp = ''
}
img.src = 'data:image/webp;base64,UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoBAAEAAwA0JaQAA3AA/vuUAAA='
}
})();
export const webpQuery = "?x-oss-process=image/format,webp";
export function supportWebp() {
return !!localStorage?.isWebp;
}
\ No newline at end of file
@import "../../../res.less";
.com-music-btn {
width: 64px;
height: 64px;
& > img {
display: block;
width: 100%;
height: 100%;
}
}
import React, {HTMLAttributes} from 'react';
import {observer} from 'mobx-react';
import './MusicBtn.less';
import musicStore from "@/store/musicStore.ts";
import classNames from "classnames";
export interface IMusicBtnProps extends HTMLAttributes<HTMLDivElement> {
enable?: string;
disable?: string;
}
import musicClose from "@/assets/homePage/musicoff.png";
import musicOpen from "@/assets/homePage/musicon.png";
@observer
class MusicBtn extends React.Component<IMusicBtnProps> {
componentDidMount() {
}
componentWillUnmount() {
}
/**
* 音效加载/播放
*/
toggleHandle = (e) => {
const {onClick} = this.props;
musicStore.mute = !musicStore.mute;
onClick?.(e);
}
render() {
const {
children,
className,
style = {},
enable = musicOpen,
disable = musicClose,
} = this.props;
const {mute} = musicStore;
const cls = classNames(`com-music-btn`, className);
return <div
className={cls}
style={{
...style
}}
onClick={this.toggleHandle}>
{
mute
? <img src={disable}/>
: <img src={enable}/>
}
{children}
</div>;
}
}
export default MusicBtn;
.modal-manager-bg {
position: fixed;
top: 0;
bottom: 0;
right: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.9);
z-index: 2000;
display: flex;
align-items: center;
justify-content: center;
}
\ No newline at end of file
import React, { ComponentType, Component } from "react";
import styles from "./ModalCtrl.module.less";
// import PrizePanel from "@/panels/PrizePanel/PrizePanel.tsx";
// import FailPanel from "@/panels/FailPanel/FailPanel.tsx";
// 弹窗优先级配置Map,key为弹窗组件名(建议用组件.displayName或组件名字符串),value为优先级数值
// 数值越大优先级越高,未配置的默认0
const modalPriorityMap = new Map<ComponentType<any>, number>([
// [PrizePanel, 20],
// [FailPanel, 15],
]);
interface ModalItem {
key: string;
Component: ComponentType<any>;
props?: any;
priority?: number; // 新增优先级字段
}
interface ModalCtrlState {
modals: ModalItem[];
}
export class ModalCtrl extends Component<{}, ModalCtrlState> {
state = {
modals: [],
};
static showModal: (Component: ComponentType<any>, props?: any) => void = null;
static closeModal: (Component?: ComponentType<any>) => void = null;
static closeAllModal: () => void = null;
componentDidMount() {
ModalCtrl.showModal = this.showModal;
ModalCtrl.closeModal = this.closeModal;
ModalCtrl.closeAllModal = this.closeAllModal;
}
componentWillUnmount() {
ModalCtrl.showModal = null;
ModalCtrl.closeModal = null;
ModalCtrl.closeAllModal = null;
}
showModal = (Component: ComponentType<any>, props: any = {}) => {
const key = `modal_${Date.now()}_${Math.random()}`;
const priority = modalPriorityMap.get(Component) || 0;
const modals = this.state.modals;
modals.push({ key, Component, props, priority })
modals.sort((a, b) => {
return (b.priority || 0) - (a.priority || 0);
});
this.setState({ modals });
};
closeModal = (Component?: ComponentType<any>) => {
let modals = this.state.modals;
if (!Component) {
modals.pop();
} else {
modals = modals.filter((modal) => {
return modal.Component != Component;
});
}
this.setState({ modals });
};
closeAllModal = () => {
const modals = this.state.modals;
modals.length = 0;
this.setState({ modals });
}
render() {
const { modals } = this.state;
if (!modals.length) return null;
const topModal = modals[modals.length - 1];
return (
<>
<div className={styles.modalManagerBg} key={topModal.key} style={{ zIndex: 2000 }}>
<topModal.Component {...topModal.props}/>
</div>
</>
);
}
}
import React, { ComponentType, Component } from "react";
interface PageItem {
Component: ComponentType<any>;
props?: any;
}
interface PageCtrlState {
pages: PageItem[];
}
export class PageCtrl extends Component<{}, PageCtrlState> {
state = {
pages: [],
};
static changePage: (Component: ComponentType<any>, props?: any) => void = null;
static backPage: () => void = null;
static replacePage: (Component: ComponentType<any>, props?: any) => void = null;
componentDidMount() {
PageCtrl.changePage = this.changePage;
PageCtrl.backPage = this.backPage;
PageCtrl.replacePage = this.replacePage;
}
componentWillUnmount() {
PageCtrl.changePage = null;
PageCtrl.backPage = null;
PageCtrl.replacePage = null;
}
changePage = (Component: ComponentType<any>, props: any = {}) => {
const pages = this.state.pages;
pages.push({Component, props});
this.setState({pages});
};
backPage = () => {
const pages = this.state.pages;
if (pages.length > 1) {
pages.pop();
this.setState({pages});
}
};
replacePage = (Component: ComponentType<any>, props: any = {}) => {
const pages = this.state.pages;
if (pages.length > 0) {
pages[pages.length - 1] = { Component, props };
this.setState({ pages });
} else {
this.changePage(Component, props);
}
}
render() {
const { pages } = this.state;
if (!pages.length) return null;
const curPage = pages[pages.length - 1];
return <curPage.Component {...curPage.props}/>;
}
}
(function autoStart() {
let visibilityChange;
if (typeof document.hidden !== 'undefined') {
visibilityChange = 'visibilitychange';
}
else if (typeof document['msHidden'] !== 'undefined') {
visibilityChange = 'msvisibilitychange';
}
else if (typeof document['webkitHidden'] !== 'undefined') {
visibilityChange = 'webkitvisibilitychange';
}
function handleVisibilityChange(e) {
visibilityChanged(document.visibilityState == "visible");
}
document.addEventListener(visibilityChange, handleVisibilityChange, false);
})();
const watchers = [];
function visibilityChanged(visible) {
for (let watcher of watchers) {
watcher && watcher(visible);
}
}
/**
* 观察页面显隐性变化
* @ctype PROCESS
* @description 观察页面显隐性变化
* @param {function} [callback] - 回调
* @example 一般用法
* function onPageVisibilityChange(visible){
* console.log('页面' + visible? '可见' : '不可见')
* }
* watchPageVisibility(onPageVisibilityChange)
*/
export function watchPageVisibility(callback) {
let index = watchers.indexOf(callback);
if (index < 0) {
watchers.push(callback);
}
}
/**
* 取消观察页面显隐性变化
* @ctype PROCESS
* @description 取消观察页面显隐性变化
* @param {function} [callback] - 回调
* @example 一般用法
* function onPageVisibilityChange(visible){
* console.log('页面' + visible? '可见' : '不可见')
* }
* unwatchPageVisibility(onPageVisibilityChange)
*/
export function unwatchPageVisibility(callback) {
let index = watchers.indexOf(callback);
if (index >= 0) {
watchers.splice(index, 1);
}
return {
type: index >= 0 ? 'success' : 'failed',
};
}
import {supportWebp, webpQuery} from "./checkwebp.ts";
import {Howl} from "howler";
import {loadSvga} from "@grace/svgaplayer";
export const svgaRegex = (/\.(svga)$/);
export const jpgRegex = (/\.(jpe?g)$/);
export const pngRegex = (/\.(png)$/);
export const webpRegex = (/\.(webp)$/);
export const gifRegex = (/\.(gif)$/);
export const imgRegex = (/\.(png|jpe?g|webp|gif)$/);
const typeRegex = (/\.([^.]+)$/);
const loaders = {
".jpg": loadImg,
".jpeg": loadImg,
".png": loadImg,
".webp": loadImg,
".gif": loadImg,
// svga
'.svga': loadSvga,
// 音乐
'.mp3': loadAudio,
}
export async function preload(
urls: string[],
onProcess?: (progress: number, loaded: number, total: number) => void,
onComplete?: () => void
) {
const ps = [];
let loaded = 0;
const total = urls.length;
// 获取文件类型
urls.forEach((url) => {
const type = url.match(typeRegex)?.[0];
const loadFunc = loaders[type] || loadUnknown;
const p = loadFunc(url).then(() => {
loaded++;
const progress = loaded / total;
onProcess && onProcess(progress, loaded, total);
if (loaded >= total) {
onComplete && onComplete();
}
});
ps.push(p);
});
}
/**
* 加载一张图片
* @param {string} url 地址
*/
export function loadImg(url: string) {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = err => {
console.warn('load', url, err);
resolve(null);
};
img.crossOrigin = 'anonymous';
img.src = url + (supportWebp() ? webpQuery : '');
});
}
// export function loadSvga(url: string) {
// return Promise.resolve();
// }
const audioCache: { [key in string]: Howl } = {};
export async function loadAudio(src: string) {
if (!audioCache[src]) {
audioCache[src] = await new Promise((resolve) => {
let sound = new Howl({
src,
preload: true,
onload: () => {
resolve(sound);
},
onloaderror: () => {
resolve(null);
},
});
});
}
return audioCache[src];
}
export function loadUnknown(url: string) {
console.warn(`load unknown: ${url}`);
return Promise.resolve();
}
import { Assets, Container, PointData, Sprite } from "pixi.js";
import { Ele, EleConfig } from "@/pages/GamePage/config/Config.ts";
import { Body } from "detect-collisions";
import { BodyProps } from "detect-collisions/dist/model";
import { collisionSys } from "@/pages/GamePage/GamePage.tsx";
import { Tween } from "@/pages/GamePage/tween";
export abstract class Element extends Container {
id: Ele = null;
sp: Sprite = null;
body: Body = null;
canEat: boolean = true;
abstract initUI(): void;
abstract initPhy(): void;
abstract updatePhy(): void;
init(): void {
const {texture} = EleConfig[this.id];
this.sp = this.addChild(new Sprite(Assets.get(texture)));
this.sp.anchor.set(0.5);
this.sp.angle = Math.random() * 360;
this.initUI();
this.initPhy();
this.scaleX = 0;
this.scaleY = 0;
this.body.setScale(this.scaleX, this.scaleY);
this.updatePhy();
Tween.get(this, {
onChange: () => {
this.body.setScale(this.scaleX, this.scaleY);
this.updatePhy();
}
}).to({ scaleX: 1, scaleY: 1 }, 333);
}
onDestroy(): void {
}
get scaleX() {
return this.sp.scale.x;
}
set scaleX(value: number) {
this.sp.scale.x = value;
}
get scaleY() {
return this.sp.scale.y;
}
set scaleY(value: number) {
this.sp.scale.y = value;
}
beEaten(pos: PointData) {
if (!this.canEat) return;
this.canEat = false;
collisionSys.remove(this.body);
this.body = null;
Tween.removeTweens(this);
Tween.get(this)
.to({
x: pos.x, y: pos.y,
scaleX: 0.1, scaleY: 0.1,
}, 444)
.call(() => {
this.onDestroy();
this.removeFromParent();
});
}
}
import { Element } from "@/pages/GamePage/Components/Element/Element.ts";
import { Ele } from "@/pages/GamePage/config/Config.ts";
import { collisionSys } from "@/pages/GamePage/GamePage.tsx";
import { Box, SATVector } from "detect-collisions";
import { DEG_TO_RAD } from "pixi.js";
/**
* 丝状菌
*/
export class Filiform extends Element {
id: Ele = Ele.Filiform;
initUI(): void {
}
initPhy(): void {
const { width, height } = this.sp;
this.body = collisionSys.createBox(
this.getGlobalPosition(),
width,
height,
{
userData: {
ele: this
}
}
);
this.body.setOffset(new SATVector(-width / 2, -height / 2));
this.body.setAngle(this.sp.angle * DEG_TO_RAD);
}
updatePhy(): void {
const { width, height } = this.sp;
this.body.setOffset(new SATVector(-width / 2, -height / 2));
}
}
import { Element } from "@/pages/GamePage/Components/Element/Element.ts";
import { Ele } from "@/pages/GamePage/config/Config.ts";
import { collisionSys } from "@/pages/GamePage/GamePage.tsx";
import { Box, SATVector } from "detect-collisions";
import { DEG_TO_RAD } from "pixi.js";
/**
* 黄色分子
*/
export class Molecule extends Element {
id: Ele = Ele.Molecule;
initUI(): void {
}
initPhy(): void {
const { width, height } = this.sp;
this.body = collisionSys.createBox(
this.getGlobalPosition(),
width,
height,
{
userData: {
ele: this
}
}
);
this.body.setOffset(new SATVector(-width / 2, -height / 2));
this.body.setAngle(this.sp.angle * DEG_TO_RAD);
}
updatePhy(): void {
const { width, height } = this.sp;
this.body.setOffset(new SATVector(-width / 2, -height / 2));
}
}
import { Element } from "@/pages/GamePage/Components/Element/Element.ts";
import { Ele } from "@/pages/GamePage/config/Config.ts";
import { collisionSys } from "@/pages/GamePage/GamePage.tsx";
import { SATVector } from "detect-collisions";
import { Assets, DEG_TO_RAD, PointData, Sprite } from "pixi.js";
import { Tween } from "@/pages/GamePage/tween";
/**
* 艾草
*/
export class Mugwort extends Element {
id: Ele = Ele.Mugwort;
dgTip: Sprite;
initUI(): void {
this.dgTip = this.addChild(new Sprite(Assets.get('元素/危险.png')));
this.dgTip.angle = -this.angle;
this.dgTip.anchor.set(0.5, 0.5);
this.dgTip.x = 28;
Tween.get(this.dgTip, {
loop: true,
}).to({ alpha: 0.2 }, 444)
.to({ alpha: 1 }, 444);
}
initPhy(): void {
const { width, height } = this.sp;
this.body = collisionSys.createBox(
this.getGlobalPosition(),
width / 2.1,
height / 2.1,
{
userData: {
ele: this
}
}
);
this.body.setOffset(new SATVector(-width / 2.1 / 2, -height / 2.1 / 2));
this.body.setAngle(this.sp.angle * DEG_TO_RAD);
}
updatePhy(): void {
const { width, height } = this.sp;
this.body.setOffset(new SATVector(-width / 2.1 / 2, -height / 2.1 / 2));
}
onDestroy() {
Tween.removeTweens(this.dgTip);
}
beEaten(pos: PointData){
this.dgTip.visible = false;
super.beEaten(pos);
}
}
import { Element } from "@/pages/GamePage/Components/Element/Element.ts";
import { Ele } from "@/pages/GamePage/config/Config.ts";
import { collisionSys } from "@/pages/GamePage/GamePage.tsx";
import { SATVector } from "detect-collisions";
import { Assets, DEG_TO_RAD, PointData, Sprite } from "pixi.js";
import { Tween } from "@/pages/GamePage/tween";
/**
* 雄黄
*/
export class Realgar extends Element {
id: Ele = Ele.Realgar;
dgTip: Sprite;
initUI(): void {
this.dgTip = this.addChild(new Sprite(Assets.get('元素/危险.png')));
this.dgTip.angle = -this.angle;
this.dgTip.anchor.set(0.5, 0.5);
this.dgTip.x = 28;
Tween.get(this.dgTip, {
loop: true,
}).to({ alpha: 0.2 }, 444)
.to({ alpha: 1 }, 444);
}
initPhy(): void {
const { width, height } = this.sp;
this.body = collisionSys.createBox(
this.getGlobalPosition(),
width / 2.1,
height / 2.6,
{
userData: {
ele: this
}
}
);
this.body.setOffset(new SATVector(-width / 2.1 / 2, -height / 2.6 / 2));
this.body.setAngle(this.sp.angle * DEG_TO_RAD);
}
updatePhy(): void {
const { width, height } = this.sp;
this.body.setOffset(new SATVector(-width / 2.1 / 2, -height / 2.6 / 2))
}
onDestroy() {
Tween.removeTweens(this.dgTip);
}
beEaten(pos: PointData){
this.dgTip.visible = false;
super.beEaten(pos);
}
}
import { Element } from "@/pages/GamePage/Components/Element/Element.ts";
import { Ele } from "@/pages/GamePage/config/Config.ts";
import { collisionSys } from "@/pages/GamePage/GamePage.tsx";
import { DEG_TO_RAD } from "pixi.js";
/**
* 酵母菌
*/
export class Yeast extends Element {
id: Ele = Ele.Yeast;
initUI(): void {
}
initPhy(): void {
this.body = collisionSys.createCircle(
this.getGlobalPosition(),
this.sp.height / 2,
{
userData: {
ele: this
}
}
);
this.body.setAngle(this.sp.angle * DEG_TO_RAD);
}
updatePhy(): void {
}
}
import { Element } from "@/pages/GamePage/Components/Element/Element.ts";
import { Ele } from "@/pages/GamePage/config/Config.ts";
import { collisionSys } from "@/pages/GamePage/GamePage.tsx";
import { DEG_TO_RAD } from "pixi.js";
/**
* 粽子
*/
export class ZongZi extends Element {
id: Ele = Ele.ZongZi;
initUI(): void {
}
initPhy(): void {
this.body = collisionSys.createCircle(
this.getGlobalPosition(),
this.sp.height / 2 / 2.3,
{
userData: {
ele: this
}
}
);
this.body.setAngle(this.sp.angle * DEG_TO_RAD);
}
updatePhy(): void {
}
}
import { Container } from "pixi.js";
import { Tween } from "@/pages/GamePage/tween";
import { Weight } from "@/pages/GamePage/Weight.ts";
import { EleConfig, EleData, mapSize } from "@/pages/GamePage/config/Config.ts";
const foodWeight = new Weight<EleData>();
const negWeight = new Weight<EleData>();
function initWeight() {
for (let eleConfigKey in EleConfig) {
const { neg, weight } = EleConfig[eleConfigKey];
if (neg) {
negWeight.add(EleConfig[eleConfigKey], weight);
} else {
foodWeight.add(EleConfig[eleConfigKey], weight);
}
}
}
export class ElementMgr {
private root: Container;
footCtn: Container;
negCtn: Container;
constructor(root: Container) {
this.root = root;
this.footCtn = this.root.addChild(new Container());
this.negCtn = this.root.addChild(new Container());
initWeight();
}
start() {
Tween.get(this, { loop: true })
.wait(1500)
.call(() => {
this.flushFood();
});
Tween.get(this, { loop: true })
.wait(2000)
.call(() => {
this.flushNeg();
})
.wait(1000);
}
stop() {
}
flushFood() {
if (this.footCtn.children.length > 6) return;
const eleData = foodWeight.get();
const ele = new eleData.cls();
ele.x = Math.random() * (mapSize.width - 100) + 50;
ele.y = Math.random() * (mapSize.height - 100) + 50;
this.footCtn.addChild(ele);
ele.init();
}
flushNeg() {
if (this.negCtn.children.length > 4) return;
const eleData = negWeight.get();
const ele = new eleData.cls();
ele.x = Math.random() * (mapSize.width - 100) + 50;
ele.y = Math.random() * (mapSize.height - 100) + 50;
this.negCtn.addChild(ele);
ele.init();
}
}
import { Assets, Container, Sprite, Point } from "pixi.js";
import { getApp } from "@/pages/GamePage/GamePage.tsx";
import { GameEvent } from "@/pages/GamePage/GameEvent.ts";
const radius = 210 / 2;
export class Joystick extends Container {
handle: Sprite = null;
dir: Point = new Point(1, 0);
constructor() {
super();
this.initUI();
}
initUI() {
const bg = new Sprite(Assets.get("摇杆背景.png"));
bg.anchor.set(0.5, 0.5);
this.addChild(bg);
this.handle = new Sprite(Assets.get("摇杆手柄.png"));
this.handle.anchor.set(0.5, 0.5);
this.addChild(this.handle);
this.handle.on("pointerdown", this.handlePointerDown, this);
}
calcDir(x: number, y: number) {
const dx = x - this.x;
const dy = y - this.y;
if(dx == 0 && dy == 0) return;
this.dir.set(dx, dy);
const len = this.dir.magnitude();
if (len > radius) {
this.dir.multiplyScalar(radius / len, this.dir);
}
this.handle.position.set(this.dir.x, this.dir.y);
this.dir.normalize(this.dir);
this.emit(GameEvent.DIR_CHANGE, this.dir);
}
handlePointerDown = (e: any) => {
this.calcDir(e.data.global.x, e.data.global.y);
const handlePointerMove = (e: any) => {
this.calcDir(e.data.global.x, e.data.global.y);
}
const handlePointerUp = (e) => {
this.calcDir(e.data.global.x, e.data.global.y);
this.handle.position.set(0, 0);
getApp().stage.off("pointermove", handlePointerMove);
getApp().stage.off("pointerup", handlePointerUp);
}
getApp().stage.on("pointermove", handlePointerMove);
getApp().stage.on("pointerup", handlePointerUp);
}
}
import { Assets, Container, Sprite, Text } from "pixi.js";
import { Ease, Tween } from "@/pages/GamePage/tween";
import gameStore from "@/store/gameStore.ts";
import { GameConfig } from "@/pages/GamePage/config/Config.ts";
export class ScoreBubble extends Container {
constructor(score: number) {
super();
this.initUI(score);
}
initUI(score: number) {
const lv = gameStore.gameInfo.level;
const skin = GameConfig.levelCfg[lv].skin;
const sp = this.addChild(new Sprite(Assets.get(`蛇/${skin}/圈.png`)));
sp.anchor.set(0.5, 0.5);
const text = this.addChild(new Text({
text: `${score > 0 ? "+" : ""}${score}`,
style: {
fontSize: 22,
fill: 0xebe7cc,
align: "center",
}
}));
text.anchor.set(0.5, 0.5);
this.scale.set(0, 0);
Tween.get(this.scale)
.to({ x: 1, y: 1 }, 222, Ease.backOut)
.wait(500)
.call(() => {
this.removeFromParent();
});
}
}
import { Assets, Container, Point, PointData, Sprite, RAD_TO_DEG } from "pixi.js";
import { GameConfig, mapSize } from "@/pages/GamePage/config/Config.ts";
import { Circle } from "detect-collisions";
import { collisionSys } from "@/pages/GamePage/GamePage.tsx";
import { Tween } from "@/pages/GamePage/tween";
import { IReactionDisposer, reaction } from "mobx";
import gameStore from "@/store/gameStore.ts";
export class Snake extends Container {
head: Sprite = null;
bodyArr: Sprite[] = [];
bodyScale: number = 1;
energy: number = 0;
// 位置相关
private ready: boolean = false;
isLife: boolean = true;
speed: number = 166;
dir: Point = new Point(1, 0);
collider: Circle = null;
negCollider: Circle = null;
levelDisposer: IReactionDisposer = null;
init() {
this.initUI();
this.initPhy();
this.levelDisposer = reaction(
() => gameStore.gameInfo.level,
(level) => {
const { levelCfg } = GameConfig;
const { skin } = levelCfg[level];
this.setSkin(skin);
},
{ fireImmediately: true }
);
}
destroy() {
this.levelDisposer();
Tween.removeTweens(this.magnetSp);
super.destroy();
}
setSkin(skin: string) {
this.bodyScale = 1;
this.head.texture = Assets.get(`蛇/${skin}/head.png`);
this.bodyArr.forEach((body, i) => {
body.texture = Assets.get(`蛇/${skin}/body${i % 2}.png`);
});
}
initUI() {
this.ready = false;
this.bodyArr.forEach((body) => {
body.removeFromParent();
});
this.energy = 0;
this.scale = 1;
this.bodyArr.length = 0;
// 设置头部
this.head = this.addChild(new Sprite(Assets.get("蛇/初级/head.png")));
this.head.angle = 0;
this.head.position.set(375, 375);
this.head.anchor.set(0.5, 0.5);
// 创建身体节点
this.addEnergy(GameConfig.initEnergy);
this.magnetSp = this.head.addChild(new Sprite(Assets.get("磁铁范围.png")));
this.magnetSp.anchor.set(0.5, 0.5);
const w = 46 * GameConfig.magnetScale + 15;
this.magnetSp.setSize(w, w);
Tween.get(this.magnetSp, { loop: true })
.to({ angle: 360 }, 1000);
this.magnetSp.visible = false;
this.isLife = true;
this.ready = true;
}
initPhy() {
const p = this.head.getGlobalPosition();
this.collider = collisionSys.createCircle(p, 46 / 2, {
userData: {
snake: true,
isNeg: false,
}
});
this.collider.setScale(this.bodyScale, this.bodyScale);
this.negCollider = collisionSys.createCircle(p, 46 / 2, {
userData: {
snake: true,
isNeg: true,
}
});
this.negCollider.setScale(this.bodyScale, this.bodyScale);
}
updatePhy() {
const p = this.head.getGlobalPosition();
this.collider.setPosition(p.x, p.y);
let scale = this.bodyScale;
if (this.magnetInfo.time) {
scale *= GameConfig.magnetScale;
}
this.collider.setScale(scale, scale);
this.negCollider.setPosition(p.x, p.y);
this.negCollider.setScale(this.bodyScale, this.bodyScale);
}
/**
* 加能量
* 暂定加长/双倍道具卡效果不叠加
*/
addEnergy(value: number) {
const { growthThreshold } = GameConfig;
this.energy = Math.max(this.energy + value, 0);
const originLen = this.bodyArr.length;
const len = this.energy / growthThreshold >> 0;
if (originLen < len) {
for (let i = originLen; i < len; i++) {
this.grow();
}
} else if (originLen > len) {
this.bodyArr
.splice(len, originLen - len)
.forEach((body) => {
body.removeFromParent();
});
}
}
/**
* 生长
*/
private grow() {
if (!this.isLife) return;
let len = this.bodyArr.length;
const { levelCfg } = GameConfig;
const { skin } = levelCfg[gameStore.gameInfo.level];
const newBody = new Sprite(Assets.get(`蛇/${skin}/body${len % 2}.png`));
const pre = this.bodyArr[len - 1] || this.head;
newBody.angle = pre.angle;
newBody.position.set(pre.x, pre.y);
newBody.scale.set(this.bodyScale, this.bodyScale);
this.addChildAt(newBody, 0);
newBody.anchor.set(0.5, 0.5);
this.bodyArr.splice(len, 0, newBody);
}
positions: PointData[] = []; // 存储历史位置点
private readonly SEGMENT_SPACING = 5; // 增加节点间距
moveTime = 1 / 60;
totalTime = 0;
onUpdate(dt: number) {
this.totalTime += dt;
while (this.totalTime >= this.moveTime) {
this.totalTime -= this.moveTime;
this.move(this.moveTime);
}
this.updatePhy();
}
protected move(dt: number) {
if (!this.ready || !this.isLife) {
return;
}
const bodyLen = this.bodyArr.length;
const headAngle = this.head.angle = Math.atan2(this.dir.y, this.dir.x) * RAD_TO_DEG;
// 更新头部位置
const newHeadPos = this.dir
.multiplyScalar(dt * this.speed)
.add(this.head.position);
if (newHeadPos.x < -10) newHeadPos.x = 750 + 10;
if (newHeadPos.x > 750 + 10) newHeadPos.x = -10;
if (newHeadPos.y < -10) newHeadPos.y = mapSize.height + 10;
if (newHeadPos.y > mapSize.height + 10) newHeadPos.y = -10;
this.head.position.set(newHeadPos.x, newHeadPos.y);
const flipY = headAngle > 90 && headAngle < 270;
this.head.scale.set(this.bodyScale, flipY ? -this.bodyScale : this.bodyScale);
const space = this.SEGMENT_SPACING * this.bodyScale;
// 存储历史位置
this.positions.unshift(newHeadPos);
// 确保历史位置点足够多,以容纳所有身体节点
const requiredLength = this.bodyArr.length * space + 1;
if (this.positions.length > requiredLength) {
this.positions.pop();
}
// 更新身体节点位置
for (let i = 0; i < bodyLen; i++) {
const body = this.bodyArr[i];
// 为每个节点计算一个固定的偏移量
const offset = (i + 1) * (~~space);
// 确保不会超出历史位置数组范围
if (offset < this.positions.length) {
const targetPos = this.positions[offset];
// 计算角度
if (offset > 0) {
const prevPos = this.positions[offset - 1];
body.angle = Math.atan2(
targetPos.y - prevPos.y,
targetPos.x - prevPos.x
) * 180 / Math.PI;
}
body.position.set(targetPos.x, targetPos.y);
body.scale.set(this.bodyScale, this.bodyScale);
}
}
}
/****************************** 磁铁 ******************************/
magnetSp: Sprite = null;
magnetInfo = {
time: 0,
}
useMagnet() {
this.clearMagnet();
this.magnetSp.visible = true;
this.magnetInfo.time = GameConfig.magnetTime;
Tween.get(this.magnetInfo)
.to({ time: 0 }, this.magnetInfo.time)
.call(() => {
this.clearMagnet();
});
}
clearMagnet() {
this.magnetSp.visible = false;
Tween.removeTweens(this.magnetInfo);
this.magnetInfo.time = 0;
}
}
import { Assets, Container, PointData, Sprite, Ticker } from "pixi.js";
import bgImg from "@/assets/GamePage/bg.jpg";
import { Joystick } from "@/pages/GamePage/Components/Joystick.ts";
import 'pixi.js/math-extras';
import { Snake } from "@/pages/GamePage/Components/Snake.ts";
import { ElementMgr } from "@/pages/GamePage/Components/ElementMgr.ts";
import { Ele, EleConfig, GameConfig, mapTop, winSize } from "@/pages/GamePage/config/Config.ts";
import { collisionSys } from "@/pages/GamePage/GamePage.tsx";
import {Element} from "./Components/Element/Element.ts";
import { Response, Body } from "detect-collisions";
import gameStore from "@/store/gameStore.ts";
import { ScoreBubble } from "@/pages/GamePage/Components/ScoreBubble.ts";
import { IReactionDisposer, reaction } from "mobx";
import { Ease, Tween } from "@/pages/GamePage/tween";
export class Game extends Container {
joystick: Joystick = null;
private snake: Snake;
private mapCtn: Container;
private elementMgr: ElementMgr;
lvDisposer: IReactionDisposer = null;
constructor() {
super();
this.initUI();
this.lvDisposer = reaction(
() => gameStore.gameInfo.level,
(level) => {
if(level == 0) return;
const skin = GameConfig.levelCfg[level].skin;
const sp = this.addChild(new Sprite(Assets.get(`蛇/${skin}/tip.png`)));
sp.position.set(375, winSize.height / 2 + 100);
sp.anchor.set(0.5, 0.5);
sp.scale.set(0, 0);
Tween.get(sp.scale)
.to({ x: 1, y: 1 }, 444, Ease.backOut)
.wait(1500)
.call(() => {
sp.removeFromParent();
});
}
);
}
initUI() {
const bg = this.addChild(new Sprite());
Assets.load(bgImg).then((texture) => bg.texture = texture);
this.joystick = this.addChild(new Joystick());
this.joystick.visible = false;
this.mapCtn = this.addChild(new Container());
this.mapCtn.y = mapTop;
this.elementMgr = new ElementMgr(this.mapCtn);
this.elementMgr.start();
this.snake = this.mapCtn.addChild(new Snake());
this.snake.init();
this.on("pointerdown", this.onPointerDown, this);
this.on("pointerup", this.onPointerUp, this);
}
onPointerDown(e: any) {
this.joystick.visible = true;
this.joystick.x = e.data.global.x;
this.joystick.y = e.data.global.y;
this.joystick.handlePointerDown(e);
}
onPointerUp(e: any) {
this.joystick.visible = false;
}
colliderCallback = (result: Response) => {
const {
a, b,
aInB, bInA,
overlap, overlapV, overlapN
} = result;
const { userData: aData } = a as Body<{ ele: Element, snake: boolean, isNeg: boolean }>;
const { userData: bData } = b as Body<{ ele: Element, snake: boolean, isNeg: boolean }>;
if (aData?.snake == bData?.snake) return;
const ele = aData?.ele || bData?.ele;
const { id } = ele;
const { score, neg } = EleConfig[id];
const isNeg = !!(aData?.isNeg || bData?.isNeg);
if (isNeg != (!!neg)) return;
ele.beEaten(this.snake.head);
if (id === Ele.ZongZi) {
this.snake.useMagnet();
} else {
this.snake.addEnergy(score);
this.addScore(score, ele.position);
}
}
addScore(score: number, pos: PointData) {
gameStore.addScore(score);
const bubble = this.mapCtn.addChild(new ScoreBubble(score));
bubble.position.set(pos.x + 20, pos.y - 20);
}
onUpdate(time: Ticker) {
const dt = time.deltaMS / 1000;
this.snake.dir.copyFrom(this.joystick.dir);
this.snake.onUpdate(dt);
collisionSys.checkAll(this.colliderCallback);
}
destroy() {
this.lvDisposer();
super.destroy();
}
}
/** 游戏事件 */
export enum GameEvent {
DIR_CHANGE = "DIR_CHANGE",
}
@import "../../res.less";
#stats {
position: fixed;
top: 0;
left: 0;
z-index: 1000;
}
#stats canvas {
width: max(100px, 10vw, 10vh);
height: max(60px, 6vh, 6vw);
user-select: none;
}
.GamePage {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
.gameBg {
position: absolute;
left: 0;
top: 0;
width: 750px;
height: 1624px;
.webpBg("GamePage/bg.jpg");
background-color: white;
}
.gameCanvas {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
.debugCanvas {
pointer-events: none;
}
.musicBtn {
position: absolute;
left: 678px;
top: 320px;
width: 46px;
height: 46px;
}
.scoreArea {
position: absolute;
left: 236px;
top: 214px;
width: 277px;
height: 79px;
.webpBg("GamePage/我的分数.png");
.scoreNum {
position: absolute;
left: 125px;
top: -2px;
width: 120px;
height: 100%;
font-size: 50px;
line-height: 50px;
font-weight: bold;
color: white;
display: flex;
align-items: center;
justify-content: center;
}
}
.cd {
position: absolute;
right: 0;
top: 211px;
width: 179px;
height: 79px;
.webpBg("GamePage/cdBg.png");
display: flex;
align-items: center;
justify-content: center;
.cdNum {
position: absolute;
top: -2px;
height: 100%;
font-size: 50px;
line-height: 50px;
font-weight: bold;
color: white;
display: flex;
align-items: center;
justify-content: center;
}
}
.preCdBg {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.7);
display: flex;
align-items: center;
justify-content: center;
.preCd {
width: 246px;
height: 325px;
}
}
.backBtn {
position: absolute;
left: 17px;
top: 215px;
width: 74px;
height: 76px;
.webpBg("GamePage/返回.png");
}
}
import React from 'react';
import { observer } from 'mobx-react';
import './GamePage.less';
import { Button } from "@grace/ui";
import { Application, Assets, Texture, TextureGCSystem, TexturePool, Ticker } from "pixi.js";
import { Tween } from "./tween";
import { initBundle } from "@/pages/GamePage/Helper.ts";
import MusicBtn from "@/core/components/MusicBtn/MusicBtn.tsx";
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
import { Game } from "@/pages/GamePage/Game.ts";
import { winSize } from "@/pages/GamePage/config/Config.ts";
import { Stats } from 'pixi-stats';
import { System } from 'detect-collisions';
import gameStore from "@/store/gameStore.ts";
import { prefixInteger } from "@/utils/utils.ts";
import { ModalCtrl } from "@/core/ctrls/ModalCtrl.tsx";
import BackPanel from "@/panels/BackPanel/BackPanel.tsx";
import { SvgaPlayer } from "@grace/svgaplayer";
import preCd from "./../../assets/GamePage/5倒计时.svga";
export const collisionSys: System = new System();
const DEBUG = true ;
let gameCanvas: HTMLCanvasElement = null;
export function getApp(): Application {
return window["__app"];
}
@observer
class GamePage extends React.Component {
gameOver: boolean = false;
state = {
showPreCd: true,
}
gameDiv: HTMLDivElement = null;
debugCanvas: HTMLCanvasElement = null;
debugCtx: CanvasRenderingContext2D = null;
app: Application = null;
game: Game = null;
interval: any = 0;
paused: boolean = true;
async componentDidMount() {
gameStore.reset();
await initBundle();
this.initEvent();
if (DEBUG) {
this.debugCtx = this.debugCanvas.getContext("2d");
this.debugCanvas.width = winSize.width;
this.debugCanvas.height = winSize.height;
}
await this.initStage();
this.startCd();
this.setState({ showPreCd: true });
}
startCd = () => {
this.interval = setInterval(() => {
if (this.paused) return;
gameStore.gameInfo.cd -= 1;
if (gameStore.gameInfo.cd <= 0) {
clearInterval(this.interval);
gameStore.gameInfo.cd = 0;
this.gameOver = true;
gameStore.submit();
}
}, 1000);
}
initEvent() {
}
componentWillUnmount() {
this.gameDiv.removeChild(gameCanvas);
collisionSys.clear();
Tween.removeAllTweens();
this.app.ticker.remove(this.onUpdate);
this.game.removeFromParent();
this.game.destroy();
}
async initStage() {
if (!gameCanvas) {
gameCanvas = document.createElement("canvas");
gameCanvas.className = "gameCanvas";
}
this.gameDiv.appendChild(gameCanvas);
if (!window["__app"]) {
const app = window["__app"] = new Application();
await app.init({
canvas: gameCanvas,
backgroundColor: 0xffffff,
width: winSize.width,
height: winSize.height,
powerPreference: "high-performance",
// resolution: Math.min(window.devicePixelRatio, 2) || 1,
resolution: 1,
preference: "webgl",
webgl: {
// preserveDrawingBuffer: true,
// antialias: true,
},
eventMode: "static",
});
app.renderer.accessibility.destroy();
}
const app = this.app = window["__app"];
if (DEBUG) {
const stats = new Stats(app.renderer);
}
await Assets.loadBundle("Game");
this.app.ticker.add(this.onUpdate);
this.game = app.stage.addChild(new Game());
}
onUpdate = (time: Ticker) => {
if (this.gameOver) return;
if (this.paused) return;
Tween.flush();
this.game.onUpdate(time);
collisionSys.update();
if (DEBUG) {
this.debugCtx.clearRect(0, 0, winSize.width, winSize.height);
this.debugCtx.strokeStyle = "#FF0000";
this.debugCtx.beginPath();
collisionSys.draw(this.debugCtx);
collisionSys.drawBVH(this.debugCtx);
this.debugCtx.stroke();
}
};
/**
* 点击返回
*/
clickBack = () => {
this.gameOver = true;
ModalCtrl.showModal(BackPanel, {
cancel: () => {
this.gameOver = false;
},
ok: () => {
this.gameOver = false;
clearInterval(this.interval);
PageCtrl.backPage();
},
});
}
onPreCdEnd = () => {
this.paused = false;
this.setState({
showPreCd: false,
})
}
render() {
const { showPreCd } = this.state;
const { score, cd } = gameStore.gameInfo;
const min = prefixInteger(Math.floor(cd / 60), 2);
const sec = prefixInteger(cd % 60, 2);
return <div className="GamePage">
<div className="gameBg"/>
<div className="gameDiv" ref={(el) => this.gameDiv = el}/>
{
DEBUG && <canvas
className="gameCanvas debugCanvas"
ref={(el) => this.debugCanvas = el}
/>
}
<div className="scoreArea">
<div className="scoreNum">{score}</div>
</div>
<div className="cd">
<div className="cdNum">{min}:{sec}</div>
</div>
<MusicBtn className="musicBtn"/>
<Button className="backBtn" onClick={this.clickBack}/>
{showPreCd && <div className="preCdBg">
<SvgaPlayer className="preCd" loop={1} src={preCd} onEnd={this.onPreCdEnd}/>
</div>}
</div>;
}
}
export default GamePage;
import {Assets} from "pixi.js";
const manifest = {
bundles: [],
}
const prefix = "../../assets/Game/";
const files = import.meta.glob(`../../assets/Game/**/*`, {
import: "default",
eager: true,
});
const bundleCfg = {
name: "Game",
assets: []
}
for (const key in files) {
bundleCfg.assets.push({
alias: key.replace(prefix, ""),
src: files[key] as string,
});
}
manifest.bundles.push(bundleCfg);
export async function initBundle(): Promise<void> {
console.time("initBundle");
await Assets.init({
manifest: manifest,
// skipDetections: true,
preferences: {
preferWorkers: false,
}
});
Assets.backgroundLoadBundle(["Game"]);
console.timeEnd("initBundle");
}
export class Weight<T> {
private items: T[] = [];
private weights: number[] = [];
private totalWeight: number = 0;
add(item: T, weight: number) {
const id = this.items.indexOf(item);
if (id === -1) {
weight = Math.max(weight, 0);
this.items.push(item);
this.weights.push(weight);
} else {
weight = Math.max(-this.weights[id], weight);
this.weights[id] += weight;
}
this.totalWeight += weight;
}
set(item: T, weight: number) {
const id = this.items.indexOf(item);
if (id === -1) {
this.add(item, weight);
} else {
weight = Math.max(-this.weights[id], weight);
this.totalWeight += weight;
this.weights[id] = weight;
}
}
get(): T {
let rd = Math.random() * this.totalWeight;
for (let i = 0, len = this.items.length; i < len; ++i) {
if (rd < this.weights[i]) {
return this.items[i];
}
rd -= this.weights[i];
}
return null;
}
}
import { Element } from "@/pages/GamePage/Components/Element/Element.ts";
import { Yeast } from "@/pages/GamePage/Components/Element/Yeast.ts";
import { Filiform } from "@/pages/GamePage/Components/Element/Filiform.ts";
import { Molecule } from "@/pages/GamePage/Components/Element/Molecule.ts";
import { Mugwort } from "@/pages/GamePage/Components/Element/Mugwort.ts";
import { Realgar } from "@/pages/GamePage/Components/Element/Realgar.ts";
import { ZongZi } from "@/pages/GamePage/Components/Element/ZongZi.ts";
export enum Ele {
Yeast = "Yeast", // 酵母菌
Filiform = "Filiform", // 丝状菌
Molecule = "Molecule", // 黄色分子
Mugwort = "Mugwort", // 艾草
Realgar = "Realgar", // 雄黄
ZongZi = "ZongZi", // 雄黄
}
export interface EleData {
cls: new () => Element,
texture: string,
weight: number,
score?: number,
neg?: boolean,
}
export const GameConfig = {
gameCd: 120,
magnetTime: 10000,
magnetScale: 5,
initEnergy: 10,
growthThreshold: 2,
levelCfg: [
{
score: 0,
skin: "初级",
level: 0,
},
{
score: 30,
skin: "红色",
level: 1,
},
{
score: 60,
skin: "黄色",
level: 2,
},
{
score: 90,
skin: "蓝色",
level: 3,
},
],
}
export const EleConfig: { [key in Ele]: EleData } = {
[Ele.Yeast]: {
cls: Yeast,
texture: "元素/酵母菌.png",
weight: 4,
score: 1,
},
[Ele.Filiform]: {
cls: Filiform,
texture: "元素/丝状菌.png",
weight: 3,
score: 2,
},
[Ele.Molecule]: {
cls: Molecule,
texture: "元素/黄色分子.png",
weight: 2,
score: 3,
},
[Ele.Mugwort]: {
cls: Mugwort,
texture: "元素/艾草.png",
weight: 1,
score: -2,
neg: true,
},
[Ele.Realgar]: {
cls: Realgar,
texture: "元素/雄黄.png",
weight: 1,
score: -2,
neg: true,
},
[Ele.ZongZi]: {
cls: ZongZi,
texture: "元素/粽子.png",
weight: 1,
}
}
export const winSize = {
width: 750,
height: window.innerHeight / window.innerWidth * 750,
}
export const mapTop = 464;
export const mapSize = {
width: winSize.width,
height: winSize.height - mapTop,
}
export class Ease {
/**
* @version
* @platform Web,Native
*/
constructor() {
}
/**
* get.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* get。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static get(amount: number) {
if (amount < -1) {
amount = -1;
}
if (amount > 1) {
amount = 1;
}
return function (t: number) {
if (amount == 0) {
return t;
}
if (amount < 0) {
return t * (t * -amount + 1 + amount);
}
return t * ((2 - t) * amount + (1 - amount));
}
}
/**
* get pow in.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* get pow in。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static getPowIn(pow: number) {
return function (t: number) {
return Math.pow(t, pow);
}
}
/**
* get pow out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* get pow out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static getPowOut(pow: number) {
return function (t: number) {
return 1 - Math.pow(1 - t, pow);
}
}
/**
* get pow in out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* get pow in out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static getPowInOut(pow: number) {
return function (t: number) {
if ((t *= 2) < 1) return 0.5 * Math.pow(t, pow);
return 1 - 0.5 * Math.abs(Math.pow(2 - t, pow));
}
}
/**
* quad in.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* quad in。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static quadIn = Ease.getPowIn(2);
/**
* quad out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* quad out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static quadOut = Ease.getPowOut(2);
/**
* quad in out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* quad in out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static quadInOut = Ease.getPowInOut(2);
/**
* cubic in.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* cubic in。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static cubicIn = Ease.getPowIn(3);
/**
* cubic out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* cubic out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static cubicOut = Ease.getPowOut(3);
/**
* cubic in out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* cubic in out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static cubicInOut = Ease.getPowInOut(3);
/**
* quart in.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* quart in。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static quartIn = Ease.getPowIn(4);
/**
* quart out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* quart out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static quartOut = Ease.getPowOut(4);
/**
* quart in out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* quart in out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static quartInOut = Ease.getPowInOut(4);
/**
* quint in.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* quint in。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static quintIn = Ease.getPowIn(5);
/**
* quint out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* quint out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static quintOut = Ease.getPowOut(5);
/**
* quint in out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* quint in out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static quintInOut = Ease.getPowInOut(5);
/**
* sine in.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* sine in。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static sineIn(t: number) {
return 1 - Math.cos(t * Math.PI / 2);
}
/**
* sine out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* sine out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static sineOut(t: number) {
return Math.sin(t * Math.PI / 2);
}
/**
* sine in out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* sine in out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static sineInOut(t: number) {
return -0.5 * (Math.cos(Math.PI * t) - 1)
}
/**
* get back in.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* get back in。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static getBackIn(amount: number) {
return function (t: number) {
return t * t * ((amount + 1) * t - amount);
}
}
/**
* back in.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* back in。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static backIn = Ease.getBackIn(1.7);
/**
* get back out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* get back out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static getBackOut(amount: number) {
return function (t) {
return (--t * t * ((amount + 1) * t + amount) + 1);
}
}
/**
* back out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* back out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static backOut = Ease.getBackOut(1.7);
/**
* get back in out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* get back in out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static getBackInOut(amount: number) {
amount *= 1.525;
return function (t: number) {
if ((t *= 2) < 1) return 0.5 * (t * t * ((amount + 1) * t - amount));
return 0.5 * ((t -= 2) * t * ((amount + 1) * t + amount) + 2);
}
}
/**
* back in out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* back in out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static backInOut = Ease.getBackInOut(1.7);
/**
* circ in.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* circ in。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static circIn(t: number) {
return -(Math.sqrt(1 - t * t) - 1);
}
/**
* circ out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* circ out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static circOut(t: number) {
return Math.sqrt(1 - (--t) * t);
}
/**
* circ in out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* circ in out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static circInOut(t: number) {
if ((t *= 2) < 1) {
return -0.5 * (Math.sqrt(1 - t * t) - 1);
}
return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
}
/**
* bounce in.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* bounce in。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static bounceIn(t: number) {
return 1 - Ease.bounceOut(1 - t);
}
/**
* bounce out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* bounce out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static bounceOut(t: number) {
if (t < 1 / 2.75) {
return (7.5625 * t * t);
} else if (t < 2 / 2.75) {
return (7.5625 * (t -= 1.5 / 2.75) * t + 0.75);
} else if (t < 2.5 / 2.75) {
return (7.5625 * (t -= 2.25 / 2.75) * t + 0.9375);
} else {
return (7.5625 * (t -= 2.625 / 2.75) * t + 0.984375);
}
}
/**
* bounce in out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* bounce in out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static bounceInOut(t: number) {
if (t < 0.5) return Ease.bounceIn(t * 2) * .5;
return Ease.bounceOut(t * 2 - 1) * 0.5 + 0.5;
}
/**
* get elastic in.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* get elastic in。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static getElasticIn(amplitude: number, period: number) {
let pi2 = Math.PI * 2;
return function (t: number) {
if (t == 0 || t == 1) return t;
let s = period / pi2 * Math.asin(1 / amplitude);
return -(amplitude * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * pi2 / period));
}
}
/**
* elastic in.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* elastic in。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static elasticIn = Ease.getElasticIn(1, 0.3);
/**
* get elastic out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* get elastic out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static getElasticOut(amplitude: number, period: number) {
let pi2 = Math.PI * 2;
return function (t: number) {
if (t == 0 || t == 1) return t;
let s = period / pi2 * Math.asin(1 / amplitude);
return (amplitude * Math.pow(2, -10 * t) * Math.sin((t - s) * pi2 / period) + 1);
}
}
/**
* elastic out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* elastic out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static elasticOut = Ease.getElasticOut(1, 0.3);
/**
* get elastic in out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* get elastic in out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static getElasticInOut(amplitude: number, period: number) {
let pi2 = Math.PI * 2;
return function (t: number) {
let s = period / pi2 * Math.asin(1 / amplitude);
if ((t *= 2) < 1) return -0.5 * (amplitude * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * pi2 / period));
return amplitude * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * pi2 / period) * 0.5 + 1;
}
}
/**
* elastic in out.See example.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* elastic in out。请查看示例
* @version
* @platform Web,Native
* @language zh_CN
*/
public static elasticInOut = Ease.getElasticInOut(1, 0.3 * 1.5);
}
// import EventDispatcher from "../core/EventDispatcher"
/**
* 只用到一个onChange监听
* //做了锁步时间,尽量用这个
*/
export default class Tween /*extends EventDispatcher*/ {
/**
* 不做特殊处理
* @constant {number} Tween.NONE
* @private
*/
private static NONE = 0;
/**
* 循环
* @constant {number} Tween.LOOP
* @private
*/
private static LOOP = 1;
/**
* 倒序
* @constant {number} Tween.REVERSE
* @private
*/
private static REVERSE = 2;
/**
* @private
*/
private static _tweens: Tween[] = [];
/**
* @private
*/
private static IGNORE = {};
/**
* @private
*/
private static _plugins = {};
/**
* @private
*/
private static _inited = false;
/**
* @private
*/
private _target: any = null;
/**
* @private
*/
private _useTicks: boolean = false;
/**
* @private
*/
private ignoreGlobalPause: boolean = false;
/**
* @private
*/
private loop: boolean = false;
/**
* @private
*/
private pluginData = null;
/**
* @private
*/
private _curQueueProps;
/**
* @private
*/
private _initQueueProps;
/**
* @private
*/
private _steps: any[] = null;
/**
* @private
*/
private paused: boolean = false;
/**
* @private
*/
private duration: number = 0;
/**
* @private
*/
private _prevPos: number = -1;
/**
* @private
*/
private position: number = null;
/**
* @private
*/
private _prevPosition: number = 0;
/**
* @private
*/
private _stepPosition: number = 0;
/**
* @private
*/
private passive: boolean = false;
/**
* Activate an object and add a Tween animation to the object
* @param target {any} The object to be activated
* @param props {any} Parameters, support loop onChange onChangeObj
* @param pluginData {any} Write realized
* @param override {boolean} Whether to remove the object before adding a tween, the default value false
* Not recommended, you can use Tween.removeTweens(target) instead.
* @version
* @platform Web,Native
* @language en_US
*/
/**
* 激活一个对象,对其添加 Tween 动画
* @param target {any} 要激活 Tween 的对象
* @param props {any} 参数,支持loop(循环播放) onChange(变化函数) onChangeObj(变化函数作用域)
* @param pluginData {any} 暂未实现
* @param override {boolean} 是否移除对象之前添加的tween,默认值false。
* 不建议使用,可使用 Tween.removeTweens(target) 代替。
* @version
* @platform Web,Native
* @language zh_CN
*/
public static get(target: any, props?: { loop?: boolean, onChange?: Function, onChangeObj?: any }, pluginData: any = null, override: boolean = false): Tween {
if (override) {
Tween.removeTweens(target);
}
return new Tween(target, props, pluginData);
}
/**
* Delete all Tween animations from an object
* @param target The object whose Tween to be deleted
* @version
* @platform Web,Native
* @language en_US
*/
/**
* 删除一个对象上的全部 Tween 动画
* @param target 需要移除 Tween 的对象
* @version
* @platform Web,Native
* @language zh_CN
*/
public static removeTweens(target: any): void {
if (!target.tween_count) {
return;
}
let tweens: Tween[] = Tween._tweens;
for (let i = tweens.length - 1; i >= 0; i--) {
if (tweens[i]._target == target) {
tweens[i].paused = true;
tweens.splice(i, 1);
}
}
target.tween_count = 0;
}
/**
* Pause all Tween animations of a certain object
* @param target The object whose Tween to be paused
* @version
* @platform Web,Native
* @language en_US
*/
/**
* 暂停某个对象的所有 Tween
* @param target 要暂停 Tween 的对象
* @version
* @platform Web,Native
* @language zh_CN
*/
public static pauseTweens(target: any): void {
if (!target.tween_count) {
return;
}
let tweens: Tween[] = Tween._tweens;
for (let i = tweens.length - 1; i >= 0; i--) {
if (tweens[i]._target == target) {
tweens[i].paused = true;
}
}
}
/**
* Resume playing all easing of a certain object
* @param target The object whose Tween to be resumed
* @version
* @platform Web,Native
* @language en_US
*/
/**
* 继续播放某个对象的所有缓动
* @param target 要继续播放 Tween 的对象
* @version
* @platform Web,Native
* @language zh_CN
*/
public static resumeTweens(target: any): void {
if (!target.tween_count) {
return;
}
let tweens: Tween[] = Tween._tweens;
for (let i = tweens.length - 1; i >= 0; i--) {
if (tweens[i]._target == target) {
tweens[i].paused = false;
}
}
}
/**
* @private
*
* @param delta
* @param paused
*/
private static tick(timeStamp: number, paused = false): boolean {
let delta = timeStamp - Tween._lastTime;
Tween._lastTime = timeStamp;
let tweens: Tween[] = Tween._tweens.concat();
for (let i = tweens.length - 1; i >= 0; i--) {
let tween: Tween = tweens[i];
if ((paused && !tween.ignoreGlobalPause) || tween.paused) {
continue;
}
tween.$tick(tween._useTicks ? 1 : delta);
}
return false;
}
/**
* flush方法,为了能加入总循环
* 默认是锁步的
* @param delta
* @param paused ,暂时不用,全局禁止
*/
public static flush(/*paused = false*/): void {
let timeStamp = Date.now()
let delta = Tween._lastTime ? (timeStamp - Tween._lastTime) : 16.67;;
Tween._lastTime = timeStamp;
let tweens: Tween[] = Tween._tweens.concat();
for (let i = tweens.length - 1; i >= 0; i--) {
let tween: Tween = tweens[i];
if (/*(paused && !tween.ignoreGlobalPause) ||*/ tween.paused) {
continue;
}
tween.$tick(tween._useTicks ? 1 : delta);
}
}
private static _lastTime: number = 0;
/**
* @private
*
* @param tween
* @param value
*/
private static _register(tween: Tween, value: boolean): void {
let target: any = tween._target;
let tweens: Tween[] = Tween._tweens;
if (value) {
if (target) {
target.tween_count = target.tween_count > 0 ? target.tween_count + 1 : 1;
}
tweens.push(tween);
if (!Tween._inited) {
// Tween._lastTime = Date.now();
//开始加入循环暂时从简,最后实际使用,最好加入Stage总循环中
// let aaa = () => {
// Tween.tick(Date.now())
// requestAnimationFrame(aaa)
// }
//必须做延时
// setTimeout(aaa, 16.7)
// aaa();
// ticker.$startTick(Tween.tick, null);
Tween._inited = true;
}
} else {
if (target) {
target.tween_count--;
}
let i = tweens.length;
while (i--) {
if (tweens[i] == tween) {
tweens.splice(i, 1);
return;
}
}
}
}
/**
* Delete all Tween
* @version
* @platform Web,Native
* @language en_US
*/
/**
* 删除所有 Tween
* @version
* @platform Web,Native
* @language zh_CN
*/
public static removeAllTweens(): void {
let tweens: Tween[] = Tween._tweens;
for (let i = 0, l = tweens.length; i < l; i++) {
let tween: Tween = tweens[i];
tween.paused = true;
tween._target.tween_count = 0;
}
tweens.length = 0;
}
/**
* 创建一个 Tween 对象
* @private
* @version
* @platform Web,Native
*/
constructor(target: any, props: any, pluginData: any) {
// super();
this.initialize(target, props, pluginData);
}
onChange: Function
/**
* @private
*
* @param target
* @param props
* @param pluginData
*/
private initialize(target: any, props: any, pluginData: any): void {
this._target = target;
if (props) {
this._useTicks = props.useTicks;
this.ignoreGlobalPause = props.ignoreGlobalPause;
this.loop = props.loop;
if (props.onChange) {
this.onChange = props.onChange.bind(props.onChangeObj)
} else {
this.onChange = null
}
// && this.addEventListener("change", props.onChange.bind(props.onChangeObj));
if (props.override) {
Tween.removeTweens(target);
}
}
this.pluginData = pluginData || {};
this._curQueueProps = {};
this._initQueueProps = {};
this._steps = [];
if (props && props.paused) {
this.paused = true;
}
else {
Tween._register(this, true);
}
if (props && props.position != null) {
this.setPosition(props.position, Tween.NONE);
}
}
/**
* @private
*
* @param value
* @param actionsMode
* @returns
*/
public setPosition(value: number, actionsMode: number = 1): boolean {
if (value < 0) {
value = 0;
}
//正常化位置
let t: number = value;
let end: boolean = false;
if (t >= this.duration) {
if (this.loop) {
var newTime = t % this.duration;
if (t > 0 && newTime === 0) {
t = this.duration;
} else {
t = newTime;
}
}
else {
t = this.duration;
end = true;
}
}
if (t == this._prevPos) {
return end;
}
if (end) {
this.setPaused(true);
}
let prevPos = this._prevPos;
this.position = this._prevPos = t;
this._prevPosition = value;
if (this._target) {
if (this._steps.length > 0) {
// 找到新的tween
let l = this._steps.length;
let stepIndex = -1;
for (let i = 0; i < l; i++) {
if (this._steps[i].type == "step") {
stepIndex = i;
if (this._steps[i].t <= t && this._steps[i].t + this._steps[i].d >= t) {
break;
}
}
}
for (let i = 0; i < l; i++) {
if (this._steps[i].type == "action") {
//执行actions
if (actionsMode != 0) {
if (this._useTicks) {
this._runAction(this._steps[i], t, t);
}
else if (actionsMode == 1 && t < prevPos) {
if (prevPos != this.duration) {
this._runAction(this._steps[i], prevPos, this.duration);
}
this._runAction(this._steps[i], 0, t, true);
}
else {
this._runAction(this._steps[i], prevPos, t);
}
}
}
else if (this._steps[i].type == "step") {
if (stepIndex == i) {
let step = this._steps[stepIndex];
this._updateTargetProps(step, Math.min((this._stepPosition = t - step.t) / step.d, 1));
}
}
}
}
}
this.onChange && this.onChange()
// this.dispatchEvent("change");
return end;
}
/**
* @private
*
* @param startPos
* @param endPos
* @param includeStart
*/
private _runAction(action: any, startPos: number, endPos: number, includeStart: boolean = false) {
let sPos: number = startPos;
let ePos: number = endPos;
if (startPos > endPos) {
//把所有的倒置
sPos = endPos;
ePos = startPos;
}
let pos = action.t;
if (pos == ePos || (pos > sPos && pos < ePos) || (includeStart && pos == startPos)) {
action.f.apply(action.o, action.p);
}
}
/**
* @private
*
* @param step
* @param ratio
*/
private _updateTargetProps(step: any, ratio: number) {
let p0, p1, v, v0, v1, arr;
if (!step && ratio == 1) {
this.passive = false;
p0 = p1 = this._curQueueProps;
} else {
this.passive = !!step.v;
//不更新props.
if (this.passive) {
return;
}
//使用ease
if (step.e) {
ratio = step.e(ratio, 0, 1, 1);
}
p0 = step.p0;
p1 = step.p1;
}
for (let n in this._initQueueProps) {
if ((v0 = p0[n]) == null) {
p0[n] = v0 = this._initQueueProps[n];
}
if ((v1 = p1[n]) == null) {
p1[n] = v1 = v0;
}
if (v0 == v1 || ratio == 0 || ratio == 1 || (typeof (v0) != "number")) {
v = ratio == 1 ? v1 : v0;
} else {
v = v0 + (v1 - v0) * ratio;
}
let ignore = false;
if (arr = Tween._plugins[n]) {
for (let i = 0, l = arr.length; i < l; i++) {
let v2 = arr[i].tween(this, n, v, p0, p1, ratio, !!step && p0 == p1, !step);
if (v2 == Tween.IGNORE) {
ignore = true;
}
else {
v = v2;
}
}
}
if (!ignore) {
this._target[n] = v;
}
}
}
/**
* Whether setting is paused
* @param value {boolean} Whether to pause
* @returns Tween object itself
* @version
* @platform Web,Native
* @language en_US
*/
/**
* 设置是否暂停
* @param value {boolean} 是否暂停
* @returns Tween对象本身
* @version
* @platform Web,Native
* @language zh_CN
*/
public setPaused(value: boolean): Tween {
if (this.paused == value) {
return this;
}
this.paused = value;
Tween._register(this, !value);
return this;
}
/**
* @private
*
* @param props
* @returns
*/
private _cloneProps(props: any): any {
let o = {};
for (let n in props) {
o[n] = props[n];
}
return o;
}
/**
* @private
*
* @param o
* @returns
*/
private _addStep(o): Tween {
if (o.d > 0) {
o.type = "step";
this._steps.push(o);
o.t = this.duration;
this.duration += o.d;
}
return this;
}
/**
* @private
*
* @param o
* @returns
*/
private _appendQueueProps(o): any {
let arr, oldValue, i, l, injectProps;
for (let n in o) {
if (this._initQueueProps[n] === undefined) {
oldValue = this._target[n];
//设置plugins
if (arr = Tween._plugins[n]) {
for (i = 0, l = arr.length; i < l; i++) {
oldValue = arr[i].init(this, n, oldValue);
}
}
this._initQueueProps[n] = this._curQueueProps[n] = (oldValue === undefined) ? null : oldValue;
} else {
oldValue = this._curQueueProps[n];
}
}
for (let n in o) {
oldValue = this._curQueueProps[n];
if (arr = Tween._plugins[n]) {
injectProps = injectProps || {};
for (i = 0, l = arr.length; i < l; i++) {
if (arr[i].step) {
arr[i].step(this, n, oldValue, o[n], injectProps);
}
}
}
this._curQueueProps[n] = o[n];
}
if (injectProps) {
this._appendQueueProps(injectProps);
}
return this._curQueueProps;
}
/**
* @private
*
* @param o
* @returns
*/
private _addAction(o): Tween {
o.t = this.duration;
o.type = "action";
this._steps.push(o);
return this;
}
/**
* @private
*
* @param props
* @param o
*/
private _set(props: any, o): void {
for (let n in props) {
o[n] = props[n];
}
}
/**
* Wait the specified milliseconds before the execution of the next animation
* @param duration {number} Waiting time, in milliseconds
* @param passive {boolean} Whether properties are updated during the waiting time
* @returns Tween object itself
* @version
* @platform Web,Native
* @language en_US
*/
/**
* 等待指定毫秒后执行下一个动画
* @param duration {number} 要等待的时间,以毫秒为单位
* @param passive {boolean} 等待期间属性是否会更新
* @returns Tween对象本身
* @version
* @platform Web,Native
* @language zh_CN
*/
public wait(duration: number, passive?: boolean): Tween {
if (duration == null || duration <= 0) {
return this;
}
let o = this._cloneProps(this._curQueueProps);
return this._addStep({ d: duration, p0: o, p1: o, v: passive });
}
/**
* Modify the property of the specified object to a specified value
* @param props {Object} Property set of an object
* @param duration {number} Duration
* @param ease {Ease} Easing algorithm
* @returns {Tween} Tween object itself
* @version
* @platform Web,Native
* @language en_US
*/
/**
* 将指定对象的属性修改为指定值
* @param props {Object} 对象的属性集合
* @param duration {number} 持续时间
* @param ease {Ease} 缓动算法
* @returns {Tween} Tween对象本身
* @version
* @platform Web,Native
* @language zh_CN
*/
public to(props: any, duration?: number, ease: Function = undefined) {
if (isNaN(duration) || duration < 0) {
duration = 0;
}
this._addStep({ d: duration || 0, p0: this._cloneProps(this._curQueueProps), e: ease, p1: this._cloneProps(this._appendQueueProps(props)) });
//加入一步set,防止游戏极其卡顿时候,to后面的call取到的属性值不对
return this.set(props);
}
/**
* Execute callback function
* @param callback {Function} Callback method
* @param thisObj {any} this action scope of the callback method
* @param params {any[]} Parameter of the callback method
* @returns {Tween} Tween object itself
* @version
* @platform Web,Native
* @example
* <pre>
* Tween.get(display).call(function (a:number, b:string) {
* console.log("a: " + a); // the first parameter passed 233
* console.log("b: " + b); // the second parameter passed “hello”
* }, this, [233, "hello"]);
* </pre>
* @language en_US
*/
/**
* 执行回调函数
* @param callback {Function} 回调方法
* @param thisObj {any} 回调方法this作用域
* @param params {any[]} 回调方法参数
* @returns {Tween} Tween对象本身
* @version
* @platform Web,Native
* @example
* <pre>
* Tween.get(display).call(function (a:number, b:string) {
* console.log("a: " + a); //对应传入的第一个参数 233
* console.log("b: " + b); //对应传入的第二个参数 “hello”
* }, this, [233, "hello"]);
* </pre>
* @language zh_CN
*/
public call(callback: Function, thisObj: any = undefined, params: any[] = undefined): Tween {
return this._addAction({ f: callback, p: params ? params : [], o: thisObj ? thisObj : this._target });
}
/**
* Now modify the properties of the specified object to the specified value
* @param props {Object} Property set of an object
* @param target The object whose Tween to be resumed
* @returns {Tween} Tween object itself
* @version
* @platform Web,Native
*/
/**
* 立即将指定对象的属性修改为指定值
* @param props {Object} 对象的属性集合
* @param target 要继续播放 Tween 的对象
* @returns {Tween} Tween对象本身
* @version
* @platform Web,Native
*/
public set(props: any, target = null): Tween {
//更新当前数据,保证缓动流畅性
this._appendQueueProps(props);
// console.log(this._target.x)
return this._addAction({ f: this._set, o: this, p: [props, target ? target : this._target] });
}
/**
* Execute
* @param tween {Tween} The Tween object to be operated. Default: this
* @returns {Tween} Tween object itself
* @version
* @platform Web,Native
* @language en_US
*/
/**
* 执行
* @param tween {Tween} 需要操作的 Tween 对象,默认this
* @returns {Tween} Tween对象本身
* @version
* @platform Web,Native
* @language zh_CN
*/
public play(tween?: Tween): Tween {
if (!tween) {
tween = this;
}
return this.call(tween.setPaused, tween, [false]);
}
/**
* Pause
* @param tween {Tween} The Tween object to be operated. Default: this
* @returns {Tween} Tween object itself
* @version
* @platform Web,Native
* @language en_US
*/
/**
* 暂停
* @param tween {Tween} 需要操作的 Tween 对象,默认this
* @returns {Tween} Tween对象本身
* @version
* @platform Web,Native
* @language zh_CN
*/
public pause(tween?: Tween): Tween {
if (!tween) {
tween = this;
}
return this.call(tween.setPaused, tween, [true]);
}
/**
* @method Tween#tick
* @param delta {number}
* @private
* @version
* @platform Web,Native
*/
public $tick(delta: number): void {
if (this.paused) {
return;
}
this.setPosition(this._prevPosition + delta);
}
}
export * from "./Ease"
export { default as Tween } from "./Tween";
\ No newline at end of file
@import "../../res.less";
.GuidePage {
width: 750px;
height: 1624px;
left: 0;
top: 0;
position: absolute;
overflow: hidden;
.bg {
width: 750px;
height: 1624px;
left: 0;
top: 0;
position: absolute;
.sparkBg("GuidePage/bg.jpg");
}
.joystick {
position: absolute;
left: 270px;
top: 1070px;
width: 210px;
height: 210px;
.sparkBg("GuidePage/方向键未触发.png");
}
.tip {
font-size: 32px;
color: rgb(255, 255, 255);
text-align: center;
position: absolute;
left: 0;
top: 1300px;
width: 100%;
}
.kuang {
width: 750px;
height: 411px;
position: absolute;
left: 0;
}
.kuang1 {
top: 575px;
}
.kuang2 {
top: 694px;
}
.kuang3 {
top: 694px;
}
.kuang4 {
top: 694px;
}
.kuang5 {
top: 344px;
}
.guide {
position: absolute;
.fadeIn();
}
.guide1 {
left: 70px;
top: 690px;
width: 613px;
height: 208px;
.sparkBg("GuidePage/guide1.png");
}
.guide2 {
left: 70px;
top: 544px;
width: 611px;
height: 479px;
.sparkBg("GuidePage/guide2.png");
}
.guide3 {
left: 92px;
top: 554px;
width: 569px;
height: 467px;
.sparkBg("GuidePage/guide3.png");
}
.guide4 {
left: 42px;
top: 571px;
width: 676px;
height: 459px;
.sparkBg("GuidePage/guide4.png");
}
.guide5 {
left: 43px;
top: 211px;
width: 707px;
height: 461px;
.sparkBg("GuidePage/guide5.png");
}
.guide6 {
position: absolute;
left: 107px;
top: 568px;
width: 534px;
height: 374px;
.sparkBg("GuidePage/文案.png");
.guide6Btn {
position: absolute;
left: 93px;
top: 218px;
width: 349px;
height: 90px;
.sparkBg("GuidePage/按钮.png");
}
}
}
.fadeIn {
opacity: 0;
animation-name: fadeInAni;
animation-timing-function: ease-in-out;
animation-fill-mode: forwards;
animation-duration: 1s;
animation-delay: 0.88s;
}
@keyframes fadeInAni {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
import React from 'react';
import { observer } from 'mobx-react';
import './GuidePage.less';
import { SvgaPlayer } from "@grace/svgaplayer";
import kuang from "../../assets/GuidePage/4输出横幅效果.svga";
import { SvgaPlayerRef } from "@grace/svgaplayer/dist/components/SvgaPlayer";
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
import GamePage from "@/pages/GamePage/GamePage.tsx";
import { Button } from "@grace/ui";
import API from "@/api";
@observer
class GuidePage extends React.Component<any, any> {
state = {
guide: 1,
canNext: false,
}
kuangSvga: SvgaPlayerRef;
componentDidMount() {
setTimeout(() => {
this.setState({ canNext: true });
}, 2000);
}
next = () => {
const { guide, canNext } = this.state;
if (guide >= 6) return;
if (!canNext) return;
this.setState({ guide: guide + 1, canNext: false });
setTimeout(() => {
this.setState({ canNext: true });
}, 1666);
this.kuangSvga.start();
}
onEnd = () => {
// this.setState({ canNext: true });
}
startGame = () => {
API.guide();
PageCtrl.changePage(GamePage);
}
render() {
const { guide, canNext } = this.state;
return <div className="GuidePage" onClick={this.next}>
<div className="bg"/>
{guide < 6 && <SvgaPlayer
ref={(el) => (this.kuangSvga = el)}
onEnd={this.onEnd}
src={kuang}
className={`kuang kuang${guide}`}
loop={1}
/>}
{guide == 1 && <div className="guide guide1"/>}
{guide == 2 && <div className="guide guide2"/>}
{guide == 3 && <div className="guide guide3"/>}
{guide == 4 && <div className="guide guide4"/>}
{guide == 5 && <div className="guide guide5"/>}
{guide >= 6 && <div className="guide6">
<Button className="guide6Btn" onClick={this.startGame}/>
</div>}
<div className="joystick"/>
{guide < 6 && canNext && <div className="tip">点击屏幕继续</div>}
</div>;
}
}
export default GuidePage;
@import "../../res.less";
.homepage {
width: 750px;
height: 100%;
left: 0;
top: 0;
position: absolute;
overflow-y: scroll;
overflow-x: hidden;
}
import React from 'react';
import { observer } from 'mobx-react';
import './HomePage.less';
import { getUrlParam } from "@/utils/utils.ts";
import store from "@/store/store.ts";
@observer
class HomePage extends React.Component<any, any> {
root: HTMLDivElement;
componentDidMount() {
store.updateIndex();
store.queryTask()
if (getUrlParam('inviteCode')) {
store.doAssist()
}
}
render() {
const { } = store.indexData
return <div className="homepage" ref={(el) => this.root = el}>
</div>;
}
}
export default HomePage;
@import "../../res.less";
.loading {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
.webpBg("LoadingPage/loadingBg.jpg");
.loading-ip {
position: absolute;
left: 198px;
top: 572-153px;
width: 570px;
height: 508px;
.webpBg("LoadingPage/loadingIp.png");
}
.progressBarBg {
position: absolute;
left: 82px;
top: 898-153px;
width: 590px;
height: 30px;
border-radius: 118px;
background: #FCE4D4;
border: 2px solid #FFFFFF;
}
.progressBar {
position: absolute;
left: 84px;
top: 900-153px;
width: 590px;
height: 30px;
overflow: hidden;
border-radius: 118px;
.progressBarFill {
position: absolute;
left: 0;
top: 0;
width: 590px;
height: 30px;
.webpBg("LoadingPage/loadingFill.png")
}
}
.progressTxt {
position: absolute;
left: 246px;
top: 952-153px;
width: 256px;
height: 22px;
opacity: 1;
font-size: 24px;
font-weight: normal;
line-height: 22px;
color: #999999;
}
}
import React from "react";
import { observer } from "mobx-react";
import { preload } from "@/core/preload.ts";
import "./LoadingDemo.less";
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
import HomePage from "@/pages/HomePage/HomePage.tsx";
@observer
class LoadingDemo extends React.Component {
state = {
curPercentage: 0
}
curPercentage = 0;
intervalId: number = 0;
componentDidMount() {
this.preloadAssetInit();
// this.jump();
}
/**
* 资源预加载
*/
preloadAssetInit = async () => {
const files = import.meta.glob("../../assets/**/*", {
import: "default",
eager: true,
});
const urls = Object.values(files) as string[];
await preload(urls, (progress, loaded, total) => {
const percentage = Math.floor(progress * 100);
this.setEvenProgress(percentage);
});
};
jump = () => {
setTimeout(() => {
PageCtrl.changePage(HomePage); // 跳转页面
}, 100);
};
/**
* 以1%匀速加载进度
* @param {*} percentage
*/
setEvenProgress = (percentage) => {
this.intervalId && clearInterval(this.intervalId);
let curPercentage = this.curPercentage;
this.intervalId = window.setInterval(() => {
if (curPercentage >= percentage) {
clearInterval(this.intervalId);
this.jump();
return;
}
curPercentage += 1;
this.curPercentage = curPercentage;
this.setState({
curPercentage,
});
}, 10);
};
render() {
const { curPercentage } = this.state;
return <div className="loading">
<div className="loading-ip" />
<div className="progressBarBg" />
<div className="progressBar">
<div className="progressBarFill" style={{
transform: `translateX(${curPercentage - 100}%)`
}} />
</div>
<span className="progressTxt">金豆正在路上...... {curPercentage}%</span>
</div>;
}
}
export default LoadingDemo;
@import "../../res.less";
.MyPrize {
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
overflow: hidden;
.MyPrizeBg {
position: absolute;
left: 0;
top: 0;
width: 750px;
height: 1624px;
.webpBg("common/bg.jpg");
}
.MyPrizeTitle {
position: absolute;
left: 182px;
top: 208px;
width: 386px;
height: 127px;
.webpBg("MyPrize/我的奖品.png");
}
.MyPrizeBack {
position: absolute;
left: 0;
top: 208px;
width: 112px;
height: 60px;
.webpBg("common/返回.png");
transform-origin: center left !important;
}
.prizeList {
position: absolute;
left: 57px;
top: 425px;
width: 631px;
height: calc(100% - 425px);
overflow: hidden auto;
.prizeItem {
position: relative;
width: 631px;
height: 186px;
margin-bottom: 46px;
.webpBg("MyPrize/itemBg.png");
.prizeImg {
position: absolute;
left: 40px;
top: 40px;
width: 110px;
height: 110px;
border-width: 1px;
border-color: rgb(105, 40, 11);
border-style: solid;
border-radius: 11px;
background-color: rgb(255, 255, 255);
}
.prizeName {
font-size: 32px;
color: rgb(105, 40, 11);
text-align: left;
position: absolute;
left: 200px;
top: 50px;
width: 330px;
font-weight: bold;
.lineClamp1();
}
.getTime {
font-size: 24.414px;
color: rgb(105, 40, 11);
text-align: left;
position: absolute;
left: 200px;
top: 110px;
}
}
}
.nothing {
position: absolute;
left: 220px;
top: 200px;
width: 194px;
height: 326px;
.sparkBg("MyPrize/nothing.png")
}
}
import React from 'react';
import {observer} from 'mobx-react';
import './MyPrize.less';
import {Button} from "@grace/ui";
import {dateFormatter} from "@/utils/utils.ts";
import API from "@/api";
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
@observer
class MyPrize extends React.Component<any, any> {
state = {
list: [],
}
componentDidMount() {
this.initList();
}
async initList() {
const {success, data} = await API.records({
ignoreSp: true,
});
if (!success) return;
this.setState({
list: data,
});
}
clickBack = () => {
PageCtrl.backPage();
}
clickItem = (item) => {
if (item.url) {
location.href = item.url
} else {
location.href = `/aaw/projectx/takePrize?projectOrderNo=${item.id}`
}
}
render() {
const {list} = this.state;
return <div className="MyPrize">
<div className="MyPrizeBg"/>
<div className="MyPrizeTitle"/>
<div className="prizeList">
{
list.length > 0 ? list.map((item, index) => {
return <Button className="prizeItem" key={index} onClick={this.clickItem.bind(this, item)}>
<img className="prizeImg" src={item.extra.icon}/>
<div className="prizeName">{item.extra.name}</div>
<div className="getTime">{dateFormatter(item.gmtCreate, "yyyy.MM.dd hh:mm:ss")}</div>
</Button>
}) : <div className="nothing"/>
}
</div>
<Button className="MyPrizeBack" onClick={this.clickBack}/>
</div>;
}
}
export default MyPrize;
@import "../../res.less";
.BackPanel {
width: 750px;
height: 1624px;
position: absolute;
left: 0;
top: 0;
.bg {
position: absolute;
left: 105px;
top: 448px;
width: 539px;
height: 533px;
.webpBg("BackPanel/bg.png");
}
.ok {
position: absolute;
left: 413px;
top: 847px;
width: 199px;
height: 90px;
.webpBg("BackPanel/确认.png");
}
.cancel {
position: absolute;
left: 140px;
top: 855px;
width: 242px;
height: 74px;
.webpBg("BackPanel/继续游戏.png");
}
}
import React from "react";
import { observer } from "mobx-react";
import "./BackPanel.less";
import { Button } from "@grace/ui";
import { _asyncThrottle } from "@/utils/utils.ts";
import { ModalCtrl } from "@/core/ctrls/ModalCtrl.tsx";
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
import HomePage from "@/pages/HomePage/HomePage.tsx";
export interface IFailPanelProps {
ok: () => void,
cancel: () => void,
}
@observer
class BackPanel extends React.Component<IFailPanelProps> {
componentDidMount() {
}
clickCancel = () => {
const { cancel } = this.props;
ModalCtrl.closeModal();
cancel && cancel();
};
clickOk = _asyncThrottle(async () => {
const { ok } = this.props;
ModalCtrl.closeModal();
ok && ok();
PageCtrl.changePage(HomePage);
});
render() {
return <div className="BackPanel">
<div className="bg"/>
<Button className="ok" onClick={this.clickOk}/>
<Button className="cancel" onClick={this.clickCancel}/>
</div>;
}
}
export default BackPanel;
@import "../../res.less";
.FailPanel {
width: 750px;
height: 1624px;
position: absolute;
left: 0;
top: 0;
.bg {
position: absolute;
left: 151px;
top: 447px;
width: 444px;
height: 560px;
.webpBg("FailPanel/bg.png");
}
.rank {
font-size: 29px;
color: rgb(255, 255, 255);
position: absolute;
left: 0;
top: 535px;
width: 100%;
text-align: center;
text-shadow: 0 0 5px #16c8c2,
0 0 5px #16c8c2,
0 0 5px #16c8c2,
0 0 10px #16c8c2,
0 0 10px #16c8c2,
0 0 20px #16c8c2;
}
.score {
font-size: 96.09px;
color: rgb(255, 255, 255);
font-weight: bold;
text-align: center;
position: absolute;
left: 0;
top: 672px;
width: 100%;
text-shadow: 0 0 5px #f3d71a,
0 0 5px #f3d71a,
0 0 5px #f3d71a,
0 0 10px #f3d71a,
0 0 10px #f3d71a;
span {
font-size: 32.34px;
}
}
.tip {
color: rgb(255, 255, 255);
font-size: 20px;
text-align: center;
position: absolute;
left: 0;
top: 800px;
width: 100%;
line-height: 33px;
span {
font-size: 26px;
color: #f3c81b;
}
}
.btn {
position: absolute;
left: 214px;
top: 887px;
width: 318px;
height: 80px;
.webpBg("FailPanel/btn.png");
}
.close {
position: absolute;
left: 340px;
top: 1023px;
width: 70px;
height: 70px;
.webpBg("FailPanel/close.png");
}
}
import React from "react";
import {observer} from "mobx-react";
import "./FailPanel.less";
import {Button} from "@grace/ui";
import {_asyncThrottle} from "@/utils/utils.ts";
import { ModalCtrl } from "@/core/ctrls/ModalCtrl.tsx";
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
import HomePage from "@/pages/HomePage/HomePage.tsx";
export interface IFailPanelProps {
score: number,
rank: number,
prizeName: string,
reachTargetScore: boolean,
drawChance: number,
}
@observer
class FailPanel extends React.Component<IFailPanelProps> {
componentDidMount() {
}
clickClose = () => {
ModalCtrl.closeModal();
PageCtrl.changePage(HomePage);
};
clickBtn = _asyncThrottle(async () => {
});
render() {
const {score, rank} = this.props;
return <div className="FailPanel">
<div className="bg"/>
<div className="rank">当前排名:NO.{rank}</div>
<div className="score">{score}<span></span></div>
<div className="tip">
单局游戏分数达200<br/>
即可获得<span>1次抽奖机会</span>
</div>
<Button className="btn" onClick={this.clickBtn}/>
<Button className="close" onClick={this.clickClose}/>
</div>;
}
}
export default FailPanel;
@import "../../res.less";
.PrizePanel {
width: 750px;
height: 1624px;
position: absolute;
left: 0;
top: 0;
.PrizeBg {
position: absolute;
left: 93px;
top: 237px;
width: 562px;
height: 809px;
.webpBg("PrizePanel/bg.png");
}
.prizeImg {
border-width: 1px;
border-color: rgb(249, 114, 28);
border-style: solid;
border-radius: 22px;
background-color: rgb(255, 255, 255);
position: absolute;
left: 273px;
top: 580px;
width: 199px;
height: 198px;
}
.prizeName {
font-size: 24px;
color: rgba(103, 25, 10, 0.8);
text-align: center;
position: absolute;
left: 93px;
top: 800px;
width: 562px;
font-weight: bold;
}
.ok {
position: absolute;
left: 215px;
top: 844px;
width: 318px;
height: 95px;
.webpBg("PrizePanel/开心收下.png");
}
.close {
position: absolute;
left: 348px;
top: 1092px;
width: 54px;
height: 54px;
.sparkBg("common/close.png");
}
}
import React from "react";
import { observer } from "mobx-react";
import "./PrizePanel.less";
import { Button } from "@grace/ui";
import { ModalCtrl } from "@/core/ctrls/ModalCtrl.tsx";
export interface IPrizePanelProps {
prizeVO: {
prizeId: string | "thanks",
prizeName: string,
prizeImg: string,
},
remainGameTimes: number,
}
@observer
class PrizePanel extends React.Component<IPrizePanelProps> {
componentDidMount() {
}
close = () => {
ModalCtrl.closeModal();
};
clickGet = () => {
};
render() {
const { prizeVO } = this.props;
return <div className="PrizePanel">
<div className="PrizeBg"/>
<img className="prizeImg" src={prizeVO.prizeImg}/>
<div className="prizeName">{prizeVO?.prizeName}</div>
<Button className="ok md18" onClick={this.clickGet}/>
<Button className="close" onClick={this.close}/>
</div>;
}
}
export default PrizePanel;
@import "../../res.less";
.SucPanel {
width: 750px;
height: 1624px;
position: absolute;
left: 0;
top: 0;
.bg {
position: absolute;
left: 153px;
top: 335px;
width: 444px;
height: 706px;
.webpBg("SucPanel/bg.png");
}
.rank {
font-size: 29px;
color: rgb(255, 255, 255);
position: absolute;
left: 0;
top: 424px;
width: 100%;
text-align: center;
text-shadow: 0 0 5px #16c8c2,
0 0 5px #16c8c2,
0 0 5px #16c8c2,
0 0 10px #16c8c2,
0 0 10px #16c8c2,
0 0 20px #16c8c2;
}
.score {
font-size: 96.09px;
color: rgb(255, 255, 255);
font-weight: bold;
text-align: center;
position: absolute;
left: 0;
top: 555px;
width: 100%;
text-shadow: 0 0 5px #f3d71a,
0 0 5px #f3d71a,
0 0 5px #f3d71a,
0 0 10px #f3d71a,
0 0 10px #f3d71a;
span {
font-size: 32.34px;
}
}
.tip {
color: rgb(255, 255, 255);
font-size: 32.34px;
text-align: center;
position: absolute;
left: 0;
top: 682px;
width: 100%;
span {
margin-left: 10px;
font-size: 32.34px;
text-shadow: 0 0 5px #f3d71a,
0 0 5px #f3d71a,
0 0 5px #f3d71a,
0 0 10px #f3d71a,
0 0 10px #f3d71a;
}
}
.btn {
position: absolute;
left: 233px;
top: 904px;
width: 284px;
height: 90px;
.webpBg("SucPanel/btn.png");
}
.close {
position: absolute;
left: 341px;
top: 1065px;
width: 70px;
height: 70px;
.webpBg("SucPanel/close.png");
}
}
import React from "react";
import {observer} from "mobx-react";
import "./SucPanel.less";
import {Button} from "@grace/ui";
import {_asyncThrottle} from "@/utils/utils.ts";
import { ModalCtrl } from "@/core/ctrls/ModalCtrl.tsx";
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
import HomePage from "@/pages/HomePage/HomePage.tsx";
import Drawpop from "@/components/drawpop/drawpop";
export interface ISucPanelProps {
score: number,
rank: number,
prizeName: string,
reachTargetScore: boolean,
drawChance: number,
}
@observer
class SucPanel extends React.Component<ISucPanelProps> {
componentDidMount() {
}
clickClose = () => {
ModalCtrl.closeModal();
PageCtrl.changePage(HomePage);
};
clickBtn = _asyncThrottle(async () => {
ModalCtrl.closeModal();
PageCtrl.changePage(HomePage);
ModalCtrl.showModal(Drawpop)
});
render() {
const {score, rank} = this.props;
return <div className="SucPanel">
<div className="bg"/>
<div className="rank">当前排名:NO.{rank}</div>
<div className="score">{score}<span></span></div>
<div className="tip">恭喜获得抽奖机会<span>+1</span></div>
<Button className="btn" onClick={this.clickBtn}/>
<Button className="close" onClick={this.clickClose}/>
</div>;
}
}
export default SucPanel;
@RES_PATH: '/src/assets/';
@webp: '?x-oss-process=image/format,webp';
.sparkBg(@value) {
background-repeat: no-repeat;
background-size: 100% 100%;
background-position: left top;
--p: url("@{RES_PATH}@{value}");
background-image: var(--p);
[duiba-webp='true'] & {
--p: url("@{RES_PATH}@{value}@{webp}");
background-image: var(--p);
}
}
.webpBg(@value) {
.sparkBg("@{value}");
}
.mask(@value) {
mask-image: url("@{RES_PATH}@{value}");
-webkit-mask-image: url("@{RES_PATH}@{value}");
mask-repeat: no-repeat;
}
// 定位-水平垂直居中
.transform_center() {
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
position: absolute;
}
// flex-水平垂直居中
.flex_center() {
display: flex;
justify-content: center;
align-items: center;
}
/* 文本过长隐藏文字并显示省略号 单行*/
.lineClamp1() {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.lineClampN(@num) {
text-overflow: -o-ellipsis-lastline;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: @num;
overflow: hidden;
}
// 按钮呼吸动效
.breathAnimation() {
animation: scale 1s linear infinite alternate;
@keyframes scale {
0% {
transform: scale(1);
}
100% {
transform: scale(1.12);
}
}
}
// 弹窗居中缩放动效
// 注意 加该样式的元素居中方式不能用translate(-50%, -50%)
// 可以用margin-left、margin-top为负的宽度、高度的一半
.popupCenterShow() {
animation: centerShowAni 300ms ease-out;
@keyframes centerShowAni {
0% {
transform: scale(0);
}
66.7% {
transform: scale(1.1);
}
100% {
transform: scale(1);
}
}
}
// 渐入动画
.fade-in {
opacity: 0;
animation: fadeIn ease-in 1;
animation-fill-mode: forwards;
animation-duration: 1s;
}
@keyframes fadeIn {
0% {
opacity: 0;
}
70% {
opacity: 0;
}
100% {
opacity: 1;
}
}
// 隐藏滚动条
.hideScrollbar() {
scrollbar-width: none;
/* firefox */
-ms-overflow-style: none;
/* IE 10+ */
&::-webkit-scrollbar {
display: none;
/* Chrome Safari */
}
}
.ruleStyle {
overflow-x: hidden;
overflow-y: scroll;
word-break: break-all;
}
// 上滑弹窗动画
.topPop_move {
animation: move_top_ani 500ms ease-in-out;
@keyframes move_top_ani {
0% {
transform: translateY(100%);
}
100% {
transform: translateY(0);
}
}
}
.imgCenter(@width:100px, @height:100px,@left:50%,@top:50%) {
max-width: @width;
max-height: @height;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-@left, -@top);
}
// 弹窗进入
.pop_move {
animation: scale_ani 500ms ease-in-out 0ms;
@keyframes scale_ani {
0% {
transform: scale(0);
}
100% {
transform: scale(1);
}
}
}
\ No newline at end of file
import { makeAutoObservable, } from 'mobx';
import API from "@/api";
import store from "@/store/store.ts";
import { Toast } from "@grace/ui";
import { AESDecrypt, AESEncrypt } from "@/utils/Crypto.ts";
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
import HomePage from "@/pages/HomePage/HomePage.tsx";
import { GameConfig } from "@/pages/GamePage/config/Config.ts";
import FailPanel from "@/panels/FailPanel/FailPanel.tsx";
import SucPanel from "@/panels/SucPanel/SucPanel.tsx";
import { ModalCtrl } from "@/core/ctrls/ModalCtrl.tsx";
import GamePage from "@/pages/GamePage/GamePage.tsx";
import GuidePage from "@/pages/GuidePage/GuidePage.tsx";
class GameStore {
constructor() {
makeAutoObservable(this);
}
startInfo: {
recordId?: number | string
countdownSeconds?: number
} = {}
async start() {
if (store.indexData.remainTimes <= 0) {
Toast.show("今日游戏次数已用尽,明天再来吧~");
return false;
}
const { success, data } = await API.start();
store.updateIndex();
if (!success) {
return false;
}
try {
const decrypt = JSON.parse(AESDecrypt(data, "3C8C48E792E9241B", "cDOiBC1n2QrkAY2P"));
this.startInfo = decrypt;
if (decrypt.guide) {
PageCtrl.changePage(GuidePage);
} else {
PageCtrl.changePage(GamePage);
}
} catch (e) {
return false;
}
return success;
}
gameInfo: {
score: number,
remainTimes: number,
level: number,
maxScore: number,
cd: number,
} = {
score: 0,
remainTimes: 0,
level: 0,
maxScore: 0,
cd: GameConfig.gameCd,
}
reset() {
this.gameInfo = {
score: 0,
remainTimes: 0,
level: 0,
maxScore: 0,
cd: this.startInfo.countdownSeconds || GameConfig.gameCd,
}
}
addScore(s: number) {
const score = this.gameInfo.score + s;
this.gameInfo.score = score;
this.gameInfo.maxScore = Math.max(score, this.gameInfo.maxScore);
const { levelCfg } = GameConfig;
for (let i = levelCfg.length - 1; i >= 0; i--) {
if (score >= levelCfg[i].score) {
this.gameInfo.level = i;
break;
}
}
}
async submit() {
const { recordId } = this.startInfo;
const { score } = this.gameInfo;
const param = AESEncrypt(JSON.stringify({
timestamp: Date.now(),
recordId,
score,
}), "3C8C48E792E9241B", "cDOiBC1n2QrkAY2P");
const { success, data } = await API.submit({ param });
if (!success) {
PageCtrl.changePage(HomePage);
return;
}
if (data.reachTargetScore) {
ModalCtrl.showModal(SucPanel, data);
} else {
ModalCtrl.showModal(FailPanel, data);
}
}
}
export default (new GameStore());
import {makeAutoObservable} from "mobx"; // 从mobx库导入makeAutoObservable,用于自动观察类的状态变化
import {loadAudio} from "@/core/preload.ts";
import {watchPageVisibility} from "@/core/page-visibility-notify.ts"; // 导入背景音乐的音频文件
let whenHideStatus = false;
// 创建一个音乐存储的类并使用mobx的makeAutoObservable进行自动观察
const musicStore = makeAutoObservable(new class {
constructor() {
// 监听页面可见性变化
watchPageVisibility(this.onPageVisibilityChange);
}
// 页面可见性变化的处理函数
onPageVisibilityChange = async (visible) => {
if (!visible) {
whenHideStatus = this.mute;
this.mute = true;
} else {
this.mute = whenHideStatus;
}
}
// 是否静音
private _mute: boolean = false;
get mute() {
return this._mute;
}
set mute(mute: boolean) {
this._mute = mute;
Howler.mute(mute);
}
async playSound(src: string, loop: boolean = false) {
const howl = await loadAudio(src);
if (howl) {
howl.loop(loop);
}
howl.play();
}
});
// 导出音乐存储实例,以便在其他模块使用
export default musicStore;
import { makeAutoObservable, } from 'mobx';
import API from '../api/index';
import { Toast } from "@grace/ui";
import { IWxShareInfo } from "@/built-in/share/weixin/weixin.ts";
import { getUrlParam } from '@/utils/utils';
class Store {
constructor() {
makeAutoObservable(this);
}
/** 前端开发配置 */
frontVariable: {
privacyTxt: string,
prizeInfoAuthTxt: string,
shareInfo: IWxShareInfo,
shopUrl?: string,
scanUrl?: string,
} = {
privacyTxt: "",
prizeInfoAuthTxt: "",
shareInfo: {
title: "",
desc: "",
link: "",
imgUrl: "",
},
};
ruleInfo = '';
/** 获取活动规则 */
async initRule() {
// 模拟获取远程的数据
const { data } = await API.getRule();
this.ruleInfo = data;
}
/** 获取前端配置项 */
async getFrontVariable() {
// 获取前端开发配置
const { data } = await API.getFrontVariable();
this.frontVariable = data || {};
console.log('前端开发配置', data)
}
indexData: {
remainTimes?: number,
uid?: string,
actEndTimestamp?: number,
timeStamp?: number,
actStartTimestamp?: number,
remainDrawTimes?: number,
newAssist?: number,
} = {};
async updateIndex() {
const { success, data, timeStamp } = await API.index();
if (!success) {
return;
}
this.indexData = data;
this.indexData.timeStamp = timeStamp;
}
judgeActTime(brakeStart = true, brakeEnd = true) {
if (brakeStart && this.indexData.timeStamp < this.indexData.actStartTimestamp) {
Toast.show("活动未开始");
return false
} else if (brakeEnd && this.indexData.timeStamp > this.indexData.actEndTimestamp) {
Toast.show("活动已结束");
return false
}
return true;
}
taskList = [];
async queryTask() {
const { success, data } = await API.queryTasks();
if (success) {
this.taskList = data.item;
}
}
async doAssist() {
let code = getUrlParam('inviteCode')
const { success, data } = await API.doAssist({ inviteCode: code });
if (success) {
Toast.show("成功为好友助力,一起来参与活动吧~");
}
history.replaceState({}, '', location.href.replace(new RegExp(`[?&]inviteCode=[^&]*`), ''));
}
}
export default (new Store());
import { mode, pad, enc, AES } from 'crypto-js';
const getOptions = (iv: string) => {
return {
iv: enc.Utf8.parse(iv),
mode: mode.CBC,
padding: pad.ZeroPadding,
};
}
/** 加密 */
export function AESEncrypt(str: string, key: string, iv: string) {
const options = getOptions(iv);
return AES.encrypt(str, enc.Utf8.parse(key), options).toString();
}
/** 解密 */
export function AESDecrypt(cipherText: string, key: string, iv: string) {
const options = getOptions(iv);
return AES.decrypt(cipherText, enc.Utf8.parse(key), options)
.toString(enc.Utf8)
.trim()
.replace(//g, '')
.replace(//g, '')
.replace(/\v/g, '')
.replace(/\x00/g, '');
}
import { Toast } from "@grace/ui";
// 需要过滤的错误码
export const filterCode = ["600002"];
export const errMessageMap = {
1020: "活动未开始",
1021: "活动已结束",
1007: "活动太火爆了,奖品已抢完咯~",
100001: "登录过期啦,请重新登录哦~",
200306: "助力失败,不能给自己助力哦~",
200303: '助力机会已用完,一起来参与活动吧~',
200304: "好友今日任务已完成,明天再来助力吧~",
200305: "已为好友助力哦~",
20002: "活动已结束,感谢您的关注~"
};
/**
* 统一错误处理
* @param e
*/
export function errorHandler(error) {
if ((error.code == 0 && error.message == "请稍后再试") || filterCode.indexOf(`${error.code}`) >= 0) return;
switch (error.code) {
default: {
const msg = errMessageMap[error.code] || error.message || '网络异常,请稍后再试';
Toast.show(msg);
break;
}
}
}
import { useRef, useEffect, useCallback } from "react";
export const shuffle = (arr) => {
let i = arr.length;
while (i) {
let j = Math.floor(Math.random() * i--);
[arr[j], arr[i]] = [arr[i], arr[j]];
}
return arr;
}
export function getQueryString(params) {
const paramArr = [];
for (const key in params) {
paramArr.push(key + "=" + params[key]);
}
return paramArr.join("&");
}
/**
* @description: 函数节流,普通防连点
* @return {Function}
* @param fun
* @param delay
*/
export const _throttle = (fun, delay = 2000) => {
let last: number;
return function () {
const now = +new Date();
if (last && now < last + delay) {
// clearTimeout(deferTimer);
// deferTimer = setTimeout(() => {
// last = now;
// }, delay);
} else {
last = now;
fun.apply(this, arguments);
}
};
};
/**
* @description: 支持异步函数的节流,防止接口时间太长击穿防连点
* @return {Function}
* @param fun
* @param delay
*/
export const _asyncThrottle = <T extends any[], R>(fun, delay = 2000) => {
let last: number;
let canClick = true;
return function (...args: T): R {
const now = Date.now();
if (!canClick) return;
if (last && now < last + delay) {
// clearTimeout(deferTimer);
// deferTimer = setTimeout(() => {
// last = now;
// }, delay);
} else {
last = now;
const ps = fun.apply(this, arguments);
if (ps instanceof Promise) {
canClick = false;
ps.finally(() => {
canClick = true;
});
}
}
};
};
export function useThrottle(fn, delay = 2000, dep = []) {
const { current } = useRef({ fn, timer: null });
useEffect(function () {
current.fn = fn;
}, [fn]);
return useCallback(function f(...args) {
if (!current.timer) {
current.timer = setTimeout(() => {
delete current.timer;
}, delay);
current.fn.call(this, ...args);
}
}, dep);
}
/**
* @description: 函数防抖
* @return {Function}
* @param fn
* @param wait
* @param immediate
*/
export const _debounce = (fn, wait = 2000, immediate = false) => {
let timer = null
return function () {
const later = function () {
fn.apply(this, arguments)
}
if (immediate && !timer) {
later()
}
if (timer) clearTimeout(timer)
timer = setTimeout(later, wait)
}
}
/**
* 获取cookie的值
* @param {*} cookieName
*/
export function getCookie(cookieName) {
const strCookie = document.cookie;
const arrCookie = strCookie.split('; ');
for (let i = 0; i < arrCookie.length; i++) {
const arr = arrCookie[i].split('=');
if (cookieName == arr[0]) {
return arr[1];
}
}
return '';
}
/**
* 获取url参数
* @param {string} name
*/
export function getUrlParam(name) {
const search = window.location.search;
const matched = search
.slice(1)
.match(new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'));
return search.length ? matched && matched[2] : null;
}
/**
* 删除url中的参数
* @param {*} url
* @param {*} arg
*/
export function delUrlParam(url, paramKey) {
const _url = new URL(url)
const search = new URLSearchParams(_url.search)
search.delete(paramKey)
_url.search = search.toString();
return _url.href;
}
/**
* 日期格式化
* @param date 接收可以被new Date()方法转换的内容
* @param format 字符串,需要的格式例如:'yyyy/MM/dd hh:mm:ss'
* @returns {String}
*/
export const dateFormatter = (date, format = "yyyy/MM/dd") => {
if (!date) return "-";
date = new Date(
// @ts-ignore
typeof date === "string" && isNaN(date)
? date.replace(/-/g, "/")
: Number(date)
);
const o = {
"M+": date.getMonth() + 1,
"d+": date.getDate(),
"h+": date.getHours(),
"m+": date.getMinutes(),
"s+": date.getSeconds(),
"q+": Math.floor((date.getMonth() + 3) / 3),
S: date.getMilliseconds(),
};
if (/(y+)/.test(format)) {
format = format.replace(
RegExp.$1,
(date.getFullYear() + "").substr(4 - RegExp.$1.length)
);
}
for (const k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(
RegExp.$1,
RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
);
}
}
return format;
};
/** 时间格式化 */
export const dealTime = (msTime) => {
const time = msTime / 1000;
let hour: number | string = Math.floor(time / 60 / 60) % 24;
let minute: number | string = Math.floor(time / 60) % 60;
let second: number | string = Math.floor(time) % 60;
hour = hour > 9 ? hour : "0" + hour;
minute = minute > 9 ? minute : "0" + minute;
second = second > 9 ? second : "0" + second;
return `${hour}:${minute}:${second}`;
}
/** 时间格式化 */
export const dealTime2 = (msTime) => {
const time = msTime / 1000;
let day: number | string = Math.floor(time / 60 / 60 / 24);
let hour: number | string = Math.floor(time / 60 / 60) % 24;
let minute: number | string = Math.floor(time / 60) % 60;
let second: number | string = Math.floor(time) % 60;
day = day > 9? day : "0" + day;
hour = hour > 9 ? hour : "0" + hour;
minute = minute > 9 ? minute : "0" + minute;
second = second > 9 ? second : "0" + second;
return { day, hour, minute, second };
}
/**
* 转换k
* @param {*} num
*/
export function getThousandToK(num) {
let s_x;
if (num >= 1000) {
let result = num / 1000;
result = Math.floor(result * 10) / 10;
s_x = result.toString();
let pos_decimal = s_x.indexOf(".");
if (pos_decimal < 0) {
pos_decimal = s_x.length;
s_x += ".";
}
while (s_x.length <= pos_decimal + 1) {
s_x += "0";
}
s_x += "k";
} else {
s_x = num;
}
return s_x;
}
/**
* 截取字符串 中2英1
* @param {*} str
* @param {*} sub_length
*/
export function subStringCE(str, sub_length) {
const temp1 = str.replace(/[^\x20-\xff]/g, "**");
const temp2 = temp1.substring(0, sub_length);
const x_length = temp2.split("*").length - 1;
const hanzi_num = x_length / 2;
sub_length = sub_length - hanzi_num;
const res = str.substring(0, sub_length);
let endStr;
if (sub_length < str.length) {
endStr = res + "...";
} else {
endStr = res;
}
return endStr;
}
/**
* 随机打乱数组
* @param {*} arr
* @returns
*/
export function shuffleArr(arr) {
for (let i = arr.length - 1; i >= 0; i--) {
const randomIndex = Math.floor(Math.random() * (i + 1))
const itemAtIndex = arr[randomIndex]
arr[randomIndex] = arr[i]
arr[i] = itemAtIndex
}
return arr
}
/**
* 获取区间随机数 [min,max)
* @export
* @param {*} min
* @param {*} max
* @return {*}
*/
export function randomNum(min, max) {
return Math.floor(Math.random() * (max - min)) + min
}
/**
* 数据扁平化
* @export
* @param {*} arr
* @return {*}
*/
export function flatten(arr) {
return arr.reduce((result, item) => {
return result.concat(Array.isArray(item) ? flatten(item) : item)
}, [])
}
/** 判断两个对象相等 */
export const check2Object = (obj1, obj2) => {
const o1 = obj1 instanceof Object
const o2 = obj2 instanceof Object
if (!o1 || !o2) { /* 判断不是对象 */
return obj1 === obj2
}
if (Object.keys(obj1).length !== Object.keys(obj2).length) {
return false
}
for (const attr in obj1) {
const t1 = obj1[attr] instanceof Object
const t2 = obj2[attr] instanceof Object
if (t1 && t2) {
return check2Object(obj1[attr], obj2[attr])
} else if (obj1[attr] !== obj2[attr]) {
return false
}
}
return true
}
/**
* 秒转时间对象
* @param {Number} totalSecond 总秒数
* @return {{
* day: String,
* hour: String,
* minute: String,
* second: String
* }}
*/
export const second2Date = (totalSecond) => {
const millisecond = totalSecond % 1000
totalSecond = totalSecond / 1000
// 获得总分钟数
const totalMinute = totalSecond / 60
// 获得剩余秒数
const second = totalSecond % 60
// 获得小时数
const totalHour = totalMinute / 60
// 获得分钟数
const minute = totalMinute % 60
// 获得天数
const day = totalHour / 24
// 获得剩余小时数
const hour = totalHour % 24
// 格式化的键值
const includesKey = ['month', 'day', 'hour', 'minute', 'second', 'totalHour', 'totalMinute']
// 日期对象
const dateObj = { day, hour, minute, second, millisecond, totalHour, totalMinute }
return Object.keys(dateObj).reduce((preVal, key) => {
// 值取整
const value = parseInt(dateObj[key])
if (includesKey.includes(key) && value < 10) {
if (value < 0) {
preVal[key] = '00'
} else {
preVal[key] = '0' + value
}
} else {
if (value.toString() === 'NaN') {
preVal[key] = '0'
} else {
preVal[key] = value.toString()
}
}
return preVal
}, {})
}
/**
* 等待一段时间再执行
* @param {number} time 等待的时间ms
*/
export function waitTime(time) {
return new Promise(resolve => setTimeout(resolve, time))
}
/** 控制滚动--兼容ios */
export const bodyScroll = (event) => {
event.preventDefault();
}
export const onCtrScroll = (flag = true) => {
if (flag) { // 禁止滚动
document.body.addEventListener('touchmove', bodyScroll, { passive: false });
} else { // 开启滚动
document.body.removeEventListener('touchmove', bodyScroll);
}
}
/**
* 删除中间所有的空格
* @param {string} str
* @returns
*/
export const trimSpace = (str) => {
let result;
result = str.replace(/(^\s+)|(\s+$)/g, "");
result = result.replace(/\s/g, "");
return result;
}
/**
* 获取当前皮肤id
* @returns
*/
export const GetCurrSkinId = () => {
// eslint-disable-next-line no-useless-escape
const matched = location.pathname.match(/\/([^\/]*).html/);
const currSkinId = matched ? matched && matched[1] : ''
console.log('当前皮肤id', currSkinId)
return currSkinId
}
export const getCustomShareId = () => {
const matched = location.href.match(/\/share\?id=(.*)/);
const shareId = matched ? matched && matched[1] : '';
console.log('自定义活动页id', shareId);
return shareId;
};
export function prefixInteger(num: number, length: number) {
return (Array(length).join('0') + num).slice(-length);
}
/**
* @description: 小程序跳转
* @param {*}
* @return {*}
*/
export const miniGoUrl = (url) => {
// @ts-ignore
wx.miniProgram.navigateTo({ url: url });
}
\ No newline at end of file
/// <reference types="vite/client" />
declare const CFG: any;
declare module "*.svga" {
const src: string;
export default src;
}
declare const remScale: number;
/* =================== USAGE ===================
import * as wx from 'jweixin';
wx.config(...);
or
import { config } from 'jweixin';
config();
=============================================== */
declare namespace wx {
type ImageSizeType = "original" | "compressed";
type ImageSourceType = "album" | "camera";
type VideoSourceType = "album" | "camera";
type ApiMethod =
| "onMenuShareTimeline"
| "onMenuShareAppMessage"
| "onMenuShareQQ"
| "onMenuShareWeibo"
| "onMenuShareQZone"
| "startRecord"
| "stopRecord"
| "onVoiceRecordEnd"
| "playVoice"
| "pauseVoice"
| "stopVoice"
| "onVoicePlayEnd"
| "uploadVoice"
| "downloadVoice"
| "chooseImage"
| "previewImage"
| "uploadImage"
| "downloadImage"
| "translateVoice"
| "getNetworkType"
| "openLocation"
| "getLocation"
| "hideOptionMenu"
| "showOptionMenu"
| "hideMenuItems"
| "showMenuItems"
| "hideAllNonBaseMenuItem"
| "showAllNonBaseMenuItem"
| "closeWindow"
| "scanQRCode"
| "chooseWXPay"
| "openProductSpecificView"
| "addCard"
| "chooseCard"
| "openCard";
// 所有JS接口列表
type jsApiList = ApiMethod[];
// 所有菜单项列表
// 基本类
type menuBase =
| "menuItem:exposeArticle"
| // 举报
"menuItem:setFont"
| // 调整字体
"menuItem:dayMode"
| // 日间模式
"menuItem:nightMode"
| // 夜间模式
"menuItem:refresh"
| // 刷新
"menuItem:profile"
| // 查看公众号(已添加)
"menuItem:addContact"; // 查看公众号(未添加)
// 传播类
type menuShare =
| "menuItem:share:appMessage"
| // 发送给朋友
"menuItem:share:timeline"
| // 分享到朋友圈
"menuItem:share:qq"
| // 分享到QQ
"menuItem:share:weiboApp"
| // 分享到Weibo
"menuItem:favorite"
| // 收藏
"menuItem:share:facebook"
| // 分享到FB
"menuItem:share:QZone"; // 分享到 QQ 空间
// 保护类
type menuProtected =
| "menuItem:editTag"
| // 编辑标签
"menuItem:delete"
| // 删除
"menuItem:copyUrl"
| // 复制链接
"menuItem:originPage"
| // 原网页
"menuItem:readMode"
| // 阅读模式
"menuItem:openWithQQBrowser"
| // 在QQ浏览器中打开
"menuItem:openWithSafari"
| // 在Safari中打开
"menuItem:share:email"
| // 邮件
"menuItem:share:brand"; // 一些特殊公众号
type menuList = Array<menuBase | menuProtected | menuShare>;
function config(conf: {
debug?: boolean | undefined; // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: string; // 必填,公众号的唯一标识
timestamp: number; // 必填,生成签名的时间戳
nonceStr: string; // 必填,生成签名的随机串
signature: string; // 必填,签名,见附录1
jsApiList: jsApiList; // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
}): void;
interface Resouce {
localId: string;
}
interface BaseParams {
success?(...args: any[]): void;
/** 接口调用失败的回调函数 */
fail?(...args: any[]): void;
/** 接口调用结束的回调函数(调用成功、失败都会执行) */
complete?(...args: any[]): void;
}
function ready(fn: () => void): void;
function error(fn: (err: { errMsg: string }) => void): void;
interface IcheckJsApi extends BaseParams {
jsApiList: jsApiList; // 需要检测的JS接口列表,所有JS接口列表见附录2,
// 以键值对的形式返回,可用的api值true,不可用为false
// 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
success(res: { checkResult: { [api: string]: boolean }; errMsg: string }): void;
}
/**
* 判断当前客户端版本是否支持指定JS接口
* 备注:checkJsApi接口是客户端6.0.2新引入的一个预留接口,第一期开放的接口均可不使用checkJsApi来检测。
*/
function checkJsApi(params: IcheckJsApi): void;
interface IonMenuShareTimeline extends BaseParams {
title: string; // 分享标题
link: string; // 分享链接
imgUrl: string; // 分享图标
// 用户确认分享后执行的回调函数
success(): void;
// 用户取消分享后执行的回调函数
cancel(): void;
}
/*=============================基础接口================================*/
/**
* 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口
*/
function onMenuShareTimeline(params: IonMenuShareTimeline): void;
interface IonMenuShareAppMessage extends BaseParams {
title: string; // 分享标题
desc: string; // 分享描述
link: string; // 分享链接
imgUrl: string; // 分享图标
type?: "music" | "video或link" | "link" | undefined; // 分享类型,music、video或link,不填默认为link
dataUrl?: string | undefined; // 如果type是music或video,则要提供数据链接,默认为空
// 用户确认分享后执行的回调函数
success(): void;
// 用户取消分享后执行的回调函数
cancel(): void;
}
/**
* 获取“分享给朋友”按钮点击状态及自定义分享内容接口
*/
function onMenuShareAppMessage(params: IonMenuShareAppMessage): void;
interface IonMenuShareQQ extends BaseParams {
title: string; // 分享标题
desc: string; // 分享描述
link: string; // 分享链接
imgUrl: string; // 分享图标
// 用户确认分享后执行的回调函数
success(): void;
// 用户取消分享后执行的回调函数
cancel(): void;
}
/**
* 获取“分享到QQ”按钮点击状态及自定义分享内容接口
*/
function onMenuShareQQ(params: IonMenuShareQQ): void;
interface IonMenuShareWeibo extends BaseParams {
title: string; // 分享标题
desc: string; // 分享描述
link: string; // 分享链接
imgUrl: string; // 分享图标
// 用户确认分享后执行的回调函数
success(): void;
// 用户取消分享后执行的回调函数
cancel(): void;
}
/**
* 获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口
*/
function onMenuShareWeibo(params: IonMenuShareWeibo): void;
interface IonMenuShareQZone extends BaseParams {
title: string; // 分享标题
desc: string; // 分享描述
link: string; // 分享链接
imgUrl: string; // 分享图标
// 用户确认分享后执行的回调函数
success(): void;
// 用户取消分享后执行的回调函数
cancel(): void;
}
/**
* 获取“分享到QQ空间”按钮点击状态及自定义分享内容接口
*/
function onMenuShareQZone(params: IonMenuShareQZone): void;
/*=============================基础接口================================*/
/*=============================图像接口================================*/
interface IchooseImage extends BaseParams {
/** 最多可以选择的图片张数,默认9 */
count?: number | undefined;
/** original 原图,compressed 压缩图,默认二者都有 */
sizeType?: ImageSizeType[] | undefined;
/** album 从相册选图,camera 使用相机,默认二者都有 */
sourceType?: ImageSourceType[] | undefined;
/** 成功则返回图片的本地文件路径列表 tempFilePaths */
success(res: {
sourceType: string; // weixin album camera
localIds: string[];
errMsg: string;
}): void;
cancel(): void;
}
/**
* 从本地相册选择图片或使用相机拍照。
*/
function chooseImage(params: IchooseImage): void;
interface IpreviewImage extends BaseParams {
current: string; // 当前显示图片的http链接
urls: string[]; // 需要预览的图片http链接列表
}
/**
* 预览图片接口
*/
function previewImage(params: IpreviewImage): void;
interface IuploadImage extends BaseParams {
localId: string; // 需要上传的图片的本地ID,由chooseImage接口获得
isShowProgressTips: number; // 默认为1,显示进度提示
// 返回图片的服务器端ID
success(res: { serverId: string }): void;
}
/**
* 上传图片接口
*/
function uploadImage(params: IuploadImage): void;
interface IdownloadImage extends BaseParams {
serverId: string; // 需要下载的图片的服务器端ID,由uploadImage接口获得
isShowProgressTips: number; // 默认为1,显示进度提示
// 返回图片下载后的本地ID
success(res: Resouce): void;
}
/**
* 下载图片接口
*/
function downloadImage(params: IdownloadImage): void;
interface IgetLocalImgData extends BaseParams {
localId: string; // 图片的localID
// localData是图片的base64数据,可以用img标签显示
success(res: { localData: string }): void;
}
/**
* 获取本地图片接口
*/
function getLocalImgData(params: IgetLocalImgData): void;
/*=============================图像接口================================*/
/*=============================音频接口================================*/
/**
* 开始录音接口
*/
function startRecord(): void;
interface IstopRecord extends BaseParams {
success(res: Resouce): void;
}
/**
* 停止录音接口
*/
function stopRecord(params: IstopRecord): void;
interface IonVoiceRecordEnd extends BaseParams {
// 录音时间超过一分钟没有停止的时候会执行 complete 回调
complete(res: Resouce): void;
}
/**
* 监听录音自动停止接口
*/
function onVoiceRecordEnd(params: IonVoiceRecordEnd): void;
interface IplaypausestopVoice extends BaseParams {
localId: string; // 需要播放的音频的本地ID,由stopRecord接口获得
}
/**
* 播放语音接口
*/
function playVoice(params: IplaypausestopVoice): void;
/**
* 暂停播放接口
*/
function pauseVoice(params: IplaypausestopVoice): void;
/**
* 停止播放接口
*/
function stopVoice(params: IplaypausestopVoice): void;
interface IonVoicePlayEnd extends BaseParams {
success(res: Resouce): void;
}
/**
* 监听语音播放完毕接口
*/
function onVoicePlayEnd(params: IonVoicePlayEnd): void;
interface IupdownloadVoice extends BaseParams {
localId: string; // 需要上传的音频的本地ID,由stopRecord接口获得
isShowProgressTips: number; // 默认为1,显示进度提示
success(res: Resouce): void;
}
/**
* 上传语音接口
* 备注:上传语音有效期3天,可用微信多媒体接口下载语音到自己的服务器
* ,此处获得的 serverId 即 media_id,参考文档
* ../12 / 58bfcfabbd501c7cd77c19bd9cfa8354.html
* 目前多媒体文件下载接口的频率限制为10000次/ 天,
* 如需要调高频率,请邮件weixin - open@qq.com,
* 邮件主题为【申请多媒体接口调用量】,请对你的项目进行简单描述,
* 附上产品体验链接,并对用户量和使用量进行说明。
*/
function uploadVoice(params: IupdownloadVoice): void;
/**
* 下载语音接口
*/
function downloadVoice(params: IupdownloadVoice): void;
/*=============================音频接口================================*/
/*=============================智能接口================================*/
interface ItranslateVoice extends BaseParams {
localId: string; // 需要识别的音频的本地Id,由录音相关接口获得
isShowProgressTips: number; // 默认为1,显示进度提示
success(res: {
translateResult: string;
}): void;
}
/**
* 识别音频并返回识别结果接口
*/
function translateVoice(params: ItranslateVoice): void;
/*=============================智能接口================================*/
/*=============================设备信息================================*/
type networkType = "2g" | "3g" | "4g" | "wifi";
interface IgetNetworkType extends BaseParams {
success(res: { networkType: networkType }): void;
}
/**
* 获取网络状态接口
*/
function getNetworkType(params: IgetNetworkType): void;
/*=============================设备信息================================*/
/*=============================地理位置================================*/
interface IopenLocation extends BaseParams {
latitude: number; // 纬度,浮点数,范围为90 ~ -90
longitude: number; // 经度,浮点数,范围为180 ~ -180。
name: string; // 位置名
address: string; // 地址详情说明
scale: number; // 地图缩放级别,整形值,范围从1~28。默认为最大
infoUrl: string; // 在查看位置界面底部显示的超链接,可点击跳转
}
/**
* 使用微信内置地图查看位置接口
*/
function openLocation(params: IopenLocation): void;
interface IgetLocation extends BaseParams {
type: "wgs84" | "gcj02"; // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success(res: {
latitude: number; // 纬度,浮点数,范围为90 ~ -90
longitude: number; // 经度,浮点数,范围为180 ~ -180。
speed: number; // 速度,以米/每秒计
accuracy: number; // 位置精度
}): void;
}
/**
* 获取地理位置接口
*/
function getLocation(params: IgetLocation): void;
/*=============================地理位置================================*/
/*=============================摇一摇周边================================*/
interface IstartSearchBeacons extends BaseParams {
ticket: string; // 摇周边的业务ticket, 系统自动添加在摇出来的页面链接后面
// 开启查找完成后的回调函数
complete(argv: any): void;
}
/**
* 开启查找周边ibeacon设备接口
* 备注:如需接入摇一摇周边功能,请参考:申请开通摇一摇周边
*/
function startSearchBeacons(params: IstartSearchBeacons): void;
interface IstopSearchBeacons extends BaseParams {
// 关闭查找完成后的回调函数
complete(res: any): void;
}
/**
* 关闭查找周边ibeacon设备接口
*/
function stopSearchBeacons(params: IstopSearchBeacons): void;
interface IonSearchBeacons extends BaseParams {
// 回调函数,可以数组形式取得该商家注册的在周边的相关设备列表
complete(argv: any): void;
}
/**
* 监听周边ibeacon设备接口
*/
function onSearchBeacons(params: IonSearchBeacons): void;
/*=============================摇一摇周边================================*/
/*=============================界面操作================================*/
/**
* 隐藏右上角菜单接口
*/
function hideOptionMenu(): void;
/**
* 显示右上角菜单接口
*/
function showOptionMenu(): void;
/**
* 关闭当前网页窗口接口
*/
function closeWindow(): void;
interface IhideMenuItems extends BaseParams {
menuList: Array<menuProtected | menuShare>; // 要隐藏的菜单项,只能隐藏“传播类”和“保护类”按钮,所有menu项见附录3
}
/**
* 批量隐藏功能按钮接口
*/
function hideMenuItems(): void;
interface IshowMenuItems extends BaseParams {
menuList: menuList; // 要显示的菜单项,所有menu项见附录3
}
/**
* 批量显示功能按钮接口
*/
function showMenuItems(params: IshowMenuItems): void;
/**
* 隐藏所有非基础按钮接口
* “基本类”按钮详见附录3
*/
function hideAllNonBaseMenuItem(): void;
/**
* 显示所有功能按钮接口
*/
function showAllNonBaseMenuItem(): void;
/*=============================界面操作================================*/
/*=============================微信扫一扫================================*/
type scanType = "qrCode" | "barCode";
interface IscanQRCode extends BaseParams {
needResult: 0 | 1; // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
scanType: scanType[]; // 可以指定扫二维码还是一维码,默认二者都有
// 当needResult 为 1 时,扫码返回的结果
success(res: { resultStr: string }): void;
}
/**
* 调起微信扫一扫接口
*/
function scanQRCode(params: IscanQRCode): void;
/*=============================微信扫一扫================================*/
/*=============================微信小店================================*/
interface IopenProductSpecificView extends BaseParams {
productId: string; // 商品id
viewType: "0" | "1" | "2"; // 0.默认值,普通商品详情页1.扫一扫商品详情页2.小店商品详情页
}
/**
* 跳转微信商品页接口
*/
function openProductSpecificView(params: IopenProductSpecificView): void;
/*=============================微信卡券================================*/
interface IchooseCard extends BaseParams {
shopId: string; // 门店Id
cardType: string; // 卡券类型
cardId: string; // 卡券Id
timestamp: number; // 卡券签名时间戳
nonceStr: string; // 卡券签名随机串
signType: string; // 签名方式,默认'SHA1'
cardSign: string; // 卡券签名
success(res: {
cardList: string[];
}): void;
}
/**
* 拉取适用卡券列表并获取用户选择信息
*/
function chooseCard(params: IchooseCard): void;
interface IaddCard extends BaseParams {
cardList: Array<{
cardId: string;
cardExt: string;
}>; // 需要添加的卡券列表
success(res: { cardList: string[] }): void;
}
/**
* 批量添加卡券接口
*/
function addCard(): void;
interface IopenCard extends BaseParams {
cardList: Array<{
cardId: string;
code: string;
}>; // 需要打开的卡券列表
}
/**
* 查看微信卡包中的卡券接口
*/
function openCard(params: IopenCard): void;
interface IconsumeAndShareCard extends BaseParams {
cardId: string;
code: string;
}
/**
* 核销后再次赠送卡券接口
*/
function consumeAndShareCard(params: IconsumeAndShareCard): void;
/*=============================微信卡券================================*/
/*=============================微信支付================================*/
interface IchooseWXPay extends BaseParams {
timestamp: number; // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
nonceStr: string; // 支付签名随机串,不长于 32 位
package: string; // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=***)
signType: string; // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
paySign: string; // 支付签名
// 支付成功后的回调函数
success(res: any): void;
}
/**
* 发起一个微信支付请求
*/
function chooseWXPay(params: IchooseWXPay): void;
/*=============================微信支付================================*/
}
import compressSvga from "../config/AssetsMin/SvgaCompress.js";
compressSvga("./1输出选中效果.svga")
{
"compilerOptions": {
"target": "es5",
"module": "ESNext",
"lib": [
"ES2020",
"DOM",
"DOM.Iterable"
],
"useDefineForClassFields": true,
"skipLibCheck": true,
"experimentalDecorators": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"jsxImportSource": "react",
"strict": false,
"noImplicitAny": false,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true,
"paths": {
"@/*": [
"./src/*"
]
},
"allowSyntheticDefaultImports": true
},
"include": [
"src"
]
}
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"lib": ["ES2023"],
"useDefineForClassFields": true,
"skipLibCheck": true,
"experimentalDecorators": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": false,
"noImplicitAny": false,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true
},
"include": [
"vite.config.ts"
]
}
import {defineConfig, UserConfig} from 'vite'
import react from '@vitejs/plugin-react'
import legacy from '@vitejs/plugin-legacy'
import autoprefixer from "autoprefixer"
import postcsspxtorem from "postcss-pxtorem"
import {viteMockServe} from "vite-plugin-mock";
import DuibaPublish from "./config/DuibaPublish/DuibaPublish.ts";
import dotenv from 'dotenv';
import * as path from "node:path";
import tailwindcss from "@tailwindcss/postcss";
import cssnano from 'cssnano';
// https://vitejs.dev/config/
export default defineConfig(({mode}): UserConfig => {
console.log(mode);
dotenv.config({path: [`./config/.env.global`, `./config/.env.${mode}`]});
const {
NODE_ENV,
UPLOAD_DIR, CDN_DOMAIN,
OSS_REGION, OSS_BUCKET,
OSS_ACCESS_KEY_ID, OSS_ACCESS_SECRET,
} = process.env;
// console.log(UPLOAD_DIR, NODE_ENV, CDN_DOMAIN, OSS_REGION, OSS_BUCKET, OSS_ACCESS_KEY_ID, OSS_ACCESS_SECRET)
const isDev = mode == "development";
const versionStamp = Date.now();
const prodBase = `${CDN_DOMAIN}/${UPLOAD_DIR}/${versionStamp}/`;
return {
base: !isDev ? prodBase : "",
server: {
open: false,
},
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
}
},
assetsInclude: [/\.(svga)$/],
build: {
cssTarget: 'chrome61',
rollupOptions: {
output: {
// 指定分块
manualChunks(id) {
if (id.includes('node_modules')) {
return 'vendor';
}
},
},
},
},
plugins: [
react({
babel: {
plugins: [
["@babel/plugin-proposal-decorators", {legacy: true}],
["@babel/plugin-proposal-class-properties", {loose: true}],
],
},
}),
legacy({
targets: ['defaults', 'not IE 11'],
}),
viteMockServe({
// default
mockPath: 'mock',
enable: true,
}),
!isDev && DuibaPublish({
buildVersion: versionStamp,
uploadDir: UPLOAD_DIR,
region: OSS_REGION,
bucket: OSS_BUCKET,
accessKeyId: OSS_ACCESS_KEY_ID,
accessKeySecret: OSS_ACCESS_SECRET,
}),
],
css: {
postcss: {
plugins: [
autoprefixer({
overrideBrowserslist: [
"Android 4.1",
"iOS 7.1",
"Chrome > 31",
"ff > 31",
"ie >= 8",
"last 10 versions", // 所有主流浏览器最近10版本用
],
grid: true
}),
postcsspxtorem({
rootValue: 100,
propList: ["*", "!border"], // 除 border 外所有px 转 rem
selectorBlackList: [".noRem-"], // 过滤掉.noRem-开头的class,不进行rem转换
}),
cssnano(),
],
},
preprocessorOptions: {
less: {
javascriptEnabled: true,
},
},
modules: {
localsConvention: 'camelCase'
}
}
}
}
)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment