├── LICENSE
├── README.md
├── images
├── 1-title-dark.JPG
├── 1-title-light.JPG
├── 10-star-debug-dark.JPG
├── 10-star-debug-light.JPG
├── 11-festive-dark.JPG
├── 11-festive-light.JPG
├── 12-hacker-dark.JPG
├── 12-hacker-light.JPG
├── 13-custom-spooky-broken.JPG
├── 13-custom-spooky-dark.JPG
├── 13-custom-spooky-light.JPG
├── 14-custom-festive-broken.JPG
├── 14-custom-festive-dark.JPG
├── 14-custom-festive-light.JPG
├── 15-custom-stencil-broken.JPG
├── 15-custom-stencil-dark.JPG
├── 15-custom-stencil-light.JPG
├── 16-blurry-dark.JPG
├── 16-blurry-light.JPG
├── 17-celestial-background.PNG
├── 18-festive-background.PNG
├── 2-250x250-dark.JPG
├── 2-250x250-light.JPG
├── 3-530x250-dark.JPG
├── 3-530x250-light.JPG
├── 4-200x600-dark.JPG
├── 4-200x600-light.JPG
├── 5-debug-dark.JPG
├── 5-debug-light.JPG
├── 6-grow-dark.JPG
├── 6-grow-light.JPG
├── 7-galaxy-dark.JPG
├── 7-galaxy-light.JPG
├── 8-galaxy-debug-dark.JPG
├── 8-galaxy-debug-light.JPG
├── 9-star-dark.JPG
├── 9-star-light.JPG
├── milky-way.HEIC
└── mountain.JPG
├── minification-instructions.md
├── minified-word-cloud.js
├── word-cloud-demo.js
└── word-cloud.js
/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 | # Dynamic Scriptable Word Cloud!
2 |
3 | 
4 |
5 | A set of classes that can create a word cloud image in the [Scriptable iOS app](https://scriptable.app/). Basic Usage:
6 | ```
7 | const wordCloudWords = [new WordCloudWord({word, weight}), ...]
8 | const wordCloud = new WordCloud({width, height, wordCloudWords});
9 | const image = await wordCloud.getImage();
10 | ```
11 |
12 | There are three word cloud scripts provided in this repo:
13 | | Script | Description |
14 | | --- | --- |
15 | | word-cloud.js | The full word cloud script that shows how everything works. |
16 | | minified-word-cloud.js | A minified version of the word cloud script that is significantly easier to build with. |
17 | | word-cloud-demo.js | An interactive demo that includes copy-pastable Scriptable scripts. |
18 |
19 | I recommend starting with the demo script or minified script. I only recommend using the full word-cloud.js script if you are experienced and are trying to modify how the word cloud itself works.
20 |
21 | ## Basic Input Parameters
22 |
23 | There are only three required fields: Width, Height, and WordCloudWords. WordCloudWords are objects with two properties: Word (string) and Weight (number). Here's an example of a WordCloudWords array:
24 | ```
25 | const wordCloudWords = [
26 | new WordCloudWord({ word: "Seattle", weight: 10 }),
27 | new WordCloudWord({ word: "Boston", weight: 10 }),
28 | new WordCloudWord({ word: "Chicago", weight: 8 }),
29 | new WordCloudWord({ word: "Denver", weight: 7 }),
30 | new WordCloudWord({ word: "Boise", weight: 7 }),
31 | new WordCloudWord({ word: "Los Angeles", weight: 7 }),
32 | new WordCloudWord({ word: "San Fransisco", weight: 6 }),
33 | new WordCloudWord({ word: "Victoria", weight: 6 }),
34 | new WordCloudWord({ word: "Portland", weight: 5 }),
35 | new WordCloudWord({ word: "London", weight: 5 }),
36 | new WordCloudWord({ word: "Dublin", weight: 3 }),
37 | new WordCloudWord({ word: "Barcelona", weight: 3 }),
38 | new WordCloudWord({ word: "Amsterdam", weight: 3 }),
39 | new WordCloudWord({ word: "Budapest", weight: 3 }),
40 | new WordCloudWord({ word: "Venice", weight: 3 }),
41 | new WordCloudWord({ word: "Florence", weight: 2 }),
42 | new WordCloudWord({ word: "Oslo", weight: 2 }),
43 | new WordCloudWord({ word: "Paris", weight: 2 }),
44 | new WordCloudWord({ word: "Tokyo", weight: 1 }),
45 | new WordCloudWord({ word: "New York", weight: 1 }),
46 | new WordCloudWord({ word: "Fort", weight: 1 })
47 | ];
48 | ```
49 |
50 | This object could be static or you could code something to generate it. I recommend calculating a word's weight by it's frequency in a dataset (Calendar events, weather, etc.), but you could use whatever you want!
51 |
52 | Next is Width and Height. These are pretty simple to work with. Here are some examples:
53 |
54 | | Dark Mode | Light Mode | Simplified Input |
55 | | --- | --- | --- |
56 | |  |  | `{ width: 250, height: 250 }` |
57 | |  |  | `{ width: 530, height: 250 }` |
58 |
59 |
60 | The word cloud is generated dynamically so it can fit different widget sizes. It will also work with weirder sizes like long ones. Get creative!
61 |
62 | | Dark Mode | Light Mode | Simplified Input |
63 | | --- | --- | --- |
64 | |  |  | `{ width: 200, height: 600 }` |
65 |
66 | The next sections will use the sample WordCloudWords object and a Width and Height of 250 each. Have fun!
67 |
68 | ## Flags!
69 | Now we get to the fun stuff. Here are some flags that you can pass in to modify the word cloud's behavior. When debug is set to true it will display the 'hitboxes' used in the placement algorithm for each word. it will also display the placement algorithm's path:
70 |
71 | | Dark Mode | Light Mode | Simplified Input |
72 | | --- | --- | --- |
73 | |  |  | `{ debug: true }` |
74 |
75 | The growToFit flag determines whether or not the canvas will 'grow' to fit all of the words provided. When set to true (default) it will continuously increase the size of the canvas until all of the provided words can be placed. If it is set to false it will simply try to place words as best it can:
76 |
77 | | Dark Mode | Light Mode | Simplified Input |
78 | | --- | --- | --- |
79 | |  |  | `{ growToFit: false }` |
80 |
81 | [The respectScreenScale flag is passed to the DrawContext](https://docs.scriptable.app/drawcontext/#respectscreenscale). If you are running into performance issues (for example, the script does not display on the homescreen) please try setting this to false. Until a performance update is made to the script you can also try removing words until it displays.
82 |
83 | | Dark Mode | Light Mode | Simplified Input |
84 | | --- | --- | --- |
85 | |  |  | `{ respectScreenScale: false }` |
86 |
87 | ## Placement Functions!
88 | Placement functions are plotting functions that return (x,y) coordinates. They are called continuously until all of the words can be plotted with their center on a coordinate (or there is no more space if growToFit is false). They can be confusing at first but they are very powerful. Before we get into it, here's an example:
89 |
90 | ```
91 | function spiralPlacementFunction(width, height, centerX, centerY, xRatio, yRatio, previousResult) {
92 | let radius, angle;
93 |
94 | if (previousResult) {
95 | ({ radius, angle } = previousResult);
96 | radius += .75;
97 | angle += (Math.PI * 2) / 50;
98 | } else {
99 | radius = 0;
100 | angle = 0;
101 | }
102 |
103 | const x = centerX + radius * Math.cos(angle) * xRatio;
104 | const y = centerY + radius * Math.sin(angle) * yRatio;
105 | return { x, y, radius, angle }
106 | }
107 | ```
108 |
109 | The inputs width, height, centerX, and centerY are pretty straightforward. xRatio and yRatio are the ratio of the side compared to the largest side and can be useful when scaling the algorithm for different input parameters. PreviousResult contains the results from the last iteration of the algorithm, which at a minimum includes the last x and y values. If it's helpful you can pass additional values in the result and use it in the next iteration, like radius and angle in the example.
110 |
111 | I recommend reading the example functions and modifying them to understand how they work. I also recommend googling some cool (x,y) plots and converting them to placement functions. For investigation you could modify [my script here](https://github.com/stanleyrya/scriptable-playground/blob/main/experiments/word-cloud-experiments/draw-spiral.js).
112 |
113 | Here are some placement algorithms I created that are different than the provided spiral one. When the debug parameter is set to true you can see what the algorithm is plotting. Please note that respectScreenScale may need to be set to false in order to render these on the home screen due to memory limitations.
114 |
115 | | Dark Mode | Light Mode | Simplified Input |
116 | | --- | --- | --- |
117 | |  |  | `{ placementFunction: galaxyPlacementFunction, respectScreenScale: false }` |
118 | |  |  | `{ placementFunction: galaxyPlacementFunction, respectScreenScale: false, debug: true }` |
119 | |  |  | `{ placementFunction: starPlacementFunction, respectScreenScale: false }` |
120 | |  |  | `{ placementFunction: starPlacementFunction,, respectScreenScale: false, debug: true }` |
121 |
122 | ## Weight Functions!
123 | Word clouds aren't complete without modifying the font! A weight function can be provided to modify how the words are displayed. You can use this function to convert weight to size, font type, opacity, color, and more! Here's the default method for context:
124 |
125 | ```
126 | /**
127 | * @param {WordCloudWord} wordCloudWord
128 | * - The word that is being processed.
129 | * @return {WordCloudProcessedWord}
130 | * - The word after processing.
131 | */
132 | _defaultWeightFunction(wordCloudWord) {
133 | const max = 60;
134 | const min = 10;
135 | return new WordCloudProcessedWord({
136 | word: wordCloudWord.word,
137 | wordCloudFont: new WordCloudFont({
138 | fontName: "TrebuchetMS-Bold"
139 | }),
140 | fontSize: (wordCloudWord.weight / 10) * (max - min) + min,
141 | color: Device.isUsingDarkAppearance() ? Color.white() : Color.black()
142 | });
143 | }
144 | ```
145 |
146 | Just as I mentioned above, I recommend playing with the functions provided and getting creative. Here are some examples using built-in fonts:
147 |
148 | | Dark Mode | Light Mode | Simplified Input |
149 | | --- | --- | --- |
150 | |  |  | `{ weightFunction: builtInFestiveWeightFunction }` |
151 | |  |  | `{ weightFunction: hackerWeightFunction }` |
152 |
153 | ## ... with Custom Fonts!
154 | You can use custom fonts too! Before you get too excited custom fonts require specific setup and are not guarranteed to work. The word cloud algorithm depends on generating word 'hitboxes' to make sure words don't overlap with each other. At this time the hitboxes are generated by rendering the word with Scriptable's WebView tool. Custom fonts aren't referencable from within the tool so they have to be installed on the fly using a CSS stylesheet URL. The word cloud itself is being rendered using Scriptable's DrawContext so the font needs to be installed locally too for the whole thing to work.
155 |
156 | TL;DR: You need to both install the font locally and provide a reference to the CSS stylesheet hosted somewhere online to use custom fonts. This has currently only been tested with Google fonts. Here's an example:
157 |
158 | ```
159 | // https://fonts.google.com/specimen/Lacquer
160 | function spookyWeightFunction(wordCloudWord) {
161 | return new WordCloudProcessedWord({
162 | word: wordCloudWord.word,
163 | wordCloudFont: new WordCloudFont({
164 | fontName: "Lacquer",
165 | cssUrl: "https://fonts.googleapis.com/css2?family=Lacquer&display=swap"
166 | }),
167 | fontSize: (wordCloudWord.weight / 10) * (maxFont - minFont) + minFont,
168 | color: Color.orange()
169 | });
170 | }
171 | ```
172 |
173 | The fontName is the font family. [This article](https://9to5mac.com/2020/06/12/fontcase-open-source-fonts-app-iphone-ipad) suggests [this app](https://apps.apple.com/us/app/fontcase-manage-your-type/id1205074470) is the safest way to download fonts to iOS. Be careful, use at your own risk!
174 |
175 | After all of that hassle I hope you agree the effort is worth it! Once these fonts are installed they will begin working:
176 |
177 | | Font Link | Dark Mode | Light Mode | Broken / Missing Font | Simplified Input |
178 | | --- | --- | --- | --- | --- |
179 | | [Lacquer](https://fonts.google.com/specimen/Lacquer) |  |  |  | `{ weightFunction: builtInFestiveWeightFunction }` |
180 | | [Cinzel Decorative](https://fonts.google.com/specimen/Cinzel+Decorative) |  |  |  | `{ weightFunction: hackerWeightFunction }` |
181 | | [Fredericka the Great](https://fonts.google.com/specimen/Fredericka+the+Great) |  |  |  | `{ weightFunction: stencilWeightFunction }` |
182 |
183 | ## Putting it all together!
184 |
185 | All of these features can be joined together with backgrounds to create beautiful word clouds. The word cloud class is transparent, so simply add another image as the background image and voila! For widgets you can add this to your script:
186 |
187 | ```
188 | widget.backgroundImage = await new Request('YOUR IMAGE URL').loadImage();
189 | ```
190 | | Image Link | Result | Simplified Input |
191 | | --- | --- | --- |
192 | | ["Milky Way"](https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/main/images/milky-way.HEIC) |  | `{ weightFunction: celestialWeightFunction, placementFunction: galaxyPlacementFunction, respectScreenScale: false }` |
193 | | ["Mountain"](https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/main/images/mountain.JPG) |  | `{ weightFunction: builtInFestiveWeightFunction }` |
194 |
195 | ## Thank You!
196 |
197 | If you enjoyed this demo or the scripts please consider buying me a coffee! I'd also love it if you tried out my other scripts on GitHub. Thanks again!
198 | * https://www.github.com/stanleyrya
199 | * https://www.paypal.me/stanleyrya
200 |
--------------------------------------------------------------------------------
/images/1-title-dark.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/1-title-dark.JPG
--------------------------------------------------------------------------------
/images/1-title-light.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/1-title-light.JPG
--------------------------------------------------------------------------------
/images/10-star-debug-dark.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/10-star-debug-dark.JPG
--------------------------------------------------------------------------------
/images/10-star-debug-light.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/10-star-debug-light.JPG
--------------------------------------------------------------------------------
/images/11-festive-dark.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/11-festive-dark.JPG
--------------------------------------------------------------------------------
/images/11-festive-light.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/11-festive-light.JPG
--------------------------------------------------------------------------------
/images/12-hacker-dark.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/12-hacker-dark.JPG
--------------------------------------------------------------------------------
/images/12-hacker-light.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/12-hacker-light.JPG
--------------------------------------------------------------------------------
/images/13-custom-spooky-broken.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/13-custom-spooky-broken.JPG
--------------------------------------------------------------------------------
/images/13-custom-spooky-dark.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/13-custom-spooky-dark.JPG
--------------------------------------------------------------------------------
/images/13-custom-spooky-light.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/13-custom-spooky-light.JPG
--------------------------------------------------------------------------------
/images/14-custom-festive-broken.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/14-custom-festive-broken.JPG
--------------------------------------------------------------------------------
/images/14-custom-festive-dark.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/14-custom-festive-dark.JPG
--------------------------------------------------------------------------------
/images/14-custom-festive-light.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/14-custom-festive-light.JPG
--------------------------------------------------------------------------------
/images/15-custom-stencil-broken.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/15-custom-stencil-broken.JPG
--------------------------------------------------------------------------------
/images/15-custom-stencil-dark.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/15-custom-stencil-dark.JPG
--------------------------------------------------------------------------------
/images/15-custom-stencil-light.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/15-custom-stencil-light.JPG
--------------------------------------------------------------------------------
/images/16-blurry-dark.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/16-blurry-dark.JPG
--------------------------------------------------------------------------------
/images/16-blurry-light.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/16-blurry-light.JPG
--------------------------------------------------------------------------------
/images/17-celestial-background.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/17-celestial-background.PNG
--------------------------------------------------------------------------------
/images/18-festive-background.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/18-festive-background.PNG
--------------------------------------------------------------------------------
/images/2-250x250-dark.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/2-250x250-dark.JPG
--------------------------------------------------------------------------------
/images/2-250x250-light.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/2-250x250-light.JPG
--------------------------------------------------------------------------------
/images/3-530x250-dark.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/3-530x250-dark.JPG
--------------------------------------------------------------------------------
/images/3-530x250-light.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/3-530x250-light.JPG
--------------------------------------------------------------------------------
/images/4-200x600-dark.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/4-200x600-dark.JPG
--------------------------------------------------------------------------------
/images/4-200x600-light.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/4-200x600-light.JPG
--------------------------------------------------------------------------------
/images/5-debug-dark.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/5-debug-dark.JPG
--------------------------------------------------------------------------------
/images/5-debug-light.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/5-debug-light.JPG
--------------------------------------------------------------------------------
/images/6-grow-dark.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/6-grow-dark.JPG
--------------------------------------------------------------------------------
/images/6-grow-light.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/6-grow-light.JPG
--------------------------------------------------------------------------------
/images/7-galaxy-dark.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/7-galaxy-dark.JPG
--------------------------------------------------------------------------------
/images/7-galaxy-light.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/7-galaxy-light.JPG
--------------------------------------------------------------------------------
/images/8-galaxy-debug-dark.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/8-galaxy-debug-dark.JPG
--------------------------------------------------------------------------------
/images/8-galaxy-debug-light.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/8-galaxy-debug-light.JPG
--------------------------------------------------------------------------------
/images/9-star-dark.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/9-star-dark.JPG
--------------------------------------------------------------------------------
/images/9-star-light.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/9-star-light.JPG
--------------------------------------------------------------------------------
/images/milky-way.HEIC:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/milky-way.HEIC
--------------------------------------------------------------------------------
/images/mountain.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/2916259cb6ad22ec151bd0b6c2f2dd539a0629ca/images/mountain.JPG
--------------------------------------------------------------------------------
/minification-instructions.md:
--------------------------------------------------------------------------------
1 | # Minification Instructions
2 |
3 | In order to minify the WordCloud class, you must first minify the HTML and Javascript text blobs. The two functions are called `_loadFontToWebView` and `_getTextDimensionsUsingWebView`.
4 |
5 | Once both of these functions are minified, you can minify the Word Cloud class as a whole.
6 |
7 | ## _loadFontToWebView before and after
8 | ```
9 | _loadFontToWebView(fontFamily, fontCssUrl) {
10 | const html = `
11 | // Preconnecting could decrease load time if using a Google font
12 | // https://www.cdnplanet.com/blog/faster-google-webfonts-preconnect/
13 |
14 |
15 |
16 |
17 | // Load the font so its available in the canvas
18 |
`
29 | .replace("REPLACE_HREF", fontCssUrl)
30 | .replace("REPLACE_FONT_FAMILY", fontFamily);
31 |
32 | return this.webView.loadHTML(html);
33 | }
34 | ```
35 |
36 | ## _getTextDimensionsUsingWebView before and after
37 | ```
38 | _getTextDimensionsUsingWebView(text, cssFont) {
39 | const javascript = `
40 | function getTextDimensions(text, font) {
41 | const canvas = document.createElement("canvas");
42 | const context = canvas.getContext("2d");
43 | context.font = font;
44 | const metrics = context.measureText(text);
45 | return {
46 | // I'm not sure why yet but 3/4 is perfect for Scriptable's DrawContext
47 | width: metrics.width * 3/4,
48 | height: (metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent) * 3/4
49 | };
50 | }
51 |
52 | getTextDimensions("REPLACE_TEXT", "REPLACE_FONT");
53 | `
54 | .replace("REPLACE_TEXT", text)
55 | .replace("REPLACE_FONT", cssFont);
56 |
57 | return this.webView.evaluateJavaScript(javascript);
58 | }
59 | ```
60 | ```
61 | _getTextDimensionsUsingWebView(text, cssFont) {
62 | const javascript = `function getTextDimensions(t,e){const n=document.createElement("canvas").getContext("2d");n.font=e;const o=n.measureText(t);return{width:3*o.width/4,height:3*(o.actualBoundingBoxAscent+o.actualBoundingBoxDescent)/4}}getTextDimensions("REPLACE_TEXT","REPLACE_FONT");`
63 | .replace("REPLACE_TEXT", text)
64 | .replace("REPLACE_FONT", cssFont);
65 |
66 | return this.webView.evaluateJavaScript(javascript);
67 | }
68 | ```
69 |
--------------------------------------------------------------------------------
/minified-word-cloud.js:
--------------------------------------------------------------------------------
1 | // Variables used by Scriptable.
2 | // These must be at the very top of the file. Do not edit.
3 | // icon-color: cyan; icon-glyph: cloud;
4 | /**
5 | * Author: Ryan Stanley (stanleyrya@gmail.com)
6 | * Github: https://www.github.com/stanleyrya
7 | * Tips: https://www.paypal.me/stanleyrya
8 | *
9 | * A set of classes that can create a word cloud image. Basic Usage:
10 | * * const wordCloudWords = [new WordCloudWord({word, weight}), ...]
11 | * * const wordCloud = new WordCloud({width, height, wordCloudWords});
12 | * * const image = await wordCloud.getImage();
13 | *
14 | * This is a minified version to make scripts easier to read,
15 | * but the full version along with a demo can be found here:
16 | * https://github.com/stanleyrya/scriptable-word-cloud
17 | *
18 | * Advanced features (explained in the demo):
19 | * * Modify how the words are displayed and processed (font, color, etc.)
20 | * * Modify how the words are placed on the word cloud (star shape, galaxy shape, etc.)
21 | * * Display the debugging algorithm by passing in debug=true
22 | * * and more!
23 | *
24 | * Here's the complete WordCloud constructor for the curious!
25 | * {
26 | * width, height, wordCloudWords, // required
27 | * respectScreenScale = true,
28 | * growToFit = true,
29 | * debug = false,
30 | * weightFunction = this._defaultWeightFunction,
31 | * placementFunction = this._defaultPlacementFunction,
32 | * growthFunction = this._defaultGrowthFunction,
33 | * }
34 | *
35 | * This script is split into four sections to make it easier to edit:
36 | * 1. WORD CLOUD OBJECTS
37 | * 2. EXAMPLE WEIGHT FUNCTIONS (the `weightFunction` parameter!)
38 | * 3. EXAMPLE PLACEMENT FUNCTIONS (the `placementFunction` parameter!)
39 | * 4. SAMPLE LOGIC
40 | *
41 | */
42 |
43 | /******************************
44 | ***** WORD CLOUD OBJECTS *****
45 | ******************************/
46 |
47 | class WordCloudWord{constructor({word:r,weight:i}){if(!r)throw"word is required!";if(!i)throw"weight is required!";this.word=r,this.weight=i}}
48 | class WordCloudFont{constructor({fontName:s,cssUrl:o}){if(!s)throw"fontName is required!";this.fontName=s,this.cssURL=o}}
49 | class WordCloudProcessedWord{constructor({word:o,wordCloudFont:r,fontSize:d,color:t}){if(!o)throw"word is required!";if(!r)throw"wordCloudFont is required!";if(!(r instanceof WordCloudFont))throw"wordCloudFont must be a WordCloudFont object!";if(!d)throw"fontSize is required!";if(!t)throw"color is required!";this.word=o,this.wordCloudFont=r,this.fontSize=d,this.color=t}}
50 | class WordCloud{constructor({width:t,height:e,wordCloudWords:i,weightFunction:o=this._defaultWeightFunction,placementFunction:s=this._defaultPlacementFunction,growToFit:n=!0,growthFunction:h=this._defaultGrowthFunction,respectScreenScale:r=!0,debug:d=!1}){if(!t||!e||!i)throw"Could not get width, height, and wordCloudWords from input. Please see documentation.";this.providedWidth=t,this.providedHeight=e,this.placementFunction=s,this.weightFunction=o,this.growToFit=!!n,this.growthFunction=h,this.respectScreenScale=!!r,this.debug=!!d,this.processedWords=i.map(t=>this.weightFunction(t)),this.wordsToPlace=[...this.processedWords],this.placedWords=[],this.webView=new WebView,this.loadedCssUrls={},this.textDimensionsMap={},this.bufferRoom=10;const c=t>e?t:e;this.xRatio=t/c,this.yRatio=e/c}_defaultWeightFunction(t){return new WordCloudProcessedWord({word:t.word,wordCloudFont:new WordCloudFont({fontName:"TrebuchetMS-Bold"}),fontSize:t.weight/10*50+10,color:Device.isUsingDarkAppearance()?Color.white():Color.black()})}_defaultPlacementFunction(t,e,i,o,s,n,h){let r,d,c,a;return h?(({radius:r,radiusDirection:d,angle:c,angleDirection:a}=h),r+=.75*d,c+=2*Math.PI/50*a):(r=0,c=0,d=Math.random()<.5?-1:1,a=Math.random()<.5?-1:1),{x:i+r*Math.cos(c)*s,y:o+r*Math.sin(c)*n,radius:r,angle:c,radiusDirection:d,angleDirection:a}}_defaultGrowthFunction(t,e,i,o){return{width:t+.1*t,height:e+.1*e}}_loadFontToWebView(t,e){const i='
.
'.replace("REPLACE_HREF",e).replace("REPLACE_FONT_FAMILY",t);return this.webView.loadHTML(i)}_getTextDimensionsUsingWebView(t,e){const i='function getTextDimensions(t,e){const n=document.createElement("canvas").getContext("2d");n.font=e;const o=n.measureText(t);return{width:3*o.width/4,height:3*(o.actualBoundingBoxAscent+o.actualBoundingBoxDescent)/4}}getTextDimensions("REPLACE_TEXT","REPLACE_FONT");'.replace("REPLACE_TEXT",t).replace("REPLACE_FONT",e);return this.webView.evaluateJavaScript(i)}async _getTextDimensions(t,e,i){const o=i+"pt "+e.fontName,s=t+" "+o;if(this.textDimensionsMap[s])return this.textDimensionsMap[s];{e.cssURL&&(this.loadedCssUrls[e.cssURL]||(await this._loadFontToWebView(e.fontName,e.cssURL),this.loadedCssUrls[e.cssURL]=!0));const i=await this._getTextDimensionsUsingWebView(t,o);return this.textDimensionsMap[s]=i,i}}_checkRectCollision(t){for(const e of this.hitBoxes)if(t.minXe.minX-this.bufferRoom&&t.minYe.minY-this.bufferRoom)return!0;return!1}_checkRectOutsideBorders(t){return t.minX<0+this.bufferRoom||t.maxX>this.width-this.bufferRoom||t.minY<0+this.bufferRoom||t.maxY>this.height-this.bufferRoom}_checkPointCollision(t,e){for(const i of this.hitBoxes)if(ti.minX-this.bufferRoom&&ei.minY-this.bufferRoom)return!0;return!1}async _addTextCentered({x:t,y:e,processedWord:i,shouldDraw:o,checkHitboxes:s}){const{word:n,wordCloudFont:h,fontSize:r,color:d}=i,c=await this._getTextDimensions(n,h,r),a=t-c.width/2,l=e-c.height/2,w=new Rect(a,l,c.width,c.height);if(s&&this._checkRectCollision(w))return{textPlaced:!1,rectCollision:!0,outsideBorders:!1};if(this._checkRectOutsideBorders(w))return{textPlaced:!1,rectCollision:!1,outsideBorders:!0};if(this.debug&&console.log("writing "+n),this.hitBoxes.push(w),o){this.debug&&(this.ctx.setLineWidth(5),this.ctx.setStrokeColor(Color.red()),this.ctx.strokeRect(w));const t=c.height/4;this.ctx.setTextColor(d),this.ctx.setFont(new Font(h.fontName,r)),this.ctx.drawText(n,new Point(a,l-t))}return{textPlaced:!0,rectCollision:!1,outsideBorders:!1}}async _writeWithPlacementFunction(t,e){let i,o,s,n=!1,h=!1,r=!1,d=!1;const c=new Path;c.move(new Point(this.centerX,this.centerY));let a=!1;for(;!(n&&h&&r&&d);)if(i=this.placementFunction(this.width,this.height,this.centerX,this.centerY,this.xRatio,this.yRatio,i),({x:o,y:s}=i),this.debug&&e&&c.addLine(new Point(o,s)),!this._checkPointCollision(o,s)){if(t){const{textPlaced:i,rectCollision:n,outsideBorders:h}=await this._addTextCentered({x:o,y:s,processedWord:t,shouldDraw:e,checkHitboxes:!0});if(i){this.placedWords.push({xFromCenter:o-this.centerX,yFromCenter:s-this.centerY,processedWord:t}),this.wordsToPlace.shift(),a=!0;break}if(h&&this.growToFit)break}o<0&&(n=!0),o>this.width&&(h=!0),s<0&&(r=!0),s>this.height&&(d=!0)}return this.debug&&e&&(this.ctx.setLineWidth(1),this.ctx.addPath(c),this.ctx.setStrokeColor(new Color("6693F5")),this.ctx.strokePath()),a}async _writePendingWords(t){this.debug&&console.log("writing pending words");let e=!0;const i=[...this.wordsToPlace];for(const o of i)if(!await this._writeWithPlacementFunction(o,t)&&(e=!1,this.growToFit))return!1;return e}async _writeAlreadyPlacedWords(t){this.debug&&console.log("writing already placed words");for(const e of this.placedWords)await this._addTextCentered({x:e.xFromCenter+this.centerX,y:e.yFromCenter+this.centerY,processedWord:e.processedWord,shouldDraw:t,checkHitboxes:!1})}async _getWordStats(){let t=0,e=0,i=0;for(const o of this.processedWords){const{word:s,wordCloudFont:n,fontSize:h,color:r}=o,d=await this._getTextDimensions(s,n,h);tt/2&&(i+=c.height),c.height>e/2&&(o+=c.width)}return{stackedMinWidth:o,stackedMinHeight:i}}async _preflightGrow(t,e){let i=t,o=e;const{minWidth:s,minHeight:n,minArea:h}=await this._getWordStats();for(;s>i||n>o;)console.log("increasing because of min width or height"),({width:i,height:o}=this.growthFunction(i,o,this.providedWidth,this.providedHeight));for(;h>i*o;)console.log("increasing because of min area"),({width:i,height:o}=this.growthFunction(i,o,this.providedWidth,this.providedHeight));let{stackedMinWidth:r,stackedMinHeight:d}=await this._getStackedMinDimensions(i,o);for(;r>i||d>o;)console.log("increasing because of stacked width or height"),({width:i,height:o}=this.growthFunction(i,o,this.providedWidth,this.providedHeight)),({stackedMinWidth:r,stackedMinHeight:d}=await this._getStackedMinDimensions(i,o));return{width:i,height:o}}async getImage(){let t=this.providedWidth,e=this.providedHeight;this.growToFit&&({width:t,height:e}=await this._preflightGrow(t,e));let i=!1;for(;!i&&(this.width=t,this.height=e,this.centerX=t/2,this.centerY=e/2,this.hitBoxes=[],await this._writeAlreadyPlacedWords(!1),i=await this._writePendingWords(!1),this.growToFit);)i||(console.log("increasing because words couldn't fit area"),({width:t,height:e}=this.growthFunction(t,e,this.providedWidth,this.providedHeight)));return this.ctx=new DrawContext,this.ctx.opaque=!1,this.ctx.respectScreenScale=this.respectScreenScale,this.ctx.size=new Size(t,e),this.debug&&(this.ctx.setLineWidth(5),this.ctx.setStrokeColor(Color.red()),this.ctx.strokeRect(new Rect(0,0,t,e)),await this._writeWithPlacementFunction(null,!0)),await this._writeAlreadyPlacedWords(!0),this.ctx.getImage()}}
51 |
52 | /************************************
53 | ***** EXAMPLE WEIGHT FUNCTIONS *****
54 | ************************************/
55 |
56 | /**
57 | * Functions that use fonts already installed in iOS.
58 | *
59 | * Find the fonts here:
60 | * http://iosfonts.com
61 | */
62 |
63 | function simpleAndCleanWeightFunction(o){return new WordCloudProcessedWord({word:o.word,wordCloudFont:new WordCloudFont({fontName:"TrebuchetMS-Bold"}),fontSize:o.weight/10*50+10,color:Device.isUsingDarkAppearance()?Color.white():Color.black()})}
64 | function builtInFestiveWeightFunction(o){return new WordCloudProcessedWord({word:o.word,wordCloudFont:new WordCloudFont({fontName:"SnellRoundhand-Black"}),fontSize:o.weight/10*50+10,color:Math.random()<.5?Color.red():new Color("#1E792C")})}
65 | function hackerWeightFunction(o){const e=new Color(Color.green().hex,Color.green().alpha*(o.weight/10));return new WordCloudProcessedWord({word:o.word,wordCloudFont:new WordCloudFont({fontName:"CourierNewPS-BoldMT"}),fontSize:60,color:e})}
66 | function celestialWeightFunction(o){return new WordCloudProcessedWord({word:o.word,wordCloudFont:new WordCloudFont({fontName:"GillSans-LightItalic"}),fontSize:o.weight/10*50+10,color:Color.lightGray()})}
67 |
68 | /**
69 | * Functions that use fonts installed through an app.
70 | * A url of the css stylesheet is still required due
71 | * to limitations of the system. The fontName is the
72 | * font family.
73 | *
74 | * This article [1] suggests this app [2] is the
75 | * safest way to download fonts to iOS. Be careful,
76 | * use at your own risk!
77 | *
78 | * [1] - https://9to5mac.com/2020/06/12/fontcase-open-source-fonts-app-iphone-ipad
79 | * [2] - https://apps.apple.com/us/app/fontcase-manage-your-type/id1205074470
80 | */
81 |
82 | // https://fonts.google.com/specimen/Lacquer
83 | function spookyWeightFunction(o){return new WordCloudProcessedWord({word:o.word,wordCloudFont:new WordCloudFont({fontName:"Lacquer",cssUrl:"https://fonts.googleapis.com/css2?family=Lacquer&display=swap"}),fontSize:o.weight/10*50+10,color:Color.orange()})}
84 | // https://fonts.google.com/specimen/Cinzel+Decorative
85 | function customFestiveWeightFunction(o){return new WordCloudProcessedWord({word:o.word,wordCloudFont:new WordCloudFont({fontName:"Cinzel Decorative",cssUrl:"https://fonts.googleapis.com/css2?family=Cinzel+Decorative&display=swap"}),fontSize:o.weight/10*50+10,color:Math.random()<.5?Color.red():new Color("#1E792C")})}
86 | // https://fonts.google.com/specimen/Fredericka+the+Great
87 | function stencilWeightFunction(o){return new WordCloudProcessedWord({word:o.word,wordCloudFont:new WordCloudFont({fontName:"Fredericka the Great",cssUrl:"https://fonts.googleapis.com/css2?family=Fredericka+the+Great&display=swap"}),fontSize:o.weight/10*50+10,color:Color.lightGray()})}
88 |
89 | /***************************************
90 | ***** EXAMPLE PLACEMENT FUNCTIONS *****
91 | ***************************************/
92 |
93 | /**
94 | * Please see this script for additional examples:
95 | * https://github.com/stanleyrya/scriptable-playground/blob/main/experiments/word-cloud-experiments/draw-spiral.js
96 | */
97 |
98 | function spiralPlacementFunction(a,n,i,t,r,e,o){let c,l,s,u;return o?(({radius:c,radiusDirection:l,angle:s,angleDirection:u}=o),c+=.75*l,s+=2*Math.PI/50*u):(c=0,s=0,l=Math.random()<.5?-1:1,u=Math.random()<.5?-1:1),{x:i+c*Math.cos(s)*r,y:t+c*Math.sin(s)*e,radius:c,angle:s,radiusDirection:l,angleDirection:u}}
99 | function galaxyPlacementFunction(n,t,a,c,i,e,o){const h=o?o.i+1:0,l=234*Math.PI/500*h;return{x:2*l*Math.cos(10*l)+a,y:2*l*Math.sin(10*l)+c,angle:l,i:h}}
100 | function starPlacementFunction(t,n,a,c,e,i,o){let s=o?o.i+1:0;const h=336*Math.PI/500*s;return{x:.25*h*Math.cos(100*h)+a,y:.25*h*Math.sin(100*h)+c,angle:h,i:s}}
101 |
102 | // Sample input
103 |
104 | const wordCloudWords = [
105 | new WordCloudWord({ word: "Seattle", weight: 10 }),
106 | new WordCloudWord({ word: "Boston", weight: 10 }),
107 | new WordCloudWord({ word: "Chicago", weight: 8 }),
108 | new WordCloudWord({ word: "Denver", weight: 7 }),
109 | new WordCloudWord({ word: "Boise", weight: 7 }),
110 | new WordCloudWord({ word: "Los Angeles", weight: 7 }),
111 | new WordCloudWord({ word: "San Fransisco", weight: 6 }),
112 | new WordCloudWord({ word: "Victoria", weight: 6 }),
113 | new WordCloudWord({ word: "Portland", weight: 5 }),
114 | new WordCloudWord({ word: "London", weight: 5 }),
115 | new WordCloudWord({ word: "Dublin", weight: 3 }),
116 | new WordCloudWord({ word: "Barcelona", weight: 3 }),
117 | new WordCloudWord({ word: "Amsterdam", weight: 3 }),
118 | new WordCloudWord({ word: "Budapest", weight: 3 }),
119 | new WordCloudWord({ word: "Venice", weight: 3 }),
120 | new WordCloudWord({ word: "Florence", weight: 2 }),
121 | new WordCloudWord({ word: "Oslo", weight: 2 }),
122 | new WordCloudWord({ word: "Paris", weight: 2 }),
123 | new WordCloudWord({ word: "Tokyo", weight: 1 }),
124 | new WordCloudWord({ word: "New York", weight: 1 }),
125 | new WordCloudWord({ word: "Fort", weight: 1 })
126 | ];
127 |
128 | let width, height;
129 | if (config.runsInWidget) {
130 | width = config.widgetFamily === "small" ? 250 : 530;
131 | height = config.widgetFamily === "large" ? 530 : 250;
132 | } else {
133 | width = 250;
134 | height = 250;
135 | }
136 |
137 | const wordCloud = new WordCloud({
138 | // required
139 |
140 | width,
141 | height,
142 | wordCloudWords,
143 |
144 | // optional
145 |
146 | // may help with homescreen memory issues
147 | // respectScreenScale: false,
148 |
149 | // shows how the algorithm works
150 | // debug: true,
151 |
152 | // changes the way way words are displayed
153 | // weightFunction: hackerWeightFunction,
154 |
155 | // changes the way words are placed
156 | // placementFunction: starPlacementFunction,
157 | });
158 | const image = await wordCloud.getImage();
159 |
160 | // Sample usage
161 |
162 | const widget = new ListWidget();
163 | widget.setPadding(0, 0, 0, 0);
164 | const widgetImage = widget.addImage(image);
165 | widgetImage.applyFillingContentMode();
166 | widgetImage.centerAlignImage();
167 | // The word cloud image has a clear background.
168 | // The default weight function uses Device.isUsingDarkAppearance()
169 | // to set the font color. It is slow to update
170 | // which could make the font blend in with the
171 | // widget's automatic background. To protect
172 | // against this you can set the background explicitly:
173 | widget.backgroundColor = Device.isUsingDarkAppearance() ? Color.black() : Color.white();
174 |
175 | // Alternatively, consider adding an image as the background :)
176 | // widget.backgroundImage = await new Request('YOUR IMAGE URL').loadImage();
177 |
178 | if (config.runsInWidget) {
179 | Script.setWidget(widget);
180 | Script.complete();
181 | } else {
182 | widget.presentLarge();
183 | }
184 |
--------------------------------------------------------------------------------
/word-cloud-demo.js:
--------------------------------------------------------------------------------
1 | // Variables used by Scriptable.
2 | // These must be at the very top of the file. Do not edit.
3 | // icon-color: cyan; icon-glyph: cloud;
4 | /**
5 | * Author: Ryan Stanley (stanleyrya@gmail.com)
6 | * Github: https://www.github.com/stanleyrya
7 | * Tips: https://www.paypal.me/stanleyrya
8 | *
9 | * A set of classes that can create a word cloud image. Basic Usage:
10 | * * const wordCloudWords = [new WordCloudWord({word, weight}), ...]
11 | * * const wordCloud = new WordCloud({width, height, wordCloudWords});
12 | * * const image = await wordCloud.getImage();
13 | *
14 | * This is a demo script to help get newcomers started, but the
15 | * full version and minified version can be found in this github repo:
16 | * https://github.com/stanleyrya/scriptable-word-cloud
17 | *
18 | * Advanced features (explained in the demo):
19 | * * Modify how the words are displayed and processed (font, color, etc.)
20 | * * Modify how the words are placed on the word cloud (star shape, galaxy shape, etc.)
21 | * * Display the debugging algorithm by passing in debug=true
22 | * * and more!
23 | *
24 | * Here's the complete WordCloud constructor for the curious!
25 | * {
26 | * width, height, wordCloudWords, // required
27 | * respectScreenScale = true,
28 | * growToFit = true,
29 | * debug = false,
30 | * weightFunction = this._defaultWeightFunction,
31 | * placementFunction = this._defaultPlacementFunction,
32 | * growthFunction = this._defaultGrowthFunction,
33 | * }
34 | *
35 | */
36 | class WordCloudWord{constructor({word:r,weight:i}){if(!r)throw"word is required!";if(!i)throw"weight is required!";this.word=r,this.weight=i}}
37 | class WordCloudFont{constructor({fontName:s,cssUrl:o}){if(!s)throw"fontName is required!";this.fontName=s,this.cssURL=o}}
38 | class WordCloudProcessedWord{constructor({word:o,wordCloudFont:r,fontSize:d,color:t}){if(!o)throw"word is required!";if(!r)throw"wordCloudFont is required!";if(!(r instanceof WordCloudFont))throw"wordCloudFont must be a WordCloudFont object!";if(!d)throw"fontSize is required!";if(!t)throw"color is required!";this.word=o,this.wordCloudFont=r,this.fontSize=d,this.color=t}}
39 | class WordCloud{constructor({width:t,height:e,wordCloudWords:i,weightFunction:o=this._defaultWeightFunction,placementFunction:s=this._defaultPlacementFunction,growToFit:n=!0,growthFunction:h=this._defaultGrowthFunction,respectScreenScale:r=!0,debug:d=!1}){if(!t||!e||!i)throw"Could not get width, height, and wordCloudWords from input. Please see documentation.";this.providedWidth=t,this.providedHeight=e,this.placementFunction=s,this.weightFunction=o,this.growToFit=!!n,this.growthFunction=h,this.respectScreenScale=!!r,this.debug=!!d,this.processedWords=i.map(t=>this.weightFunction(t)),this.wordsToPlace=[...this.processedWords],this.placedWords=[],this.webView=new WebView,this.loadedCssUrls={},this.textDimensionsMap={},this.bufferRoom=10;const c=t>e?t:e;this.xRatio=t/c,this.yRatio=e/c}_defaultWeightFunction(t){return new WordCloudProcessedWord({word:t.word,wordCloudFont:new WordCloudFont({fontName:"TrebuchetMS-Bold"}),fontSize:t.weight/10*50+10,color:Device.isUsingDarkAppearance()?Color.white():Color.black()})}_defaultPlacementFunction(t,e,i,o,s,n,h){let r,d,c,a;return h?(({radius:r,radiusDirection:d,angle:c,angleDirection:a}=h),r+=.75*d,c+=2*Math.PI/50*a):(r=0,c=0,d=Math.random()<.5?-1:1,a=Math.random()<.5?-1:1),{x:i+r*Math.cos(c)*s,y:o+r*Math.sin(c)*n,radius:r,angle:c,radiusDirection:d,angleDirection:a}}_defaultGrowthFunction(t,e,i,o){return{width:t+.1*t,height:e+.1*e}}_loadFontToWebView(t,e){const i='
.
'.replace("REPLACE_HREF",e).replace("REPLACE_FONT_FAMILY",t);return this.webView.loadHTML(i)}_getTextDimensionsUsingWebView(t,e){const i='function getTextDimensions(t,e){const n=document.createElement("canvas").getContext("2d");n.font=e;const o=n.measureText(t);return{width:3*o.width/4,height:3*(o.actualBoundingBoxAscent+o.actualBoundingBoxDescent)/4}}getTextDimensions("REPLACE_TEXT","REPLACE_FONT");'.replace("REPLACE_TEXT",t).replace("REPLACE_FONT",e);return this.webView.evaluateJavaScript(i)}async _getTextDimensions(t,e,i){const o=i+"pt "+e.fontName,s=t+" "+o;if(this.textDimensionsMap[s])return this.textDimensionsMap[s];{e.cssURL&&(this.loadedCssUrls[e.cssURL]||(await this._loadFontToWebView(e.fontName,e.cssURL),this.loadedCssUrls[e.cssURL]=!0));const i=await this._getTextDimensionsUsingWebView(t,o);return this.textDimensionsMap[s]=i,i}}_checkRectCollision(t){for(const e of this.hitBoxes)if(t.minXe.minX-this.bufferRoom&&t.minYe.minY-this.bufferRoom)return!0;return!1}_checkRectOutsideBorders(t){return t.minX<0+this.bufferRoom||t.maxX>this.width-this.bufferRoom||t.minY<0+this.bufferRoom||t.maxY>this.height-this.bufferRoom}_checkPointCollision(t,e){for(const i of this.hitBoxes)if(ti.minX-this.bufferRoom&&ei.minY-this.bufferRoom)return!0;return!1}async _addTextCentered({x:t,y:e,processedWord:i,shouldDraw:o,checkHitboxes:s}){const{word:n,wordCloudFont:h,fontSize:r,color:d}=i,c=await this._getTextDimensions(n,h,r),a=t-c.width/2,l=e-c.height/2,w=new Rect(a,l,c.width,c.height);if(s&&this._checkRectCollision(w))return{textPlaced:!1,rectCollision:!0,outsideBorders:!1};if(this._checkRectOutsideBorders(w))return{textPlaced:!1,rectCollision:!1,outsideBorders:!0};if(this.debug&&console.log("writing "+n),this.hitBoxes.push(w),o){this.debug&&(this.ctx.setLineWidth(5),this.ctx.setStrokeColor(Color.red()),this.ctx.strokeRect(w));const t=c.height/4;this.ctx.setTextColor(d),this.ctx.setFont(new Font(h.fontName,r)),this.ctx.drawText(n,new Point(a,l-t))}return{textPlaced:!0,rectCollision:!1,outsideBorders:!1}}async _writeWithPlacementFunction(t,e){let i,o,s,n=!1,h=!1,r=!1,d=!1;const c=new Path;c.move(new Point(this.centerX,this.centerY));let a=!1;for(;!(n&&h&&r&&d);)if(i=this.placementFunction(this.width,this.height,this.centerX,this.centerY,this.xRatio,this.yRatio,i),({x:o,y:s}=i),this.debug&&e&&c.addLine(new Point(o,s)),!this._checkPointCollision(o,s)){if(t){const{textPlaced:i,rectCollision:n,outsideBorders:h}=await this._addTextCentered({x:o,y:s,processedWord:t,shouldDraw:e,checkHitboxes:!0});if(i){this.placedWords.push({xFromCenter:o-this.centerX,yFromCenter:s-this.centerY,processedWord:t}),this.wordsToPlace.shift(),a=!0;break}if(h&&this.growToFit)break}o<0&&(n=!0),o>this.width&&(h=!0),s<0&&(r=!0),s>this.height&&(d=!0)}return this.debug&&e&&(this.ctx.setLineWidth(1),this.ctx.addPath(c),this.ctx.setStrokeColor(new Color("6693F5")),this.ctx.strokePath()),a}async _writePendingWords(t){this.debug&&console.log("writing pending words");let e=!0;const i=[...this.wordsToPlace];for(const o of i)if(!await this._writeWithPlacementFunction(o,t)&&(e=!1,this.growToFit))return!1;return e}async _writeAlreadyPlacedWords(t){this.debug&&console.log("writing already placed words");for(const e of this.placedWords)await this._addTextCentered({x:e.xFromCenter+this.centerX,y:e.yFromCenter+this.centerY,processedWord:e.processedWord,shouldDraw:t,checkHitboxes:!1})}async _getWordStats(){let t=0,e=0,i=0;for(const o of this.processedWords){const{word:s,wordCloudFont:n,fontSize:h,color:r}=o,d=await this._getTextDimensions(s,n,h);tt/2&&(i+=c.height),c.height>e/2&&(o+=c.width)}return{stackedMinWidth:o,stackedMinHeight:i}}async _preflightGrow(t,e){let i=t,o=e;const{minWidth:s,minHeight:n,minArea:h}=await this._getWordStats();for(;s>i||n>o;)console.log("increasing because of min width or height"),({width:i,height:o}=this.growthFunction(i,o,this.providedWidth,this.providedHeight));for(;h>i*o;)console.log("increasing because of min area"),({width:i,height:o}=this.growthFunction(i,o,this.providedWidth,this.providedHeight));let{stackedMinWidth:r,stackedMinHeight:d}=await this._getStackedMinDimensions(i,o);for(;r>i||d>o;)console.log("increasing because of stacked width or height"),({width:i,height:o}=this.growthFunction(i,o,this.providedWidth,this.providedHeight)),({stackedMinWidth:r,stackedMinHeight:d}=await this._getStackedMinDimensions(i,o));return{width:i,height:o}}async getImage(){let t=this.providedWidth,e=this.providedHeight;this.growToFit&&({width:t,height:e}=await this._preflightGrow(t,e));let i=!1;for(;!i&&(this.width=t,this.height=e,this.centerX=t/2,this.centerY=e/2,this.hitBoxes=[],await this._writeAlreadyPlacedWords(!1),i=await this._writePendingWords(!1),this.growToFit);)i||(console.log("increasing because words couldn't fit area"),({width:t,height:e}=this.growthFunction(t,e,this.providedWidth,this.providedHeight)));return this.ctx=new DrawContext,this.ctx.opaque=!1,this.ctx.respectScreenScale=this.respectScreenScale,this.ctx.size=new Size(t,e),this.debug&&(this.ctx.setLineWidth(5),this.ctx.setStrokeColor(Color.red()),this.ctx.strokeRect(new Rect(0,0,t,e)),await this._writeWithPlacementFunction(null,!0)),await this._writeAlreadyPlacedWords(!0),this.ctx.getImage()}}
40 |
41 | /************************************
42 | ***** EXAMPLE WEIGHT FUNCTIONS *****
43 | ************************************/
44 |
45 | /**
46 | * Functions that use fonts already installed in iOS.
47 | *
48 | * Find the fonts here:
49 | * http://iosfonts.com
50 | */
51 |
52 | function simpleAndCleanWeightFunction(wordCloudWord) {
53 | const max = 60;
54 | const min = 10;
55 | return new WordCloudProcessedWord({
56 | word: wordCloudWord.word,
57 | wordCloudFont: new WordCloudFont({
58 | fontName: 'TrebuchetMS-Bold'
59 | }),
60 | fontSize: (wordCloudWord.weight / 10) * (max - min) + min,
61 | color: Device.isUsingDarkAppearance() ? Color.white() : Color.black()
62 | });
63 | }
64 |
65 | function builtInFestiveWeightFunction(wordCloudWord) {
66 | const max = 60;
67 | const min = 10;
68 | return new WordCloudProcessedWord({
69 | word: wordCloudWord.word,
70 | wordCloudFont: new WordCloudFont({
71 | fontName: 'SnellRoundhand-Black'
72 | }),
73 | fontSize: (wordCloudWord.weight / 10) * (max - min) + min,
74 | color: Math.random() < 0.5 ? Color.red() : new Color('#1E792C')
75 | });
76 | }
77 |
78 | function hackerWeightFunction(wordCloudWord) {
79 | const color = new Color(
80 | Color.green().hex,
81 | Color.green().alpha * (wordCloudWord.weight / 10)
82 | );
83 | return new WordCloudProcessedWord({
84 | word: wordCloudWord.word,
85 | wordCloudFont: new WordCloudFont({
86 | fontName: 'CourierNewPS-BoldMT'
87 | }),
88 | fontSize: 60,
89 | color: color
90 | });
91 | }
92 |
93 | function celestialWeightFunction(wordCloudWord) {
94 | const max = 60;
95 | const min = 10;
96 | return new WordCloudProcessedWord({
97 | word: wordCloudWord.word,
98 | wordCloudFont: new WordCloudFont({
99 | fontName: 'GillSans-LightItalic'
100 | }),
101 | fontSize: (wordCloudWord.weight / 10) * (max - min) + min,
102 | color: Color.lightGray()
103 | });
104 | }
105 |
106 | /**
107 | * Functions that use fonts installed through an app.
108 | * A url of the css stylesheet is still required due
109 | * to limitations of the system. The fontName is the
110 | * font family.
111 | *
112 | * This article [1] suggests this app [2] is the
113 | * safest way to download fonts to iOS. Be careful,
114 | * use at your own risk!
115 | *
116 | * [1] - https://9to5mac.com/2020/06/12/fontcase-open-source-fonts-app-iphone-ipad
117 | * [2] - https://apps.apple.com/us/app/fontcase-manage-your-type/id1205074470
118 | */
119 |
120 | // https://fonts.google.com/specimen/Lacquer
121 | function spookyWeightFunction(wordCloudWord) {
122 | const max = 60;
123 | const min = 10;
124 | return new WordCloudProcessedWord({
125 | word: wordCloudWord.word,
126 | wordCloudFont: new WordCloudFont({
127 | fontName: 'Lacquer',
128 | cssUrl: 'https://fonts.googleapis.com/css2?family=Lacquer&display=swap'
129 | }),
130 | fontSize: (wordCloudWord.weight / 10) * (max - min) + min,
131 | color: Color.orange()
132 | });
133 | }
134 |
135 | // https://fonts.google.com/specimen/Cinzel+Decorative
136 | function customFestiveWeightFunction(wordCloudWord) {
137 | const max = 60;
138 | const min = 10;
139 | return new WordCloudProcessedWord({
140 | word: wordCloudWord.word,
141 | wordCloudFont: new WordCloudFont({
142 | fontName: 'Cinzel Decorative',
143 | cssUrl: 'https://fonts.googleapis.com/css2?family=Cinzel+Decorative&display=swap'
144 | }),
145 | fontSize: (wordCloudWord.weight / 10) * (max - min) + min,
146 | color: Math.random() < 0.5 ? Color.red() : new Color('#1E792C')
147 | });
148 | }
149 |
150 | // https://fonts.google.com/specimen/Fredericka+the+Great
151 | function stencilWeightFunction(wordCloudWord) {
152 | const max = 60;
153 | const min = 10;
154 | return new WordCloudProcessedWord({
155 | word: wordCloudWord.word,
156 | wordCloudFont: new WordCloudFont({
157 | fontName: 'Fredericka the Great',
158 | cssUrl: 'https://fonts.googleapis.com/css2?family=Fredericka+the+Great&display=swap'
159 | }),
160 | fontSize: (wordCloudWord.weight / 10) * (max - min) + min,
161 | color: Color.lightGray()
162 | });
163 | }
164 |
165 | /***************************************
166 | ***** EXAMPLE PLACEMENT FUNCTIONS *****
167 | ***************************************/
168 |
169 | /**
170 | * Please see this script for additional examples:
171 | * https://github.com/stanleyrya/scriptable-playground/blob/main/experiments/word-cloud-experiments/draw-spiral.js
172 | */
173 |
174 | function spiralPlacementFunction(width, height, centerX, centerY, xRatio, yRatio, previousResult) {
175 | let radius, radiusDirection, angle, angleDirection;
176 | if (previousResult) {
177 | ({
178 | radius,
179 | radiusDirection,
180 | angle,
181 | angleDirection
182 | } = previousResult);
183 | // Try these values too: 0.75 -> 0.1, 50 -> 100
184 | radius += .75 * radiusDirection;
185 | angle += (Math.PI * 2) / 50 * angleDirection;
186 | } else {
187 | radius = 0;
188 | angle = 0;
189 | radiusDirection = Math.random() < 0.5 ? -1 : 1;
190 | angleDirection = Math.random() < 0.5 ? -1 : 1;
191 | }
192 |
193 | const x = centerX + radius * Math.cos(angle) * xRatio;
194 | const y = centerY + radius * Math.sin(angle) * yRatio;
195 | return { x, y, radius, angle, radiusDirection, angleDirection }
196 | }
197 |
198 | function galaxyPlacementFunction(width, height, centerX, centerY, xRatio, yRatio, previousResult) {
199 | const i = previousResult ? previousResult.i + 1 : 0;
200 | const scale = 2;
201 | const dots = 10;
202 | const range = 234;
203 | const angle = Math.PI * range / 500 * i;
204 | const x = scale * angle * Math.cos(dots * angle) + centerX;
205 | const y = scale * angle * Math.sin(dots * angle) + centerY;
206 | return { x, y, angle, i }
207 | }
208 |
209 | function starPlacementFunction(width, height, centerX, centerY, xRatio, yRatio, previousResult) {
210 | let i = previousResult ?
211 | previousResult.i + 1 :
212 | 0;
213 | const scale = .25;
214 | const dots = 100;
215 | const range = 336;
216 | const angle = Math.PI * range / 500 * i;
217 | const x = scale * angle * Math.cos(dots * angle) + centerX;
218 | const y = scale * angle * Math.sin(dots * angle) + centerY;
219 | return { x, y, angle, i }
220 | }
221 |
222 | /*********************************
223 | ***** SAMPLE AND DEMO LOGIC *****
224 | *********************************/
225 |
226 | const wordCloudWords = [
227 | new WordCloudWord({ word: "Seattle", weight: 10 }),
228 | new WordCloudWord({ word: "Boston", weight: 10 }),
229 | new WordCloudWord({ word: "Chicago", weight: 8 }),
230 | new WordCloudWord({ word: "Denver", weight: 7 }),
231 | new WordCloudWord({ word: "Boise", weight: 7 }),
232 | new WordCloudWord({ word: "Los Angeles", weight: 7 }),
233 | new WordCloudWord({ word: "San Fransisco", weight: 6 }),
234 | new WordCloudWord({ word: "Victoria", weight: 6 }),
235 | new WordCloudWord({ word: "Portland", weight: 5 }),
236 | new WordCloudWord({ word: "London", weight: 5 }),
237 | new WordCloudWord({ word: "Dublin", weight: 3 }),
238 | new WordCloudWord({ word: "Barcelona", weight: 3 }),
239 | new WordCloudWord({ word: "Amsterdam", weight: 3 }),
240 | new WordCloudWord({ word: "Budapest", weight: 3 }),
241 | new WordCloudWord({ word: "Venice", weight: 3 }),
242 | new WordCloudWord({ word: "Florence", weight: 2 }),
243 | new WordCloudWord({ word: "Oslo", weight: 2 }),
244 | new WordCloudWord({ word: "Paris", weight: 2 }),
245 | new WordCloudWord({ word: "Tokyo", weight: 1 }),
246 | new WordCloudWord({ word: "New York", weight: 1 }),
247 | new WordCloudWord({ word: "Fort", weight: 1 })
248 | ];
249 |
250 | function createTitleRow(text) {
251 | const row = new UITableRow();
252 |
253 | const titleCell = row.addText(text);
254 | titleCell.titleFont = Font.mediumMonospacedSystemFont(20);
255 | titleCell.centerAligned();
256 |
257 | return row;
258 | }
259 |
260 | function createDescriptionRow(text, height, url, copyText) {
261 | const row = new UITableRow();
262 |
263 | const descriptionCell = row.addText(text);
264 | descriptionCell.titleFont = Font.mediumMonospacedSystemFont(12);
265 | descriptionCell.leftAligned();
266 |
267 | row.height = height || 50;
268 | if (url) {
269 | row.onSelect = () => Safari.open(url);
270 | } else if (copyText) {
271 | row.onSelect = () => Pasteboard.copyString(copyText)
272 | }
273 | return row;
274 | }
275 |
276 | // A replacer to be used with JSON.stringify when displaying WordCloud inputs examples
277 | function demoDisplayReplacer(key, val) {
278 | const blocklist = ['wordCloudWords'];
279 |
280 | if (typeof val === 'function') {
281 | return val.name;
282 | } else if (blocklist.includes(key)) {
283 | return;
284 | }
285 | return val;
286 | }
287 |
288 | // Replace {{INPUT_HERE}} with input
289 | // Mostly copied from minified wordcloud script
290 | const demoTemplate = `
291 | /**
292 | * Author: Ryan Stanley (stanleyrya@gmail.com)
293 | * Github: https://www.github.com/stanleyrya
294 | * Tips: https://www.paypal.me/stanleyrya
295 | *
296 | * A set of classes that can create a word cloud image. Basic Usage:
297 | * * const wordCloudWords = [new WordCloudWord({word, weight}), ...]
298 | * * const wordCloud = new WordCloud({width, height, wordCloudWords});
299 | * * const image = await wordCloud.getImage();
300 | *
301 | * This copy was created from the demo script and uses the minified objects
302 | * for readability. The demo, full version, and minified versions can all be
303 | * found in this github repo:
304 | * https://github.com/stanleyrya/scriptable-word-cloud
305 | *
306 | * Advanced features (explained in full version and demo):
307 | * * Modify how the words are displayed and processed (font, color, etc.)
308 | * * Modify how the words are placed on the word cloud (star shape, galaxy shape, etc.)
309 | * * Display the debugging algorithm by passing in debug=true
310 | * * and more!
311 | *
312 | * Here's the complete WordCloud constructor for the curious!
313 | * {
314 | * width, height, wordCloudWords, // required
315 | * respectScreenScale = true,
316 | * growToFit = true,
317 | * debug = false,
318 | * weightFunction = this._defaultWeightFunction,
319 | * placementFunction = this._defaultPlacementFunction,
320 | * growthFunction = this._defaultGrowthFunction,
321 | * }
322 | *
323 | */
324 | class WordCloudWord{constructor({word:r,weight:i}){if(!r)throw"word is required!";if(!i)throw"weight is required!";this.word=r,this.weight=i}}
325 | class WordCloudFont{constructor({fontName:s,cssUrl:o}){if(!s)throw"fontName is required!";this.fontName=s,this.cssURL=o}}
326 | class WordCloudProcessedWord{constructor({word:o,wordCloudFont:r,fontSize:d,color:t}){if(!o)throw"word is required!";if(!r)throw"wordCloudFont is required!";if(!(r instanceof WordCloudFont))throw"wordCloudFont must be a WordCloudFont object!";if(!d)throw"fontSize is required!";if(!t)throw"color is required!";this.word=o,this.wordCloudFont=r,this.fontSize=d,this.color=t}}
327 | class WordCloud{constructor({width:t,height:e,wordCloudWords:i,weightFunction:o=this._defaultWeightFunction,placementFunction:s=this._defaultPlacementFunction,growToFit:n=!0,growthFunction:h=this._defaultGrowthFunction,respectScreenScale:r=!0,debug:d=!1}){if(!t||!e||!i)throw"Could not get width, height, and wordCloudWords from input. Please see documentation.";this.providedWidth=t,this.providedHeight=e,this.placementFunction=s,this.weightFunction=o,this.growToFit=!!n,this.growthFunction=h,this.respectScreenScale=!!r,this.debug=!!d,this.processedWords=i.map(t=>this.weightFunction(t)),this.wordsToPlace=[...this.processedWords],this.placedWords=[],this.webView=new WebView,this.loadedCssUrls={},this.textDimensionsMap={},this.bufferRoom=10;const c=t>e?t:e;this.xRatio=t/c,this.yRatio=e/c}_defaultWeightFunction(t){return new WordCloudProcessedWord({word:t.word,wordCloudFont:new WordCloudFont({fontName:"TrebuchetMS-Bold"}),fontSize:t.weight/10*50+10,color:Device.isUsingDarkAppearance()?Color.white():Color.black()})}_defaultPlacementFunction(t,e,i,o,s,n,h){let r,d,c,a;return h?(({radius:r,radiusDirection:d,angle:c,angleDirection:a}=h),r+=.75*d,c+=2*Math.PI/50*a):(r=0,c=0,d=Math.random()<.5?-1:1,a=Math.random()<.5?-1:1),{x:i+r*Math.cos(c)*s,y:o+r*Math.sin(c)*n,radius:r,angle:c,radiusDirection:d,angleDirection:a}}_defaultGrowthFunction(t,e,i,o){return{width:t+.1*t,height:e+.1*e}}_loadFontToWebView(t,e){const i='
.
'.replace("REPLACE_HREF",e).replace("REPLACE_FONT_FAMILY",t);return this.webView.loadHTML(i)}_getTextDimensionsUsingWebView(t,e){const i='function getTextDimensions(t,e){const n=document.createElement("canvas").getContext("2d");n.font=e;const o=n.measureText(t);return{width:3*o.width/4,height:3*(o.actualBoundingBoxAscent+o.actualBoundingBoxDescent)/4}}getTextDimensions("REPLACE_TEXT","REPLACE_FONT");'.replace("REPLACE_TEXT",t).replace("REPLACE_FONT",e);return this.webView.evaluateJavaScript(i)}async _getTextDimensions(t,e,i){const o=i+"pt "+e.fontName,s=t+" "+o;if(this.textDimensionsMap[s])return this.textDimensionsMap[s];{e.cssURL&&(this.loadedCssUrls[e.cssURL]||(await this._loadFontToWebView(e.fontName,e.cssURL),this.loadedCssUrls[e.cssURL]=!0));const i=await this._getTextDimensionsUsingWebView(t,o);return this.textDimensionsMap[s]=i,i}}_checkRectCollision(t){for(const e of this.hitBoxes)if(t.minXe.minX-this.bufferRoom&&t.minYe.minY-this.bufferRoom)return!0;return!1}_checkRectOutsideBorders(t){return t.minX<0+this.bufferRoom||t.maxX>this.width-this.bufferRoom||t.minY<0+this.bufferRoom||t.maxY>this.height-this.bufferRoom}_checkPointCollision(t,e){for(const i of this.hitBoxes)if(ti.minX-this.bufferRoom&&ei.minY-this.bufferRoom)return!0;return!1}async _addTextCentered({x:t,y:e,processedWord:i,shouldDraw:o,checkHitboxes:s}){const{word:n,wordCloudFont:h,fontSize:r,color:d}=i,c=await this._getTextDimensions(n,h,r),a=t-c.width/2,l=e-c.height/2,w=new Rect(a,l,c.width,c.height);if(s&&this._checkRectCollision(w))return{textPlaced:!1,rectCollision:!0,outsideBorders:!1};if(this._checkRectOutsideBorders(w))return{textPlaced:!1,rectCollision:!1,outsideBorders:!0};if(this.debug&&console.log("writing "+n),this.hitBoxes.push(w),o){this.debug&&(this.ctx.setLineWidth(5),this.ctx.setStrokeColor(Color.red()),this.ctx.strokeRect(w));const t=c.height/4;this.ctx.setTextColor(d),this.ctx.setFont(new Font(h.fontName,r)),this.ctx.drawText(n,new Point(a,l-t))}return{textPlaced:!0,rectCollision:!1,outsideBorders:!1}}async _writeWithPlacementFunction(t,e){let i,o,s,n=!1,h=!1,r=!1,d=!1;const c=new Path;c.move(new Point(this.centerX,this.centerY));let a=!1;for(;!(n&&h&&r&&d);)if(i=this.placementFunction(this.width,this.height,this.centerX,this.centerY,this.xRatio,this.yRatio,i),({x:o,y:s}=i),this.debug&&e&&c.addLine(new Point(o,s)),!this._checkPointCollision(o,s)){if(t){const{textPlaced:i,rectCollision:n,outsideBorders:h}=await this._addTextCentered({x:o,y:s,processedWord:t,shouldDraw:e,checkHitboxes:!0});if(i){this.placedWords.push({xFromCenter:o-this.centerX,yFromCenter:s-this.centerY,processedWord:t}),this.wordsToPlace.shift(),a=!0;break}if(h&&this.growToFit)break}o<0&&(n=!0),o>this.width&&(h=!0),s<0&&(r=!0),s>this.height&&(d=!0)}return this.debug&&e&&(this.ctx.setLineWidth(1),this.ctx.addPath(c),this.ctx.setStrokeColor(new Color("6693F5")),this.ctx.strokePath()),a}async _writePendingWords(t){this.debug&&console.log("writing pending words");let e=!0;const i=[...this.wordsToPlace];for(const o of i)if(!await this._writeWithPlacementFunction(o,t)&&(e=!1,this.growToFit))return!1;return e}async _writeAlreadyPlacedWords(t){this.debug&&console.log("writing already placed words");for(const e of this.placedWords)await this._addTextCentered({x:e.xFromCenter+this.centerX,y:e.yFromCenter+this.centerY,processedWord:e.processedWord,shouldDraw:t,checkHitboxes:!1})}async _getWordStats(){let t=0,e=0,i=0;for(const o of this.processedWords){const{word:s,wordCloudFont:n,fontSize:h,color:r}=o,d=await this._getTextDimensions(s,n,h);tt/2&&(i+=c.height),c.height>e/2&&(o+=c.width)}return{stackedMinWidth:o,stackedMinHeight:i}}async _preflightGrow(t,e){let i=t,o=e;const{minWidth:s,minHeight:n,minArea:h}=await this._getWordStats();for(;s>i||n>o;)console.log("increasing because of min width or height"),({width:i,height:o}=this.growthFunction(i,o,this.providedWidth,this.providedHeight));for(;h>i*o;)console.log("increasing because of min area"),({width:i,height:o}=this.growthFunction(i,o,this.providedWidth,this.providedHeight));let{stackedMinWidth:r,stackedMinHeight:d}=await this._getStackedMinDimensions(i,o);for(;r>i||d>o;)console.log("increasing because of stacked width or height"),({width:i,height:o}=this.growthFunction(i,o,this.providedWidth,this.providedHeight)),({stackedMinWidth:r,stackedMinHeight:d}=await this._getStackedMinDimensions(i,o));return{width:i,height:o}}async getImage(){let t=this.providedWidth,e=this.providedHeight;this.growToFit&&({width:t,height:e}=await this._preflightGrow(t,e));let i=!1;for(;!i&&(this.width=t,this.height=e,this.centerX=t/2,this.centerY=e/2,this.hitBoxes=[],await this._writeAlreadyPlacedWords(!1),i=await this._writePendingWords(!1),this.growToFit);)i||(console.log("increasing because words couldn't fit area"),({width:t,height:e}=this.growthFunction(t,e,this.providedWidth,this.providedHeight)));return this.ctx=new DrawContext,this.ctx.opaque=!1,this.ctx.respectScreenScale=this.respectScreenScale,this.ctx.size=new Size(t,e),this.debug&&(this.ctx.setLineWidth(5),this.ctx.setStrokeColor(Color.red()),this.ctx.strokeRect(new Rect(0,0,t,e)),await this._writeWithPlacementFunction(null,!0)),await this._writeAlreadyPlacedWords(!0),this.ctx.getImage()}}
328 |
329 | // Sample input
330 |
331 | const wordCloud = new WordCloud({{INPUT_HERE}});
332 | const image = await wordCloud.getImage();
333 |
334 | // Sample usage
335 |
336 | const widget = new ListWidget();
337 | widget.setPadding(0, 0, 0, 0);
338 | const widgetImage = widget.addImage(image);
339 | widgetImage.applyFillingContentMode();
340 | widgetImage.centerAlignImage();
341 | // The word cloud image has a clear background.
342 | // The default weight function uses Device.isUsingDarkAppearance()
343 | // to set the font color. It is slow to update
344 | // which could make the font blend in with the
345 | // widget's automatic background. To protect
346 | // against this you can set the background explicitly:
347 | widget.backgroundColor = Device.isUsingDarkAppearance() ? Color.black() : Color.white();
348 |
349 | // Alternatively, consider adding an image as the background :)
350 | // widget.backgroundImage = await new Request('YOUR IMAGE URL').loadImage();
351 |
352 | if (config.runsInWidget) {
353 | Script.setWidget(widget);
354 | Script.complete();
355 | } else {
356 | widget.presentLarge();
357 | }
358 |
359 | `
360 |
361 | // Given an object that contains functions, stringify them in a way that can still be run as a script.
362 | function createCopyPasteableInput(wordCloudData) {
363 | function demoCopyReplacer(key, val) {
364 | if (typeof val === 'function') {
365 | return val.toString().replace(/(\r\n|\n|\r)/gm, "");
366 | }
367 | return val;
368 | }
369 | const objWithStringFuncs = JSON.stringify(wordCloudData, demoCopyReplacer, "\t");
370 |
371 | function removeQuotes(match, p1, offset, string) {
372 | const fixedFunc = p1.slice(1, -1);
373 | return match.replace(p1, fixedFunc);
374 | }
375 | const objWithRealFuncs = objWithStringFuncs.replace(/^.*Function".*: (".*")/gm, removeQuotes);
376 |
377 | return demoTemplate.replace("{{INPUT_HERE}}", objWithRealFuncs)
378 | }
379 |
380 | async function createDemoRow(wordCloudData, showJson = true, displayImageUrl) {
381 | const smallRow = new UITableRow();
382 | smallRow.height = 150;
383 |
384 | const input = JSON.stringify(wordCloudData, demoDisplayReplacer, "\t");
385 | if (wordCloudData.width === undefined) {
386 | wordCloudData.width = 250;
387 | }
388 | if (wordCloudData.height === undefined) {
389 | wordCloudData.height = 250;
390 | }
391 | wordCloudData.wordCloudWords = wordCloudWords;
392 |
393 | let image;
394 | if (displayImageUrl) {
395 | image = await new Request(displayImageUrl).loadImage();
396 | } else {
397 | const wordCloud = new WordCloud(wordCloudData);
398 | image = await wordCloud.getImage();
399 | }
400 |
401 | const imageCell = smallRow.addImage(image);
402 | imageCell.centerAligned();
403 |
404 | if (showJson) {
405 | const textCell = smallRow.addText(input);
406 | textCell.titleFont = Font.mediumMonospacedSystemFont(12);
407 | smallRow.onSelect = () => Pasteboard.copyString(createCopyPasteableInput(wordCloudData));
408 | }
409 |
410 | return smallRow;
411 | }
412 |
413 | async function createDemoTable() {
414 | const table = new UITable();
415 |
416 | const rows = [
417 | createTitleRow("Dynamic Word Cloud!"),
418 | await createDemoRow({ width: 700, height: 250 }, false),
419 | createDescriptionRow("This demo shows off a dynamic word cloud class that can be copy-pasted to your own script! Throughout the demo simply press on an example row to copy a full-working Scriptable script. These examples use a minified version of the word cloud classes which are easier to read. You can also cut to the chase and use either the normal [1] or minified [2] versions on Github. I strongly recommend using the minified version to start.", 160),
420 | createDescriptionRow(`-> [1] - https://github.com/stanleyrya/scriptable-word-cloud/blob/main/word-cloud.js`, 60, "https://github.com/stanleyrya/scriptable-word-cloud/blob/main/word-cloud.js"),
421 | createDescriptionRow(`-> [2] - https://github.com/stanleyrya/scriptable-word-cloud/blob/main/minified-word-cloud.js`, 60, "https://github.com/stanleyrya/scriptable-word-cloud/blob/main/minified-word-cloud.js"),
422 |
423 | createDescriptionRow("There are only three required fields: Width, Height, and WordCloudWords. WordCloudWords are objects with two properties: Word (string) and Weight (number). Here's an example of a WordCloudWords array:", 80),
424 | createDescriptionRow(JSON.stringify(wordCloudWords, undefined, "\t"), 300),
425 | createDescriptionRow("This object could be static or you could code something to generate it. I recommend calculating a word's weight by it's frequency in a dataset (Calendar events, weather, etc.), but you could use whatever you want!", 100),
426 |
427 | createDescriptionRow("Next is Width and Height. These are pretty simple to work with. Here are some examples:", 60),
428 | await createDemoRow({ width: 250, height: 250 }),
429 | await createDemoRow({ width: 530, height: 250 }),
430 | createDescriptionRow("The word cloud is generated dynamically so it can fit different widget sizes. It will also work with weirder sizes like long ones. Get creative!", 60),
431 | await createDemoRow({ width: 200, height: 600 }),
432 | createDescriptionRow("The next sections will use the sample WordCloudWords object and a Width and Height of 250 each. Remember you can press any example row to get a working script example. Have fun!", 80),
433 |
434 |
435 | // -------------------------------- //
436 |
437 | createTitleRow("Flags!"),
438 | createDescriptionRow("Now we get to the fun stuff. Here are some flags that you can pass in to modify the word cloud's behavior. When debug is set to true it will display the 'hitboxes' used in the placement algorithm for each word. it will also display the placement algorithm's path:", 120),
439 | await createDemoRow({ debug: true }),
440 | createDescriptionRow("The growToFit flag determines whether or not the canvas will 'grow' to fit all of the words provided. When set to true (default) it will continuously increase the size of the canvas until all of the provided words can be placed. If it is set to false it will simply try to place words as best it can:", 120),
441 | await createDemoRow({ growToFit: false }),
442 | createDescriptionRow("The respectScreenScale flag is passed to the DrawContext [1]. If you are running into performance issues (for example, the script does not display on the homescreen) please try setting this to false. Until a performance update is made to the script you can also try removing words until it displays.", 120),
443 | createDescriptionRow(`-> [1] - https://docs.scriptable.app/drawcontext/#respectscreenscale`, 60, "https://docs.scriptable.app/drawcontext/#respectscreenscale"),
444 | await createDemoRow({ respectScreenScale: false }),
445 |
446 | // -------------------------------- //
447 |
448 | createTitleRow("Placement Functions!"),
449 | createDescriptionRow("Placement functions are plotting functions that return (x,y) coordinates. They are called continuously until all of the words can be plotted with their center on a coordinate (or there is no more space if growToFit is false). They can be confusing at first but they are very powerful. Before we get into it, here's an example:", 140),
450 | createDescriptionRow(`
451 | function spiralPlacementFunction(width, height, centerX, centerY, xRatio, yRatio, previousResult) {
452 | let radius, angle;
453 |
454 | if (previousResult) {
455 | ({ radius, angle } = previousResult);
456 | radius += .75;
457 | angle += (Math.PI * 2) / 50;
458 | } else {
459 | radius = 0;
460 | angle = 0;
461 | }
462 |
463 | const x = centerX + radius * Math.cos(angle) * xRatio;
464 | const y = centerY + radius * Math.sin(angle) * yRatio;
465 | return { x, y, radius, angle }
466 | }
467 | `, 320),
468 | createDescriptionRow("The inputs width, height, centerX, and centerY are pretty straightforward. xRatio and yRatio are the ratio of the side compared to the largest side and can be useful when scaling the algorithm for different input parameters. PreviousResult contains the results from the last iteration of the algorithm, which at a minimum includes the last x and y values. If it's helpful you can pass additional values in the result and use it in the next iteration, like radius and angle in the example.", 180),
469 | createDescriptionRow("I recommend reading the example functions and modifying them to understand how they work. I also recommend googling some cool (x,y) plots and converting them to placement functions. For investigation you could modify my script here:", 100),
470 | createDescriptionRow("-> https://github.com/stanleyrya/scriptable-playground/blob/main/experiments/word-cloud-experiments/draw-spiral.js", 60, 'https://github.com/stanleyrya/scriptable-playground/blob/main/experiments/word-cloud-experiments/draw-spiral.js'),
471 | createDescriptionRow("Here are some placement algorithms I created that are different than the provided spiral one. When the debug parameter is set to true you can see what the algorithm is plotting. Please note that respectScreenScale may need to be set to false in order to render these on the home screen due to memory limitations.", 140),
472 | await createDemoRow({
473 | placementFunction: galaxyPlacementFunction,
474 | respectScreenScale: false,
475 | }),
476 | await createDemoRow({
477 | placementFunction: galaxyPlacementFunction,
478 | respectScreenScale: false,
479 | debug: true
480 | }),
481 | await createDemoRow({
482 | placementFunction: starPlacementFunction,
483 | respectScreenScale: false,
484 | }),
485 | await createDemoRow({
486 | placementFunction: starPlacementFunction,
487 | respectScreenScale: false,
488 | debug: true
489 | }),
490 |
491 | // -------------------------------- //
492 |
493 | createTitleRow("Weight Functions!"),
494 | createDescriptionRow("Word clouds aren't complete without modifying the font! A weight function can be provided to modify how the words are displayed. You can use this function to convert weight to size, font type, opacity, color, and more! Here's the default method for context:", 120),
495 | createDescriptionRow(`
496 | /**
497 | * @param {WordCloudWord} wordCloudWord
498 | * - The word that is being processed.
499 | * @return {WordCloudProcessedWord}
500 | * - The word after processing.
501 | */
502 | _defaultWeightFunction(wordCloudWord) {
503 | const max = 60;
504 | const min = 10;
505 | return new WordCloudProcessedWord({
506 | word: wordCloudWord.word,
507 | wordCloudFont: new WordCloudFont({
508 | fontName: "TrebuchetMS-Bold"
509 | }),
510 | fontSize: (wordCloudWord.weight / 10) * (max - min) + min,
511 | color: Device.isUsingDarkAppearance() ? Color.white() : Color.black()
512 | });
513 | }
514 | `, 360),
515 | createDescriptionRow("Just as I mentioned above, I recommend playing with the functions provided and getting creative. Here are some examples using built-in fonts:", 60),
516 | await createDemoRow({
517 | weightFunction: builtInFestiveWeightFunction,
518 | }),
519 | await createDemoRow({
520 | weightFunction: hackerWeightFunction,
521 | }),
522 |
523 | // -------------------------------- //
524 |
525 | createTitleRow("... with Custom Fonts!"),
526 | createDescriptionRow("You can use custom fonts too! Before you get too excited custom fonts require specific setup and are not guarranteed to work. The word cloud algorithm depends on generating word 'hitboxes' to make sure words don't overlap with each other. At this time the hitboxes are generated by rendering the word with Scriptable's WebView tool. Custom fonts aren't referencable from within the tool so they have to be installed on the fly using a CSS stylesheet URL. The word cloud itself is being rendered using Scriptable's DrawContext so the font needs to be installed locally too for the whole thing to work.", 240),
527 | createDescriptionRow("TL;DR: You need to both install the font locally and provide a reference to the CSS stylesheet hosted somewhere online to use custom fonts. This has currently only been tested with Google fonts. Here's an example:", 100),
528 | createDescriptionRow(`
529 | // https://fonts.google.com/specimen/Lacquer
530 | function spookyWeightFunction(wordCloudWord) {
531 | return new WordCloudProcessedWord({
532 | word: wordCloudWord.word,
533 | wordCloudFont: new WordCloudFont({
534 | fontName: "Lacquer",
535 | cssUrl: "https://fonts.googleapis.com/css2?family=Lacquer&display=swap"
536 | }),
537 | fontSize: (wordCloudWord.weight / 10) * (maxFont - minFont) + minFont,
538 | color: Color.orange()
539 | });
540 | }
541 | `, 240),
542 | createDescriptionRow(`The fontName is the font family. This article [1] suggests this app [2] is the safest way to download fonts to iOS. Be careful, use at your own risk!`, 100),
543 | createDescriptionRow(`-> [1] - https://9to5mac.com/2020/06/12/fontcase-open-source-fonts-app-iphone-ipad`, 60, "https://9to5mac.com/2020/06/12/fontcase-open-source-fonts-app-iphone-ipad"),
544 | createDescriptionRow(`-> [2] - https://apps.apple.com/us/app/fontcase-manage-your-type/id1205074470`, 60, "https://apps.apple.com/us/app/fontcase-manage-your-type/id1205074470"),
545 | createDescriptionRow(`After all of that hassle I hope you agree the effort is worth it! Once these fonts are installed they will begin working:`, 60),
546 | createDescriptionRow(`-> https://fonts.google.com/specimen/Lacquer`, 60, "https://fonts.google.com/specimen/Lacquer"),
547 | await createDemoRow({
548 | weightFunction: spookyWeightFunction,
549 | }),
550 | createDescriptionRow(`-> https://fonts.google.com/specimen/Cinzel+Decorative`, 60, "https://fonts.google.com/specimen/Cinzel+Decorative"),
551 | await createDemoRow({
552 | weightFunction: customFestiveWeightFunction,
553 | }),
554 | createDescriptionRow(`-> https://fonts.google.com/specimen/Fredericka+the+Great`, 60, "https://fonts.google.com/specimen/Fredericka+the+Great"),
555 | await createDemoRow({
556 | weightFunction: stencilWeightFunction,
557 | }),
558 |
559 |
560 | // -------------------------------- //
561 |
562 |
563 | createTitleRow("Putting it all together!"),
564 | createDescriptionRow("All of these features can be joined together with backgrounds to create beautiful word clouds. The word cloud class is transparent, so simply add another image as the background image and voila! For widgets you can add this to your script:", 100),
565 | createDescriptionRow(`
566 | widget.backgroundImage = await new Request('YOUR IMAGE URL').loadImage();
567 | `, 60),
568 | createDescriptionRow("Please note that these scripts won't automatically work by copy-paste like the others in the demo. At this time you will need to copy-paste the image URL into the script to get it working. Sorry!", 80),
569 | createDescriptionRow(`copy -> https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/main/images/milky-way.HEIC`, 60, undefined, "https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/main/images/milky-way.HEIC"),
570 | await createDemoRow({
571 | weightFunction: celestialWeightFunction,
572 | placementFunction: galaxyPlacementFunction,
573 | respectScreenScale: false,
574 | }, true, 'https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/main/images/17-celestial-background.PNG'),
575 | createDescriptionRow(`copy -> https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/main/images/mountain.JPG`, 60, undefined, "https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/main/images/mountain.JPG"),
576 | await createDemoRow({
577 | weightFunction: builtInFestiveWeightFunction,
578 | }, true, 'https://raw.githubusercontent.com/stanleyrya/scriptable-word-cloud/main/images/18-festive-background.PNG'),
579 |
580 | // -------------------------------- //
581 |
582 | createTitleRow("Thank You!"),
583 | createDescriptionRow(`If you enjoyed this demo or the scripts please consider buying me a coffee! I'd also love it if you tried out my other scripts on GitHub. Thanks again!`, 60),
584 | createDescriptionRow("-> https://www.github.com/stanleyrya", 40, "https://www.github.com/stanleyrya"),
585 | createDescriptionRow("-> https://www.paypal.me/stanleyrya", 40, "https://www.paypal.me/stanleyrya"),
586 | ];
587 |
588 | rows.forEach((row) => {
589 | // Device.isUsingDarkAppearance() is slow to update, but seems to be the
590 | // only way to safely update the background and font color at the same time.
591 | // This is partly due to Color.dynamic() not working in the Draw Context.
592 | row.backgroundColor = Device.isUsingDarkAppearance() ? Color.black() : Color.white();
593 | table.addRow(row);
594 | });
595 | return table;
596 | }
597 |
598 | await QuickLook.present(await createDemoTable());
599 |
--------------------------------------------------------------------------------
/word-cloud.js:
--------------------------------------------------------------------------------
1 | // Variables used by Scriptable.
2 | // These must be at the very top of the file. Do not edit.
3 | // icon-color: cyan; icon-glyph: cloud;
4 | /**
5 | * Author: Ryan Stanley (stanleyrya@gmail.com)
6 | * Github: https://www.github.com/stanleyrya
7 | * Tips: https://www.paypal.me/stanleyrya
8 | *
9 | * A set of classes that can create a word cloud image. Basic Usage:
10 | * * const wordCloudWords = [new WordCloudWord({word, weight}), ...]
11 | * * const wordCloud = new WordCloud({width, height, wordCloudWords});
12 | * * const image = await wordCloud.getImage();
13 | *
14 | * This is the full version to make the script easier to edit,
15 | * but a minified version (MUCH easier to read) along with a demo can be found here:
16 | * https://github.com/stanleyrya/scriptable-word-cloud
17 | *
18 | * Advanced features (explained in the comments and demo):
19 | * * Modify how the words are displayed and processed (font, color, etc.)
20 | * * Modify how the words are placed on the word cloud (star shape, galaxy shape, etc.)
21 | * * Display the debugging algorithm by passing in debug=true
22 | * * and more!
23 | *
24 | * Here's the complete WordCloud constructor for the curious!
25 | * {
26 | * width, height, wordCloudWords, // required
27 | * respectScreenScale = true,
28 | * growToFit = true,
29 | * debug = false,
30 | * weightFunction = this._defaultWeightFunction,
31 | * placementFunction = this._defaultPlacementFunction,
32 | * growthFunction = this._defaultGrowthFunction,
33 | * }
34 | *
35 | * This script is split into four sections to make it easier to edit:
36 | * 1. WORD CLOUD OBJECTS
37 | * 2. EXAMPLE WEIGHT FUNCTIONS (the `weightFunction` parameter!)
38 | * 3. EXAMPLE PLACEMENT FUNCTIONS (the `placementFunction` parameter!)
39 | * 4. SAMPLE LOGIC
40 | */
41 |
42 | /******************************
43 | ***** WORD CLOUD OBJECTS *****
44 | ******************************/
45 |
46 | /**
47 | * A word that can be used by the WordCloud.
48 | */
49 | class WordCloudWord {
50 | constructor({ word, weight }) {
51 | if (!word) {
52 | throw ("word is required!");
53 | }
54 | if (!weight) {
55 | throw ("weight is required!");
56 | }
57 | this.word = word;
58 | this.weight = weight;
59 | }
60 | }
61 |
62 | /**
63 | * A font that can be used in a WordCloud.
64 | *
65 | * Please note that pre-installed fonts need to use
66 | * the name provieded here: http://iosfonts.com
67 | * For example: TrebuchetMS-Bold
68 | *
69 | * Custom fonts such as google's fonts need to use
70 | * the name of their font family and the URL to
71 | * their css stylesheet. Here's an example for
72 | * google:
73 | * https://fonts.google.com/specimen/Fredericka+the+Great?sidebar.open=true&selection.family=Fredericka+the+Great#about
74 | * -> fontName: Fredericka the Great
75 | * -> cssUrl: https://fonts.googleapis.com/css2?family=Fredericka+the+Great&display=swap
76 | */
77 | class WordCloudFont {
78 | constructor({ fontName, cssUrl }) {
79 | if (!fontName) {
80 | throw ("fontName is required!");
81 | }
82 | this.fontName = fontName;
83 | this.cssURL = cssUrl; // only for custom fonts
84 | }
85 | }
86 |
87 | /**
88 | * A word after processing from a weight function.
89 | * All weight functions, including the default, must
90 | * return WordCloudProcessedWords.
91 | */
92 | class WordCloudProcessedWord {
93 | constructor({ word, wordCloudFont, fontSize, color }) {
94 | if (!word) {
95 | throw ("word is required!");
96 | }
97 | if (!wordCloudFont) {
98 | throw ("wordCloudFont is required!");
99 | }
100 | if (!(wordCloudFont instanceof WordCloudFont)) {
101 | throw ("wordCloudFont must be a WordCloudFont object!");
102 | }
103 | if (!fontSize) {
104 | throw ("fontSize is required!");
105 | }
106 | if (!color) {
107 | throw ("color is required!");
108 | }
109 | this.word = word;
110 | this.wordCloudFont = wordCloudFont;
111 | this.fontSize = fontSize;
112 | this.color = color;
113 | }
114 | }
115 |
116 | /**
117 | * A word cloud.
118 | */
119 | class WordCloud {
120 |
121 | /**
122 | * Required:
123 | *
124 | * @param {number} width
125 | * - The width of the canvas.
126 | * @param {number} height
127 | * - The height of the canvas.
128 | * @param {WordCloudWord[]} wordData
129 | * - The words that will be displayed on the
130 | * canvas.
131 | *
132 | * Optional:
133 | *
134 | * @param {weightFunction}
135 | * [weightFunction=this._defaultWeightFunction]
136 | * - A function that processes words before they
137 | * are placed on the canvas.
138 | * @param {placementFunction}
139 | * [placementFunction=this._defaultPlacementFunction]
140 | * - A function that decides where the next word
141 | * should attempt to be placed.
142 | * @param {boolean} [growToFit=true]
143 | * - A boolean that determines if the word cloud
144 | * should expand the canvas to fit all of the
145 | * provided words.
146 | * @param {growthFunction}
147 | * [growthFunction=this._defaultGrowthFunction]
148 | * - A function that determines how the canvas
149 | * should grow if growToFit is true.
150 | * @param {boolean} [respectScreenScale=true]
151 | * - A boolean that modifies the
152 | * "respectScreenScale" feature in the
153 | * DrawContext. Turning it off may help
154 | * performance and memory issues on the
155 | * homescreen.
156 | * @param {boolean} [debug=false]
157 | * - A boolean that writes additional context to
158 | * the canvas for debugging.
159 | */
160 | constructor({
161 | width,
162 | height,
163 | wordCloudWords,
164 | weightFunction = this._defaultWeightFunction,
165 | placementFunction = this._defaultPlacementFunction,
166 | growToFit = true,
167 | growthFunction = this._defaultGrowthFunction,
168 | respectScreenScale = true,
169 | debug = false
170 | }) {
171 | if (!width || !height || !wordCloudWords) {
172 | throw ("Could not get width, height, and wordCloudWords from input. Please see documentation.");
173 | }
174 |
175 | this.providedWidth = width;
176 | this.providedHeight = height;
177 | this.placementFunction = placementFunction;
178 | this.weightFunction = weightFunction;
179 | this.growToFit = !!growToFit;
180 | this.growthFunction = growthFunction;
181 | this.respectScreenScale = !!respectScreenScale;
182 | this.debug = !!debug;
183 |
184 | this.processedWords = wordCloudWords.map(wordCloudWord => this.weightFunction(wordCloudWord));
185 | this.wordsToPlace = [...this.processedWords];
186 | this.placedWords = [];
187 |
188 | this.webView = new WebView();
189 | this.loadedCssUrls = {};
190 | this.textDimensionsMap = {};
191 |
192 | // Controls buffer around words and border
193 | this.bufferRoom = 10;
194 |
195 | // Can be used to stretch the placementFunction
196 | const biggestSide = width > height ? width : height;
197 | this.xRatio = width / biggestSide;
198 | this.yRatio = height / biggestSide;
199 | }
200 |
201 | /**
202 | * This is the default weight function that gets
203 | * included with the WordCloud class.
204 | * Please use it as an example!
205 | *
206 | * @param {WordCloudWord} wordCloudWord
207 | * - The word that is being processed.
208 | * @return {WordCloudProcessedWord}
209 | * - The word after processing.
210 | */
211 | _defaultWeightFunction(wordCloudWord) {
212 | const max = 60;
213 | const min = 10;
214 | return new WordCloudProcessedWord({
215 | word: wordCloudWord.word,
216 | wordCloudFont: new WordCloudFont({
217 | fontName: "TrebuchetMS-Bold"
218 | }),
219 | fontSize: (wordCloudWord.weight / 10) * (max - min) + min,
220 | color: Device.isUsingDarkAppearance() ? Color.white() : Color.black()
221 | });
222 | }
223 |
224 | /**
225 | * This is the default placement function that gets
226 | * included with the WordCloud class.
227 | * Please use it as an example!
228 | *
229 | * @param {number} width - of the Canvas (after growth if applicable)
230 | * @param {number} height - of the Canvas (after growth if applicable)
231 | * @param {number} centerX - center X value
232 | * @param {number} centerY - center Y value
233 | * @param {number} xRatio - (width / biggestSide) - useful for scaling
234 | * @param {number} yRatio - (height / biggestSide) - useful for scaling
235 | * @param {Object} previousResult
236 | * - The previously returned object. Useful to
237 | * store state.
238 | * @return { number, number, ... } { x, y, ... }
239 | * - The new x and y after processing. Return
240 | * any other information you may find useful!
241 | */
242 | _defaultPlacementFunction(width, height, centerX, centerY, xRatio, yRatio, previousResult) {
243 | let radius, radiusDirection, angle, angleDirection;
244 | if (previousResult) {
245 | ({
246 | radius,
247 | radiusDirection,
248 | angle,
249 | angleDirection
250 | } = previousResult);
251 | // Try these values too: 0.75 -> 0.1, 50 -> 100
252 | radius += .75 * radiusDirection;
253 | angle += (Math.PI * 2) / 50 * angleDirection;
254 | } else {
255 | radius = 0;
256 | angle = 0;
257 | radiusDirection = Math.random() < 0.5 ? -1 : 1;
258 | angleDirection = Math.random() < 0.5 ? -1 : 1;
259 | }
260 |
261 | const x = centerX + radius * Math.cos(angle) * xRatio;
262 | const y = centerY + radius * Math.sin(angle) * yRatio;
263 | return { x, y, radius, angle, radiusDirection, angleDirection };
264 | }
265 |
266 | /**
267 | * This is the default growth function that gets
268 | * included with the WordCloud class.
269 | * Please use it as an example!
270 | *
271 | * @param {number} currentWidth
272 | * @param {number} currentHeight
273 | * @param {number} originalWidth
274 | * @param {number} originalHeight
275 | * @return { number, number } { width, height }
276 | * - The new width and height after processing.
277 | */
278 | _defaultGrowthFunction(currentWidth, currentHeight, originalWidth, originalHeight) {
279 | return {
280 | width: currentWidth + currentWidth * 0.1,
281 | height: currentHeight + currentHeight * 0.1
282 | };
283 | }
284 |
285 | /**
286 | * Uses Scriptable's WebView to load a custom font.
287 | * iOS custom fonts aren't loaded on the HTML
288 | * document canvas so they have to be loaded using
289 | * their css stylesheet.
290 | *
291 | * @param {string} fontFamily
292 | * - The font family being loaded.
293 | * @param {string} fontCssUrl
294 | * - The css url that will be loaded.
295 | * @return {Promise}
296 | * - A promise that the font was loaded.
297 | */
298 | _loadFontToWebView(fontFamily, fontCssUrl) {
299 | const html = `
300 | // Preconnecting could decrease load time if using a Google font
301 | // https://www.cdnplanet.com/blog/faster-google-webfonts-preconnect/
302 |
303 |
304 |
305 |
306 | // Load the font so its available in the canvas
307 |
.
308 | `
309 | .replace("REPLACE_HREF", fontCssUrl)
310 | .replace("REPLACE_FONT_FAMILY", fontFamily);
311 |
312 | return this.webView.loadHTML(html);
313 | }
314 |
315 | /**
316 | * Uses Scriptable's WebView to call
317 | * canvas.measureText on the given text of given
318 | * font in pixels.
319 | *
320 | * @param {string} text
321 | * - The text to be rendered.
322 | * @param {string} font
323 | * - The css font descriptor that text is to be
324 | * rendered with (e.g. "bold 14px verdana").
325 | * @return { number, number } { width, height }
326 | * - The width and height of the text.
327 | *
328 | * @see Inspired from: https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
329 | */
330 | _getTextDimensionsUsingWebView(text, cssFont) {
331 | const javascript = `
332 | function getTextDimensions(text, font) {
333 | const canvas = document.createElement("canvas");
334 | const context = canvas.getContext("2d");
335 | context.font = font;
336 | const metrics = context.measureText(text);
337 | return {
338 | // I'm not sure why yet but 3/4 is perfect for Scriptable's DrawContext
339 | width: metrics.width * 3/4,
340 | height: (metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent) * 3/4
341 | };
342 | }
343 |
344 | getTextDimensions("REPLACE_TEXT", "REPLACE_FONT");
345 | `
346 | .replace("REPLACE_TEXT", text)
347 | .replace("REPLACE_FONT", cssFont);
348 |
349 | return this.webView.evaluateJavaScript(javascript);
350 | }
351 |
352 | /**
353 | * The Scriptable WebView can use the HTML document
354 | * canvas to measure a word's width and height. It
355 | * can't return an image file so the rest of the
356 | * script uses the Scriptable DrawContext to create
357 | * the image.
358 | *
359 | * Custom fonts aren't loaded on the HTML document
360 | * canvas so they have to be loaded using their css
361 | * stylesheet.
362 | */
363 | async _getTextDimensions(text, wordCloudFont, fontSize) {
364 | const cssFont = fontSize + "pt " + wordCloudFont.fontName;
365 | const key = text + " " + cssFont;
366 |
367 | if (this.textDimensionsMap[key]) {
368 | return this.textDimensionsMap[key];
369 | } else {
370 | // If we are using a custom font and it hasn't
371 | // been loaded before, load it to the WebView.
372 | if (wordCloudFont.cssURL) {
373 | if (!this.loadedCssUrls[wordCloudFont.cssURL]) {
374 | await this._loadFontToWebView(wordCloudFont.fontName, wordCloudFont.cssURL);
375 | this.loadedCssUrls[wordCloudFont.cssURL] = true;
376 | }
377 | }
378 |
379 | const value = await this._getTextDimensionsUsingWebView(text, cssFont);
380 | this.textDimensionsMap[key] = value;
381 | return value;
382 | }
383 | }
384 |
385 | /**
386 | * Does the new rectangle hit any of the existing
387 | * ones?
388 | *
389 | * if (RectA.Left < RectB.Right &&
390 | * RectA.Right > RectB.Left &&
391 | * RectA.Top < RectB.Bottom &&
392 | * RectA.Bottom > RectB.Top)
393 | *
394 | * https://stackoverflow.com/a/306332
395 | */
396 | _checkRectCollision(newRect) {
397 | for (const placedRect of this.hitBoxes) {
398 | if (newRect.minX < placedRect.maxX + this.bufferRoom &&
399 | newRect.maxX > placedRect.minX - this.bufferRoom &&
400 | newRect.minY < placedRect.maxY + this.bufferRoom &&
401 | newRect.maxY > placedRect.minY - this.bufferRoom) {
402 | return true;
403 | }
404 | }
405 | return false;
406 | }
407 |
408 | /**
409 | * Does the new rectangle hit any of the sides?
410 | */
411 | _checkRectOutsideBorders(newRect) {
412 | if (newRect.minX < 0 + this.bufferRoom ||
413 | newRect.maxX > this.width - this.bufferRoom ||
414 | newRect.minY < 0 + this.bufferRoom ||
415 | newRect.maxY > this.height - this.bufferRoom) {
416 | return true;
417 | }
418 | return false;
419 | }
420 |
421 | /**
422 | * Does the point hit any of the existing
423 | * rectangles?
424 | */
425 | _checkPointCollision(x, y) {
426 | for (const placedRect of this.hitBoxes) {
427 | if (x < placedRect.maxX + this.bufferRoom &&
428 | x > placedRect.minX - this.bufferRoom &&
429 | y < placedRect.maxY + this.bufferRoom &&
430 | y > placedRect.minY - this.bufferRoom) {
431 | return true;
432 | }
433 | }
434 | return false;
435 | }
436 |
437 | async _addTextCentered({ x, y, processedWord, shouldDraw, checkHitboxes }) {
438 | const { word, wordCloudFont, fontSize, color } = processedWord;
439 | const dimensions = await this._getTextDimensions(word, wordCloudFont, fontSize);
440 | const topLeftX = x - (dimensions.width / 2);
441 | const topLeftY = y - (dimensions.height / 2);
442 | const rect = new Rect(
443 | topLeftX,
444 | topLeftY,
445 | dimensions.width,
446 | dimensions.height
447 | );
448 |
449 | if (checkHitboxes && this._checkRectCollision(rect)) {
450 | return {
451 | textPlaced: false,
452 | rectCollision: true,
453 | outsideBorders: false
454 | };
455 | }
456 | if (this._checkRectOutsideBorders(rect)) {
457 | return {
458 | textPlaced: false,
459 | rectCollision: false,
460 | outsideBorders: true
461 | };
462 | }
463 |
464 | if (this.debug) {
465 | console.log("writing " + word);
466 | }
467 | this.hitBoxes.push(rect);
468 |
469 | if (shouldDraw) {
470 | if (this.debug) {
471 | this.ctx.setLineWidth(5);
472 | this.ctx.setStrokeColor(Color.red());
473 | this.ctx.strokeRect(rect);
474 | }
475 |
476 | // I'm not sure why, but the text is a quarter off from the box.
477 | const quarterHeight = dimensions.height / 4;
478 | this.ctx.setTextColor(color);
479 | this.ctx.setFont(new Font(wordCloudFont.fontName, fontSize));
480 | this.ctx.drawText(word, new Point(topLeftX, topLeftY - quarterHeight));
481 | }
482 | return {
483 | textPlaced: true,
484 | rectCollision: false,
485 | outsideBorders: false
486 | };
487 | }
488 |
489 | async _writeWithPlacementFunction(processedWord, shouldDraw) {
490 | let breachedLeft = false;
491 | let breachedRight = false;
492 | let breachedTop = false;
493 | let breachedBottom = false;
494 | let previousResult, x, y;
495 |
496 | const path = new Path();
497 | path.move(new Point(this.centerX, this.centerY));
498 |
499 | let placed = false;
500 | while (!(breachedLeft && breachedRight && breachedTop && breachedBottom)) {
501 | previousResult = this.placementFunction(
502 | this.width,
503 | this.height,
504 | this.centerX,
505 | this.centerY,
506 | this.xRatio,
507 | this.yRatio,
508 | previousResult
509 | );
510 | ({ x, y } = previousResult);
511 |
512 | if (this.debug && shouldDraw) {
513 | path.addLine(new Point(x, y));
514 | }
515 | // TODO: Check point outside borders?
516 | if (this._checkPointCollision(x, y)) {
517 | continue;
518 | }
519 |
520 | if (processedWord) {
521 | const { textPlaced, rectCollision, outsideBorders } = await this._addTextCentered({
522 | x,
523 | y,
524 | processedWord,
525 | shouldDraw,
526 | checkHitboxes: true
527 | });
528 | if (textPlaced) {
529 | this.placedWords.push({
530 | xFromCenter: x - this.centerX,
531 | yFromCenter: y - this.centerY,
532 | processedWord
533 | });
534 | this.wordsToPlace.shift();
535 | placed = true;
536 | break;
537 | }
538 | // If we're growing to fit, break out so the word cloud is tightly packed
539 | if (outsideBorders && this.growToFit) {
540 | break;
541 | }
542 | }
543 |
544 | if (x < 0) {
545 | breachedLeft = true;
546 | }
547 | if (x > this.width) {
548 | breachedRight = true;
549 | }
550 | if (y < 0) {
551 | breachedTop = true;
552 | }
553 | if (y > this.height) {
554 | breachedBottom = true;
555 | }
556 | }
557 |
558 | if (this.debug && shouldDraw) {
559 | this.ctx.setLineWidth(1);
560 | this.ctx.addPath(path);
561 | this.ctx.setStrokeColor(new Color("6693F5"));
562 | this.ctx.strokePath();
563 | }
564 | return placed;
565 | }
566 |
567 | async _writePendingWords(shouldDraw) {
568 | if (this.debug) {
569 | console.log("writing pending words");
570 | }
571 | let placedAll = true;
572 | // this.wordsToPlace is edited as words are placed
573 | // To be safe, copy it locally first
574 | const copiedWordsToPlace = [...this.wordsToPlace];
575 | for (const processedWord of copiedWordsToPlace) {
576 | if (!(await this._writeWithPlacementFunction(processedWord, shouldDraw))) {
577 | placedAll = false;
578 | // Stop trying to place words if growToFit
579 | if (this.growToFit) {
580 | return false;
581 | }
582 | }
583 | }
584 | return placedAll;
585 | }
586 |
587 | async _writeAlreadyPlacedWords(shouldDraw) {
588 | if (this.debug) {
589 | console.log("writing already placed words");
590 | }
591 | for (const placedWord of this.placedWords) {
592 | await this._addTextCentered({
593 | x: placedWord.xFromCenter + this.centerX,
594 | y: placedWord.yFromCenter + this.centerY,
595 | processedWord: placedWord.processedWord,
596 | shouldDraw,
597 | checkHitboxes: false
598 | });
599 | }
600 | }
601 |
602 | /**
603 | * Returns some statistics about the words provided
604 | * so the DrawContext can be adjusted to fit them.
605 | *
606 | * @return { number, number, number }
607 | * { minWidth, minHeight, minArea }
608 | * - The minimum width, height, and area that the
609 | * canvas needs to fit the words.
610 | */
611 | async _getWordStats() {
612 | let minWidth = 0;
613 | let minHeight = 0;
614 | let minArea = 0;
615 | for (const processedWord of this.processedWords) {
616 | const { word, wordCloudFont, fontSize, color } = processedWord;
617 | const dimensions = await this._getTextDimensions(word, wordCloudFont, fontSize);
618 |
619 | if (minWidth < dimensions.width) {
620 | minWidth = dimensions.width;
621 | }
622 | if (minHeight < dimensions.height) {
623 | minHeight = dimensions.height;
624 | }
625 |
626 | minArea += dimensions.width * dimensions.height;
627 | }
628 | return { minWidth, minHeight, minArea };
629 | }
630 |
631 | /**
632 | * All words that are more than half of the width
633 | * can't be placed next to each other. This means
634 | * they have to be stacked and their combined
635 | * height needs to be at least as long as the draw
636 | * context. The same can be said about words that
637 | * are larger than half of the height.
638 | *
639 | * Unlike the _getWordStats() function, this
640 | * function will return a different result
641 | * depending on the current width and height.
642 | *
643 | * @param {number} ctxWidth
644 | * - The width the words are being checked
645 | * against.
646 | * @param {number} ctxHeight
647 | * - The height the words are being checked
648 | * against.
649 | * @return { number, number }
650 | * { stackedMinWidth, stackedMinHeight }
651 | * - The minimum width and height the canvas needs
652 | * to fit the words.
653 | */
654 | async _getStackedMinDimensions(ctxWidth, ctxHeight) {
655 | let stackedMinHeight = 0;
656 | let stackedMinWidth = 0;
657 | for (const processedWord of this.processedWords) {
658 | const { word, wordCloudFont, fontSize, color } = processedWord;
659 | const dimensions = await this._getTextDimensions(word, wordCloudFont, fontSize);
660 |
661 | if (dimensions.width > ctxWidth / 2) {
662 | stackedMinHeight += dimensions.height;
663 | }
664 | if (dimensions.height > ctxHeight / 2) {
665 | stackedMinWidth += dimensions.width;
666 | }
667 | }
668 | return { stackedMinWidth, stackedMinHeight };
669 | }
670 |
671 | /**
672 | * Before words are placed on the spiral it's
673 | * possible to grow the canvas using information
674 | * we know about the words. This is faster than
675 | * placing all of the words on the spiral and
676 | * iterating so it's preferred to run this function
677 | * first.
678 | *
679 | * @param {number} ctxWidth
680 | * - The current width of the canvas.
681 | * @param {number} ctxHeight
682 | * - The current height of the canvas.
683 | * @return { number, number } { width, height }
684 | * - The new width and height for the canvas.
685 | */
686 | async _preflightGrow(ctxWidth, ctxHeight) {
687 | let width = ctxWidth;
688 | let height = ctxHeight;
689 | const { minWidth, minHeight, minArea } = await this._getWordStats();
690 |
691 | // The biggest height and width of the words have
692 | // to fit the DrawContext
693 | while (minWidth > width || minHeight > height) {
694 | console.log("increasing because of min width or height");
695 | ({ width, height } = this.growthFunction(width, height, this.providedWidth, this.providedHeight));
696 | }
697 |
698 | // The area of the words have to fit the area of
699 | // the DrawContext
700 | while (minArea > (width * height)) {
701 | console.log("increasing because of min area");
702 | ({ width, height } = this.growthFunction(width, height, this.providedWidth, this.providedHeight));
703 | }
704 |
705 | // All words that are more than half of the width
706 | // can't be placed next to each other. This means
707 | // they have to be stacked and their combined
708 | // height needs to be at least as long as the
709 | // draw context. The same can be said about words
710 | // that are larger than half of the height.
711 | let { stackedMinWidth, stackedMinHeight } = await this._getStackedMinDimensions(width, height);
712 | while (stackedMinWidth > width || stackedMinHeight > height) {
713 | console.log("increasing because of stacked width or height");
714 | ({ width, height } = this.growthFunction(width, height, this.providedWidth, this.providedHeight));
715 | ({ stackedMinWidth, stackedMinHeight } = await this._getStackedMinDimensions(width, height));
716 | }
717 |
718 | return { width, height };
719 | }
720 |
721 | /**
722 | * If growToFit is true, the canvas will grow until
723 | * all of the words fit on the canvas. This is done
724 | * using the following algorithm:
725 | *
726 | * 1. "Preflight": The words are analyzed to see
727 | * if the canvas needs growing before anything
728 | * is written to the canvas.
729 | * 2. "Placement": The words are placed on the
730 | * canvas until either:
731 | * A) a word can't be placed anymore or
732 | * B) a word overlaps with the outside of the
733 | * canvas. We check for B so the result stays
734 | * "tight". Skipping this step usually
735 | * results in "tall" word clouds.
736 | * 3. "Grow and Repeat": The canvas is grown, the
737 | * words that have already been placed before
738 | * are placed in their last positions, and the
739 | * "Placement" step starts over again. This
740 | * repeats until all of the words are placed on
741 | * the canvas.
742 | *
743 | * @return { Image } - The image of the WordCloud!
744 | */
745 | async getImage() {
746 | let width = this.providedWidth;
747 | let height = this.providedHeight;
748 | if (this.growToFit) {
749 | ({ width, height } = await this._preflightGrow(width, height));
750 | }
751 |
752 | let placedAll = false;
753 | while (!placedAll) {
754 | this.width = width;
755 | this.height = height;
756 | this.centerX = width / 2;
757 | this.centerY = height / 2;
758 | this.hitBoxes = [];
759 |
760 | await this._writeAlreadyPlacedWords(false);
761 | placedAll = await this._writePendingWords(false);
762 |
763 | if (!this.growToFit) {
764 | break;
765 | }
766 |
767 | if (!placedAll) {
768 | console.log("increasing because words couldn't fit area");
769 | ({ width, height } = this.growthFunction(width, height, this.providedWidth, this.providedHeight));
770 | }
771 | }
772 |
773 | this.ctx = new DrawContext();
774 | this.ctx.opaque = false;
775 | this.ctx.respectScreenScale = this.respectScreenScale;
776 | this.ctx.size = new Size(width, height);
777 |
778 | // If debug is on, run the placement function one
779 | // last time to display how the function works.
780 | if (this.debug) {
781 | this.ctx.setLineWidth(5);
782 | this.ctx.setStrokeColor(Color.red());
783 | this.ctx.strokeRect(new Rect(0, 0, width, height));
784 | await this._writeWithPlacementFunction(null, true);
785 | }
786 |
787 | await this._writeAlreadyPlacedWords(true);
788 | return this.ctx.getImage();
789 | }
790 |
791 | }
792 |
793 | /************************************
794 | ***** EXAMPLE WEIGHT FUNCTIONS *****
795 | ************************************/
796 |
797 | /**
798 | * Functions that use fonts already installed in iOS.
799 | *
800 | * Find the fonts here:
801 | * http://iosfonts.com
802 | */
803 |
804 | function simpleAndCleanWeightFunction(wordCloudWord) {
805 | const max = 60;
806 | const min = 10;
807 | return new WordCloudProcessedWord({
808 | word: wordCloudWord.word,
809 | wordCloudFont: new WordCloudFont({
810 | fontName: 'TrebuchetMS-Bold'
811 | }),
812 | fontSize: (wordCloudWord.weight / 10) * (max - min) + min,
813 | color: Device.isUsingDarkAppearance() ? Color.white() : Color.black()
814 | });
815 | }
816 |
817 | function builtInFestiveWeightFunction(wordCloudWord) {
818 | const max = 60;
819 | const min = 10;
820 | return new WordCloudProcessedWord({
821 | word: wordCloudWord.word,
822 | wordCloudFont: new WordCloudFont({
823 | fontName: 'SnellRoundhand-Black'
824 | }),
825 | fontSize: (wordCloudWord.weight / 10) * (max - min) + min,
826 | color: Math.random() < 0.5 ? Color.red() : new Color('#1E792C')
827 | });
828 | }
829 |
830 | function hackerWeightFunction(wordCloudWord) {
831 | const color = new Color(
832 | Color.green().hex,
833 | Color.green().alpha * (wordCloudWord.weight / 10)
834 | );
835 | return new WordCloudProcessedWord({
836 | word: wordCloudWord.word,
837 | wordCloudFont: new WordCloudFont({
838 | fontName: 'CourierNewPS-BoldMT'
839 | }),
840 | fontSize: 60,
841 | color: color
842 | });
843 | }
844 |
845 | function celestialWeightFunction(wordCloudWord) {
846 | const max = 60;
847 | const min = 10;
848 | return new WordCloudProcessedWord({
849 | word: wordCloudWord.word,
850 | wordCloudFont: new WordCloudFont({
851 | fontName: 'GillSans-LightItalic'
852 | }),
853 | fontSize: (wordCloudWord.weight / 10) * (max - min) + min,
854 | color: Color.lightGray()
855 | });
856 | }
857 |
858 | /**
859 | * Functions that use fonts installed through an app.
860 | * A url of the css stylesheet is still required due
861 | * to limitations of the system. The fontName is the
862 | * font family.
863 | *
864 | * This article [1] suggests this app [2] is the
865 | * safest way to download fonts to iOS. Be careful,
866 | * use at your own risk!
867 | *
868 | * [1] - https://9to5mac.com/2020/06/12/fontcase-open-source-fonts-app-iphone-ipad
869 | * [2] - https://apps.apple.com/us/app/fontcase-manage-your-type/id1205074470
870 | */
871 |
872 | // https://fonts.google.com/specimen/Lacquer
873 | function spookyWeightFunction(wordCloudWord) {
874 | const max = 60;
875 | const min = 10;
876 | return new WordCloudProcessedWord({
877 | word: wordCloudWord.word,
878 | wordCloudFont: new WordCloudFont({
879 | fontName: 'Lacquer',
880 | cssUrl: 'https://fonts.googleapis.com/css2?family=Lacquer&display=swap'
881 | }),
882 | fontSize: (wordCloudWord.weight / 10) * (max - min) + min,
883 | color: Color.orange()
884 | });
885 | }
886 |
887 | // https://fonts.google.com/specimen/Cinzel+Decorative
888 | function customFestiveWeightFunction(wordCloudWord) {
889 | const max = 60;
890 | const min = 10;
891 | return new WordCloudProcessedWord({
892 | word: wordCloudWord.word,
893 | wordCloudFont: new WordCloudFont({
894 | fontName: 'Cinzel Decorative',
895 | cssUrl: 'https://fonts.googleapis.com/css2?family=Cinzel+Decorative&display=swap'
896 | }),
897 | fontSize: (wordCloudWord.weight / 10) * (max - min) + min,
898 | color: Math.random() < 0.5 ? Color.red() : new Color('#1E792C')
899 | });
900 | }
901 |
902 | // https://fonts.google.com/specimen/Fredericka+the+Great
903 | function stencilWeightFunction(wordCloudWord) {
904 | const max = 60;
905 | const min = 10;
906 | return new WordCloudProcessedWord({
907 | word: wordCloudWord.word,
908 | wordCloudFont: new WordCloudFont({
909 | fontName: 'Fredericka the Great',
910 | cssUrl: 'https://fonts.googleapis.com/css2?family=Fredericka+the+Great&display=swap'
911 | }),
912 | fontSize: (wordCloudWord.weight / 10) * (max - min) + min,
913 | color: Color.lightGray()
914 | });
915 | }
916 |
917 | /***************************************
918 | ***** EXAMPLE PLACEMENT FUNCTIONS *****
919 | ***************************************/
920 |
921 | /**
922 | * Please see this script for additional examples:
923 | * https://github.com/stanleyrya/scriptable-playground/blob/main/experiments/word-cloud-experiments/draw-spiral.js
924 | */
925 |
926 | function spiralPlacementFunction(width, height, centerX, centerY, xRatio, yRatio, previousResult) {
927 | let radius, radiusDirection, angle, angleDirection;
928 | if (previousResult) {
929 | ({
930 | radius,
931 | radiusDirection,
932 | angle,
933 | angleDirection
934 | } = previousResult);
935 | // Try these values too: 0.75 -> 0.1, 50 -> 100
936 | radius += .75 * radiusDirection;
937 | angle += (Math.PI * 2) / 50 * angleDirection;
938 | } else {
939 | radius = 0;
940 | angle = 0;
941 | radiusDirection = Math.random() < 0.5 ? -1 : 1;
942 | angleDirection = Math.random() < 0.5 ? -1 : 1;
943 | }
944 |
945 | const x = centerX + radius * Math.cos(angle) * xRatio;
946 | const y = centerY + radius * Math.sin(angle) * yRatio;
947 | return { x, y, radius, angle, radiusDirection, angleDirection }
948 | }
949 |
950 | function galaxyPlacementFunction(width, height, centerX, centerY, xRatio, yRatio, previousResult) {
951 | const i = previousResult ? previousResult.i + 1 : 0;
952 | const scale = 2;
953 | const dots = 10;
954 | const range = 234;
955 | const angle = Math.PI * range / 500 * i;
956 | const x = scale * angle * Math.cos(dots * angle) + centerX;
957 | const y = scale * angle * Math.sin(dots * angle) + centerY;
958 | return { x, y, angle, i }
959 | }
960 |
961 | function starPlacementFunction(width, height, centerX, centerY, xRatio, yRatio, previousResult) {
962 | let i = previousResult ?
963 | previousResult.i + 1 :
964 | 0;
965 | const scale = .25;
966 | const dots = 100;
967 | const range = 336;
968 | const angle = Math.PI * range / 500 * i;
969 | const x = scale * angle * Math.cos(dots * angle) + centerX;
970 | const y = scale * angle * Math.sin(dots * angle) + centerY;
971 | return { x, y, angle, i }
972 | }
973 |
974 | /************************
975 | ***** SAMPLE LOGIC *****
976 | ************************/
977 |
978 | // Sample input
979 |
980 | const wordCloudWords = [
981 | new WordCloudWord({ word: "Seattle", weight: 10 }),
982 | new WordCloudWord({ word: "Boston", weight: 10 }),
983 | new WordCloudWord({ word: "Chicago", weight: 8 }),
984 | new WordCloudWord({ word: "Denver", weight: 7 }),
985 | new WordCloudWord({ word: "Boise", weight: 7 }),
986 | new WordCloudWord({ word: "Los Angeles", weight: 7 }),
987 | new WordCloudWord({ word: "San Fransisco", weight: 6 }),
988 | new WordCloudWord({ word: "Victoria", weight: 6 }),
989 | new WordCloudWord({ word: "Portland", weight: 5 }),
990 | new WordCloudWord({ word: "London", weight: 5 }),
991 | new WordCloudWord({ word: "Dublin", weight: 3 }),
992 | new WordCloudWord({ word: "Barcelona", weight: 3 }),
993 | new WordCloudWord({ word: "Amsterdam", weight: 3 }),
994 | new WordCloudWord({ word: "Budapest", weight: 3 }),
995 | new WordCloudWord({ word: "Venice", weight: 3 }),
996 | new WordCloudWord({ word: "Florence", weight: 2 }),
997 | new WordCloudWord({ word: "Oslo", weight: 2 }),
998 | new WordCloudWord({ word: "Paris", weight: 2 }),
999 | new WordCloudWord({ word: "Tokyo", weight: 1 }),
1000 | new WordCloudWord({ word: "New York", weight: 1 }),
1001 | new WordCloudWord({ word: "Fort", weight: 1 })
1002 | ];
1003 |
1004 | let width, height;
1005 | if (config.runsInWidget) {
1006 | width = config.widgetFamily === "small" ? 250 : 530;
1007 | height = config.widgetFamily === "large" ? 530 : 250;
1008 | } else {
1009 | width = 250;
1010 | height = 250;
1011 | }
1012 |
1013 | const wordCloud = new WordCloud({
1014 | // required
1015 |
1016 | width,
1017 | height,
1018 | wordCloudWords,
1019 |
1020 | // optional
1021 |
1022 | // may help with homescreen memory issues
1023 | // respectScreenScale: false,
1024 |
1025 | // shows how the algorithm works
1026 | // debug: true,
1027 |
1028 | // changes the way way words are displayed
1029 | // weightFunction: hackerWeightFunction,
1030 |
1031 | // changes the way words are placed
1032 | // placementFunction: starPlacementFunction,
1033 | });
1034 | const image = await wordCloud.getImage();
1035 |
1036 | // Sample usage
1037 |
1038 | const widget = new ListWidget();
1039 | widget.setPadding(0, 0, 0, 0);
1040 | const widgetImage = widget.addImage(image);
1041 | widgetImage.applyFillingContentMode();
1042 | widgetImage.centerAlignImage();
1043 |
1044 | // The word cloud image has a clear background.
1045 | // The default weight function uses Device.isUsingDarkAppearance()
1046 | // to set the font color. It is slow to update
1047 | // which could make the font blend in with the
1048 | // widget's automatic background. To protect
1049 | // against this you can set the background explicitly:
1050 | widget.backgroundColor = Device.isUsingDarkAppearance() ? Color.black() : Color.white();
1051 |
1052 | // Alternatively, consider adding an image as the background :)
1053 | // widget.backgroundImage = await new Request('YOUR IMAGE URL').loadImage();
1054 |
1055 | if (config.runsInWidget) {
1056 | Script.setWidget(widget);
1057 | Script.complete();
1058 | } else {
1059 | widget.presentLarge();
1060 | }
1061 |
--------------------------------------------------------------------------------