├── .gitignore
├── LICENSE
├── README.md
├── assets
├── icon.png
├── icon
│ └── github.com.jpeg
└── today
│ ├── 10010.js
│ └── demo.js
├── config.json
├── main.js
├── scripts
├── app.js
├── libs
│ ├── easy-jsbox.js
│ ├── logger.js
│ └── server.js
└── ui
│ ├── main
│ ├── card.js
│ ├── cards
│ │ ├── backup.js
│ │ ├── log.js
│ │ ├── remote-access.js
│ │ └── today.js
│ ├── home.js
│ ├── matrix.js
│ └── toolbox.js
│ └── today
│ └── today.js
├── setting.json
└── strings
├── en.strings
└── zh-Hans.strings
/.gitignore:
--------------------------------------------------------------------------------
1 | .output
2 | .idea
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # BoxJsHelper
2 |
3 | > BoxJs 助手,帮助您通过 iCloud 同步数据,并提供局域网内多设备访问能力。
4 |
5 | [通过Erots安装](https://liuguogy.github.io/JSBox-addins/?q=show&objectId=5f38086c3f19480006698974)
6 |
7 | 若您不知道如何配置 BoxJs,可以参考以下方法:
8 |
9 | 在 Loon 中添加以下插件即可:
10 |
11 |
12 |
13 | 注:本人只有 Loon,所以此方法仅限 Loon 用户,其他用户请自行添加相关脚本。
14 |
15 | # 工具箱
16 |
17 | 右上角按钮为工具箱,工具箱内设有多项工具
18 |
19 | - ### 远程访问
20 | 开启后可在任意局域网设备访问当前设备的 BoxJs。
21 |
22 | 点击该卡片除开关以外的部分将显示访问路径。
23 |
24 | 注意:远程访问期间需要手机保持应用开启且亮屏。
25 |
26 | - ### 备份
27 | 备份功能可将 BoxJs 内的备份数据拷贝到 iCloud。
28 |
29 | 进入备份页面后,会显示当前 BoxJs 内的备份数据,可通过此页面进行快速管理(删除、恢复)
30 |
31 | 直接点击会提示是否恢复数据。(也就是 BoxJs 的还原备份)
32 |
33 | 点击右上角加号生成新备份。
34 |
35 | 下拉页面可进行同步。
36 |
37 | - ### Today小组件
38 |
39 | 可以自己写脚本在小组件里显示,内置了一个 `10010.js` 和 `demo.js`
40 |
41 | `demo.js`: 内有注释,完全看得懂。
42 |
43 | `10010.js`: Demo,自动获取 BoxJs 的数据,什么也不用填,左划点应用,在通知中心添加一个 JSBox 小组件,点选择脚本,选本应用即可。(需要 BoxJs 内有 `chavy_signheader_10010` )
44 |
45 | # 设置
46 |
47 | ## BoxJs
48 |
49 | - ### 访问入口
50 |
51 | 选择 BoxJs 的入口。更换入口的话,重启应用后才会生效
52 |
53 | 默认情况下为 `boxjs.net`
54 |
55 | - ### 超时时间
56 |
57 | 向 BoxJs 发送网络请求的超时时间,单位秒
58 |
59 | QuantumultX 用户可以设置的久一点
60 |
61 | 默认情况下为 `3`
62 |
63 | ## 远程访问
64 |
65 | - ### 端口
66 |
67 | 设置内置服务器的端口
68 |
69 | # 深色模式
70 |
71 | 本应用 BoxJs 页面直接渲染 HTML,深色模式适配由 BoxJs 作者适配。
72 |
73 | 注:在切换模式时 BoxJs 可能未切换,刷新后即可自动切换(需要在 BoxJs 中设置跟随系统)
74 |
--------------------------------------------------------------------------------
/assets/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ipuppet/BoxJsHelper/fd28293ef0d9a6574368a96e068093c737108f38/assets/icon.png
--------------------------------------------------------------------------------
/assets/icon/github.com.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ipuppet/BoxJsHelper/fd28293ef0d9a6574368a96e068093c737108f38/assets/icon/github.com.jpeg
--------------------------------------------------------------------------------
/assets/today/10010.js:
--------------------------------------------------------------------------------
1 | // 查询有效期,单位小时。1就是数据缓存1个小时,超过后重新获取。
2 | // 注意,并非超过一小时后立即重新获取,而是你查看小部件时重新获取数据,会有一段时间的空白
3 | const validity = 1
4 |
5 | // 需要显示的内容 fee(话费) 默认显示
6 | // flow: 流量
7 | // voice: 语音
8 | // credit: 信用积分
9 | const needed = ["flow", "voice"]
10 |
11 | const version = "1.0.1"
12 |
13 | function template_fee(data) {
14 | return {
15 | type: "view",
16 | layout: (make, view) => {
17 | make.width.equalTo(view.super)
18 | make.height.equalTo(30)
19 | make.top.equalTo(view.prev.bottom)
20 | },
21 | views: [
22 | {
23 | type: "label",
24 | props: {
25 | text: `${data.title}: ${data.number}${data.unit}`,
26 | font: $font(14)
27 | },
28 | layout: make => {
29 | make.left.right.inset(10)
30 | make.height.equalTo(20)
31 | }
32 | },
33 | {
34 | type: "label",
35 | props: {
36 | text: data.flush_date_time,
37 | font: $font(12),
38 | align: $align.right
39 | },
40 | layout: make => {
41 | make.left.right.inset(10)
42 | make.height.equalTo(20)
43 | }
44 | }
45 | ]
46 | }
47 | }
48 |
49 | function template(data) {
50 | let text_left = `${data.title}: ${data.number}${data.unit}`
51 | let text_right = `${data.persent}%`
52 | let persent_hidden = false
53 | if (data.persent === 0 || data.persent === "0" || data.persent === "") {
54 | text_right = ""
55 | persent_hidden = true
56 | }
57 | return {
58 | type: "view",
59 | layout: (make, view) => {
60 | make.width.equalTo(view.super)
61 | make.height.equalTo(35)
62 | make.top.equalTo(view.prev.bottom).offset(5)
63 | },
64 | views: [
65 | {
66 | type: "label",
67 | props: {
68 | text: text_left,
69 | font: $font(14)
70 | },
71 | layout: make => {
72 | make.left.right.inset(10)
73 | make.height.equalTo(20)
74 | }
75 | },
76 | {
77 | type: "label",
78 | props: {
79 | text: text_right,
80 | font: $font(12),
81 | align: $align.right
82 | },
83 | layout: make => {
84 | make.left.right.inset(10)
85 | make.height.equalTo(20)
86 | }
87 | },
88 | {
89 | type: "progress",
90 | props: {
91 | value: data.persent / 100,
92 | cornerRadius: 3,
93 | hidden: persent_hidden,
94 | progressColor: get_color(data.persent / 100),
95 | trackColor: $color("clear")
96 |
97 | },
98 | layout: (make, view) => {
99 | make.top.equalTo(view.prev.bottom).offset(3)
100 | make.right.left.inset(10)
101 | make.height.equalTo(3)
102 | }
103 | }
104 | ]
105 | }
106 | }
107 |
108 | function get_color(persent) {
109 | if (persent > 0 && persent < 0.6) {
110 | return $color("green")
111 | } else if (persent > 0.6 && persent < 0.85) {
112 | return $color("orange")
113 | } else if (persent > 0.85) {
114 | return $color("red")
115 | }
116 | }
117 |
118 | function render(data) {
119 | let views = []
120 | for (let item of data.data.dataList) {
121 | if (item.type === "fee") {
122 | views.unshift(template_fee({
123 | title: item.remainTitle, // 标题
124 | number: item.number, // 以用数值
125 | unit: item.unit, // 单位
126 | flush_date_time: data.flush_date_time
127 | }))
128 | } else if (needed.includes(item.type))
129 | views.push(template({
130 | title: item.remainTitle, // 标题
131 | number: item.number, // 以用数值
132 | persent: item.persent, // 以用百分比
133 | unit: item.unit // 单位
134 | }))
135 | }
136 | $("base-ui-prepare").remove()
137 | $ui.render({
138 | type: "view",
139 | layout: $layout.fill,
140 | views: views
141 | })
142 | }
143 |
144 | function get_data(boxdata) {
145 | // 从boxjs获取信息
146 | let cookie = JSON.parse(boxdata.datas["chavy_signheader_10010"])["Cookie"]
147 | let start_index = cookie.indexOf("req_mobile=")
148 | let end_index = cookie.indexOf(";", start_index)
149 | let phone = cookie.slice(start_index, end_index).split("=")[1]
150 | // 从10010获取信息
151 | $http.get({
152 | url: `https://m.client.10010.com/mobileService/home/queryUserInfoSeven.htm?version=iphone_c@7.0403&desmobiel=${phone}&showType=3`,
153 | header: {
154 | "Cookie": cookie,
155 | "Accept": "*/*",
156 | "Content-Type": "application/json"
157 | },
158 | handler: response => {
159 | if (response.error !== null) {
160 | $("base-ui-prepare").remove()
161 | $ui.toast("查询失败")
162 | return
163 | }
164 | // 更新
165 | $cache.set("today_10010_date", new Date().getTime())
166 | $cache.set("today_10010_data", response.data)
167 | render(response.data)
168 | }
169 | })
170 | }
171 |
172 | function get_cache() {
173 | if (!$cache.get("today_10010_date")) {
174 | // 首次写入时间信息
175 | $cache.set("today_10010_date", new Date().getTime() - 1000 * 60 * 60 * validity + 1)
176 | }
177 | // 每小时只查询一次
178 | if (new Date().getTime() - $cache.get("today_10010_date") < 1000 * 60 * 60 * validity) {
179 | let data = $cache.get("today_10010_data")
180 | if (data) {
181 | render(data)
182 | return true
183 | }
184 | }
185 | return false
186 | }
187 |
188 | function prepare() {
189 | $ui.render({
190 | props: {
191 | navBarHidden: true,
192 | statusBarStyle: 0
193 | },
194 | views: [{
195 | type: "view",
196 | props: {
197 | id: "base-ui-prepare"
198 | },
199 | views: [{
200 | type: "spinner",
201 | props: {
202 | loading: true
203 | },
204 | layout: (make, view) => {
205 | make.center.equalTo(view.super)
206 | }
207 | }],
208 | layout: $layout.fill
209 | }]
210 | })
211 | }
212 |
213 | /**
214 | * 该函数用来检查是否有更新
215 | */
216 | async function update() {
217 | // TODO 展开小组件后显示更新按钮~
218 | let name = "10010"
219 | let url = "https://raw.githubusercontent.com/ipuppet/BoxJsHelper/master/assets/today/10010.js"
220 | const update_alert = () => {
221 | $ui.alert({
222 | title: "你该升级啦!",
223 | actions: [
224 | {
225 | title: "更新",
226 | handler: () => {
227 | $file.write({
228 | data: $data({ string: $cache.get(`today_update_${name}_script`) }),
229 | path: `/assets/today/${name}.js`
230 | })
231 | $ui.alert("操作成功,重新进入Today即可完成更新")
232 | }
233 | },
234 | { title: $l10n("CANCEL") }
235 | ]
236 | })
237 | }
238 | if ($cache.get(`today_update_${name}`)) {
239 | update_alert()
240 | return
241 | }
242 | $http.get({
243 | url: url,
244 | handler: response => {
245 | let remote_version = eval(response.data).version
246 | if (remote_version !== version) {
247 | $cache.set(`today_update_${name}`, true)
248 | $cache.set(`today_update_${name}_script`, response.data)
249 | update_alert()
250 | }
251 | }
252 | })
253 | }
254 |
255 | async function main(boxdata) {
256 | prepare()
257 | update()
258 | if (!get_cache()) {
259 | let data = await boxdata()
260 | get_data(data)
261 | }
262 | }
263 |
264 | module.exports = {
265 | main: main,
266 | version: version // 用于检查更新
267 | }
--------------------------------------------------------------------------------
/assets/today/demo.js:
--------------------------------------------------------------------------------
1 | /**
2 | * 该函数为Today小组件入口函数
3 | * @param {Object} boxdata BoxJs中的数据
4 | * boxdata.datas 为保存的信息,如Cookie等
5 | * 通过/query/boxdata获取,该数据是实时数据
6 | * 该数据结构可查看如下链接 http://boxjs.net/query/boxdata
7 | */
8 | function main(boxdata) {
9 | $ui.alert({
10 | title: "Hi",
11 | message: boxdata.sysapps[0].author
12 | })
13 | }
14 |
15 | module.exports = {
16 | main: main
17 | }
--------------------------------------------------------------------------------
/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "info": {
3 | "name": "BoxJsHelper",
4 | "version": "1.4.10",
5 | "author": "ipuppet",
6 | "module": false
7 | },
8 | "settings": {
9 | "theme": "auto",
10 | "minSDKVer": "2.0.0",
11 | "minOSVer": "13.0.0",
12 | "idleTimerDisabled": false,
13 | "keyboardToolbarEnabled": true,
14 | "rotateDisabled": false
15 | }
16 | }
--------------------------------------------------------------------------------
/main.js:
--------------------------------------------------------------------------------
1 | // run app
2 | const app = require("./scripts/app")
3 | app.run()
--------------------------------------------------------------------------------
/scripts/app.js:
--------------------------------------------------------------------------------
1 | const { UIKit, Kernel, FileStorage, Logger, Setting } = require("./libs/easy-jsbox")
2 | const Server = require("./libs/server")
3 |
4 | /**
5 | * @typedef {AppKernel} AppKernel
6 | */
7 | class AppKernel extends Kernel {
8 | constructor() {
9 | super()
10 | this.fileStorage = new FileStorage({ basePath: "shared://BoxjsHelper" })
11 |
12 | this.logger = new Logger()
13 | this.logger.setWriter(this.fileStorage, "logs/boxjs-helper.log")
14 |
15 | this.setting = new Setting({ logger: this.logger, fileStorage: this.fileStorage })
16 |
17 | this.server = new Server(this)
18 | this.initSettingMethods()
19 | this.initSettingEvents()
20 | }
21 |
22 | iCloudPath(path) {
23 | let start = path.slice(0, 8) === "drive://" ? 8 : 0
24 | path = path.slice(start)
25 | path = path[0] === "/" ? path.slice(1) : path
26 | let end = path.lastIndexOf("/") === path.length - 1 ? -1 : undefined
27 | path = path.slice(0, end)
28 | return `drive://${path}/`
29 | }
30 |
31 | initSettingEvents() {
32 | this.setting.setEvent("onSet", (key, value) => {
33 | const serverConfigKeys = ["advanced.timeout", "advanced.domain", "advanced.serverPort", "server.logRequest"]
34 | if (serverConfigKeys.includes(key)) {
35 | this.server.reloadServer()
36 | }
37 | })
38 | }
39 |
40 | /**
41 | * 注入设置中的脚本类型方法
42 | */
43 | initSettingMethods() {
44 | this.setting.method.tips = () => {
45 | $ui.alert({
46 | title: $l10n("TIPS"),
47 | message: $l10n("DOMAIN") + "与浏览器访问地址一致" + "\n QuantumultX 用户超时时间可以设置的久一点"
48 | })
49 | }
50 | }
51 | }
52 |
53 | module.exports = {
54 | run: () => {
55 | const kernel = new AppKernel()
56 | // 设置样式
57 | kernel.useJsboxNav()
58 | // 设置 navButtons
59 | kernel.setNavButtons([
60 | {
61 | symbol: "arrow.clockwise",
62 | handler: () => {
63 | require("./ui/main/home").refresh()
64 | }
65 | },
66 | {
67 | symbol: "square.grid.2x2",
68 | handler: () => {
69 | const ToolboxUI = require("./ui/main/toolbox")
70 | const interfaceUi = new ToolboxUI(kernel)
71 | UIKit.push({
72 | title: $l10n("TOOLBOX"),
73 | views: [interfaceUi.getView()],
74 | navButtons: [
75 | {
76 | symbol: "gear",
77 | handler: () => {
78 | UIKit.push({
79 | title: $l10n("SETTING"),
80 | views: [kernel.setting.getListView()]
81 | })
82 | }
83 | }
84 | ]
85 | })
86 | }
87 | }
88 | ])
89 | const HomeUI = require("./ui/main/home")
90 | const interfaceUi = new HomeUI(kernel)
91 | kernel.UIRender({
92 | views: [interfaceUi.getView()]
93 | })
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/scripts/libs/easy-jsbox.js:
--------------------------------------------------------------------------------
1 | var vt="1.4.4",q=class{title;handler;constructor({title:t=$l10n("OK"),disabled:e=!1,style:i=$alertActionType.default,handler:s=()=>{}}={}){this.title=t,this.disabled=e,this.style=i,this.handler=s}},at=class a{id=$text.uuid;title;message;actions;titleFont=$font("bold",20);messageFont=$font(14);actionButtonFontSize=16;actionButtonHighlight=$color($rgba(0,0,0,.2),$rgba(255,255,255,.2));actionButtonHeight=35;actionButtonBoderWidth=.5;actionButtonBorderColor=$color("#C9C9C9","#383838");boxWidth=250;textVerticalMargin=20;textHorizontalMargin=50;constructor({title:t="",message:e="",actions:i=[]}={}){this.title=t,this.message=e,this.actions=i,this.actions.length===0&&this.actions.push(new q),this.titleSize=h.getContentSize(this.titleFont,this.title,this.boxWidth-this.textHorizontalMargin*2),this.messageSize=h.getContentSize(this.messageFont,this.message,this.boxWidth-this.textHorizontalMargin*2)}textView(){return{type:"view",views:[{type:"label",props:{lines:0,font:this.titleFont,text:this.title,color:$color("tint"),align:$align.center},layout:(t,e)=>{t.centerX.equalTo(e.super),t.width.equalTo(this.boxWidth-this.textHorizontalMargin*2),t.height.equalTo(this.titleSize.height),t.top.equalTo(this.textVerticalMargin)}},{type:"label",props:{lines:0,font:this.messageFont,text:this.message,align:$align.center},layout:(t,e)=>{t.centerX.equalTo(e.super),t.width.equalTo(this.boxWidth-this.textHorizontalMargin*2),t.height.equalTo(this.messageSize.height),t.top.equalTo(e.prev.bottom)}}],layout:(t,e)=>{t.top.width.equalTo(e.super),t.height.equalTo(this.titleSize.height+this.messageSize.height+this.textVerticalMargin*2)}}}actionView(){let t=(e,i)=>{let s=l=>this.actions.length===2?l.y>=0&&l.x>=0&&l.y<=this.actionButtonHeight&&l.x<=this.boxWidth/2:l.y>=0&&l.x>=0&&l.y<=this.actionButtonHeight&&l.x<=this.boxWidth,o=async(l,c,p)=>{e.disabled||(l.bgcolor=$color("clear"),s(c)&&(typeof e.handler=="function"&&await e.handler({index:i,title:e.title}),this.dismiss()))},r=$color("tint"),n=$font(this.actionButtonFontSize);return e.disabled?r=$color("gray"):e.style===$alertActionType.destructive?r=$color("red"):e.style===$alertActionType.cancel&&(n=$font("bold",this.actionButtonFontSize)),{type:"label",props:{lines:1,text:e.title,align:$align.center,font:n,color:r,borderWidth:this.actionButtonBoderWidth,borderColor:this.actionButtonBorderColor,bgcolor:$color("clear")},events:{tapped:()=>{},touchesBegan:l=>{e.disabled||(l.bgcolor=this.actionButtonHighlight)},touchesEnded:o,touchesCancelled:o,touchesMoved:(l,c,p)=>{e.disabled||(s(c)?l.bgcolor=this.actionButtonHighlight:l.bgcolor=$color("clear"))}},layout:(l,c)=>{this.actions.length===2?c.prev?(l.left.equalTo(c.prev.right).offset(-this.actionButtonBoderWidth),l.width.equalTo(c.super).dividedBy(2).offset(this.actionButtonBoderWidth)):l.width.equalTo(c.super).dividedBy(2):(l.width.equalTo(c.super),c.prev&&l.top.equalTo(c.prev.bottom).offset(-this.actionButtonBoderWidth)),l.height.equalTo(this.actionButtonHeight)}}};return{type:"view",views:this.actions.map((e,i)=>t(e,i)),layout:(e,i)=>{e.left.equalTo(i.super).offset(-this.actionButtonBoderWidth),e.width.equalTo(i.super).offset(this.actionButtonBoderWidth*2),e.bottom.equalTo(i.super),e.top.equalTo(i.prev.bottom)}}}getView(){let t={type:"view",props:{id:this.id+"-box",smoothCorners:!0,cornerRadius:20,bgcolor:$color("#FFFFFF","#000000")},views:[this.textView(),this.actionView()],layout:(e,i)=>{e.center.equalTo(i.super.safeArea);let s=this.titleSize.height+this.messageSize.height+this.textVerticalMargin*2,o=this.actions.length>2?this.actions.length:1;s+=this.actionButtonHeight*o,s-=this.actionButtonBoderWidth*o;let r=this.boxWidth-this.actionButtonBoderWidth*2;e.size.equalTo($size(r,s))}};return{type:"view",props:{id:this.id,alpha:0,bgcolor:$rgba(0,0,0,.6)},views:[t],layout:$layout.fill}}present(){let t=$ui.create(this.getView());$ui.controller.view.hidden?$ui.controller.view.super.insertAtIndex(t,0):$ui.controller.view.insertAtIndex(t,0);let e=$(this.id);e.layout($layout.fill),e.moveToFront(),$ui.animate({duration:.3,animation:()=>{e.alpha=1}})}dismiss(){let t=$(this.id);$ui.animate({duration:.3,animation:()=>{t.alpha=0},completion:()=>{t.remove()}})}static fromJsbox(t){return new Promise((e,i)=>{new a({title:t.title,message:t.message,actions:t?.actions?.map(o=>(o.handler||(o.handler=r=>{e(r)}),new q(o)))}).present()})}},v=class{events={};setEvents(t){return Object.keys(t).forEach(e=>this.setEvent(e,t[e])),this}setEvent(t,e){return this.events[t]=e,this}appendEvent(t,e){let i=this.events[t];return typeof i=="function"?this.events[t]=(...s)=>{i(...s),e(...s)}:this.setEvent(t,e),this}callEvent(t,...e){typeof this.events[t]=="function"&&this.events[t](...e)}},nt=class{viewController;constructor(){this.edges=10,this.iconSize=25}setViewController(t){this.viewController=t}get menu(){return{items:[{title:$l10n("SHARE"),symbol:"square.and.arrow.up",handler:async(t,e)=>{let i=t.object(e).info.info;$share.sheet([$file.absolutePath(i.path)])}}]}}delete(t){$file.delete(t.path)}edit(t){let e=$file.read(t.path);if(e.info?.mimeType?.startsWith("image"))b.quickLookImage(e,t.path.substring(t.path.lastIndexOf("/")+1));else{let i=new b,s=$text.uuid;i.setView({type:"code",layout:$layout.fill,props:{id:s,lineNumbers:!0,theme:$device.isDarkMode?"atom-one-dark":"atom-one-light",text:e.string,insets:$insets(15,15,15,15)}}).addNavBar({title:t.file,popButton:{title:$l10n("CLOSE")},rightButtons:[{title:$l10n("SAVE"),tapped:()=>{$file.write({data:$data({string:$(s).text}),path:t.path}),$ui.success($l10n("SAVE_SUCCESS"))}}]}),i.init().present()}}getFiles(t=""){return $file.list(t).map(e=>{let i=t+"/"+e,s=$file.isDirectory(i);return{info:{info:{path:i,file:e,isDirectory:s}},icon:{symbol:s?"folder.fill":"doc"},name:{text:e},size:{text:s?"":"--"}}}).sort((e,i)=>{if(e.info.info.isDirectory!==i.info.info.isDirectory)return e.info.info.isDirectory?-1:1;if(e.info.info.isDirectory===i.info.info.isDirectory)return e.info.info.file.localeCompare(i.info.info.file)})}async loadFileSize(t){return t.map((e,i)=>{let s=e.info.info;if(!s.isDirectory)try{t[i].size.text=h.bytesToSize($file.read(s.path).info.size)}catch(o){t[i].size.text=o}}),t}get listTemplate(){return{props:{bgcolor:$color("clear")},views:[{props:{id:"info"}},{type:"image",props:{id:"icon"},layout:(t,e)=>{t.centerY.equalTo(e.super),t.left.inset(this.edges),t.size.equalTo(this.iconSize)}},{type:"view",views:[{type:"label",props:{id:"size",color:$color("secondaryText"),lines:1},layout:(t,e)=>{t.height.equalTo(e.super),t.right.inset(this.edges)}},{type:"label",props:{id:"name",lines:1},layout:(t,e)=>{t.height.left.equalTo(e.super),t.right.equalTo(e.prev.left).offset(-this.edges)}}],layout:(t,e)=>{t.height.right.equalTo(e.super),t.left.equalTo(e.prev.right).offset(this.edges)}}]}}#t(t){let e=t.lastIndexOf("/"),i=t.substring(e<0?0:e+1),s=this.getListView(t),o=async()=>{let r=$file.absolutePath(t);(await $ui.alert({title:"Path",message:r,actions:[{title:$l10n("COPY")},{title:$l10n("OK")}]})).index===0&&($clipboard.text=r,$ui.toast($l10n("COPIED")))};if(this.viewController){let r=new m;r.setView(s).navigationBarTitle(i),r.navigationBar.setLargeTitleDisplayMode(g.largeTitleDisplayModeNever),r.navigationBarItems.addRightButton({symbol:"info.circle",tapped:o}),this.viewController.push(r)}else h.push({title:i,views:[s],navButtons:[{symbol:"info.circle",handler:o}]})}getListView(t=""){return{type:"list",props:{menu:this.menu,bgcolor:h.primaryViewBackgroundColor,separatorInset:$insets(0,this.edges,0,0),data:[],template:this.listTemplate,actions:[{title:" "+$l10n("DELETE")+" ",color:$color("red"),handler:(e,i)=>{let s=e.object(i).info.info;h.deleteConfirm($l10n("FILE_MANAGER_DELETE_CONFIRM_MSG")+' "'+s.file+'" ?',()=>{this.delete(s),e.delete(i)})}}]},layout:$layout.fill,events:{ready:e=>{let i=this.getFiles(t);e.data=i,this.loadFileSize(i).then(s=>{e.data=s})},pulled:async e=>{let i=this.getFiles(t);e.data=i,e.data=await this.loadFileSize(i),$delay(.5,()=>{e.endRefreshing()})},didSelect:(e,i,s)=>{let o=s.info.info;o.isDirectory?this.#t(o.path):this.edit(o)}}}}push(t=""){this.#t(t)}},S=class a{basePath;constructor({basePath:t="storage"}={}){this.basePath=t,this.#t(this.basePath)}static join(...t){let e=t.length,i=t[0];if(e<2)return i;for(let s=0;ss&&(i=t.substring(s+1),t=t.substring(0,s+1))}return e&&this.#t(t),t+i}exists(t=""){return t=this.filePath(t,!1),!!$file.exists(t)}write(t="",e){return new Promise((i,s)=>{try{let o=this.writeSync(t,e);o?i(o):s(o)}catch(o){s(o)}})}writeSync(t="",e){if(!e)throw new A("data");return $file.write({data:e,path:this.filePath(t)})}read(t=""){return new Promise((e,i)=>{try{let s=this.readSync(t);s?e(s):i()}catch(s){i(s)}})}readSync(t=""){if(t=this.filePath(t),!$file.exists(t))throw new x(t);return $file.isDirectory(t)?$file.list(t):$file.read(t)}readAsJSON(t="",e=null){try{let i=this.readSync(t)?.string;return JSON.parse(i)}catch{return e}}static readFromRoot(t=""){return new Promise((e,i)=>{try{let s=a.readFromRootSync(t);s?e(s):i()}catch(s){i(s)}})}static readFromRootSync(t=""){if(!t)throw new A("path");if(!$file.exists(t))throw new x(t);return $file.isDirectory(t)?$file.list(t):$file.read(t)}static readFromRootAsJSON(t="",e=null){try{let i=a.readFromRootSync(t)?.string;return JSON.parse(i)}catch{return e}}delete(t=""){return $file.delete(this.filePath(t,!1))}copy(t,e){t=this.filePath(t),e=this.filePath(e),$file.copy({src:t,dst:e})}move(t,e){t=this.filePath(t),e=this.filePath(e),$file.move({src:t,dst:e})}},lt=class a{startTime=Date.now();isUseJsboxNav=!1;title=$addin?.current?.name;constructor(){$app.isDebugging&&(console.log("You are running EasyJsBox in debug mode."),$app.idleTimerDisabled=!0),H.init()}static isObject(t){return t!=null&&typeof t=="object"}static objectEqual(t,e){let i=Object.keys(t),s=Object.keys(e);if(i.length!==s.length)return!1;i.sort(),s.sort();for(let o=0;on?i[n]:0,c=isNaN(Number(l))?l.charCodeAt():Number(l),p=s.length>n?s[n]:0,f=isNaN(Number(p))?p.charCodeAt():Number(p);if(cf){r=1;break}}return r}useJsboxNav(){return this.isUseJsboxNav=!0,this}setTitle(t){this.isUseJsboxNav&&($ui.title=t),this.title=t}setNavButtons(t){this.navButtons=t}openInJsbox(){$app.openURL(`jsbox://run?name=${this.title}`)}UIRender(t={}){let e=$context.query;if(e.type==="alertFromKeyboard"){let i=JSON.parse($text.URLDecode(e.value));i.actions=[{title:$l10n("CANCEL")}],$ui.alert(i);return}try{t.props=Object.assign({title:this.title,navBarHidden:!this.isUseJsboxNav,navButtons:this.navButtons??[],statusBarStyle:0},t.props),t.events||(t.events={});let i=t.events.layoutSubviews;t.events.layoutSubviews=()=>{$app.notify({name:"interfaceOrientationEvent",object:{statusBarOrientation:h.statusBarOrientation,isHorizontal:h.isHorizontal}}),typeof i=="function"&&i()},$ui.render(t)}catch(i){this.print(i)}}KeyboardRender(t={}){t.id||(t.id=$text.uuid),$ui.render(),$delay(0,()=>{$ui.controller.view=$ui.create(t),$ui.controller.view.layout(t.layout)})}KeyboardRenderWithViewFunc(t){$ui.render(),$delay(0,()=>{$ui.controller.view=$ui.create({type:"view"}),$delay(0,async()=>{let e=await t();e.id||(e.id=$text.uuid),$ui.controller.view=$ui.create(e),$ui.controller.view.layout(e.layout)})})}async checkUpdate(){let t="dev",e=await $http.get(`https://raw.githubusercontent.com/ipuppet/EasyJsBox/${t}/src/version.js`);if(e.error)throw e.error;let i=e.data.match(/.*VERSION.+\"([0-9\.]+)\"/)[1];if(this.print(`easy-jsbox latest version: ${i}`),a.versionCompare(i,vt)>0){let s=await $http.get(`https://raw.githubusercontent.com/ipuppet/EasyJsBox/${t}/dist/easy-jsbox.js`);if(s.error)throw s.error;return s.data}return!1}},H=class{static l10n(t,e,i){if(typeof e=="string"){let o={};e.split(";").forEach(n=>{if(n=n.trim(),n!==""){let l=n.split("=");o[l[0].trim().slice(1,-1)]=l[1].trim().slice(1,-1)}}),e=o}let s=$app.strings;if(i)Object.assign(s[t],e);else for(let o in e)s[t][o]||(s[t][o]=e[o]);$app.strings=s}static set(t,e){this.l10n(t,e,!0)}static add(t,e){this.l10n(t,e,!1)}static init(){this.add("zh-Hans",{OK:"\u597D",DONE:"\u5B8C\u6210",CANCEL:"\u53D6\u6D88",CLEAR:"\u6E05\u9664",BACK:"\u8FD4\u56DE",ERROR:"\u53D1\u751F\u9519\u8BEF",SUCCESS:"\u6210\u529F",INVALID_VALUE:"\u975E\u6CD5\u53C2\u6570",CONFIRM_CHANGES:"\u6570\u636E\u5DF2\u53D8\u5316\uFF0C\u786E\u8BA4\u4FEE\u6539\uFF1F",SETTING:"\u8BBE\u7F6E",GENERAL:"\u4E00\u822C",ADVANCED:"\u9AD8\u7EA7",TIPS:"\u5C0F\u8D34\u58EB",COLOR:"\u989C\u8272",COPY:"\u590D\u5236",COPIED:"\u590D\u5236\u6210\u529F",JSBOX_ICON:"JSBox \u5185\u7F6E\u56FE\u6807",SF_SYMBOLS:"SF Symbols",IMAGE_BASE64:"\u56FE\u7247 / base64",PREVIEW:"\u9884\u89C8",SELECT_IMAGE_PHOTO:"\u4ECE\u76F8\u518C\u9009\u62E9\u56FE\u7247",SELECT_IMAGE_ICLOUD:"\u4ECE iCloud \u9009\u62E9\u56FE\u7247",CLEAR_IMAGE:"\u6E05\u9664\u56FE\u7247",NO_IMAGE:"\u65E0\u56FE\u7247",ABOUT:"\u5173\u4E8E",VERSION:"Version",AUTHOR:"\u4F5C\u8005",AT_BOTTOM:"\u5DF2\u7ECF\u5230\u5E95\u5566~"}),this.add("en",{OK:"OK",DONE:"Done",CANCEL:"Cancel",CLEAR:"Clear",BACK:"Back",ERROR:"Error",SUCCESS:"Success",INVALID_VALUE:"Invalid value",CONFIRM_CHANGES:"The data has changed, confirm the modification?",SETTING:"Setting",GENERAL:"General",ADVANCED:"Advanced",TIPS:"Tips",COLOR:"Color",COPY:"Copy",COPIED:"Copide",JSBOX_ICON:"JSBox in app icon",SF_SYMBOLS:"SF Symbols",IMAGE_BASE64:"Image / base64",PREVIEW:"Preview",SELECT_IMAGE_PHOTO:"Select From Photo",SELECT_IMAGE_ICLOUD:"Select From iCloud",CLEAR_IMAGE:"Clear Image",NO_IMAGE:"No Image",ABOUT:"About",VERSION:"Version",AUTHOR:"Author",AT_BOTTOM:"It's the end~"}),this.add("zh-Hans",{DELETE_CONFIRM_TITLE:"\u5220\u9664\u524D\u786E\u8BA4"}),this.add("en",{DELETE_CONFIRM_TITLE:"Delete Confirmation"}),this.add("zh-Hans",{FILE_MANAGER_DELETE_CONFIRM_MSG:"\u786E\u8BA4\u8981\u5220\u9664\u5417",DELETE:"\u5220\u9664",CANCEL:"\u53D6\u6D88",CLOSE:"\u5173\u95ED",SHARE:"\u5206\u4EAB",SAVE:"\u4FDD\u5B58",SAVE_SUCCESS:"\u4FDD\u5B58\u6210\u529F"}),this.add("en",{FILE_MANAGER_DELETE_CONFIRM_MSG:"Are you sure you want to delete",DELETE:"Delete",CANCEL:"Cancel",CLOSE:"Close",SHARE:"Share",SAVE:"Save",SAVE_SUCCESS:"Save Success"})}},V=class a{static level={info:"info",warn:"warn",error:"error"};writer;fsLevels=[a.level.error];printToFile(t){this.fsLevels=t}setWriter(t,e){this.writer=i=>{t.exists(e)&&(i=(t.readSync(e)?.string??"")+i),t.writeSync(e,$data({string:i}))}}format(t,e){return`${new Date().toUTCString()} [${e.toUpperCase()}] ${t}
2 | `}log(t,e){this.writer&&this.fsLevels.includes(e)&&this.writer(this.format(t,e)),$app.isDebugging&&console[e](t)}info(t){this.log(t,a.level.info)}warn(t){this.log(t,a.level.warn)}error(t){this.log(t,a.level.error)}},R=class{rightButtons=[];leftButtons=[];#t={};hasbutton=!1;isPinTitleView=!1;setTitleView(t){return this.titleView=t,this}pinTitleView(){return this.isPinTitleView=!0,this}setFixedFooterView(t){return this.fixedFooterView=t,this}setRightButtons(t){return t.forEach(e=>this.addRightButton(e)),this.hasbutton||(this.hasbutton=!0),this}setLeftButtons(t){return t.forEach(e=>this.addLeftButton(e)),this.hasbutton||(this.hasbutton=!0),this}addRightButton({id:t,symbol:e,title:i,tapped:s,menu:o,events:r,color:n}={}){let l=E.creat({id:t,symbol:e,title:i,tapped:s,menu:o,events:r,color:n,align:h.align.right});return this.rightButtons.push(l),this.#t[t??l.id]=l,this.hasbutton||(this.hasbutton=!0),this}addLeftButton({id:t,symbol:e,title:i,tapped:s,menu:o,events:r,color:n}={}){let l=E.creat({id:t,symbol:e,title:i,tapped:s,menu:o,events:r,color:n,align:h.align.left});return this.leftButtons.push(l),this.#t[t??l.id]=l,this.hasbutton||(this.hasbutton=!0),this}getButton(t){return this.#t[t]}getButtons(){return Object.values(this.#t)}addPopButton(t,e,i){return t||(t=$l10n("BACK")),this.popButtonView=e??{type:"button",props:{bgcolor:$color("clear"),symbol:"chevron.left",tintColor:h.linkColor,title:` ${t}`,titleColor:h.linkColor,font:$font("bold",16)},layout:(s,o)=>{s.left.equalTo(o.super.safeArea).offset(E.style.edges),s.centerY.equalTo(o.super.safeArea)},events:{tapped:()=>{$ui.pop(),typeof i=="function"&&i()}}},this}removePopButton(){return this.popButtonView=void 0,this}},ht=class{constructor(t){this.content=t}valueToJs(t){switch(t.tag){case"dict":return this.dictToJs(t);case"true":case"false":return t.tag==="true";case"integer":return t.number;case"key":case"string":return t.string;case"date":return new Date(t.string);case"array":return this.arrayToJs(t);default:return t.node}}arrayToJs(t){let e=[];return t.children().forEach(i=>{e.push(this.valueToJs(i))}),e}dictToJs(t){let e=[],i=[];return t.children().forEach(s=>{s.tag==="key"?e.push(this.valueToJs(s)):i.push(this.valueToJs(s))}),Object.fromEntries(e.map((s,o)=>[s,i[o]]))}getObject(){if(!this.content)return!1;let t=$xml.parse({string:this.content,mode:"xml"});return this.valueToJs(t.rootElement.firstChild({xPath:"//plist/dict"}))}static get(t){return new this(t).getObject()}},w=class a{static method={get:"GET",post:"POST",put:"PUT",delete:"DELETE",patch:"PATCH",head:"HEAD",options:"OPTIONS"};static errorType={http:0,network:1};cacheContainerKey=$addin?.current?.name+".request.cache";#t;#e=!1;#i=!1;cacheLife=1e3*60*60*24*30;#s=!1;timeout=5;logger;constructor(t){t instanceof V&&(this.logger=t)}get cache(){return $cache.get(this.cacheContainerKey)??{}}#o(t){this.#s&&this.logger instanceof V&&this.logger.info(t)}logRequest(){return this.#s=!0,this}disableLogRequest(){this.#s=!1}getCacheKey(t){return $text.MD5(t)}getCache(t,e=null){return this.cache[t]??e}setCache(t,e){if(!e)return;let i=this.cache;i[t]=e,$cache.set(this.cacheContainerKey,i)}removeCache(t){let e=this.cache;delete e[t],$cache.set(this.cacheContainerKey,e)}clearCache(){$cache.remove(this.cacheContainerKey)}clearNSURLCache(){this.#t||(this.#t=$objc("NSURLCache").$sharedURLCache()),this.#t.$removeAllCachedResponses()}enableCache(){return this.#e=!0,this}disableCache(){return this.#e=!1,this}ignoreCacheExp(){this.#i=!0}async request(t,e,i={},s={},o=this.cacheLife,r){let n,l=this.#e&&e===a.method.get;if(l){n=this.getCacheKey(t);let p=this.getCache(n);if(p&&(this.#i||p.exp>Date.now()))return this.#o("get data from cache: "+t),p.data}this.#o(`sending request [${e}]: ${t}`);let c=await $http.request(Object.assign({header:s,url:t,method:e,body:e===a.method.get?null:i,timeout:this.timeout},r));if(c.error)throw new O({type:a.errorType.network,message:c.error.localizedDescription,code:c.error.code});if(c?.response?.statusCode>=400){let p=c.data;throw typeof p=="object"&&(p=JSON.stringify(p)),new O({type:a.errorType.http,message:p,code:c.response.statusCode})}return l&&this.setCache(n,{exp:Date.now()+o,data:c}),c}},u=class a{static rowHeight=50;static edgeOffset=10;static iconSize=30;static iconDefaultColor="#00CC00";setting;#t;#e;#i;title;#s={};#o;constructor({setting:t,key:e,title:i,icon:s,value:o=null}={}){this.setting=t,this.key=e,this.title=$l10n(i),this.icon=s,this.default=o}get method(){return this.setting.method}set key(t){return this.#e=t??$text.uuid,this.#t=void 0,this}get key(){return this.#e}get id(){return this.#t||(this.#t=`setting-${$text.uuid}-${this.key}`),this.#t}set icon(t){return t?Array.isArray(t)||(t=[t,a.iconDefaultColor]):t=["square.grid.2x2.fill",a.iconDefaultColor],Array.isArray(t[0])||(t[0]=[t[0],t[0]]),t[1]?Array.isArray(t[1])||(t[1]=[t[1],t[1]]):t[1]=[a.iconDefaultColor,a.iconDefaultColor],this.#i=t,this}get icon(){return this.#i}get options(){return this.#s}set options(t){return this.#s=t??{},this}set(t){return typeof this.#o=="function"&&this.#o(t),this.setting.set(this.key,t)}onSet(t){return this.#o=t,this}get(t=this.default){return this.setting.getOriginal(this.key,t)}evalValues(t,e=[]){let i;return typeof t=="string"?t.startsWith("this.method")?i=new Function("method",`return ${t.replace("this.","")}()`)(this.method):i=new Function(`return {${t}}`)():typeof t=="function"?i=t():i=t??e,i}createLineLabel(){return{type:"view",views:[{type:"view",props:{bgcolor:$color(this.icon[1][0],this.icon[1][1]),cornerRadius:5,smoothCorners:!0},views:[{type:"image",props:Object.assign({tintColor:$color("white")},this.icon[0][0].startsWith("icon_")?{icon:$icon(this.icon[0][0].slice(5,this.icon[0][0].indexOf(".")>0?this.icon[0][0].indexOf("."):this.icon[0][0].length),$color("#ffffff"))}:{image:$image(this.icon[0][0],this.icon[0][1])}),layout:(t,e)=>{t.center.equalTo(e.super),t.size.equalTo(20)}}],layout:(t,e)=>{t.centerY.equalTo(e.super),t.size.equalTo(a.iconSize),t.left.inset(a.edgeOffset)}},{type:"label",props:{text:this.title,lines:1,align:$align.left},layout:(t,e)=>{t.centerY.equalTo(e.super),t.height.equalTo(e.super),t.left.equalTo(e.prev.right).offset(a.edgeOffset),t.width.greaterThanOrEqualTo(10)}}],layout:(t,e)=>{t.height.centerY.equalTo(e.super),t.left.inset(0)}}}getView(){}create(){return this.getView(this.options)}},b=class a{#t=()=>{};#e=()=>{};style=a.UIModalPresentationStyle.PageSheet;#i=!1;#s;#o;#r;static UIModalPresentationStyle={Automatic:-2,FullScreen:0,PageSheet:1,FormSheet:2,CurrentContext:3,Custom:4,OverFullScreen:5,OverCurrentContext:6,Popover:7,BlurOverFullScreen:8};navigationView;init(){this.initNavBar(),$define({type:"SheetViewController: UIViewController",events:{"viewWillDisappear:":e=>{typeof this.#o=="function"&&this.#o(e)},"viewDidDisappear:":e=>{typeof this.#r=="function"&&this.#r(e)}}}),this.sheetVC=$objc("SheetViewController").$new();let t=this.sheetVC.$view();return t.$addSubview($ui.create({type:"view"})),this.sheetVC.$setModalPresentationStyle(this.style),this.sheetVC.$setModalInPresentation(this.#i),this.#t=()=>{t.jsValue().add(this.navigationView?.getPage().definition??this.view),$ui.vc.ocValue().invoke("presentViewController:animated:completion:",this.sheetVC,!0,null)},this.#e=()=>this.sheetVC.invoke("dismissViewControllerAnimated:completion:",!0,null),this}initNavBar(){if(!this.#s)return;let{title:t="",popButton:e={title:$l10n("CLOSE")},rightButtons:i=[]}=this.#s;if(this.view===void 0)throw new W;this.navigationView=new m;let s=this.navigationView.navigationBar;s.setLargeTitleDisplayMode(g.largeTitleDisplayModeNever),s.navigationBarLargeTitleHeight-=s.navigationBarNormalHeight,s.navigationBarNormalHeight=h.PageSheetNavigationBarNormalHeight,s.navigationBarLargeTitleHeight+=s.navigationBarNormalHeight,this.style===a.UIModalPresentationStyle.FullScreen||this.style===a.UIModalPresentationStyle.OverFullScreen||this.style===a.UIModalPresentationStyle.BlurOverFullScreen?s.setTopSafeArea():s.removeTopSafeArea(),e.events=Object.assign({tapped:async()=>{typeof e.tapped=="function"&&await e.tapped(),this.dismiss()}},e.events??{}),this.navigationView.navigationBarItems.addLeftButton(e).setRightButtons(i),this.navigationView.setView(this.view).navigationBarTitle(t),this.view.props?.bgcolor&&this.navigationView?.getPage().setProp("bgcolor",this.view.props?.bgcolor)}preventDismiss(){return this.#i=!0,this}setStyle(t){return this.style=t,this}setView(t={}){if(typeof t!="object")throw new rt("view","object");return this.view=t,this}addNavBar(t){return this.#s=t,this}present(){this.#t()}dismiss(){this.#e()}willDismiss(t){return this.#o=t,this}didDismiss(t){return this.#r=t,this}static quickLookImage(t,e=$l10n("PREVIEW")){new a().setView({type:"view",views:[{type:"scroll",props:{zoomEnabled:!0,maxZoomScale:3},layout:$layout.fill,views:[{type:"image",props:{data:t},layout:$layout.fill}]}],layout:$layout.fill}).addNavBar({title:e,rightButtons:[{symbol:"square.and.arrow.up",tapped:()=>$share.sheet(t)}]}).init().present()}},ut=class{#t={};addTask(t,e=0){let i=$text.uuid;return this.#t[i]=$delay(e,async()=>{await t(),delete this.#t[i]}),i}cancelTask(t){this.#t[t].cancel()}clearTasks(){Object.values(this.#t).forEach(t=>t.cancel())}},ct=class a{static type={info:void 0,success:"checkmark",warning:"exclamationmark.triangle",error:"xmark.circle"};static edges=40;static iconSize=100;static labelTopMargin=10;static defaultFont=$font("default",26);width=Math.min(h.windowSize.width*.6,260);labelWidth=this.width-a.edges*2;id=$text.uuid;#t="";font=a.defaultFont;type=a.type.info;labelLines=2;constructor(t,e=a.type.info,i=2,s=a.defaultFont){this.type=e,this.message=t,this.labelLines=i,this.font=s}get message(){return this.#t}set message(t){this.#t=t,this.fontHeight=h.getContentSize(this.font,this.message,this.labelWidth,this.labelLines).height,this.height=(this.hasIcon?a.labelTopMargin+a.iconSize:0)+this.fontHeight+a.edges*2}get hasIcon(){return this.type!==void 0}get blurBox(){let t=h.blurBox({id:this.id,cornerRadius:15,alpha:0},[{type:"image",props:{symbol:this.type,hidden:!this.hasIcon,tintColor:$color("lightGray")},layout:(e,i)=>{e.top.inset(a.edges),e.size.equalTo(a.iconSize),e.centerX.equalTo(i.super)}},{type:"label",props:{font:this.font,text:this.message,align:$align.center,lines:this.labelLines,color:$color("lightGray")},layout:(e,i)=>{e.bottom.equalTo(i.supper).offset(-a.edges),e.width.equalTo(this.labelWidth),e.height.equalTo(this.fontHeight),e.centerX.equalTo(i.super)}}]);return t.events={tapped:()=>{this.remove()}},t}show(){let t=$ui.create(this.blurBox);$ui.controller.view.hidden?$ui.controller.view.super.insertAtIndex(t,0):$ui.controller.view.insertAtIndex(t,0);let e=$(this.id);e.layout((i,s)=>{i.center.equalTo(s.super),i.size.equalTo($size(this.width,this.height))}),e.moveToFront(),$ui.animate({duration:.2,animation:()=>{e.alpha=1}})}remove(){let t=$(this.id);t&&$ui.animate({duration:.2,animation:()=>{t.alpha=0},completion:()=>{t.remove()}})}static toast({message:t,type:e=a.type.info,show:i=!0,displayTime:s=2,labelLines:o=2,font:r=a.defaultFont}){let n=new a(t,e,o,r);return i&&(n.show(),$delay(s,()=>{n.remove()})),n}static info(t,e={}){return a.toast(Object.assign({message:t,type:a.type.info},e))}static success(t,e={}){return a.toast(Object.assign({message:t,type:a.type.success},e))}static warning(t,e={}){return a.toast(Object.assign({message:t,type:a.type.warning},e))}static error(t,e={}){return a.toast(Object.assign({message:t,type:a.type.error},e))}},h=class a{static#t=$objc("UIApplication").$sharedApplication();static#e=$objc("UINotificationFeedbackGenerator").$new();static feedbackSuccess(){a.#e.$notificationOccurred(0)}static feedbackError(){a.#e.$notificationOccurred(2)}static isTaio=$app.info.bundleID.includes("taio");static align={left:0,right:1,top:2,bottom:3};static textColor=$color("primaryText");static linkColor=$color("systemLink");static primaryViewBackgroundColor=$color("primarySurface");static scrollViewBackgroundColor=$color("insetGroupedBackground");static scrollViewList=["list","matrix"];static isLargeScreen=$device.isIpad||$device.isIpadPro;static get windowSize(){return $objc("UIWindow").$keyWindow().jsValue().size}static NavigationBarNormalHeight=$objc("UINavigationController").invoke("alloc.init").$navigationBar().jsValue().frame.height;static NavigationBarLargeTitleHeight=$objc("UITabBarController").invoke("alloc.init").$tabBar().jsValue().frame.height+a.NavigationBarNormalHeight;static PageSheetNavigationBarNormalHeight=56;static get isSplitScreenMode(){return a.isLargeScreen&&$device.info.screen.width!==a.windowSize.width}static get topSafeAreaInsets(){return a.isTaio?0:a.#t?.$keyWindow()?.$safeAreaInsets()?.top??0}static get bottomSafeAreaInsets(){return a.#t?.$keyWindow()?.$safeAreaInsets()?.bottom??0}static get statusBarOrientation(){return a.#t.$statusBarOrientation()}static get consoleBarHeight(){if($app.isDebugging){let t=a.#t.$statusBarFrame().height+26;return $device.isIphoneX&&(t+=30),t}return 0}static get isHorizontal(){return a.statusBarOrientation===3||a.statusBarOrientation===4}static loading(){let t=$ui.create(a.blurBox({cornerRadius:15},[{type:"spinner",props:{loading:!0,style:0},layout:(e,i)=>{e.size.equalTo(i.prev),e.center.equalTo(i.super)}}]));return{start:()=>{$ui.controller.view.insertAtIndex(t,0),t.layout((e,i)=>{e.center.equalTo(i.super);let s=Math.min(Math.min(a.windowSize.width,a.windowSize.height)*.6,260);e.size.equalTo($size(s,s))}),t.moveToFront()},end:()=>{t.remove()}}}static defaultBackgroundColor(t){return a.scrollViewList.indexOf(t)>-1?a.scrollViewBackgroundColor:a.primaryViewBackgroundColor}static separatorLine(t={},e=a.align.bottom){return{type:"canvas",props:t,layout:(i,s)=>{s.prev===void 0?i.top.equalTo(s.super):e===a.align.bottom?i.top.equalTo(s.prev.bottom):i.top.equalTo(s.prev.top),i.height.equalTo(1/$device.info.screen.scale),i.left.right.inset(0)},events:{draw:(i,s)=>{s.strokeColor=t.bgcolor??$color("separatorColor"),s.setLineWidth(1),s.moveToPoint(0,0),s.addLineToPoint(i.frame.width,0),s.strokePath()}}}}static blurBox(t={},e=[],i=$layout.fill){return{type:"blur",props:Object.assign({style:$blurStyle.thinMaterial},t),views:e,layout:i}}static getContentSize(t,e="A",i=a.windowSize.width,s=void 0){let o={text:e,width:i,font:t};return s!==void 0&&(o.lineSpacing=s),$text.sizeThatFits(o)}static getSymbolSize(t,e){t=typeof t=="string"?$image(t):t;let i=t.size.width/t.size.height;return t.size.width>t.size.height?$size(e,e/i):$size(e*i,e)}static push({views:t,statusBarStyle:e=0,title:i="",navButtons:s=[{title:""}],bgcolor:o=t[0]?.props?.bgcolor??"primarySurface",titleView:r=void 0,disappeared:n}={}){let l={statusBarStyle:e,navButtons:s,title:i,bgcolor:typeof o=="string"?$color(o):o};r&&(l.titleView=r),$ui.push({props:l,events:{disappeared:()=>{n!==void 0&&n()}},views:[{type:"view",views:t,layout:(c,p)=>{c.top.equalTo(p.super.safeArea),c.bottom.equalTo(p.super),c.left.right.equalTo(p.super.safeArea)}}]})}static compressImage(t,e=1280*720){let i=$imagekit.info(t);if(i.height*i.width>e){let s=e/(i.height*i.width);t=$imagekit.scaleBy(t,s)}return t}static deleteConfirm(t,e){$ui.alert({title:$l10n("DELETE_CONFIRM_TITLE"),message:t,actions:[{title:$l10n("DELETE"),style:$alertActionType.destructive,handler:()=>{e()}},{title:$l10n("CANCEL")}]})}static bytesToSize(t){if(t===0)return"0 B";let e=1024,i=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],s=Math.floor(Math.log(t)/Math.log(e));return(t/Math.pow(e,s)).toPrecision(3)+" "+i[s]}},pt=class{#t;text="";interval;fullScreen=!1;#e=()=>{};constructor(){this.#t=$text.uuid}updateText(t){$(this.#t).text=t}setLoop(t){if(typeof t!="function")throw"loop must be a function";this.#e=t}done(){clearInterval(this.interval)}load(){$ui.render({props:{navBarHidden:this.fullScreen},views:[{type:"spinner",props:{loading:!0},layout:(t,e)=>{t.centerY.equalTo(e.super).offset(-15),t.width.equalTo(e.super)}},{type:"label",props:{id:this.#t,align:$align.center,text:""},layout:(t,e)=>{t.top.equalTo(e.prev.bottom).offset(10),t.left.right.equalTo(e.super)}}],layout:$layout.fill,events:{appeared:()=>{this.interval=setInterval(()=>{this.#e()},100)}}})}},d=class a{id=$text.uuid;type;props;views;events;layout;#t=void 0;#e=null;constructor({type:t="view",props:e={},views:i=[],events:s={},layout:o=$layout.fill}={}){this.type=t,this.props=e,this.views=i,this.events=s,this.layout=o,this.props.id?this.id=this.props.id:this.props.id=this.id}static create(t){return new this(t)}static createFromViews(t){return new this({views:t})}get scrollableView(){return this.scrollable?this.#e:null}set scrollableView(t){this.#e=t}get scrollable(){if(this.#t===void 0){if(this.#t=!1,h.scrollViewList.indexOf(this.type)>-1)this.scrollableView=this,this.#t=!0;else if(this.views.length>0){let t=e=>{if(!this.#t&&e?.length>0)for(let i=0;i-1){typeof e[i]!==a&&(e[i]=a.create(e[i])),this.scrollableView=e[i],this.#t=!0;return}else t(e[i].views)};t(this.views)}}return this.#t}set scrollable(t){throw new Error("[scrollable] is readonly prop.")}setProps(t){return Object.keys(t).forEach(e=>this.setProp(e,t[e])),this}setProp(t,e){return t==="id"&&(this.id=e),this.props[t]=e,this}setViews(t){return this.views=t,this.#t=void 0,this}setEvents(t){return Object.keys(t).forEach(e=>this.setEvent(e,t[e])),this}setEvent(t,e){return this.events[t]=e,this}eventMiddleware(t,e){let i=this.events[t];return this.events[t]=(...s)=>{typeof i=="function"&&e(i,...s)},this}assignEvent(t,e){let i=this.events[t];return this.events[t]=(...s)=>{typeof i=="function"&&i(...s),e(...s)},this}setLayout(t){return this.layout=t,this}getView(){return this}get definition(){return this.getView()}},A=class extends Error{constructor(t){super(`Parameter [${t}] is required.`),this.name="FileStorageParameterError"}},x=class extends Error{constructor(t){super(`File not found: ${t}`),this.name="FileStorageFileNotFoundError"}},O=class extends Error{constructor({message:t,code:e,type:i}={}){super(t),this.name="RequestError",this.code=e,this.type=i}},k=class extends Error{constructor(){super("Call loadConfig() first."),this.name="SettingLoadConfigError"}},j=class extends Error{constructor(){super("Attempted to assign to readonly property."),this.name="SettingReadonlyError"}},W=class extends Error{constructor(){super("Please call setView(view) first."),this.name="SheetViewUndefinedError"}},D=class extends Error{constructor(t,e){super(`The type of the parameter '${t}' must be '${e}'`),this.name="ValidationError"}},dt=class extends d{height=60;getView(){return this.type="view",this.setProp("bgcolor",h.primaryViewBackgroundColor),this.layout=(t,e)=>{t.left.right.bottom.equalTo(e.super),t.top.equalTo(e.super.safeAreaBottom).offset(-this.height)},this.views=[d.create({props:this.props,views:this.views,layout:(t,e)=>{t.left.right.top.equalTo(e.super),t.height.equalTo(this.height)}})],this}},gt=class extends d{titleStyle={font:$font("bold",21),height:30};#t;#e;templateIdByIndex(t){return this.props.template.views[t]?.props?.id===void 0&&(this.props.template.views[t].props===void 0&&(this.props.template.views[t].props={}),this.props.template.views[t].props.id=$text.uuid),this.props.template.views[t].props.id}get templateHiddenStatus(){if(!this.#e){this.#e={};for(let t=0;t{i.items=i.items.filter(s=>s?.__title?.hidden===!0),e.push(i)}),e}set data(t){this.props.data=this.rebuildData(t),$(this.id).data=this.props.data}#i(t){let e={...this.hiddenViews};return Object.assign(e,{__templateProps:{hidden:!0},__title:{hidden:!1,text:t,info:{title:!0}}}),e}rebuildData(t=[]){return t.map(e=>(e.items=e.items.map(i=>(Object.keys(i).forEach(s=>{i[s].hidden=this.templateHiddenStatus[s]??!1}),Object.keys(this.templateHiddenStatus).forEach(s=>{i[s]||(i[s]={}),i[s].hidden=this.templateHiddenStatus[s]}),i.__templateProps={hidden:!1},i.__title={hidden:!0},i)),e.title&&e.items.unshift(this.#i(e.title)),e))}rebuildTemplate(){let t={};this.props.template.props!==void 0&&(this.props.template.props.cornerRadius!==void 0&&(this.props.template.props.clipsToBounds=!1),t=Object.assign(this.props.template.props,{id:"__templateProps",hidden:!1}));let e=[{type:"view",props:t,layout:$layout.fill},{type:"label",props:{id:"__title",hidden:!0,font:this.titleStyle.font},layout:(i,s)=>{i.top.inset(-(this.titleStyle.height/4)*3),i.height.equalTo(this.titleStyle.height),i.width.equalTo(s.super.safeArea)}}].concat(this.props.template.views);this.props.template.views=e}insert(t,e=!0){return t.indexPath=this.indexPath(t.indexPath,e),$(this.id).insert(t)}delete(t,e=!0){return t=this.indexPath(t,e),$(this.id).delete(t)}object(t,e=!0){return t=this.indexPath(t,e),$(this.id).object(t)}cell(t,e=!0){return t=this.indexPath(t,e),$(this.id).cell(t)}indexPath(t,e){let i=e?1:0;return typeof t=="number"?t=$indexPath(0,t+i):t=$indexPath(t.section,t.row+i),t}getView(){return this.props.data=this.rebuildData(this.props.data),this.rebuildTemplate(),this.setEvent("itemSize",(t,e)=>{if(t.object(e)?.__title?.info?.title)return $size(Math.max($device.info.screen.width,$device.info.screen.height),0);let s=this.props.columns??2,o=this.props.spacing??15,r=this.props.itemWidth??this.props.itemSize?.width??(t.super.frame.width-o*(s+1))/s,n=this.props.itemHeight??this.props.itemSize?.height??100;return $size(r,n)}),this}},U=class extends d{controller={};setController(t){return this.controller=t,this}},E=class a extends d{static#t;edges=15;buttonEdges=this.edges/2;iconSize=24;fontSize=17;color=h.textColor;title;#e;#i;align=h.align.right;get symbol(){return typeof this.#e=="string"?this.#i==="icon"?$icon(this.#e,this.color):$image(this.#e):this.#e}set symbol(t){typeof this.#e=="string"?isNaN(t)?this.#i="image":this.#i="icon":String(t)==="[object BBFileIcon]"?this.#i="icon":this.#i="image",this.#e=t}get width(){if(this.title){let t=$text.sizeThatFits({text:this.title,width:h.windowSize.width,font:$font(this.fontSize)});return Math.ceil(t.width)+this.edges}return this.iconSize+this.edges}static get style(){return this.#t===void 0&&(this.#t=new a),this.#t}setEdges(t){return this.edges=t,this}setFontSize(t){return this.fontSize=t,$(this.id)&&($(this.id).font=$font(this.fontSize)),this}setColor(t=h.textColor){return this.color=t,$(this.id)&&($(this.id).titleColor=this.color,$(`icon-button-${this.id}`).titleColor=this.color,$(`icon-checkmark-${this.id}`).titleColor=this.color),this}setTitle(t){return this.title=t,$(this.id)&&($(this.id).title=this.title),this}setSymbol(t){return this.symbol=t,$(`icon-button-${this.id}`)&&(this.#i==="icon"?$(`icon-button-${this.id}`).icon=this.symbol:$(`icon-button-${this.id}`).image=this.symbol),this}setMenu(t){return this.menu=t,this}setAlign(t){return this.align=t,this}setLoading(t){t?($(this.id).hidden=!0,$("spinner-"+this.id).hidden=!1):($(this.id).hidden=!1,$("spinner-"+this.id).hidden=!0)}#s(){let t=$(`icon-button-${this.id}`),e=$(`icon-checkmark-${this.id}`);t.alpha=0,$(this.id).hidden=!1,$("spinner-"+this.id).hidden=!0,$ui.animate({duration:.6,animation:()=>{e.alpha=1},completion:()=>{$delay(.3,()=>$ui.animate({duration:.6,animation:()=>{e.alpha=0},completion:()=>{$ui.animate({duration:.4,animation:()=>{t.alpha=1},completion:()=>{t.alpha=1}})}}))}})}hide(){$(this.id+"-container").hidden=!0}show(){$(this.id+"-container").hidden=!1}getView(){let t=this.events.tapped;return this.events.tapped=e=>{t&&t({start:()=>this.setLoading(!0),done:()=>this.#s(),cancel:()=>this.setLoading(!1)},e)},{type:"view",props:{id:this.id+"-container",info:{align:this.align}},views:[{type:"button",props:Object.assign({id:this.id,bgcolor:$color("clear"),font:$font(this.fontSize),titleColor:this.color,contentEdgeInsets:$insets(0,0,0,0),titleEdgeInsets:$insets(0,0,0,0),imageEdgeInsets:$insets(0,0,0,0)},this.menu?{menu:this.menu}:{},this.title?{title:this.title}:{},this.props),views:[{type:"image",props:Object.assign({id:`icon-button-${this.id}`,hidden:this.symbol===void 0,tintColor:this.color},this.symbol?this.#i==="icon"?{icon:this.symbol}:{image:this.symbol}:{}),layout:(e,i)=>{this.symbol&&this.#i==="image"&&e.size.equalTo(h.getSymbolSize(this.symbol,this.iconSize)),e.center.equalTo(i.super)}},{type:"image",props:{id:`icon-checkmark-${this.id}`,alpha:0,tintColor:this.color,symbol:"checkmark"},layout:(e,i)=>{e.center.equalTo(i.super),e.size.equalTo(h.getSymbolSize("checkmark",this.iconSize))}}],events:this.events,layout:$layout.fill},{type:"spinner",props:{id:"spinner-"+this.id,loading:!0,hidden:!0},layout:$layout.fill}],layout:(e,i)=>{if(e.size.equalTo($size(this.width,h.NavigationBarNormalHeight)),e.centerY.equalTo(i.super),i.prev&&i.prev?.info?.align===this.align)this.align===h.align.right?e.right.equalTo(i.prev.left).offset(-this.buttonEdges):e.left.equalTo(i.prev.right).offset(this.buttonEdges);else{let s=this.edges/2;this.align===h.align.right?e.right.inset(s):e.left.inset(s)}}}}static creat({id:t,symbol:e,title:i,tapped:s,menu:o,events:r,color:n,align:l=h.align.right}={}){let c=new a;return c.setEvents(Object.assign({tapped:s},r)).setAlign(l).setSymbol(e).setTitle(i).setColor(n).setMenu(o),t&&c.setProp("id",t),c}},g=class a extends d{static largeTitleDisplayModeAutomatic=0;static largeTitleDisplayModeAlways=1;static largeTitleDisplayModeNever=2;navigationBarItems;title="";prefersLargeTitles=!0;largeTitleDisplayMode=a.largeTitleDisplayModeAutomatic;fontFamily="bold";largeTitleFontSize=34;largeTitleFontHeight=$text.sizeThatFits({text:"A",width:100,font:$font(this.fontFamily,this.largeTitleFontSize)}).height;navigationBarTitleFontSize=17;topSafeArea=!0;contentViewHeightOffset=0;navigationBarNormalHeight=h.NavigationBarNormalHeight;navigationBarLargeTitleHeight=h.NavigationBarLargeTitleHeight;setTopSafeArea(){return this.topSafeArea=!0,this}removeTopSafeArea(){return this.topSafeArea=!1,this}setLargeTitleDisplayMode(t){return this.largeTitleDisplayMode=t,this}setBackgroundColor(t){return this.backgroundColor=t,this}setTitle(t){return this.title=t,this}setPrefersLargeTitles(t){return this.prefersLargeTitles=t,this}setContentViewHeightOffset(t){return this.contentViewHeightOffset=t,this}getLargeTitleView(){return this.prefersLargeTitles&&this.largeTitleDisplayMode!==a.largeTitleDisplayModeNever?{type:"label",props:{id:this.id+"-large-title",text:this.title,textColor:h.textColor,align:$align.left,font:$font(this.fontFamily,this.largeTitleFontSize),line:1},layout:(t,e)=>{t.left.equalTo(e.super.safeArea).offset(15),t.height.equalTo(this.largeTitleFontHeight),t.top.equalTo(e.super.safeAreaTop).offset(this.navigationBarNormalHeight)}}:{props:{id:this.id+"-large-title"},layout:(t,e)=>{t.left.top.right.inset(0),t.bottom.equalTo(e.super.safeAreaTop).offset(this.navigationBarNormalHeight)}}}getNavigationBarView(){let t=(r,n)=>{let l=(y,B)=>{y.top.equalTo(B.super.safeAreaTop),y.bottom.equalTo(B.super.safeAreaTop).offset(this.navigationBarNormalHeight),n===h.align.left?y.left.equalTo(B.super.safeArea):y.right.equalTo(B.super.safeArea)};if(r&&!Array.isArray(r))return{type:"view",views:[r],layout:l};let c=0,p=[];r.forEach(y=>{c+=y.width,p.push(y.definition)});let f=r[0]?.edges??0;return c+=r.length>=2?f*2:f,r.length>0?{type:"view",views:p,info:{width:c},layout:(y,B)=>{l(y,B),y.width.equalTo(c)}}:{type:"view",layout:y=>y.size.equalTo(0)}},e=t(this.navigationBarItems.popButtonView??this.navigationBarItems.leftButtons,h.align.left),i=t(this.navigationBarItems.rightButtons,h.align.right),s=this.prefersLargeTitles,o=!this.prefersLargeTitles||this.largeTitleDisplayMode===a.largeTitleDisplayModeNever;return{type:"view",props:{id:this.id+"-navigation",bgcolor:$color("clear")},layout:(r,n)=>{r.left.top.right.inset(0),r.bottom.equalTo(n.super.safeAreaTop).offset(this.navigationBarNormalHeight)},views:[this.backgroundColor?{type:"view",props:{hidden:s,bgcolor:this.backgroundColor,id:this.id+"-background"},layout:$layout.fill}:h.blurBox({hidden:s,id:this.id+"-background"}),h.separatorLine({id:this.id+"-underline",alpha:s?0:1}),{type:"view",props:{alpha:0,bgcolor:$color("clear"),id:this.id+"-large-title-mask"},events:{ready:r=>{r.bgcolor=$(this.id+"-large-title")?.prev.bgcolor}},layout:$layout.fill},e,i,{type:"view",views:[{type:"label",props:{id:this.id+"-small-title",alpha:o?1:0,text:this.title,font:$font(this.fontFamily,this.navigationBarTitleFontSize),align:$align.center,bgcolor:$color("clear"),textColor:h.textColor},layout:(r,n)=>{r.edges.equalTo(n.super.safeArea);let l=h.getContentSize($font(this.fontFamily,this.navigationBarTitleFontSize),n.text).width,c=Math.max(e.info?.width??0,i.info?.width??0);h.windowSize.width-c*2>l&&r.centerX.equalTo(n.super.super)}}],layout:(r,n)=>{r.top.bottom.equalTo(n.super.safeArea),r.left.equalTo(n.prev.prev.right),r.right.equalTo(n.prev.left)}}]}}},G=class a extends v{static largeTitleViewSmallMode=0;static largeTitleViewLargeMode=1;navigationBar;updateSelector(){this.selector={navigation:$(this.navigationBar.id+"-navigation"),largeTitleView:$(this.navigationBar.id+"-large-title"),smallTitleView:$(this.navigationBar.id+"-small-title"),underlineView:this.navigationBar.navigationBarItems.isPinTitleView?$(this.navigationBar.id+"-title-view-underline"):$(this.navigationBar.id+"-underline"),largeTitleMaskView:$(this.navigationBar.id+"-large-title-mask"),backgroundView:$(this.navigationBar.id+"-background"),titleViewBackgroundView:$(this.navigationBar.id+"-title-view-background")}}toNormal(t=!0){this.updateSelector(),this.selector.backgroundView.hidden=!1,$ui.animate({duration:.2,animation:()=>{this.selector.underlineView.alpha=1,this.selector.smallTitleView.alpha=1,this.selector.largeTitleView.alpha=0}}),t&&this.navigationBar.navigationBarItems&&(this.navigationBar.largeTitleDisplayMode=g.largeTitleDisplayModeNever)}toLargeTitle(t=!0){this.updateSelector(),this.selector.backgroundView.hidden=!0,$ui.animate({duration:.2,animation:()=>{this.selector.underlineView.alpha=0,this.selector.smallTitleView.alpha=0,this.selector.largeTitleView.alpha=1}}),t&&this.navigationBar.navigationBarItems&&(this.navigationBar.largeTitleDisplayMode=g.largeTitleDisplayModeAlways)}#t(t){let e=t===a.largeTitleViewSmallMode;this.selector.largeTitleView.alpha=e?0:1,$ui.animate({duration:.2,animation:()=>{this.selector.smallTitleView.alpha=e?1:0}})}#e(t){if(this.selector.largeTitleView.updateLayout((i,s)=>{this.navigationBar.navigationBarNormalHeight-t>0?i.top.equalTo(s.super.safeAreaTop).offset(this.navigationBar.navigationBarNormalHeight-t):i.top.equalTo(s.super.safeAreaTop).offset(0)}),t>0)t>=this.navigationBar.navigationBarNormalHeight?this.#t(a.largeTitleViewSmallMode):this.#t(a.largeTitleViewLargeMode);else{this.#t(a.largeTitleViewLargeMode);let i=this.navigationBar.largeTitleFontSize-t*.04;i>40&&(i=40),this.selector.largeTitleView.font=$font(this.navigationBar.fontFamily,i)}}#i(t){let e=this.navigationBar.largeTitleDisplayMode===g.largeTitleDisplayModeNever?5:this.navigationBar.navigationBarNormalHeight,i=this.selector.titleViewBackgroundView!==void 0;if(t>e){this.selector.backgroundView.hidden=!1;let s=()=>{i&&this.navigationBar.navigationBarItems.isPinTitleView&&(this.selector.titleViewBackgroundView.alpha=1),this.selector.largeTitleMaskView.alpha=0,this.selector.underlineView.alpha=1};(t-e)/3>=1?s():$ui.animate({duration:.2,animation:()=>{s()}})}else this.selector.largeTitleMaskView.alpha=t>0?1:0,this.selector.underlineView.alpha=0,i&&(this.selector.titleViewBackgroundView.alpha=0),this.selector.backgroundView.hidden=!0}didScroll(t){if(!this.navigationBar.prefersLargeTitles)return;let e=this.navigationBar.largeTitleDisplayMode;if(e!==g.largeTitleDisplayModeAlways)if(this.updateSelector(),e===g.largeTitleDisplayModeAutomatic){if(!this.navigationBar.navigationBarItems?.isPinTitleView&&(this.navigationBar.navigationBarItems?.titleView?.controller.didScroll(t),t>0)){let i=this.navigationBar.navigationBarItems?.titleView?.height??0;t-=i,t<0&&(t=0)}this.#e(t),this.#i(t)}else e===g.largeTitleDisplayModeNever&&this.#i(t)}didEndDragging(t,e,i,s){if(!this.navigationBar.prefersLargeTitles)return;let o=this.navigationBar.largeTitleDisplayMode;if(o!==g.largeTitleDisplayModeAlways&&(this.updateSelector(),o===g.largeTitleDisplayModeAutomatic)){let r=0;this.navigationBar.navigationBarItems?.isPinTitleView||(this.navigationBar.navigationBarItems?.titleView?.controller.didEndDragging(t,e,i,s),r=this.navigationBar.navigationBarItems?.titleView?.height??0,t-=r),t>=0&&t<=this.navigationBar.largeTitleFontHeight&&i($point(0,t>=this.navigationBar.largeTitleFontHeight/2?this.navigationBar.navigationBarNormalHeight+r-s:r-s))}}},C=class extends D{constructor(t,e){super(t,e),this.name="NavigationViewTypeError"}},m=class extends v{page;navigationController=new G;navigationBar=new g;navigationBarItems=new R;constructor(){super(),this.navigationBar.navigationBarItems=this.navigationBarItems,this.navigationController.navigationBar=this.navigationBar}navigationBarTitle(t){return this.navigationBar.setTitle(t),this}setView(t){if(typeof t!="object")throw new C("view","object");return this.view=d.create(t),this}getTopOffset(){if(!(this.view instanceof d))throw new C("view","View");let t=this.view.scrollableView,e=$app.isDebugging?0:h.topSafeAreaInsets,i=this.navigationBar.largeTitleDisplayMode===g.largeTitleDisplayModeNever?this.navigationBar.navigationBarNormalHeight:this.navigationBar.navigationBarLargeTitleHeight,s=this.navigationBar.contentViewHeightOffset+i;if(this.navigationBarItems.titleView&&(s+=this.navigationBarItems.titleView.topOffset,s+=this.navigationBarItems.titleView.height,s+=this.navigationBarItems.titleView.bottomOffset),!this.view.scrollable||t.props.associateWithNavigationBar===!1){let o=s-this.navigationBar.contentViewHeightOffset;return(!h.isHorizontal||h.isLargeScreen)&&this.navigationBar.topSafeArea&&(o+=e),o}return t.props.stickyHeader&&(s-=i,s+=this.navigationBar.largeTitleFontHeight),s}getBottomOffset(){return this.navigationBarItems.fixedFooterView?.height??0}#t(){if(!(this.view instanceof d))throw new C("view","View");let t=this.view.scrollableView,e=$app.isDebugging?0:h.topSafeAreaInsets,i=this.getTopOffset();if(!this.view.scrollable||t.props.associateWithNavigationBar===!1){this.view.layout=(o,r)=>{o.left.right.equalTo(r.super.safeArea),o.bottom.equalTo(r.super),o.top.equalTo(i)};return}let s=this.navigationBarItems.isPinTitleView?this.navigationBarItems.titleView.height+this.navigationBarItems.titleView.bottomOffset+this.navigationBar.contentViewHeightOffset:0;if(t.props.indicatorInsets){let o=t.props.indicatorInsets;t.props.indicatorInsets=$insets(o.top+this.navigationBar.navigationBarNormalHeight+s,o.left,o.bottom+this.getBottomOffset(),o.right)}else t.props.indicatorInsets=$insets(this.navigationBar.navigationBarNormalHeight+s,0,this.navigationBarItems.fixedFooterView?.height??0,0);if(t.props.contentInset){let o=t.props.contentInset;t.props.contentInset=$insets(o.top+i+s,o.left,o.bottom+this.getBottomOffset(),o.right)}else t.props.contentInset=$insets(i+s,0,this.navigationBarItems.fixedFooterView?.height??0,0);t.props.contentOffset=$point(0,-i),t.layout=(o,r)=>{t.props.stickyHeader?o.top.equalTo(r.super.safeArea).offset(this.navigationBar.navigationBarNormalHeight):o.top.equalTo(r.super),o.left.right.equalTo(r.super.safeArea),o.bottom.equalTo(r.super)},t.assignEvent("didScroll",o=>{let r=o.contentOffset.y;(!h.isHorizontal||h.isLargeScreen)&&this.navigationBar.topSafeArea&&!t.props.stickyHeader&&(r+=e),r+=i,this.navigationController.didScroll(r)}).assignEvent("didEndDragging",(o,r)=>{let n=o.contentOffset.y,l=0;(!h.isHorizontal||h.isLargeScreen)&&this.navigationBar.topSafeArea&&!t.props.stickyHeader&&(n+=e,l=e),n+=i,l+=i,this.navigationController.didEndDragging(n,r,(...c)=>o.scrollToOffset(...c),l)}).assignEvent("didEndDecelerating",(...o)=>{o[0].tracking||t.events?.didEndDragging(...o)})}#e(){if(this.navigationBar.prefersLargeTitles){this.#t();let t={};if(this.navigationBarItems.titleView){let e=this.navigationBar.largeTitleDisplayMode===g.largeTitleDisplayModeNever?1:0;t=d.create({views:[this.navigationBar.backgroundColor?{type:"view",props:{alpha:e,bgcolor:this.navigationBar.backgroundColor,id:this.navigationBar.id+"-title-view-background"},layout:$layout.fill}:h.blurBox({alpha:e,id:this.navigationBar.id+"-title-view-background"}),h.separatorLine({id:this.navigationBar.id+"-title-view-underline",alpha:e}),this.navigationBarItems.titleView.definition],layout:(i,s)=>{i.top.equalTo(s.prev.bottom),i.width.equalTo(s.super),i.height.equalTo(this.navigationBarItems.titleView.topOffset+this.navigationBarItems.titleView.height+this.navigationBarItems.titleView.bottomOffset)}})}this.page=T.createFromViews([this.view,this.navigationBar.getLargeTitleView(),t,this.navigationBar.getNavigationBarView(),this.navigationBarItems.fixedFooterView?.definition??{}])}else this.page=T.createFromViews([this.view]);this.view.props?.bgcolor?this.page.setProp("bgcolor",this.view.props.bgcolor):this.page.setProp("bgcolor",h.defaultBackgroundColor(this.view.type))}getPage(){return this.page||this.#e(),this.page}},ft=class extends U{height=35;topOffset=15;bottomOffset=10;horizontalOffset=15;kbType=$kbType.search;placeholder=$l10n("SEARCH");inputEvents={};keyboardView;accessoryView;cancelButtonFont=$font(16);constructor(t){super(t),this.setController(new J),this.controller.setSearchBar(this)}get cancelButtonWidth(){return h.getContentSize(this.cancelButtonFont,$l10n("CANCEL")).width}setEvent(t,e){return this.inputEvents[t]=e,this}setPlaceholder(t){return this.placeholder=t,this}setKbType(t){return this.kbType=t,this}setKeyboardView(t){return this.keyboardView=t,this}setAccessoryView(t){return this.accessoryView=t,this}onBeginEditingAnimate(){$ui.animate({duration:.3,animation:()=>{let t=this.cancelButtonWidth;$(this.id+"-cancel-button").updateLayout((e,i)=>{e.left.equalTo(i.super.right).offset(-t)}),$(this.id+"-cancel-button").alpha=1,$(this.id+"-cancel-button").relayout(),$(this.id+"-input").updateLayout(e=>{e.right.inset(t+this.horizontalOffset/2)}),$(this.id+"-input").relayout()}})}onEndEditingAnimate(){$ui.animate({duration:.3,animation:()=>{$(this.id+"-cancel-button").updateLayout((t,e)=>{t.left.equalTo(e.super.right)}),$(this.id+"-cancel-button").alpha=0,$(this.id+"-cancel-button").relayout(),$(this.id+"-input").updateLayout($layout.fill),$(this.id+"-input").relayout()}})}cancel(){$(this.id+"-input").blur(),$(this.id+"-input").text="",this.onEndEditingAnimate(),this.controller.callEvent("onCancel")}getView(){return this.props={id:this.id,smoothCorners:!0,cornerRadius:6},this.views=[{type:"input",props:{id:this.id+"-input",type:this.kbType,bgcolor:$color("#EEF1F1","#212121"),placeholder:this.placeholder,keyboardView:this.keyboardView,accessoryView:this.accessoryView},layout:$layout.fill,events:Object.assign({didBeginEditing:t=>{this.onBeginEditingAnimate(),this.controller.callEvent("onBeginEditing",t.text)},didEndEditing:t=>{this.controller.callEvent("onEndEditing",t.text)},changed:t=>this.controller.callEvent("onChange",t.text),returned:t=>this.controller.callEvent("onReturn",t.text)},this.inputEvents)},{type:"button",props:{id:this.id+"-cancel-button",title:$l10n("CANCEL"),font:this.cancelButtonFont,titleColor:$color("tintColor"),bgcolor:$color("clear"),alpha:0,hidden:!1},events:{tapped:()=>this.cancel()},layout:(t,e)=>{t.height.equalTo(e.super),t.width.equalTo(this.cancelButtonWidth),t.left.equalTo(e.super.right)}}],this.layout=(t,e)=>{t.height.equalTo(this.height),t.top.equalTo(e.super.safeArea).offset(this.topOffset),t.left.equalTo(e.super.safeArea).offset(this.horizontalOffset),t.right.equalTo(e.super.safeArea).offset(-this.horizontalOffset)},this}},J=class extends v{setSearchBar(t){return this.searchBar=t,this}updateSelector(){this.selector={inputBox:$(this.searchBar.id),input:$(this.searchBar.id+"-input")}}hide(){this.updateSelector(),this.selector.inputBox.updateLayout(t=>{t.height.equalTo(0)})}show(){this.updateSelector(),this.selector.inputBox.updateLayout(t=>{t.height.equalTo(this.searchBar.height)})}didScroll(t){this.updateSelector();let e=this.searchBar.height-t;if(e=e>0?e>this.searchBar.height?this.searchBar.height:e:0,this.selector.inputBox.updateLayout(i=>{i.height.equalTo(e)}),t>0){let i=(this.searchBar.height/2-5-t)/10;this.selector.input.alpha=i}else this.selector.input.alpha=1}didEndDragging(t,e,i){this.updateSelector(),t>=0&&t<=this.searchBar.height&&i($point(0,t>=this.searchBar.height/2?this.searchBar.height:0))}},K=class extends v{#t=[];#e(t){t.callEvent("onPop"),this.callEvent("onPop",t),this.#t.pop()}push(t){let e=this.#t[this.#t.length-1];t.navigationBarItems.addPopButton(e?.navigationBar.title),this.#t.push(t),$ui.push({props:{statusBarStyle:0,navBarHidden:!0},events:{disappeared:()=>{this.#e(t)}},views:[t.getPage().definition],layout:$layout.fill})}},L=class extends u{get isArray(){return Array.isArray(this.default)}async tapped(){let t=this.isArray?this.default[1]:this.default;(await $ui.alert({title:this.title,message:t,actions:[{title:$l10n("COPY")},{title:$l10n("OK")}]})).index===0&&($clipboard.text=t,$ui.toast($l10n("COPIED")))}getView(){return{type:"view",props:{selectable:!0,info:{key:this.key}},views:[this.createLineLabel(),{type:"label",props:{text:this.isArray?this.default[0]:this.default,align:$align.right,textColor:$color("darkGray")},layout:(t,e)=>{t.centerY.equalTo(e.prev),t.right.inset(u.edgeOffset),t.width.equalTo(180)}}],layout:$layout.fill}}},Y=class extends u{getView(){return{type:"view",props:{id:this.id,selectable:!0},views:[this.createLineLabel(),{type:"switch",props:{on:this.get(),onColor:$color("#00CC00")},events:{changed:t=>{try{this.set(t.on)}catch(e){throw t.on=!t.on,e}}},layout:(t,e)=>{t.centerY.equalTo(e.prev),t.right.inset(u.edgeOffset)}}],layout:$layout.fill}}},X=class extends u{getView(){return{type:"view",props:{id:this.id,selectable:!0},views:[this.createLineLabel(),{type:"button",props:{symbol:"square.and.pencil",bgcolor:$color("clear"),tintColor:$color("primaryText")},events:{tapped:t=>{let e=$ui.popover({sourceView:t,sourceRect:t.bounds,directions:$popoverDirection.down,size:$size(320,150),views:[{type:"text",props:{id:`${this.id}-string`,align:$align.left,text:this.get()},layout:i=>{i.left.right.inset(10),i.top.inset(20),i.height.equalTo(90)}},{type:"button",props:{symbol:"checkmark",bgcolor:$color("clear"),titleEdgeInsets:10,contentEdgeInsets:0},layout:i=>{i.right.inset(10),i.bottom.inset(25),i.size.equalTo(30)},events:{tapped:()=>{this.set($(`${this.id}-string`).text),e.dismiss()}}}]})}},layout:(t,e)=>{t.centerY.equalTo(e.prev),t.right.inset(0),t.size.equalTo(50)}}],layout:$layout.fill}}},_=class extends u{with({min:t,max:e}={}){return this.options={min:t,max:e},this}getView({min:t,max:e}={}){let i=`${this.id}-label`;return{type:"view",props:{id:this.id,selectable:!0},views:[this.createLineLabel(),{type:"label",props:{id:i,text:this.get(),align:$align.left},layout:(s,o)=>{s.height.equalTo(o.super),s.right.inset(120)}},{type:"stepper",props:{min:t,max:e,value:this.get()},events:{changed:s=>{$(i).text=s.value;try{this.set(s.value)}catch(o){throw $(i).text=this.get(),o}}},layout:(s,o)=>{s.centerY.equalTo(o.prev),s.right.inset(u.edgeOffset)}}],layout:$layout.fill}}},z=class extends u{rightSymbol="chevron.right";buttonId=`${this.id}-button`;start(){$(this.buttonId).alpha=0,$(`${this.buttonId}-spinner`).alpha=1}cancel(){$(this.buttonId).alpha=1,$(`${this.buttonId}-spinner`).alpha=0}done(){$(`${this.buttonId}-spinner`).alpha=0;let t=$(this.buttonId);t.symbol="checkmark",$ui.animate({duration:.6,animation:()=>t.alpha=1,completion:()=>{$ui.animate({duration:.4,animation:()=>t.alpha=0,completion:()=>{t.symbol=this.rightSymbol,$ui.animate({duration:.4,animation:()=>t.alpha=1})}})}})}with({script:t}={}){return this.options={script:t},this}async tapped(){let t={start:()=>this.start(),cancel:()=>this.cancel(),done:()=>this.done()},{script:e}=this.options;typeof e=="function"?await e(t):e.startsWith("this.method")?await new Function("method","animate",`return async()=>{await ${e.replace("this.","")}(animate)}`)(this.method,t)():await new Function("animate",`return async()=>{${e}}`)(t)()}getView(){let t="chevron.right";return{type:"view",props:{id:this.id,selectable:!0,info:{key:this.key}},views:[this.createLineLabel(),{type:"view",views:[{type:"button",props:{id:this.buttonId,symbol:t,bgcolor:$color("clear"),tintColor:$color("secondaryText")},events:{tapped:()=>this.tapped()},layout:(e,i)=>{e.centerY.equalTo(i.super),e.right.inset(0),e.height.equalTo(i.super)}},{type:"spinner",props:{id:`${this.buttonId}-spinner`,loading:!0,alpha:0},layout:(e,i)=>{e.size.equalTo(15),e.centerY.equalTo(i.super),e.right.equalTo(i.prev)}}],layout:(e,i)=>{e.right.inset(u.edgeOffset),e.height.equalTo(u.rowHeight),e.width.equalTo(i.super)}}],layout:$layout.fill}}},Z=class extends u{with({items:t,values:e}={}){return Array.isArray(t)&&(t=t.map(i=>$l10n(i))),this.options={items:t,values:e},this}getView({items:t,values:e}={}){t=this.evalValues(t),e=this.evalValues(e);let i=t?.length>0&&e?.length===t?.length;return{type:"view",props:{id:this.id,selectable:!0},views:[this.createLineLabel(),{type:"tab",props:{items:t??[],index:i?e.indexOf(this.get()):this.get(),dynamicWidth:!0},layout:(s,o)=>{s.right.inset(u.edgeOffset),s.centerY.equalTo(o.prev)},events:{changed:s=>{i?this.set(e[s.index]):this.set(s.index)}}}],layout:$layout.fill}}},Q=class extends u{with({items:t,values:e,pullDown:i}={}){return Array.isArray(t)&&(t=t.map(s=>$l10n(s))),this.options={items:t,values:e,pullDown:i},this}getView({items:t,values:e,pullDown:i}={}){let s=`${this.id}-label`,o=this.evalValues(t),r=this.evalValues(e),n=o?.length>0&&r?.length===o?.length,l=(p,f)=>{if(n){let y=this.evalValues(e);this.set(y[f])}else this.set(f);$(s).title=p},c=()=>{i||$ui.menu({items:this.evalValues(t),handler:l})};return{type:"view",props:{id:this.id,selectable:!0},views:[this.createLineLabel(),{type:"view",views:[{type:"button",props:{menu:i?{pullDown:!0,asPrimary:!0,items:o.map((p,f)=>({title:p,handler:()=>l(p,f)}))}:void 0,title:n?o[r.indexOf(this.get())]:o[this.get()],titleColor:$color("secondaryText"),bgcolor:$color("clear"),id:s},events:{tapped:c},layout:(p,f)=>{p.right.inset(0),p.height.equalTo(f.super)}}],layout:(p,f)=>{p.right.inset(u.edgeOffset),p.height.equalTo(u.rowHeight),p.width.equalTo(f.super)}}],layout:$layout.fill}}},tt=class extends u{get(t=null){let e=super.get(t);return e?typeof e=="string"?$color(e):$rgba(e.red,e.green,e.blue,e.alpha):t}getView(){let t=`${this.id}-color`;return{type:"view",props:{id:this.id,selectable:!0},views:[this.createLineLabel(),{type:"view",views:[{type:"view",props:{id:t,bgcolor:this.get(),circular:!0,borderWidth:1,borderColor:$color("#e3e3e3")},layout:(e,i)=>{e.centerY.equalTo(i.super),e.right.inset(u.edgeOffset),e.size.equalTo(20)}},{type:"view",events:{tapped:async()=>{let e=await $picker.color({color:this.get()});this.set(e.components),$(t).bgcolor=$rgba(e.components.red,e.components.green,e.components.blue,e.components.alpha)}},layout:(e,i)=>{e.right.inset(0),e.height.width.equalTo(i.super.height)}}],layout:(e,i)=>{e.height.equalTo(u.rowHeight),e.width.equalTo(i.super)}}],layout:$layout.fill}}},et=class extends u{with({mode:t=2}={}){return this.options={mode:t},this}getView({mode:t=2}={}){let e=i=>{let s="";switch(typeof i=="number"&&(i=new Date(i)),t){case 0:s=i.toLocaleTimeString();break;case 1:s=i.toLocaleDateString();break;case 2:s=i.toLocaleString();break}return s};return{type:"view",props:{id:this.id,selectable:!0},views:[this.createLineLabel(),{type:"view",views:[{type:"label",props:{id:`${this.id}-label`,color:$color("secondaryText"),text:this.get()?e(this.get()):"None"},layout:(i,s)=>{i.right.inset(0),i.height.equalTo(s.super)}}],events:{tapped:async()=>{let i=this.get(),s=await $picker.date({props:{mode:t,date:i||Date.now()}});this.set(s.getTime()),$(`${this.id}-label`).text=e(s)}},layout:(i,s)=>{i.right.inset(u.edgeOffset),i.height.equalTo(u.rowHeight),i.width.equalTo(s.super)}}],layout:$layout.fill}}},N=class extends u{with({secure:t=!1,kbType:e=$kbType.default,saveFunc:i}={}){return this.options={secure:t,kbType:e,saveFunc:i},this}getView({secure:t=!1,kbType:e=$kbType.default,saveFunc:i}={}){i===void 0&&(i=o=>this.set(o));let s=this.id+"-input";return{type:"view",props:{id:this.id,selectable:!0},views:[this.createLineLabel(),{type:"input",props:{id:s,type:e,align:$align.right,bgcolor:$color("clear"),textColor:$color("secondaryText"),text:this.get(),font:$font(16),secure:t,accessoryView:h.blurBox({height:44},[h.separatorLine({},h.align.top),{type:"button",props:{title:$l10n("DONE"),bgcolor:$color("clear"),titleColor:$color("primaryText")},layout:(o,r)=>{o.right.inset(u.edgeOffset),o.centerY.equalTo(r.super)},events:{tapped:()=>{$(s).blur()}}},{type:"button",props:{title:$l10n("CANCEL"),bgcolor:$color("clear"),titleColor:$color("primaryText")},layout:(o,r)=>{o.left.inset(u.edgeOffset),o.centerY.equalTo(r.super)},events:{tapped:()=>{let o=$(s),r=this.get("");o.text!==r&&(o.text=r),o.blur()}}}])},layout:(o,r)=>{o.left.equalTo(r.prev.get("label").right).offset(u.edgeOffset),o.right.inset(u.edgeOffset),o.width.greaterThanOrEqualTo(50),o.height.equalTo(r.super),o.left.priority(10),o.width.priority(10)},events:{didBeginEditing:o=>{o.secure=!1,$app.autoKeyboardEnabled||($app.autoKeyboardEnabled=!0)},returned:o=>{o.blur()},didEndEditing:async o=>{let r=this.get("");i(o.text)||(o.text=r),t&&(o.secure=t)}}}],layout:$layout.fill}}},it=class extends u{getView(){return new N(this).getView({secure:!1,kbType:$kbType.decimal,saveFunc:t=>t===""||!(i=>/^[0-9]+.?[0-9]*$/.test(i))(t)?($ui.toast($l10n("INVALID_VALUE")),!1):this.set(Number(t))})}},st=class extends u{with({bgcolor:t="#000000"}={}){return this.options={bgcolor:t},this}getView({bgcolor:t="#000000"}={}){let e=`${this.id}-image`;return{type:"view",props:{id:this.id,selectable:!0},views:[this.createLineLabel(),{type:"view",views:[{type:"image",props:{cornerRadius:8,bgcolor:typeof t=="string"?$color(t):t,smoothCorners:!0},layout:(i,s)=>{i.right.inset(u.edgeOffset),i.centerY.equalTo(s.super),i.size.equalTo($size(30,30))}},{type:"image",props:{id:e,image:$image(this.get()),icon:$icon(this.get()?.slice(5,this.get().indexOf(".")),$color("#ffffff")),tintColor:$color("#ffffff")},layout:(i,s)=>{i.right.equalTo(s.prev).offset(-5),i.centerY.equalTo(s.super),i.size.equalTo($size(20,20))}}],events:{tapped:()=>{$ui.menu({items:[$l10n("JSBOX_ICON"),$l10n("SF_SYMBOLS"),$l10n("IMAGE_BASE64")],handler:async(i,s)=>{if(s===0){let o=await $ui.selectIcon();this.set(o),$(e).icon=$icon(o.slice(5,o.indexOf(".")),$color("#ffffff"))}else(s===1||s===2)&&$input.text({text:"",placeholder:i,handler:o=>{if(o===""){$ui.toast($l10n("INVALID_VALUE"));return}this.set(o),s===1?$(e).symbol=o:$(e).image=$image(o)}})}})}},layout:(i,s)=>{i.right.inset(0),i.height.equalTo(u.rowHeight),i.width.equalTo(s.super)}}],layout:$layout.fill}}},P=class extends u{with({view:t,navButtons:e=[]}={}){return this.options={view:t,navButtons:e},this}tapped(){let{view:t,navButtons:e}=this.options;return t=this.evalValues(t,{}),e=this.evalValues(e),e.length>0&&e.map(i=>{if(typeof i.tapped=="string"){let s=i.tapped;i.tapped=()=>{this.evalValues(s)}}return i.handler=i.tapped,i}),new Promise((i,s)=>{if(this.setting.isUseJsboxNav){let o={title:this.title,props:t.props??{},views:[t],disappeared:()=>i()};e.length>0&&(o.navButtons=e),h.push(o)}else{let o=new m;o.setView(t).navigationBarTitle(this.title),o.navigationBarItems.addPopButton(),o.navigationBar.setLargeTitleDisplayMode(g.largeTitleDisplayModeNever),this.setting.hasSectionTitle(t)&&o.navigationBar.setContentViewHeightOffset(-10),e.length>0&&o.navigationBarItems.setRightButtons(e),this.setting.viewController.setEvent("onPop",()=>i()),this.setting.viewController.push(o)}})}getView(){return{type:"view",props:{id:this.id,selectable:!0,info:{key:this.key}},views:[this.createLineLabel(),{type:"button",props:{symbol:"chevron.right",bgcolor:$color("clear"),tintColor:$color("secondaryText")},events:{tapped:()=>this.tapped()},layout:(t,e)=>{t.centerY.equalTo(e.super),t.right.inset(u.edgeOffset),t.height.equalTo(e.super)}}],layout:$layout.fill}}},M=class extends P{with({children:t}={}){return super.with({view:()=>this.setting.getListView(t,{},this.id)}),this.options.children=t,this}},ot=class extends u{getImagePath(t=!1){let e=$text.MD5(this.key)+".jpg";return t&&(e="compress."+e),this.setting.imagePath+e}getImage(t=!1){try{return this.setting.fileStorage.readSync(this.getImagePath(t))}catch(e){if(e instanceof x)return null;throw e}}get(t=null){return this.getImage(!1)??null}getView(){let t=`${this.id}-image`,e=$image("questionmark.square.dashed"),i=o=>async()=>{$(t).hidden=!0,$(`${t}-spinner`).hidden=!1,await $wait(.1);try{await o()}catch(r){$ui.alert({title:$l10n("ERROR"),message:String(r)})}await $wait(.1),$(`${t}-spinner`).hidden=!0,$(t).hidden=!1},s=[{title:$l10n("PREVIEW"),handler:i(()=>{let o=this.getImage(!1);o?b.quickLookImage(o):$ui.toast($l10n("NO_IMAGE"))})},{inline:!0,items:[{title:$l10n("SELECT_IMAGE_PHOTO"),handler:i(async()=>{let o=await $photo.pick({format:"data"});if(!o.status||!o.data){if(o?.error?.description!=="canceled")throw new Error(o?.error?.description);return}let r=h.compressImage(o.data.image);this.setting.fileStorage.write(this.getImagePath(!0),r.jpg(.8)),this.setting.fileStorage.write(this.getImagePath(),o.data),$(t).image=r,$ui.success($l10n("SUCCESS"))})},{title:$l10n("SELECT_IMAGE_ICLOUD"),handler:i(async()=>{let o=await $drive.open();if(!o)return;let r=h.compressImage(o.image);this.setting.fileStorage.write(this.getImagePath(!0),r.jpg(.8)),this.setting.fileStorage.write(this.getImagePath(),o),$(t).image=r,$ui.success($l10n("SUCCESS"))})}]},{title:$l10n("CLEAR_IMAGE"),destructive:!0,handler:i(()=>{this.setting.fileStorage.delete(this.getImagePath(!0)),this.setting.fileStorage.delete(this.getImagePath()),$(t).image=e,$ui.success($l10n("SUCCESS"))})}];return{type:"view",props:{id:this.id,selectable:!0},views:[this.createLineLabel(),{type:"view",views:[{type:"image",props:{id:t,image:this.getImage(!0)?.image??e},layout:(o,r)=>{o.right.inset(u.edgeOffset),o.centerY.equalTo(r.super),o.size.equalTo($size(30,30))}},{type:"spinner",props:{id:`${t}-spinner`,loading:!0,hidden:!0},layout:(o,r)=>{o.size.equalTo(r.prev),o.left.top.equalTo(r.prev)}},{type:"button",props:{menu:{pullDown:!0,asPrimary:!0,items:s},bgcolor:$color("clear")},layout:(o,r)=>{o.right.inset(u.edgeOffset),o.centerY.equalTo(r.super),o.size.equalTo($size(30,30))}}],layout:(o,r)=>{o.right.inset(0),o.height.equalTo(u.rowHeight),o.width.equalTo(r.super)}}],layout:$layout.fill}}},yt=class extends v{name;setting={};settingItems={};userData;fileStorage;logger;imagePath;viewController=new K;method={readme:()=>{let t=(()=>{let i=$device.info?.language?.startsWith("zh")?"README_CN.md":"README.md";try{return __README__[i]??__README__["README.md"]}catch{return $file.read(i)?.string??$file.read("README.md")?.string}})();new b().setView({type:"markdown",props:{content:t},layout:(i,s)=>{i.size.equalTo(s.super)}}).addNavBar({title:"README",popButton:{symbol:"x.circle"}}).init().present()}};#t=!1;#e=!1;#i;constructor(t={}){super(),typeof t.set=="function"&&typeof t.get=="function"?(this.set=t.set,this.getOriginal=t.get,this.setUserData(t.userData??{})):(this.fileStorage=t.fileStorage??new S,this.dataFile=t.dataFile??"setting.json"),t.structure?this.setStructure(t.structure):this.setStructurePath(t.structurePath??"setting.json"),this.logger=t.logger??new V,this.isUseJsboxNav=t.isUseJsboxNav??!1,this.imagePath=(t.name??"default")+".image/",this.setName(t.name??$text.uuid)}useJsboxNav(){return this.isUseJsboxNav=!0,this}#s(){if(!this.#e)throw new k}loader(t){let e=null;switch(t.type){case"info":e=new L(t);break;case"switch":e=new Y(t);break;case"string":e=new X(t);break;case"stepper":e=new _(t).with({min:t.min??1,max:t.max??12});break;case"script":e=new z(t).with({script:t.script??t.value});break;case"tab":e=new Z(t).with({items:t.items,values:t.values});break;case"menu":e=new Q(t).with({items:t.items,values:t.values,pullDown:t.pullDown??!1});break;case"color":e=new tt(t);break;case"date":e=new et(t).with({mode:t.mode});break;case"input":e=new N(t).with({secure:t.secure});break;case"number":e=new it(t);break;case"icon":e=new st(t).with({bgcolor:t.bgcolor});break;case"push":e=new P(t).with({view:t.view,navButtons:t.navButtons});break;case"child":e=new M(t).with({children:t.children});break;case"image":e=new ot(t);break;default:e=t,e.default=t.value,e.get=(...i)=>this.get(...i),e.set=(...i)=>this.set(...i)}return e}loadConfig(){this.#e=!1;let t=this.userData??this.fileStorage.readAsJSON(this.dataFile,{}),e=i=>{for(let s in i)for(let o in i[s].items){let r=i[s].items[o];r instanceof u||(i[s].items[o]=this.loader(r),r=i[s].items[o]),r.setting||(r.setting=this),this.settingItems[r.key]=r,r instanceof M?e(r.options.children):r instanceof z||r instanceof L||(r.key in t?this.setting[r.key]=t[r.key]:this.setting[r.key]=r.default)}};return e(this.structure),this.#e=!0,this}hasSectionTitle(t){return this.#s(),!!t[0]?.title}setUserData(t){return this.userData=t,this}setStructure(t){return this.structure=t,this.loadConfig()}setStructurePath(t){return this.structure||this.setStructure(S.readFromRootAsJSON(t)),this}setName(t){return this.name=t,this}set footer(t){this.#i=t}get footer(){if(this.#i===void 0){let t=S.readFromRootAsJSON("config.json",{}).info??{};if(!t.version||!t.author)try{t=__INFO__}catch{}this.#i={},t.version&&t.author&&(this.#i={type:"view",props:{height:70},views:[{type:"label",props:{font:$font(14),text:`${$l10n("VERSION")} ${t.version} \u2665 ${t.author}`,textColor:$color({light:"#C0C0C0",dark:"#545454"}),align:$align.center},layout:e=>{e.left.right.inset(0),e.top.inset(10)}}]})}return this.#i}setFooter(t){return this.footer=t,this}setReadonly(){return this.#t=!0,this}set(t,e){if(this.#t)throw new j;return this.#s(),this.setting[t]=e,this.fileStorage.write(this.dataFile,$data({string:JSON.stringify(this.setting)})),this.callEvent("onSet",t,e),!0}getOriginal(t,e=null){return this.#s(),Object.prototype.hasOwnProperty.call(this.setting,t)?this.setting[t]:e}getItem(t){return this.settingItems[t]}get(t,e=null){return this.#s(),this.getItem(t)instanceof u?this.getItem(t).get(e):this.getOriginal(t,e)}#o(t){let e=[];for(let i in t){let s=[];for(let o in t[i].items){let r=t[i].items[o];r instanceof u&&s.push(r.create())}e.push({title:$l10n(t[i].title??""),rows:s})}return e}getListView(t=this.structure,e=this.footer,i=this.name){return{type:"list",props:{id:i,style:2,separatorInset:$insets(0,u.iconSize+u.edgeOffset*2,0,u.edgeOffset),footer:e,data:this.#o(t)},layout:$layout.fill,events:{rowHeight:(s,o)=>(s.object(o)?.props?.info??{}).rowHeight??u.rowHeight,didSelect:async(s,o,r)=>{s=s.ocValue();let n=this.getItem(r.props.info.key);if(typeof n?.tapped=="function"){s.$selectRowAtIndexPath_animated_scrollPosition(o.ocValue(),!1,0);try{await n.tapped()}catch(l){this.logger.error(l)}}s.$deselectRowAtIndexPath_animated(o,!0)}}}}getNavigationView(){let t=new m;return t.setView(this.getListView(this.structure)).navigationBarTitle($l10n("SETTING")),this.hasSectionTitle(this.structure)&&t.navigationBar.setContentViewHeightOffset(-10),t}getPage(){return this.getNavigationView().getPage()}},rt=class extends D{constructor(t,e){super(t,e),this.name="SheetViewTypeError"}},F=class extends d{constructor(t={}){super(t),this.setIcon(t.icon),this.setTitle(t.title),t.activeStatus!==void 0&&(this.activeStatus=t.activeStatus)}setIcon(t){return t instanceof Array?this.icon=t:this.icon=[t,t],this}setTitle(t){return this.title=t,this}active(){$(`${this.props.id}-icon`).image=$image(this.icon[1]),$(`${this.props.id}-icon`).tintColor=$color("systemLink"),$(`${this.props.id}-title`).textColor=$color("systemLink"),this.activeStatus=!0}inactive(){$(`${this.props.id}-icon`).image=$image(this.icon[0]),$(`${this.props.id}-icon`).tintColor=$color("lightGray"),$(`${this.props.id}-title`).textColor=$color("lightGray"),this.activeStatus=!1}getView(){return this.views=[{type:"image",props:{id:`${this.props.id}-icon`,image:$image(this.activeStatus?this.icon[1]:this.icon[0]),bgcolor:$color("clear"),tintColor:$color(this.activeStatus?"systemLink":"lightGray")},layout:(t,e)=>{t.centerX.equalTo(e.super);let i=I.tabBarHeight/2;t.size.equalTo(i),t.top.inset((I.tabBarHeight-i-13)/2)}},{type:"label",props:{id:`${this.props.id}-title`,text:this.title,font:$font(10),textColor:$color(this.activeStatus?"systemLink":"lightGray")},layout:(t,e)=>{t.centerX.equalTo(e.prev),t.top.equalTo(e.prev.bottom).offset(3)}}],this}},wt=class extends d{height=60;getView(){return this.type="view",this.setProp("bgcolor",this.props.bgcolor??h.primaryViewBackgroundColor),this.layout=(t,e)=>{t.left.right.bottom.equalTo(e.super),t.top.equalTo(e.super.safeAreaBottom).offset(-this.height-I.tabBarHeight)},this.views=[d.create({props:this.props,views:this.views,layout:(t,e)=>{t.left.right.top.equalTo(e.super),t.height.equalTo(this.height)}})],this}},I=class a extends v{static tabBarHeight=50;#t={};#e={};#i;#s;#o=$text.uuid;#r=$text.uuid;bottomSafeAreaInsets=$app.isDebugging?0:h.bottomSafeAreaInsets;get selected(){return this.#s}set selected(t){this.switchPageTo(t)}get contentOffset(){return a.tabBarHeight+(this.#i?.height??0)}setPages(t={}){return Object.keys(t).forEach(e=>this.setPage(e,t[e])),this}setPage(t,e){return this.#s===void 0&&(this.#s=t),e instanceof T?this.#t[t]=e:this.#t[t]=T.create(e),this.#s!==t&&(this.#t[t].activeStatus=!1),this}switchPageTo(t){if(this.#t[t]){if(this.#s===t)return;$ui.animate({duration:.4,animation:()=>{this.#e[t].active()}}),this.#e[this.#s].inactive(),this.#t[this.#s].hide(),this.#t[t].show(),this.callEvent("onChange",this.#s,t),this.#s=t,this.initBackground()}}hideBackground(t=!0){$(this.#r).hidden=!0,$ui.animate({duration:t?.2:1e-4,animation:()=>{$(this.#o).alpha=0}})}showBackground(t=!0){$(this.#r).hidden=!1,$ui.animate({duration:t?.2:1e-4,animation:()=>{$(this.#o).alpha=1}})}initBackground(){let t=this.#t[this.selected];t.scrollable&&$delay(0,()=>{let e=$(t.id).get(t.scrollableView.id),i=e.contentOffset.y;e.contentSize.height+this.bottomSafeAreaInsets-e.frame.height-i<=0?this.hideBackground(!1):this.showBackground(!1)})}setCells(t={}){return Object.keys(t).forEach(e=>this.setCell(e,t[e])),this}setCell(t,e){return this.#s===void 0&&(this.#s=t),e instanceof F||(e=new F({props:{info:{key:t}},icon:e.icon,title:e.title,activeStatus:this.#s===t})),this.#e[t]=e,this}setHeader(t){return this.#i=t,this}#a(){let t=[];return Object.values(this.#e).forEach(e=>{e.setEvent("tapped",i=>{let s=i.info.key;this.switchPageTo(s)}),t.push(e.getView())}),t}#n(){return Object.values(this.#t).map(t=>{if(t.scrollable){let e=t.scrollableView;if(e.props.indicatorInsets){let i=e.props.indicatorInsets;e.props.indicatorInsets=$insets(i.top,i.left,i.bottom+this.contentOffset,i.right)}else e.props.indicatorInsets=$insets(0,0,this.contentOffset,0);if(e.props.contentInset){let i=e.props.contentInset;e.props.contentInset=$insets(i.top,i.left,i.bottom+this.contentOffset,i.right)}else e.props.contentInset=$insets(0,0,this.contentOffset,0);typeof e.assignEvent=="function"&&e.assignEvent("didScroll",i=>{let s=i.contentOffset.y-this.contentOffset;i.contentSize.height+this.bottomSafeAreaInsets-i.frame.height-s<=1?this.hideBackground():this.showBackground()})}return t.definition})}generateView(){let t={type:"view",layout:(e,i)=>{e.centerX.equalTo(i.super),e.width.equalTo(i.super),e.top.equalTo(i.super.safeAreaBottom).offset(-a.tabBarHeight),e.bottom.equalTo(i.super)},views:[h.blurBox({id:this.#o}),{type:"stack",layout:$layout.fillSafeArea,props:{axis:$stackViewAxis.horizontal,distribution:$stackViewDistribution.fillEqually,spacing:0,stack:{views:this.#a()}}},h.separatorLine({id:this.#r},h.align.top)],events:{ready:()=>this.initBackground()}};return d.createFromViews(this.#n().concat(this.#i?.definition??[],t))}},T=class extends d{constructor(t={}){super(t),this.activeStatus=!0}show(){$(this.props.id).hidden=!1,this.activeStatus=!0}hide(){$(this.props.id).hidden=!0,this.activeStatus=!1}setHorizontalSafeArea(t){return this.horizontalSafeArea=t,this}#t(t,e){t.top.bottom.equalTo(e.super),this.horizontalSafeArea?t.left.right.equalTo(e.super.safeArea):t.left.right.equalTo(e.super)}getView(){return this.layout=this.#t,this.props.clipsToBounds=!0,this.props.hidden=!this.activeStatus,super.getView()}},$t=class extends w{#t;user;password;#e;namespace="JSBox.WebDAV";lockTokenCacheKey=this.namespace+".lockToken";get host(){return this.#t}set host(t){for(this.#t=t.trim();this.#t.endsWith("/");)this.#t=this.#t.substring(0,this.#t.length-1);this.#t.startsWith("http")||(this.#t="http://"+this.#t)}get basepath(){return this.#e}set basepath(t){for(this.#e=t.trim();this.#e.endsWith("/");)this.#e=this.#e.substring(0,this.#e.length-1);for(;this.#e.startsWith("/");)this.#e=this.#e.substring(1);this.#e="/"+this.#e}constructor({host:t,user:e,password:i,basepath:s=""}={}){super(),this.host=t,this.user=e,this.password=i,this.basepath=s}#i(t){return t=t.trim(),t=t.startsWith("/")?t:"/"+t,this.basepath+t}async request(t,e,i=null,s={}){return s=Object.assign({"Content-Type":"text/xml; charset=UTF-8",Authorization:"Basic "+$text.base64Encode(`${this.user}:${this.password}`)},s),await super.request(this.host+this.#i(t),e,i,s)}async allow(t){let e=await this.request(t,w.method.options);return(e.response.headers?.allow??e.response.headers?.Allow)?.split(",").map(s=>s.trim().toUpperCase())??[]}async propfind(t,e=[],i=0){Array.isArray(e)||(e=[e]);let o=`${e.map(n=>``).join()}`,r=await this.request(t,"PROPFIND",o,{Depth:i});return $xml.parse({string:r.data})}async propfindAll(t,e=0){let i='',s=await this.request(t,"PROPFIND",i,{Depth:e});return $xml.parse({string:s.data})}async ls(t,e=1){let i=await this.request(t,"PROPFIND",null,{Depth:e});return $xml.parse({string:i.data})}async exists(t){try{return(await this.allow(t)).includes(w.method.get)?await this.request(t,w.method.head):await this.ls(t,0),!0}catch(e){if(e?.code===404)return!1;throw e}}async mkdir(t){return await this.request(t,"MKCOL")}async get(t){return await this.request(t,w.method.get,null)}async put(t,e,{withLock:i=!0,waitInterval:s=2,maxTry:o=3}={}){let r={};for(;await this.isLocked(t);){if(--o<=0)throw new Error("Resource Locked");await $wait(s)}if(i)try{await this.lock(t),r.If=`(${this.#o(t)})`}catch(n){if(n.code!==404)throw n;i=!1}await this.request(t,w.method.put,e,r),i&&await this.unlock(t)}async delete(t){if(!t)throw new Error("path empty");return await this.request(t,w.method.delete)}#s(t,e){let i=$cache.get(this.lockTokenCacheKey)??{};i[t]=e,$cache.set(this.lockTokenCacheKey,i)}#o(t){return($cache.get(this.lockTokenCacheKey)??{})[t]}async isSupportLock(t){try{return!!(await this.propfind(t,"supportedlock")).rootElement.firstChild({xPath:"//D:response/D:propstat/D:prop/D:supportedlock/D:lockentry"}).firstChild({xPath:"//D:locktype/D:write"})}catch(e){if(e.code!==404)return!1;throw e}}async lock(t,{infinity:e=!1,timeout:i="Second-10"}={}){if(!await this.isSupportLock(t))throw new Error("Your WebDAV service does not support the `LOCK` method.");let o=`${this.namespace}`,r=await this.request(t,"LOCK",o,{Timeout:i,Depth:e?"infinity":0}),n=r.response.headers["lock-token"]??r.response.headers["Lock-Token"];return this.#s(t,n),$xml.parse({string:r.data})}async isLocked(t){try{let i=(await this.propfind(t,"lockdiscovery")).rootElement;if(!i.firstChild({xPath:"//D:response/D:propstat/D:status"}).string.includes("404")){let n=i.firstChild({xPath:"//D:response/D:propstat/D:prop/D:lockdiscovery"}).children()??[];for(let l=0;l= this.maxSize) {
34 | $cache.set(this.name, new Date().getTime())
35 | path = `${this.path}${$cache.get(this.name)}.log`
36 | file = undefined
37 | }
38 | let oldContent = file ? file.string : ""
39 | let content = `${new Date().toISOString()} [${level}] ${message}\n`
40 | $file.write({
41 | data: $data({ string: oldContent + content }),
42 | path: path
43 | })
44 | }
45 |
46 | info(message) {
47 | this.write(message, "INFO")
48 | }
49 |
50 | alert(message) {
51 | this.write(message, "ALERT")
52 | }
53 |
54 | error(message) {
55 | this.write(message, "ERROR")
56 | }
57 | }
58 |
59 | module.exports = Logger
60 |
--------------------------------------------------------------------------------
/scripts/libs/server.js:
--------------------------------------------------------------------------------
1 | const Logger = require("./logger")
2 |
3 | /**
4 | * @typedef {import("../app").AppKernel} AppKernel
5 | */
6 | class Server {
7 | /**
8 | * @param {AppKernel} kernel
9 | */
10 | constructor(kernel) {
11 | this.kernel = kernel
12 | this.setting = this.kernel.setting
13 |
14 | this.logger = new Logger(this.kernel.fileStorage.basePath)
15 |
16 | if (this.domain.startsWith("http")) {
17 | this.domain = this.domain.slice(this.domain.indexOf("//") + 2)
18 | }
19 | this.handler = {}
20 | this.server = $server.new()
21 | }
22 |
23 | get domain() {
24 | return this.setting.get("advanced.domain", "boxjs.net")
25 | }
26 |
27 | get port() {
28 | return this.setting.get("advanced.serverPort")
29 | }
30 |
31 | get timeout() {
32 | return this.setting.get("advanced.timeout", 3)
33 | }
34 |
35 | get logRequest() {
36 | return this.setting.get("server.logRequest")
37 | }
38 |
39 | startServer() {
40 | if (this.server.running) return
41 | if (!this.logRequest) {
42 | this.logger.disable()
43 | }
44 |
45 | this.server.addHandler(this.getHandler())
46 | let options = {
47 | port: this.port
48 | }
49 | this.server.start(options)
50 | this.logger.info("Server started.")
51 | // 访问地址
52 | this.serverURL = `http://localhost:${this.port}`
53 | if (this.server.serverURL) {
54 | this.remoteURL = this.server.serverURL.string
55 | if (this.remoteURL.lastIndexOf("/") === this.remoteURL.length - 1) {
56 | this.remoteURL = this.remoteURL.slice(0, -1)
57 | }
58 | } else {
59 | this.remoteURL = `http://${$device.wlanAddress}:${this.port}`
60 | }
61 | }
62 |
63 | stopServer() {
64 | this.server.stop()
65 | this.logger.info("Server stoped.")
66 | }
67 |
68 | reloadServer() {
69 | this.stopServer()
70 | this.startServer()
71 | }
72 |
73 | requestLogTemplate(request) {
74 | return `"${request.remoteAddress}" "${request.method}" "${request.path}"`
75 | }
76 |
77 | isLocalhost(request) {
78 | let reqHost = request.remoteAddress
79 | reqHost = reqHost.substring(0, reqHost.lastIndexOf(":"))
80 | const localhost = ["localhost", "::1", "127.0.0.1", $device.wlanAddress]
81 | return localhost.includes(reqHost)
82 | }
83 |
84 | async response(request) {
85 | let content = {}
86 |
87 | if (request.method === "POST") {
88 | let body = {}
89 | try {
90 | body = JSON.parse(request.data.string)
91 | } catch {}
92 | content = await $http.post({
93 | timeout: this.timeout,
94 | url: `http://${this.domain}${request.path}`,
95 | body: body
96 | })
97 | if (content.data === "") {
98 | content.data = {}
99 | }
100 | } else if (request.method === "GET") {
101 | content = await $http.get({
102 | timeout: this.timeout,
103 | url: `http://${this.domain}${request.path}`
104 | })
105 | } else if (request.method === "OPTIONS") {
106 | content = await $http.request({
107 | method: "OPTIONS",
108 | timeout: this.timeout,
109 | url: `http://${this.domain}${request.path}`
110 | })
111 | }
112 |
113 | // 检查结构
114 | let response = {
115 | statusCode: content?.response?.statusCode ?? 500
116 | }
117 | if (content.error) {
118 | const error = content.error
119 | response.text = error.localizedDescription
120 | this.logger.error(this.requestLogTemplate(request) + ` ${error.code}: ${error.localizedDescription}`)
121 | } else if (content.data && typeof content.data === "object") {
122 | response.json = content.data
123 | } else {
124 | response.html = content.data + ""
125 | }
126 | return response
127 | }
128 |
129 | async handle(request) {
130 | $delay(0, () => this.logger.info(this.requestLogTemplate(request)))
131 |
132 | let response = { statusCode: 401, hasBody: false }
133 | if (this.isLocalhost(request) || this.setting.get("server.remoteAccess")) {
134 | response = await this.response(request)
135 | }
136 | return response
137 | }
138 |
139 | getHandler() {
140 | this.handler.filter = () => {
141 | // 全部使用data
142 | return "data"
143 | }
144 | this.handler.asyncResponse = (request, completion) => {
145 | this.handle(request).then(response => {
146 | completion({
147 | type: "data",
148 | props: response
149 | })
150 | })
151 | }
152 | return this.handler
153 | }
154 | }
155 |
156 | module.exports = Server
157 |
--------------------------------------------------------------------------------
/scripts/ui/main/card.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @typedef {import("../../app").AppKernel} AppKernel
3 | */
4 |
5 | class CardBase {
6 | /**
7 | * @param {AppKernel} kernel
8 | */
9 | constructor(kernel) {
10 | this.kernel = kernel
11 | this.iCloud = this.kernel.iCloudPath("/BoxJsHepler")
12 | this.emptyList = {
13 | type: "label",
14 | layout: (make, view) => {
15 | make.centerX.equalTo(view.super)
16 | make.top.inset(20)
17 | },
18 | props: {
19 | id: "cardEmptyListTemplate",
20 | text: $l10n("EMPTY_LIST"),
21 | align: $align.center,
22 | color: $color("darkGray")
23 | }
24 | }
25 | }
26 | }
27 |
28 | module.exports = CardBase
29 |
--------------------------------------------------------------------------------
/scripts/ui/main/cards/backup.js:
--------------------------------------------------------------------------------
1 | const { UIKit } = require("../../../libs/easy-jsbox")
2 | const Card = require("../card")
3 |
4 | class BackupCard extends Card {
5 | constructor(kernel) {
6 | super(kernel)
7 | this.listId = "list-backup"
8 | this.backupStatus = {}
9 | if (!this.hasiCloud()) {
10 | $file.mkdir(this.iCloudPath())
11 | }
12 | }
13 |
14 | getiCloudId(id = "") {
15 | if (id.endsWith(".icloud")) {
16 | id = id.substring(1, id.length - 7)
17 | }
18 | return id
19 | }
20 |
21 | iCloudPath(id = "", cloud = false) {
22 | if (id.endsWith(".icloud")) {
23 | if (!cloud) {
24 | id = this.getiCloudId(id)
25 | }
26 | } else if (cloud) {
27 | return `${this.iCloud}/backup/.${id}.icloud`
28 | }
29 |
30 | return `${this.iCloud}/backup/${id}`
31 | }
32 |
33 | hasiCloud(id = "") {
34 | return $file.exists(this.iCloudPath(id)) || $file.exists(this.iCloudPath(id, true))
35 | }
36 |
37 | async hasBoxBackup(id = "") {
38 | const response = await $http.get({
39 | url: `${this.kernel.server.serverURL}/query/baks/${id}`
40 | })
41 | if (null !== response.error) {
42 | $ui.toast($l10n("ERROR_GET_DATA"))
43 | this.kernel.print(error)
44 | throw response.error
45 | }
46 | return response.data !== ""
47 | }
48 |
49 | async boxdata() {
50 | const response = await $http.get({
51 | url: `${this.kernel.server.serverURL}/query/boxdata`
52 | })
53 | if (null !== response.error) {
54 | $ui.toast($l10n("ERROR_GET_DATA"))
55 | this.kernel.print(error)
56 | throw response.error
57 | }
58 | return response.data
59 | }
60 |
61 | async updateList() {
62 | const list = []
63 | // boxdata
64 | const boxdata = await this.boxdata()
65 | const boxBackupMap = {}
66 | for (let item of boxdata.globalbaks) {
67 | list.push({
68 | id: { info: item.id },
69 | name: { text: item.name },
70 | tags: { text: item.tags.join(" ") },
71 | date: { text: new Date(item.createTime).toLocaleString() }
72 | })
73 | boxBackupMap[item.id] = true
74 | }
75 | // iCloud
76 | const files = $file.list(this.iCloudPath())
77 | files.forEach(fileName => {
78 | const id = this.getiCloudId(fileName)
79 | if (boxBackupMap[id]) {
80 | // 跳过已存在备份
81 | return
82 | }
83 | list.push({
84 | id: { info: id },
85 | name: { text: id },
86 | tags: { text: "iCloud" },
87 | date: { text: "" }
88 | })
89 | })
90 |
91 | $(this.listId).data = list
92 | $(this.emptyList.props.id).hidden = list.length > 0
93 | }
94 |
95 | recoverToBoxJs(id, name) {
96 | $ui.alert({
97 | title: `${$l10n("RECOVER_TO_BOXJS")}`,
98 | message: name,
99 | actions: [
100 | {
101 | title: $l10n("OK"),
102 | handler: () => {
103 | $ui.toast($l10n("LOADING"), 10000)
104 | $http.post({
105 | url: `${this.kernel.server.serverURL}/api/revertGlobalBak`,
106 | body: { id },
107 | handler: response => {
108 | let error
109 | if (null !== response.error) {
110 | error = response.error.localizedDescription
111 | } else if (response?.response?.statusCode >= 300) {
112 | error = response.data
113 | }
114 | if (error) {
115 | $ui.error(error)
116 | return false
117 | }
118 | $ui.success($l10n("SUCCESS_RECOVER"))
119 | }
120 | })
121 | }
122 | },
123 | { title: $l10n("CANCEL") }
124 | ]
125 | })
126 | }
127 |
128 | delete(id, name, callback) {
129 | $ui.alert({
130 | title: `${$l10n("DELETE")} ${name}`,
131 | message: `${$l10n("ALSO_DELETE_ICLOUD")}`,
132 | actions: [
133 | {
134 | title: $l10n("OK"),
135 | handler: () => {
136 | $http.post({
137 | url: `${this.kernel.server.serverURL}/api/delGlobalBak`,
138 | body: { id },
139 | handler: response => {
140 | if (null !== response.error) {
141 | $ui.toast($l10n("ERROR"))
142 | return false
143 | }
144 | // 删除 iCloud 文件
145 | if (this.hasiCloud(id)) {
146 | $file.delete(this.iCloudPath(id, false))
147 | }
148 | if (typeof callback === "function") {
149 | callback()
150 | }
151 | }
152 | })
153 | }
154 | },
155 | { title: $l10n("CANCEL") }
156 | ]
157 | })
158 | }
159 |
160 | async createBackup() {
161 | $ui.toast($l10n("LOADING"), 10000)
162 | try {
163 | const boxdata = await this.boxdata()
164 | const syscfgs = boxdata.syscfgs
165 | const response = await $http.post({
166 | url: `${this.kernel.server.serverURL}/api/saveGlobalBak`,
167 | body: {
168 | id: $text.uuid,
169 | createTime: new Date().toISOString(),
170 | name: `BoxJsHelper`,
171 | tags: ["BoxJsHelper", syscfgs.env, syscfgs.version, syscfgs.versionType],
172 | version: syscfgs.version,
173 | versionType: syscfgs.versionType,
174 | env: syscfgs.env
175 | }
176 | })
177 | if (null !== response.error) {
178 | $ui.toast($l10n("ERROE_BACKUP"))
179 | return
180 | }
181 | return response
182 | } catch (error) {
183 | throw error
184 | } finally {
185 | $ui.clearToast()
186 | }
187 | }
188 |
189 | async sync() {
190 | this.uploadToiCloud()
191 | await this.recoverAllFromiCloud()
192 | this.updateList()
193 | }
194 |
195 | async uploadToiCloud() {
196 | const data = await this.boxdata()
197 | const length = data.globalbaks.length
198 | if (length === 0) {
199 | return
200 | }
201 | let uploaded = 0
202 | let errorList = []
203 | data.globalbaks.forEach(backup => {
204 | // 文件存在则跳过
205 | if (this.hasiCloud(backup.id)) {
206 | uploaded++
207 | return
208 | }
209 | // 显示加载动画
210 | this.backupStatus[backup.id]?.loading(true)
211 | $http.get({
212 | url: `${this.kernel.server.serverURL}/query/baks/${backup.id}`,
213 | handler: response => {
214 | // 增加计数器
215 | uploaded++
216 | // 保存至 iCloud
217 | if (
218 | $file.write({
219 | data: $data({
220 | string: JSON.stringify({
221 | info: backup,
222 | data: response.data
223 | })
224 | }),
225 | path: this.iCloudPath(backup.id)
226 | })
227 | ) {
228 | $delay(0.3, () => {
229 | // 显示成功图标
230 | this.backupStatus[backup.id]?.ok()
231 | })
232 | } else {
233 | errorList.push(backup.name)
234 | }
235 | // 动作结束
236 | if (uploaded === length) {
237 | this.updateList()
238 | if (errorList.length > 0) {
239 | $ui.alert({
240 | title: $l10n("ERROE_BACKUP"),
241 | message: errorList.join("\n")
242 | })
243 | }
244 | }
245 | }
246 | })
247 | })
248 | }
249 |
250 | async recoverFromiCloud(id) {
251 | this.backupStatus[id].loading()
252 | await $wait(0.2) // 等待显示动画
253 | await $file.download(this.iCloudPath(id, true))
254 | const fileContent = $file.read(this.iCloudPath(id))
255 | const data = JSON.parse(fileContent?.string ?? "{}")
256 | // 添加新的备份到 BoxJs
257 | const response = await $http.post({
258 | url: `${this.kernel.server.serverURL}/api/impGlobalBak`,
259 | body: Object.assign(data.info, {
260 | bak: data.data
261 | })
262 | })
263 | if (null === response.error) {
264 | this.backupStatus[id].ok()
265 | }
266 | return response
267 | }
268 |
269 | async recoverAllFromiCloud() {
270 | await $wait(0.2) // 等待显示动画
271 | // 从 iCloud 恢复
272 | const files = $file.list(this.iCloudPath())
273 | const length = files.length
274 | if (length === 0) {
275 | return
276 | }
277 | let recovered = 0
278 | let errorList = []
279 | const backupMap = {}
280 | ;(await this.boxdata())?.globalbaks?.forEach(item => {
281 | backupMap[item.id] = item.name + " " + new Date(item.createTime).toLocaleString()
282 | })
283 | files.forEach(async id => {
284 | if (backupMap[id]) {
285 | // 跳过已存在备份
286 | recovered++
287 | return
288 | }
289 | const response = await this.recoverFromiCloud(id)
290 | if (null !== response.error) {
291 | errorList.push(backupMap[id])
292 | }
293 | recovered++
294 | // 控制行为
295 | if (recovered === length) {
296 | this.updateList()
297 | if (errorList.length > 0) {
298 | $ui.alert({
299 | title: $l10n("ERROE_BACKUP"),
300 | message: errorList.join("\n")
301 | })
302 | }
303 | }
304 | })
305 | }
306 |
307 | get listView() {
308 | return {
309 | type: "list",
310 | props: {
311 | rowHeight: 60,
312 | data: [],
313 | id: this.listId,
314 | template: {
315 | views: [
316 | {
317 | type: "label",
318 | props: {
319 | id: "id",
320 | hidden: true
321 | }
322 | },
323 | {
324 | type: "spinner",
325 | props: { loading: true },
326 | layout: make => {
327 | make.top.inset(10)
328 | make.right.inset(10)
329 | make.width.equalTo(25)
330 | }
331 | },
332 | // 同步状态 icon
333 | {
334 | type: "image",
335 | props: { hidden: true },
336 | layout: (make, view) => {
337 | make.width.equalTo(view.prev)
338 | make.top.inset(10)
339 | make.right.inset(10)
340 | },
341 | events: {
342 | ready: async sender => {
343 | const id = sender.super.get("id").info
344 | const loading = (loading = true) => {
345 | if (loading) {
346 | sender.prev.hidden = false
347 | sender.hidden = true
348 | } else {
349 | sender.prev.hidden = true
350 | sender.hidden = false
351 | }
352 | }
353 | this.backupStatus[id] = {
354 | loading: loading,
355 | ok: () => {
356 | loading(false)
357 | sender.symbol = "checkmark.icloud"
358 | },
359 | no: () => {
360 | loading(false)
361 | sender.symbol = "icloud.slash"
362 | },
363 | iCloud: () => {
364 | loading(false)
365 | sender.symbol = "icloud.and.arrow.down"
366 | }
367 | }
368 | if (!(await this.hasBoxBackup(id))) {
369 | this.backupStatus[id].iCloud()
370 | } else if (this.hasiCloud(id)) {
371 | this.backupStatus[id].ok()
372 | } else {
373 | this.backupStatus[id].no()
374 | }
375 | loading(false)
376 | }
377 | }
378 | },
379 | {
380 | type: "label",
381 | props: {
382 | id: "name",
383 | font: $font(18),
384 | align: $align.left
385 | },
386 | layout: (make, view) => {
387 | make.top.inset(10)
388 | make.left.inset(10)
389 | make.right.equalTo(view.prev.left)
390 | }
391 | },
392 | {
393 | type: "label",
394 | props: {
395 | id: "tags",
396 | font: $font(14),
397 | textColor: $color({
398 | light: "#C0C0C0",
399 | dark: "#545454"
400 | }),
401 | align: $align.left
402 | },
403 | layout: make => {
404 | make.bottom.inset(5)
405 | make.left.inset(10)
406 | }
407 | },
408 | {
409 | type: "label",
410 | props: {
411 | id: "date",
412 | font: $font(14),
413 | textColor: $color({
414 | light: "#C0C0C0",
415 | dark: "#545454"
416 | }),
417 | align: $align.right
418 | },
419 | layout: make => {
420 | make.bottom.inset(5)
421 | make.right.inset(10)
422 | }
423 | }
424 | ]
425 | },
426 | actions: [
427 | {
428 | title: " " + $l10n("DELETE") + " ", // 加空格防止被检测为默认的删除行为
429 | color: $color("red"),
430 | handler: (sender, indexPath) => {
431 | const id = sender.object(indexPath).id.info
432 | const name = sender.object(indexPath).name.text
433 | this.delete(id, name, async () => {
434 | sender.delete(indexPath)
435 | await $wait(0.3)
436 | this.updateList()
437 | })
438 | }
439 | }
440 | ]
441 | },
442 | events: {
443 | pulled: async sender => {
444 | await this.sync()
445 | sender.endRefreshing()
446 | },
447 | didSelect: async (sender, indexPath) => {
448 | const id = sender.object(indexPath).id.info
449 | if (!(await this.hasBoxBackup(id))) {
450 | await this.recoverFromiCloud(id)
451 | this.updateList()
452 | return
453 | }
454 | const name = sender.object(indexPath).name.text
455 | this.recoverToBoxJs(id, name)
456 | },
457 | ready: sender => {
458 | // 加载数据
459 | this.updateList()
460 | }
461 | },
462 | layout: $layout.fillSafeArea
463 | }
464 | }
465 |
466 | card() {
467 | return {
468 | icon: { symbol: "icloud.circle" },
469 | title: { text: $l10n("BACKUP") },
470 | events: {
471 | tapped: () => {
472 | UIKit.push({
473 | title: $l10n("BACKUP"),
474 | views: [this.listView, this.emptyList],
475 | navButtons: [
476 | {
477 | symbol: "plus",
478 | handler: async () => {
479 | await this.createBackup()
480 | await this.updateList()
481 | await this.uploadToiCloud()
482 | }
483 | }
484 | ]
485 | })
486 | }
487 | }
488 | }
489 | }
490 | }
491 |
492 | module.exports = BackupCard
493 |
--------------------------------------------------------------------------------
/scripts/ui/main/cards/log.js:
--------------------------------------------------------------------------------
1 | const { UIKit } = require("../../../libs/easy-jsbox")
2 | const Card = require("../card")
3 |
4 | class LogCard extends Card {
5 | card() {
6 | return {
7 | icon: { symbol: "doc.circle" },
8 | title: { text: $l10n("LOG") },
9 | extra: {
10 | type: "switch",
11 | props: { on: this.kernel.setting.get("server.logRequest") },
12 | events: {
13 | changed: sender => {
14 | if (sender.on) {
15 | this.kernel.setting.set("server.logRequest", true)
16 | } else {
17 | this.kernel.setting.set("server.logRequest", false)
18 | }
19 | }
20 | }
21 | },
22 | events: {
23 | tapped: () => {
24 | let logPath = this.kernel.server.logger?.path
25 | const logListTemplate = path => {
26 | let files = $file.list(path) ?? []
27 | let dataTemplate = []
28 | for (let file of files) {
29 | dataTemplate.push({ label: { text: file } })
30 | }
31 | return dataTemplate
32 | }
33 | const data = logListTemplate(logPath)
34 | UIKit.push({
35 | views: [data.length === 0 ? this.emptyList : {
36 | type: "list",
37 | props: {
38 | data: data,
39 | id: "list-log",
40 | template: [
41 | {
42 | type: "label",
43 | props: {
44 | id: "label",
45 | textColor: $color("primaryText", "secondaryText")
46 | },
47 | layout: (make, view) => {
48 | make.left.inset(10)
49 | make.centerY.equalTo(view.super)
50 | }
51 | }
52 | ],
53 | actions: [
54 | {
55 | title: " " + $l10n("DELETE") + " ",
56 | color: $color("red"),
57 | handler: (sender, indexPath) => {
58 | let file = sender.object(indexPath).label.text
59 | $file.delete(logPath + file)
60 | sender.delete(indexPath)
61 | }
62 | }
63 | ]
64 | },
65 | events: {
66 | didSelect: (sender, indexPath, data) => {
67 | UIKit.push({
68 | views: [{
69 | type: "code",
70 | props: {
71 | editable: false,
72 | accessoryView: {},
73 | text: $file.read(logPath + data.label.text).string
74 | },
75 | layout: $layout.fillSafeArea
76 | }],
77 | title: $l10n("LOG")
78 | })
79 | }
80 | },
81 | layout: $layout.fillSafeArea
82 | }],
83 | title: $l10n("LOG"),
84 | navButtons: [
85 | {
86 | symbol: "trash",
87 | handler: () => {
88 | $ui.alert({
89 | title: $l10n("ALERT_INFO"),
90 | message: $l10n("CLEAR_LOG_MSG"),
91 | actions: [
92 | {
93 | title: $l10n("OK"),
94 | handler: () => {
95 | $file.delete(logPath)
96 | $file.mkdir(logPath)
97 | $("list-log").data = logListTemplate(logPath)
98 | }
99 | },
100 | { title: $l10n("CANCEL") }
101 | ]
102 | })
103 | }
104 | }
105 | ]
106 | })
107 | }
108 | }
109 | }
110 | }
111 | }
112 |
113 | module.exports = LogCard
--------------------------------------------------------------------------------
/scripts/ui/main/cards/remote-access.js:
--------------------------------------------------------------------------------
1 | const Card = require("../card")
2 |
3 | class RemoteAccessCard extends Card {
4 | card() {
5 | return {
6 | icon: { symbol: "paperplane.circle" },
7 | title: { text: $l10n("REMOTE_ACCESS") },
8 | extra: {
9 | type: "switch",
10 | props: { on: this.kernel.setting.get("server.remoteAccess") },
11 | events: {
12 | changed: sender => {
13 | if (sender.on) {
14 | this.kernel.setting.set("server.remoteAccess", true)
15 | $ui.toast($l10n("REMOTE_ACCESS_STARTED"))
16 | } else {
17 | this.kernel.setting.set("server.remoteAccess", false)
18 | $ui.toast($l10n("REMOTE_ACCESS_CLOSED"))
19 | }
20 | }
21 | }
22 | },
23 | events: {
24 | tapped: () => {
25 | $ui.alert(this.kernel.server.remoteURL)
26 | }
27 | }
28 | }
29 | }
30 | }
31 |
32 | module.exports = RemoteAccessCard
--------------------------------------------------------------------------------
/scripts/ui/main/cards/today.js:
--------------------------------------------------------------------------------
1 | const { UIKit } = require("../../../libs/easy-jsbox")
2 | const Card = require("../card")
3 |
4 | class TodayCard extends Card {
5 | constructor(kernel) {
6 | super(kernel)
7 | this.todayPath = "/assets/today/"
8 | }
9 |
10 | editor(name, content, callback) {
11 | UIKit.push({
12 | views: [
13 | {
14 | type: "code",
15 | props: {
16 | id: "editor",
17 | language: "javascript",
18 | lineNumbers: true,
19 | theme: $device.isDarkMode ? "atom-one-dark" : "atom-one-light",
20 | info: name,
21 | text: content
22 | },
23 | layout: (make, view) => {
24 | make.left.right.bottom.equalTo(view.super.safeArea)
25 | make.top.equalTo(view.super)
26 | }
27 | }
28 | ],
29 | title: $l10n("EDIT"),
30 | navButtons: [
31 | {
32 | symbol: "checkmark",
33 | handler: () => {
34 | let editor = $("editor")
35 | this.saveScript(editor.info, editor.text)
36 | $ui.toast($l10n("SUCCESS_SAVE"))
37 | setTimeout(() => {
38 | $ui.pop()
39 | callback()
40 | }, 600)
41 | }
42 | }
43 | ]
44 | })
45 | }
46 |
47 | saveScript(name, content) {
48 | if (name.slice(-3) !== ".js") {
49 | name = name + ".js"
50 | }
51 | if (name[0] === "/") {
52 | name = name.slice(1)
53 | }
54 | $file.write({
55 | data: $data({ string: content }),
56 | path: this.todayPath + name
57 | })
58 | }
59 |
60 | card() {
61 | return {
62 | icon: { symbol: "calendar.circle" },
63 | title: { text: $l10n("TODAY") },
64 | events: {
65 | tapped: () => {
66 | const scriptName = () => {
67 | let script = this.kernel.setting.get("today.script")
68 | script = script.slice(script.lastIndexOf("/") + 1)
69 | return script
70 | }
71 | const scriptTemplate = () => {
72 | const files = $file.list(this.todayPath)
73 | let dataTemplate = []
74 | for (let i = 0; i < files.length; i++) {
75 | dataTemplate.push({ label: { text: files[i] } })
76 | }
77 | return dataTemplate
78 | }
79 | const data = scriptTemplate()
80 | UIKit.push({
81 | views: [data.length === 0 ? this.emptyList : {
82 | type: "list",
83 | props: {
84 | id: "list-script",
85 | data: data,
86 | template: [
87 | {
88 | type: "label",
89 | props: {
90 | id: "label",
91 | textColor: $color("primaryText", "secondaryText")
92 | },
93 | layout: (make, view) => {
94 | make.left.inset(10)
95 | make.centerY.equalTo(view.super)
96 | }
97 | }
98 | ],
99 | actions: [
100 | { // delete
101 | title: $l10n("DELETE"),
102 | color: $color("red"),
103 | handler: (sender, indexPath) => {
104 | let name = sender.object(indexPath).label.text
105 | $ui.alert({
106 | title: $l10n("ALERT_INFO"),
107 | message: `${$l10n("DELETE")} ${name} ?`,
108 | actions: [
109 | {
110 | title: $l10n("OK"),
111 | handler: () => {
112 | let file = sender.object(indexPath).label.text
113 | $file.delete(this.todayPath + file)
114 | sender.delete(indexPath)
115 | }
116 | },
117 | { title: $l10n("CANCEL") }
118 | ]
119 | })
120 | }
121 | },
122 | { // apply
123 | title: $l10n("APPLY"),
124 | color: $color("orange"),
125 | handler: (sender, indexPath) => {
126 | let script = this.todayPath + sender.object(indexPath).label.text.trim()
127 | this.kernel.setting.set("today.script", script)
128 | $("selected-script").text = scriptName()
129 | }
130 | }
131 | ]
132 | },
133 | events: {
134 | didSelect: (sender, indexPath, data) => {
135 | this.editor(data.label.text,
136 | $file.read(this.todayPath + data.label.text).string,
137 | () => {
138 | setTimeout(() => {
139 | // 更新列表
140 | $("list-script").data = scriptTemplate()
141 | }, 500)
142 | }
143 | )
144 | }
145 | },
146 | layout: $layout.fillSafeArea
147 | }],
148 | title: $l10n("TODAY"),
149 | navButtons: [
150 | // 新脚本
151 | {
152 | symbol: "plus",
153 | handler: () => {
154 | $ui.menu({
155 | items: [$l10n("NEW_FILE"), $l10n("URL")],
156 | handler: (title, idx) => {
157 | if (idx === 0) {
158 | $input.text({
159 | type: $kbType.default,
160 | text: "MyScript",
161 | placeholder: $l10n("FILE_NAME"),
162 | handler: text => {
163 | this.editor(text, "", () => {
164 | setTimeout(() => {
165 | // 更新列表
166 | $("list-script").data = scriptTemplate()
167 | }, 500)
168 | })
169 | }
170 | })
171 | } else if (idx === 1) {
172 | $input.text({
173 | type: $kbType.url,
174 | placeholder: $l10n("URL"),
175 | handler: text => {
176 | $http.get({
177 | url: text,
178 | handler: response => {
179 | let name = text.slice(text.lastIndexOf("/") + 1)
180 | this.saveScript(name, response.data + "")
181 | $("list-script").data = scriptTemplate()
182 | }
183 | })
184 | }
185 | })
186 | }
187 | }
188 | })
189 | }
190 | },
191 | // 备份脚本
192 | {
193 | symbol: "cloud",
194 | handler: () => {
195 | $ui.menu({
196 | items: [$l10n("UPLOAD_TO_ICLOUD"), $l10n("REVERT_FROM_ICLOUD")],
197 | handler: (title, idx) => {
198 | if (idx === 0) { // 备份
199 | // 备份文件
200 | let dst = this.iCloud + "Today"
201 | if (!$file.exists(dst)) {
202 | $file.mkdir(dst)
203 | }
204 | $file.copy({
205 | src: this.todayPath,
206 | dst: dst
207 | })
208 | } else if (idx === 1) { // 恢复
209 | // 恢复文件
210 | if (!$file.exists(this.todayPath)) {
211 | $file.mkdir(this.todayPath)
212 | }
213 | $file.copy({
214 | src: this.iCloud + "Today",
215 | dst: this.todayPath
216 | })
217 | $("list-script").data = scriptTemplate()
218 | }
219 | }
220 | })
221 | }
222 | }
223 | ]
224 | })
225 | }
226 | }
227 | }
228 | }
229 | }
230 |
231 | module.exports = TodayCard
--------------------------------------------------------------------------------
/scripts/ui/main/home.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @typedef {import("../../app").AppKernel} AppKernel
3 | */
4 |
5 | class HomeUI {
6 | /**
7 | * @param {AppKernel} kernel
8 | */
9 | constructor(kernel) {
10 | this.kernel = kernel
11 | // 开启服务器并记录访问url
12 | this.kernel.server.startServer()
13 | }
14 |
15 | static refresh() {
16 | $("web-boxjs").reload()
17 | $ui.toast($l10n("REFRESH_SUCCESS"))
18 | }
19 |
20 | getView() {
21 | return {
22 | type: "web",
23 | props: {
24 | allowsNavigation: true,
25 | id: "web-boxjs",
26 | url: this.kernel.server.serverURL,
27 | opaque: false
28 | },
29 | layout: $layout.fill
30 | }
31 | }
32 | }
33 |
34 | module.exports = HomeUI
35 |
--------------------------------------------------------------------------------
/scripts/ui/main/matrix.js:
--------------------------------------------------------------------------------
1 | class Matrix {
2 | constructor() {
3 | this.indexFlag = 1
4 | this.height = 90
5 | this.spacing = 15
6 | this.columns = 2
7 | this.id = "Matrix"
8 | this.contentViewId = this.id + "Content"
9 | }
10 |
11 | getWidth() {
12 | this.width = $device.info.screen.width / this.columns
13 | this.width = this.width - (this.spacing * (this.columns + 1)) / this.columns
14 | return this.width
15 | }
16 |
17 | cardTemplate(views, events) {
18 | return {
19 | type: "view",
20 | props: {
21 | bgcolor: $color("tertiarySurface"),
22 | cornerRadius: 10
23 | },
24 | layout: (make, view) => {
25 | make.width
26 | .equalTo(view.super.width)
27 | .multipliedBy(1 / this.columns)
28 | // this.spacing / this.columns 是应为最后一个块右侧边距为0,需要所有块均摊最后一个块右侧边距
29 | .offset(-this.spacing - this.spacing / this.columns)
30 | make.height.equalTo(this.height)
31 | // 边距控制
32 | if (this.indexFlag === 1) {
33 | make.left.inset(this.spacing)
34 | if (!view.prev) {
35 | make.top.equalTo(view.super).offset(this.spacing)
36 | } else {
37 | make.top.equalTo(view.prev).offset(this.height + this.spacing)
38 | }
39 | } else {
40 | make.left.equalTo(view.prev.right).offset(this.spacing)
41 | make.top.equalTo(view.prev)
42 | }
43 | this.indexFlag === this.columns ? (this.indexFlag = 1) : this.indexFlag++
44 | },
45 | views: views,
46 | events: events
47 | }
48 | }
49 |
50 | scrollTemplate(data, bottomOffset = this.spacing) {
51 | // 计算尺寸
52 | const line = Math.ceil(data.length / this.columns)
53 | const height = line * (this.height + this.spacing) + bottomOffset
54 | return {
55 | type: "scroll",
56 | props: {
57 | id: this.id,
58 | bgcolor: $color("insetGroupedBackground"),
59 | scrollEnabled: true,
60 | indicatorInsets: $insets(this.spacing, 0, 50, 0),
61 | contentSize: $size(0, height)
62 | },
63 | layout: (make, view) => {
64 | make.left.right.equalTo(view.super.safeArea)
65 | make.bottom.inset(0)
66 | view.prev ? make.top.equalTo(view.prev).offset(50) : make.top.inset(0)
67 | },
68 | events: {
69 | layoutSubviews: () => {
70 | const addView = () => {
71 | // 重置变量
72 | this.indexFlag = 1
73 | // 插入视图
74 | if ($(this.contentViewId)) $(this.contentViewId).remove()
75 | $(this.id).add({
76 | type: "view",
77 | props: { id: this.contentViewId },
78 | views: data,
79 | layout: (make, view) => {
80 | make.size.equalTo(view.super)
81 | }
82 | })
83 | }
84 | if (!this.orientation) {
85 | this.orientation = $device.info.screen.orientation
86 | addView()
87 | return
88 | }
89 | if (this.orientation !== $device.info.screen.orientation) {
90 | this.orientation = $device.info.screen.orientation
91 | addView()
92 | }
93 | }
94 | }
95 | }
96 | }
97 | }
98 |
99 | module.exports = {
100 | VERSION: "1.0.0",
101 | Matrix
102 | }
103 |
--------------------------------------------------------------------------------
/scripts/ui/main/toolbox.js:
--------------------------------------------------------------------------------
1 | const { UIKit } = require("../../libs/easy-jsbox")
2 | const { Matrix } = require("./matrix")
3 |
4 | class ToolboxUI {
5 | constructor(kernel) {
6 | this.kernel = kernel
7 | this.matrix = new Matrix()
8 | this.matrix.columns = 2
9 | this.matrix.height = 90
10 | this.matrix.spacing = 15
11 | this.cards = []
12 | }
13 |
14 | loadCards() {
15 | const cards = $file.list("scripts/ui/main/cards")
16 | cards.forEach(card => {
17 | const Card = require(`./cards/${card}`)
18 | this.cards.push(new Card(this.kernel).card())
19 | })
20 | }
21 |
22 | /**
23 | * 卡片内容样式
24 | * @param {*} data
25 | */
26 | template(data) {
27 | let views = [
28 | {
29 | type: "image",
30 | props: Object.assign(
31 | {
32 | tintColor: UIKit.textColor
33 | },
34 | data.icon
35 | ),
36 | layout: make => {
37 | make.top.left.inset(10)
38 | make.size.equalTo(35)
39 | }
40 | },
41 | {
42 | type: "label",
43 | props: Object.assign(
44 | {
45 | font: $font(18),
46 | textColor: $color("primaryText", "secondaryText")
47 | },
48 | data.title
49 | ),
50 | layout: make => {
51 | make.bottom.left.inset(10)
52 | }
53 | }
54 | ]
55 | if (data.extra) {
56 | views.push({
57 | type: data.extra.type,
58 | props: Object.assign({}, data.extra.props),
59 | events: data.extra.events,
60 | layout: make => {
61 | make.right.top.inset(10)
62 | make.height.equalTo(30)
63 | }
64 | })
65 | }
66 | return views
67 | }
68 |
69 | cardTemplate() {
70 | // TODO 排序
71 | let data = []
72 | for (let i = 0; i < this.cards.length; i++) {
73 | let card = this.cards[i]
74 | data[i] = this.matrix.cardTemplate(this.template(card), card["events"])
75 | }
76 | return data
77 | }
78 |
79 | getView() {
80 | this.loadCards()
81 | return this.matrix.scrollTemplate(this.cardTemplate())
82 | }
83 | }
84 |
85 | module.exports = ToolboxUI
86 |
--------------------------------------------------------------------------------
/scripts/ui/today/today.js:
--------------------------------------------------------------------------------
1 | class TodayUI {
2 | constructor(kernel) {
3 | this.kernel = kernel
4 | }
5 |
6 | render() {
7 | // 加载脚本
8 | let script = this.kernel.setting.get("today.script")
9 | if (script === "" || !$file.exists(script)) {
10 | $ui.alert($l10n("NO_SCRIPT"))
11 | } else {
12 | require(script).main(async () => {
13 | // 获取boxdata
14 | let response = await $http.get(`http://boxjs.net/query/boxdata`)
15 | if (response.error !== null) {
16 | let message = response.error
17 | if (typeof message === "object") {
18 | message = JSON.stringify(message)
19 | }
20 | $ui.toast(`${$l10n("GET_BOXJS_DATA_ERROR")} ${message}`)
21 | return
22 | }
23 | return response.data
24 | })
25 | }
26 | }
27 | }
28 |
29 | module.exports = TodayUI
--------------------------------------------------------------------------------
/setting.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "title": "BoxJs",
4 | "items": [
5 | {
6 | "icon": ["tag.fill", "#9B59B6"],
7 | "title": "TIPS",
8 | "type": "script",
9 | "key": "boxjs.tips",
10 | "value": "this.method.tips"
11 | },
12 | {
13 | "icon": ["location.fill", "#FF9900"],
14 | "title": "DOMAIN",
15 | "type": "input",
16 | "key": "advanced.domain",
17 | "value": "boxjs.net"
18 | },
19 | {
20 | "icon": ["wifi.slash"],
21 | "title": "TIMEOUT",
22 | "type": "number",
23 | "key": "advanced.timeout",
24 | "value": 3
25 | }
26 | ]
27 | },
28 | {
29 | "title": "REMOTE_ACCESS",
30 | "items": [
31 | {
32 | "icon": ["dot.radiowaves.right", "#3498DB"],
33 | "title": "PORT",
34 | "type": "number",
35 | "key": "advanced.serverPort",
36 | "value": 6060
37 | },
38 | {
39 | "key": "server.remoteAccess",
40 | "value": false
41 | },
42 | {
43 | "key": "server.logRequest",
44 | "value": false
45 | },
46 | {
47 | "key": "today.script",
48 | "value": ""
49 | }
50 | ]
51 | },
52 | {
53 | "title": "ABOUT",
54 | "items": [
55 | {
56 | "icon": ["icon_177", "black"],
57 | "title": "Github",
58 | "type": "info",
59 | "value": ["ipuppet/BoxJsHelper", "https://github.com/ipuppet/BoxJsHelper"]
60 | },
61 | {
62 | "icon": ["icon_172", "#1888bf"],
63 | "title": "Telegram",
64 | "type": "info",
65 | "value": ["JSBoxTG", "https://t.me/JSBoxTG"]
66 | },
67 | {
68 | "icon": ["person.fill", "#FF9900"],
69 | "title": "AUTHOR",
70 | "type": "info",
71 | "value": ["ipuppet", "https://blog.ultagic.com"]
72 | },
73 | {
74 | "icon": ["book.fill", "#A569BD"],
75 | "title": "README",
76 | "type": "script",
77 | "value": "this.method.readme"
78 | }
79 | ]
80 | }
81 | ]
82 |
--------------------------------------------------------------------------------
/strings/en.strings:
--------------------------------------------------------------------------------
1 | "LOADING" = "Loading...";
2 | "ALERT_INFO" = "Info";
3 | "SUCCESS" = "Success";
4 | "ERROR" = "Error";
5 | "INVALID_VALUE" = "Invalid value";
6 | "OK" = "OK";
7 | "CANCEL" = "Cancel";
8 | "BACK" = "Back";
9 | "COPY" = "Copy";
10 | "COPY_SUCCESS" = "Copy successfully";
11 | "EMPTY_LIST" = "List is empty";
12 |
13 | "GET_BOXJS_DATA_ERROR" = "Failed to get data from BoxJs";
14 | "NO_TODAY_CACHE" = "Failed to obtain data, please open the Today card in the toolbox and click the refresh button";
15 | "NO_SCRIPT" = "No script is selected or the script is deleted, please select the script in the toolbox";
16 |
17 | "BOXJS" = "BoxJs";
18 |
19 | "TOOLBOX" = "Toolbox";
20 | "REFRESH" = "Refresh";
21 | "REFRESH_SUCCESS" = "Refresh successfully";
22 | "REMOTE_ACCESS" = "Remote Access";
23 | "REMOTE_ACCESS_CLOSED" = "Remote access is off";
24 | "REMOTE_ACCESS_STARTED" = "Remote access is on";
25 | "LOG" = "Log";
26 | "CLEAR_LOG" = "Clean up the log";
27 | "CLEAR_LOG_MSG" = "Are you sure you want to clear all logs?";
28 | "BACKUP" = "Backup";
29 | "UPLOAD_TO_ICLOUD" = "Upload to iCloud";
30 | "NOTHING_HAPPENS" = "Nothing happens";
31 | "UPLOAD_TO_ICLOUD_ALERT" = "If the list is empty, a backup will be created automatically.\nFiles with the same name in iCloud will be skipped.";
32 | "ALSO_DELETE_ICLOUD" = "This operation will also delete iCloud file.";
33 | "ERROR_GET_DATA" = "Error while fetching data";
34 | "ERROE_BACKUP" = "An error occurred while making the backup";
35 | "SUCCESS_BACKUP" = "Backup successfully";
36 | "REVERT_FROM_ICLOUD" = "Recover from iCloud";
37 | "RECOVER_TO_BOXJS" = "Recover to BoxJs";
38 | "SUCCESS_RECOVER" = "Recover successfully";
39 | "DELETE" = "Delete";
40 | "TODAY" = "Today Widget";
41 | "SELECTED_SCRIPT" = "Selected script";
42 | "NO_SCRIPT_FROM_URL" = "No script";
43 | "UPDATE_ALL_SCRIPT" = "Update all scripts?";
44 | "UPDATE" = "Update all?";
45 | "URL" = "From URL";
46 | "NEW_FILE" = "New flie";
47 | "FILE_NAME" = "File name";
48 | "EDIT" = "Edit";
49 | "APPLY" = "Apply";
50 | "SUCCESS_SAVE" = "Saved";
51 |
52 | "ADVANCED" = "Advanced";
53 | "DOMAIN" = "Access Domain";
54 | "TIMEOUT" = "Timeout (s)";
55 | "PORT" = "Port";
--------------------------------------------------------------------------------
/strings/zh-Hans.strings:
--------------------------------------------------------------------------------
1 | "LOADING" = "加载中...";
2 | "ALERT_INFO" = "提示";
3 | "SUCCESS" = "成功";
4 | "ERROR" = "发生错误";
5 | "INVALID_VALUE" = "该值无效";
6 | "OK" = "好";
7 | "CANCEL" = "取消";
8 | "BACK" = "返回";
9 | "COPY" = "复制";
10 | "COPY_SUCCESS" = "复制成功";
11 | "EMPTY_LIST" = "列表为空";
12 |
13 | "GET_BOXJS_DATA_ERROR" = "从 BoxJs 获取数据失败";
14 | "NO_TODAY_CACHE" = "获取数据失败,请打开工具箱中的 Today 卡片,点击刷新按钮";
15 | "NO_SCRIPT" = "未选择脚本或脚本被删除,请在工具箱中选择脚本";
16 |
17 | "BOXJS" = "BoxJs";
18 |
19 | "TOOLBOX" = "工具箱";
20 | "REFRESH" = "刷新";
21 | "REFRESH_SUCCESS" = "刷新成功";
22 | "REMOTE_ACCESS" = "远程访问";
23 | "REMOTE_ACCESS_CLOSED" = "远程访问已关闭";
24 | "REMOTE_ACCESS_STARTED" = "远程访问已开启";
25 | "LOG" = "日志";
26 | "CLEAR_LOG" = "清理日志";
27 | "CLEAR_LOG_MSG" = "确认要清除所有日志吗?";
28 | "BACKUP" = "备份";
29 | "UPLOAD_TO_ICLOUD" = "上传至 iCloud";
30 | "NOTHING_HAPPENS" = "无事发生";
31 | "UPLOAD_TO_ICLOUD_ALERT" = "若列表为空则会自动创建一份备份\n会跳过 iCloud 内同名文件";
32 | "ALSO_DELETE_ICLOUD" = "该操作也会删除 iCloud 文件";
33 | "ERROR_GET_DATA" = "获取数据时出错";
34 | "ERROE_BACKUP" = "制作备份时出错";
35 | "SUCCESS_BACKUP" = "备份成功";
36 | "REVERT_FROM_ICLOUD" = "从 iCloud 恢复备份";
37 | "RECOVER_TO_BOXJS" = "恢复至 BoxJs";
38 | "SUCCESS_RECOVER" = "恢复成功";
39 | "DELETE" = "删除";
40 | "TODAY" = "Today 小组件";
41 | "SELECTED_SCRIPT" = "选中的脚本";
42 | "NO_SCRIPT_FROM_URL" = "没有从 URL 获取的脚本";
43 | "UPDATE_ALL_SCRIPT" = "更新所有脚本?";
44 | "UPDATE" = "更新所有脚本?";
45 | "URL" = "从 URL 添加";
46 | "NEW_FILE" = "新建文件";
47 | "FILE_NAME" = "文件名称";
48 | "EDIT" = "编辑";
49 | "APPLY" = "应用";
50 | "SUCCESS_SAVE" = "保存成功";
51 |
52 | "ADVANCED" = "高级";
53 | "DOMAIN" = "访问入口";
54 | "TIMEOUT" = "超时时间 (s)";
55 | "PORT" = "端口";
--------------------------------------------------------------------------------