界面和词云图

main
LiRen-qiu 4 months ago
parent 9417fef276
commit 1f732bfb2a

@ -0,0 +1,26 @@
#################
## Eclipse
#################
.project
.metadata
bin/
tmp/
work/
*.DS_Store
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.tomcatplugin
.settings/
/target
src/main/webapp/WEB-INF/classes
src/main/webapp/WEB-INF/lib
src/main/webapp/.\#webclasspath
src/main/webapp/resources/spyral/node_modules
src/main/resources/oath.properties
/.pydevproject
.vscode/

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

@ -0,0 +1,53 @@
#### With the passing of Stéfan Sinclair, this repository has been archived. ####
#### Please see [voyanttools/Voyant](https://github.com/voyanttools/Voyant) for future development. ####
Voyant Tools
======
Voyant Tools is a web-based text analysis, reading and visualization environment. Developed by a small team of digital humanities scholars led by [Stéfan Sinclair ](http://stefansinclair.name/) and [Geoffrey Rockwell](http://geoffreyrockwell.com/), Voyant Tools is designed for a very wide range of applications and users, from students to researchers and journalists to market analysts. It strives to balance user-friendliness with a range of analytic and interpretive functions.
# Features
Some of the important features of Voyant Tools include:
* importing documents in various formats (plain text, HTML, XML, PDF, RTF, MS Word, ODF, etc.)
* several tools for studying term frequencies and distributions within documents and within a collection of documents (a corpus)
* a full-text reader that support very large texts and includes interactive features
* interaction between the the tools that facilitates navigation and exploration at diffent scales (from "close reading" to "distant reading")
* a mechanism for bookmarking and sharing instances of Voyant Tools (specific texts and tools) through persistent URLs
* access to a [hosted version of Voyant Tools](http://Voyant-tools.org/) or a [downloadable standalone version](http://github.com/sgsinclair/VoyantServer)
* Voyant Tools is free and open source (GPLv3)
# Documentation
The GitHub-hosted repository is oriented toward development of Voyant Tools, including bug and issue tracking. Help with using the interface is available from the [Voyant Tools Documentation](http://docs.voyant-tools.org) site.
# Contributing
There are many ways of contributing to the development of Voyant Tools:
* use it and let us know ([@VoyantTools](http://twitter.com/VoyantTools)), having people use it is our reward :)
* if appropriate, please consider citing it
* if you find a bug, identify an issue or have requests, submit a [GitHub ticket](https://github.com/sgsinclair/Voyant/issues) (or [tweet](http://twitter.com/VoyantTools))
* if you're a developer, see instructions for setting up a development environment and consider submitting a patch or pull request
# License
Voyant Tools is an open-source project and the code is available through [GitHub](http://github.com/sgsinclair/Voyant). The code is under a [GPL3 license](http://www.gnu.org/licenses/gpl-3.0.en.html) and the content of the web application is under a [Creative Commons By Attribution license](https://creativecommons.org/licenses/by/4.0/).
# Voyant Tools 2.0
The currently available version of [Voyant Tools](http://voyant-tools.org/) is 2.0. It isa complete rewrite that is focused on better performance and scalability, as well as improved functionality (such as more powerful search). Voyant 3.0 is expected by 2020.
## Releases
For a somewhat more detailed overview of releases please see [VoyantServer releases](https://github.com/sgsinclair/VoyantServer/releases)
## Known Issues
* several skins and tools are not yet implemented
* Voyant slows down as the index grows
## Road Map
* new architecture to better support distributed indices (multiple users)
* update code to latest version of Lucene
* integrate some language-specific functionality such as part-of-speech tagging
* add functionality for word groups
* resume development of Spyral (Voyant Notebooks)
# Credits

@ -0,0 +1,132 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.voyant-tools</groupId>
<artifactId>Voyant</artifactId>
<packaging>war</packaging>
<name>Voyant</name>
<version>2.0.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<build>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<outputDirectory>${basedir}/src/main/webapp/WEB-INF/classes</outputDirectory>
<resources>
<resource>
<directory>${basedir}/src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<!-- make sure we grab the Voyant JS file liste -->
<resource>
<directory>${basedir}/src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/src/main/webapp/WEB-INF/lib</outputDirectory>
<includeScope>runtime</includeScope>
<!-- we have to skip trombone to ensure that we're using compiled
classes from project -->
<excludeArtifactIds>trombone</excludeArtifactIds>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<!-- http://maven.apache.org/plugins/maven-war-plugin/overlays.html -->
<artifactId>maven-war-plugin</artifactId>
<configuration>
<outputDirectory>${basedir}/target</outputDirectory>
<webappDirectory>${basedir}/src/main/webapp</webappDirectory>
<warSourceDirectory>${basedir}/src/main/webapp</warSourceDirectory>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.voyant-tools</groupId>
<artifactId>trombone</artifactId>
<version>5.2.0-SNAPSHOT</version>
</dependency>
<!-- <dependency> <groupId>caja</groupId> <artifactId>caja</artifactId>
<version>r5127</version> <scope>compile</scope> </dependency> -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>com.google.javascript</groupId>
<artifactId>closure-compiler</artifactId>
<version>v20190929</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>maven2-repository.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</repository>
<repository>
<id>caja</id>
<name>Google Caja</name>
<url>http://google-caja.googlecode.com/svn/maven</url>
</repository>
<repository>
<id>trombone-mvn-repo</id>
<url>https://raw.github.com/sgsinclair/trombone/mvn-repo/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
</repositories>
</project>

@ -0,0 +1,140 @@
package org.voyanttools.voyant;
import static java.security.AccessController.doPrivileged;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.voyanttools.trombone.input.source.InputSourcesBuilder;
import org.voyanttools.trombone.util.FlexibleParameters;
import sun.security.action.GetPropertyAction;
/**
* This is a utility class for instantiating {@link FlexibleParameters} from {@link HttpServletRequest}s.
* @author Stéfan Sinclair, Cyril Briquet
*/
public class FlexibleParametersFactory {
private String build;
private String version;
public FlexibleParametersFactory(ServletContext servlet) {
this.build = servlet.getInitParameter("build");
this.version = servlet.getInitParameter("version");
}
/**
* Get an instance of {@link FlexibleParameters} from the {@link HttpServletRequest}.
*
* <p>This method handles simple forms as wells as multipart forms with file uploads.</p>
* @param request
* @return {@link FlexibleParameters} instance
* @throws Exception
*/
public FlexibleParameters getInstance(HttpServletRequest request) throws Exception {
return getInstance(request, false);
}
/**
* Get an instance of {@link FlexibleParameters} from the {@link HttpServletRequest}.
*
* <p>This method handles simple forms as wells as multipart forms with file uploads.</p>
* @param request
* @return {@link FlexibleParameters} instance
* @throws Exception
*/
@SuppressWarnings("unchecked")
public FlexibleParameters getInstance(HttpServletRequest request, boolean allowLocalFileSystemAccess) throws Exception {
if (request == null) {
throw new NullPointerException("illegal request");
}
final FlexibleParameters parameters = new FlexibleParameters();
parameters.setParameter("VOYANT_VERSION", version!=null ? version : "");
parameters.setParameter("VOYANT_BUILD", build!=null ? build : "");
parameters.setParameter("VOYANT_REMOTE_ID", request.getHeader("X-FORWARDED-FOR")!=null ? request.getHeader("X-FORWARDED-FOR") : request.getRemoteAddr());
final HttpParametersDecoder parametersDecoder = new HttpParametersDecoder(parameters);
if (ServletFileUpload.isMultipartContent(request) && !(request instanceof Voyant.PostedInputRequestWrapper)) {
final List<FileItem> items = getRequestItems(request);
Path tmpPath = Paths.get(Paths.get(doPrivileged(new GetPropertyAction("java.io.tmpdir"))).toString(), "tmp.voyant.uploads");
if (!Files.exists(tmpPath)) {
Files.createDirectory(tmpPath);
}
for (FileItem item : items) {
if (item.isFormField()) { // normal form field
parametersDecoder.decodeParameter(item.getFieldName(), item.getString(), allowLocalFileSystemAccess);
}
else { // file form field: this is uploaded, therefore the local access check can be bypassed
Path path = Files.createTempDirectory(tmpPath, "tmp.voyant.uploads");
File file = new File(path.toFile(), item.getName());
item.write(file);
parametersDecoder.decodeParameter("upload", file.toString(), true);
}
}
}
else {
if (request.getMethod().equals("GET")) {
// I couldn't for the life of me convince a GET request to use the specified character encoding (tried req.setCharacterEncoding() etc.)
// so we'll not use the simpler request.getParameterMap() and instead parse the query string ourselves
String queryString = request.getQueryString();
if (queryString!=null) {
List<NameValuePair> pairs = URLEncodedUtils.parse(request.getQueryString(), Charset.forName("UTF-8"));
for (NameValuePair pair : pairs) {
if (pair.getName().equals("_dc")==false) { // ignore the EXTJS param for GET requests
parametersDecoder.decodeParameters(pair.getName(), new String[]{pair.getValue()}, allowLocalFileSystemAccess);
}
}
}
}
else {
for (Map.Entry<String, String[]> param : ((Map<String, String[]>) request.getParameterMap()).entrySet()) {
parametersDecoder.decodeParameters(param.getKey(), param.getValue(), allowLocalFileSystemAccess || (request instanceof Voyant.PostedInputRequestWrapper && param.getKey().equals("upload")));
}
}
}
// check to see if this instance allows new input
if (System.getProperty("org.voyanttools.server.allowinput", "true").equals("false") && InputSourcesBuilder.hasParameterSources(parameters)) {
throw new IllegalArgumentException("This server has been configured to refuse new input.");
}
return parameters;
}
private static List<FileItem> getRequestItems(HttpServletRequest request) throws FileUploadException {
if (request == null) {
throw new NullPointerException("illegal request");
}
final DiskFileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload upload = new ServletFileUpload(factory);
final List<FileItem> items = upload.parseRequest(request);
return items;
}
}

@ -0,0 +1,169 @@
package org.voyanttools.voyant;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import org.voyanttools.trombone.util.FlexibleParameters;
/**
* This is a utility class for decoding HTTP parameters intended to configure the behavior of a Trombone {@link Controller}.
* @author Stéfan Sinclair, Cyril Briquet
*/
public class HttpParametersDecoder {
private static final Pattern VALID_URL_PATTERN = Pattern.compile("^((https?|ftp)://|([\\w-]+\\.)+[\\w-]+($|/))");
private final FlexibleParameters parameters;
public HttpParametersDecoder(FlexibleParameters parameters) {
if (parameters == null) {
throw new NullPointerException("illegal properties");
}
this.parameters = parameters;
}
public synchronized void decodeParameter(String key, String value, boolean allowLocalFileSystemAccess) {
if (key == null) {
throw new NullPointerException("illegal key");
}
if (value == null) {
throw new NullPointerException("illegal value");
}
decodeParameters(key, new String[] { value }, allowLocalFileSystemAccess);
}
public synchronized void decodeParameters(String key, String[] values, boolean allowLocalFileSystemAccess) {
if (key == null) {
throw new NullPointerException("illegal key");
}
if (values == null) {
throw new NullPointerException("illegal values");
}
// let's strip the brackets that indicate an array
if (key.endsWith("[]") && key.length()>2) {key = key.substring(0, key.length()-2);}
if (key.equals("uri")) {
decodeURIParameters(key, values);
}
else if (key.equals("input")) {
decodeInlineParameters(key, values);
}
else if (key.equals("file") || key.equals("directory") || key.equals("upload")) {
if (allowLocalFileSystemAccess) {
addParameter(key, values);
}
}
else {
addParameter(key, values);
}
}
private synchronized void decodeURIParameters(String key, String[] values) {
if (key == null) {
throw new NullPointerException("illegal key");
}
if (values == null) {
throw new NullPointerException("illegal values");
}
final Set<String> uris = new HashSet<String>();
for (String uri : values) {
if (uri.trim().startsWith("file:")) {
throw new IllegalArgumentException("file:// protocol is not supported");
}
else {
uris.add(uri);
}
}
if (uris.isEmpty() == false) {
addParameter(key, uris.toArray(values));
}
}
private synchronized void decodeInlineParameters(String key, String[] values) {
if (key == null) {
throw new NullPointerException("illegal key");
}
if (values == null) {
throw new NullPointerException("illegal values");
}
final List<String> uris = new ArrayList<String>();
final List<String> strings = new ArrayList<String>();
for (String input : values) {
input = input.trim();
if (input.length() == 0) {
continue;
}
if (VALID_URL_PATTERN.matcher(input).find()) { // inline URI or URIs
for (String uri : input.split("\n+")) {
uri = uri.trim();
if (VALID_URL_PATTERN.matcher(uri).find()) {
if (uri.startsWith("http") || uri.startsWith("ftp")) {
uris.add(uri);
}
else {
uris.add("http://" + uri); // the protocol is probably http anyways ;)
}
}
}
}
else { // inline text chunk
strings.add(input);
}
}
if (uris.isEmpty() == false) {
addParameter("uri", uris.toArray(new String[0]));
}
if (strings.isEmpty() == false) {
addParameter("string", strings.toArray(new String[0]));
}
}
private synchronized void addParameter(String key, String[] values) {
if (key == null) {
throw new NullPointerException("illegal key");
}
if (values == null) {
throw new NullPointerException("illegal values");
}
/*
final String[] decodedValues = new String[values.length];
for (int y = 0 ; y < decodedValues.length ; ++y) {
try {
decodedValues[y] = URLDecoder.decode(values[y], "UTF-8");
}
catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
*/
this.parameters.addParameter(key, values);
}
}

@ -0,0 +1,157 @@
package org.voyanttools.voyant;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import com.google.javascript.jscomp.CompilationLevel;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.Result;
import com.google.javascript.jscomp.SourceFile;
import com.google.javascript.jscomp.SourceMap;
import com.google.javascript.jscomp.SourceMap.PrefixLocationMapping;
/**
* @author Andrew MacDonald and Stéfan Sinclair
*/
public class JSCacher {
final static String ENCODING = "UTF-8";
final static String CACHED_FILENAME = "voyant.js";
final static String CACHED_FILENAME_MINIFIED = "voyant.min.js";
final static String SOURCE_MAP_FILENAME = "voyant.min.map.js";
// Closure options
final static int SUMMARY_DETAIL_LEVEL = 1;
public static void sendCache(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setCharacterEncoding(ENCODING);
// TODO add config for this?
boolean doSourceMap = true;
File basePath = new File(request.getSession().getServletContext().getRealPath("/"));
String debug = request.getParameter("debug");
File cachedFile = new File(basePath, "/resources/voyant/current/"+CACHED_FILENAME);
File cachedFileMinified = new File(basePath, "/resources/voyant/current/"+CACHED_FILENAME_MINIFIED);
File sourceMapFile = new File(basePath, "/resources/voyant/current/"+SOURCE_MAP_FILENAME);
if (debug!=null && debug.equals("true") && cachedFile.canWrite() && cachedFileMinified.canWrite() && sourceMapFile.canWrite()) {
long lastModifiedCachedFile = cachedFile.lastModified();
List<File> files = getCacheableFiles(basePath);
// look for any file that's been updated since last cache
boolean needsUpdate = false;
for (File file : files) {
if (file.lastModified() > lastModifiedCachedFile) {
needsUpdate = true;
break;
}
}
if (needsUpdate) {
List<SourceFile> sourceFiles = new ArrayList<SourceFile>();
String header = "/* This file created by JSCacher. Last modified: "+new Date().toString()+" */\n";
String footer = doSourceMap ? "\n//# sourceMappingURL=" + SOURCE_MAP_FILENAME : "";
StringBuffer cache = new StringBuffer(header);
for (File file : files) {
String s = FileUtils.readFileToString(file, Charset.forName(ENCODING));
cache.append(s).append("\n"); // assuming UTF-8
sourceFiles.add(SourceFile.fromFile(file.getPath()));
}
// non-minified version
FileUtils.writeStringToFile(cachedFile, cache.toString(), Charset.forName(ENCODING));
// minified version
Compiler compiler = new Compiler();
CompilerOptions options = new CompilerOptions();
List<String> tags = new ArrayList<String>();
tags.add("cfg");
tags.add("exports");
tags.add("choices");
tags.add("distinguishingFldsArray");
tags.add("undistinguishedRoot");
options.setExtraAnnotationNames(tags);
options.setStrictModeInput(false); // needed to avoid error on "arguments.callee.caller"
options.setSummaryDetailLevel(SUMMARY_DETAIL_LEVEL);
options.setLanguageIn(CompilerOptions.LanguageMode.ECMASCRIPT_2019);
options.setLanguageOut(CompilerOptions.LanguageMode.ECMASCRIPT5);
if (doSourceMap) {
options.setSourceMapOutputPath(SOURCE_MAP_FILENAME);
options.setSourceMapFormat(SourceMap.Format.V3);
options.setSourceMapIncludeSourcesContent(true);
List<PrefixLocationMapping> prefixes = new ArrayList<>();
String baseLocation = basePath.toString().replaceAll("\\\\", "/");
prefixes.add(new PrefixLocationMapping(baseLocation, ""));
options.setSourceMapLocationMappings(prefixes);
}
CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options);
Result result = compiler.compile(new ArrayList<SourceFile>(), sourceFiles, options);
cache.setLength(0);
cache.append(header);
cache.append(compiler.toSource());
cache.append(footer);
FileUtils.writeStringToFile(cachedFileMinified, cache.toString(), Charset.forName(ENCODING));
// source map
if (doSourceMap && result.sourceMap != null) {
StringBuilder sourceMap = new StringBuilder();
result.sourceMap.appendTo(sourceMap, SOURCE_MAP_FILENAME);
FileUtils.writeStringToFile(sourceMapFile, sourceMap.toString(), Charset.forName(ENCODING));
}
}
response.sendRedirect(CACHED_FILENAME);
}
else {
response.sendRedirect(CACHED_FILENAME_MINIFIED);
}
}
private static List<File> getCacheableFiles(File basePath) throws IOException {
InputStream is = org.voyanttools.voyant.JSCacher.class.getResourceAsStream("voyant-js.txt");
List<String> lines = IOUtils.readLines(is, Charset.forName(ENCODING));
is.close();
List<File> files = new ArrayList<File>();
for (String jsFile : lines) {
if (jsFile.trim().startsWith("#") || jsFile.trim().isEmpty()) {continue;}
File f = new File(basePath, jsFile);
if (f.exists()) {files.add(f);}
else {
throw new IOException("File does not exist:"+f);
}
}
return files;
}
}

@ -0,0 +1,66 @@
package org.voyanttools.voyant;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
public class Localizer {
public static void sendCache(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setCharacterEncoding("UTF-8");
File basePath = new File(request.getSession().getServletContext().getRealPath("/"), "/resources/voyant/current");
String lang = request.getParameter("lang");
if (lang==null || lang.isEmpty()) {lang="en";}
File cachedFile = new File(basePath, "voyant-locale-"+lang+".js");
File sourceFile = new File(basePath, "localization.tsv");
if (!cachedFile.exists() || sourceFile.lastModified()>cachedFile.lastModified()) {
update(lang, sourceFile, cachedFile);
}
response.sendRedirect(cachedFile.getName());
}
private static void update(String lang, File sourceFile, File cachedFile) throws IOException {
List<String> lines = FileUtils.readLines(sourceFile, "UTF-8");
String header = lines.get(0);
int pos = header.indexOf("("+lang+")");
if (pos==-1) {
throw new IllegalArgumentException("Unable to find language: "+lang);
}
int column = StringUtils.countMatches(header.substring(0, pos), "\t");
int english = 3;
lines.remove(0);
Map<String, Map<String, String>> locationsMap = new HashMap<String, Map<String, String>>();
for (String line : lines) {
String[] cells = line.split("\t");
if (cells.length < 4 || cells[0].isEmpty() || cells[1].isEmpty() || cells[2].isEmpty() || cells[3].isEmpty()) {continue;}
String location = cells[1];
if (locationsMap.containsKey(location)==false) {
locationsMap.put(location, new HashMap<String, String>());
}
locationsMap.get(location).put(cells[2], cells.length>column && cells[column].isEmpty()==false ? cells[column] : cells[english]);
}
StringBuilder sb = new StringBuilder("Voyant.util.Localization.LANGUAGE='").append(lang).append("'\n");
for (Map.Entry<String, Map<String, String>> locationEntry : locationsMap.entrySet()) {
sb.append("Ext.apply(").append(locationEntry.getKey()).append(".i18n, {\n");
for (Map.Entry<String, String> classEntry : locationEntry.getValue().entrySet()) {
sb.append("\"").append(classEntry.getKey()).append("\":\"").append(classEntry.getValue().replace("\"", "\\\"")).append("\",\n");
}
sb.setLength(sb.length()-2);
sb.append("});\n");
}
FileUtils.writeStringToFile(cachedFile, sb.toString(), "UTF-8");
}
}

@ -0,0 +1,76 @@
package org.voyanttools.voyant;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
public class SpyralAuth extends HttpServlet {
private static final long serialVersionUID = 1048044723303994604L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
doRequest(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
doRequest(req, resp);
}
private void doRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Properties oauthprops = new Properties();
String propfile = this.getInitParameter("oauthprops");
oauthprops.load(getClass().getClassLoader().getResourceAsStream(propfile));
String clientId = (String) oauthprops.get("clientId");
String clientSecret = (String) oauthprops.get("clientSecret");
String oauthCallbackRedirect = (String) oauthprops.get("oauthCallbackRedirect");
String code = req.getParameter("code");
String charset = StandardCharsets.UTF_8.name();
String tokenURL = "https://github.com/login/oauth/access_token?code="+code+"&client_id="+clientId+"&client_secret="+clientSecret;
URL url = new URL(tokenURL);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
InputStream is = null;
try {
is = connection.getInputStream();
String respString = IOUtils.toString(is, charset);
Pattern pattern = Pattern.compile("(access_token=)(\\w+)");
Matcher matcher = pattern.matcher(respString);
if (matcher.find()) {
String accessToken = matcher.group(2);
Cookie cookie = new Cookie("access-token", accessToken);
cookie.setPath("/");
resp.addCookie(cookie);
resp.sendRedirect(oauthCallbackRedirect);
}
} finally {
if (is != null) {
is.close();
}
}
}
}

@ -0,0 +1,496 @@
package org.voyanttools.voyant;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.voyanttools.trombone.Controller;
import org.voyanttools.trombone.model.Corpus;
import org.voyanttools.trombone.model.CorpusAccess;
import org.voyanttools.trombone.results.ResultsOutputFormat;
import org.voyanttools.trombone.storage.Storage;
import org.voyanttools.trombone.storage.file.FileStorage;
import org.voyanttools.trombone.storage.memory.MemoryStorage;
import org.voyanttools.trombone.tool.corpus.CorpusManager;
import org.voyanttools.trombone.util.FlexibleParameters;
/**
* @author Stéfan Sinclair, Cyril Briquet
*/
public class Trombone extends HttpServlet {
private static final long serialVersionUID = 392155275393370320L;
private final Set<String> hiddenParameters = new HashSet<String>();
private Storage storage;
private FlexibleParametersFactory flexibleParametersFactory;
public Trombone() throws IOException {
this.storage = null;
String storage = System.getProperty("org.voyanttools.server.storage", "file-per-corpus").toLowerCase();
if (storage.equals("memory")) {
this.storage = new MemoryStorage();
} else {
FlexibleParameters parameters = new FlexibleParameters();
parameters.setParameter("storage", storage);
this.storage = new FileStorage(parameters);
}
}
@Override
public void init() {
this.flexibleParametersFactory = new FlexibleParametersFactory(this.getServletContext());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
doRequest(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
doRequest(req, resp);
}
private void doRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
if (req == null) {
throw new NullPointerException("illegal servlet request");
}
if (resp == null) {
throw new NullPointerException("illegal servlet response");
}
final FlexibleParameters parameters = getFlexibleParameters(req);
// append accessIP in case it's needed
parameters.setParameter("accessIP", req.getRemoteAddr());
if (parameters.containsKey("corpus")) {
String id = parameters.getParameterValue("corpus");
// check for password, for now just setting the session value (error will be raised later if needed)
if (parameters.containsKey("passwordForSession")) {
String password = parameters.getParameterValue("passwordForSession");
Corpus corpus = CorpusManager.getCorpus(storage, new FlexibleParameters(new String[]{"corpus="+id}));
FlexibleParameters newParams = parameters.clone();
newParams.setParameter("password", password);
CorpusAccess corpusAccess = corpus.getValidatedCorpusAccess(newParams);
if (corpusAccess==CorpusAccess.ADMIN || corpusAccess==CorpusAccess.ACCESS) {
req.getSession().setAttribute("password-"+id, password);
}
resp.setContentType("text/plain");
resp.getWriter().write(corpusAccess.name());
return;
}
else if (parameters.containsKey("passwordForSessionRemove")) {
HttpSession session = req.getSession();
session.removeAttribute("password-"+id);
return;
}
// see if we have a session-stored password
else {
HttpSession session = req.getSession();
String password = (String) session.getAttribute("password-"+id);
if (password!=null) {
password = password.trim();
if (password.isEmpty()==false) {
parameters.setParameter("password", password);
}
}
}
}
if (parameters == null) {
return;
}
try {
doRequest(parameters, req, resp);
this.log(generateLogMessageForSuccessfulRequest(parameters, req));
}
catch (Exception e) {
this.log("ERROR: "+e.getLocalizedMessage(), e);
this.log(generateLogMessageForFailedRequest(parameters, this.hiddenParameters));
resp.setStatus(500);
try {
final PrintWriter writer = resp.getWriter();
String message = e.getMessage();
if (message!=null && message.isEmpty()==false) {
writer.write(e.getMessage()+"\n");
}
e.printStackTrace(writer);
}
catch (IOException ioe) {
this.log("ERROR: Unable to write results", ioe);
}
}
}
private FlexibleParameters getFlexibleParameters(HttpServletRequest req) {
if (req == null) {
throw new NullPointerException("illegal servlet request");
}
try {
return this.flexibleParametersFactory.getInstance(req);
}
catch (Exception e) {
this.log("ERROR: Unable to create parameters", e);
this.log(generateLogMessageForUnprocessableParameters(((Map<String, String[]>) req.getParameterMap()).entrySet(), this.hiddenParameters));
return null;
}
}
private void doRequest(FlexibleParameters parameters, HttpServletRequest req, HttpServletResponse resp) throws IOException, TransformerException {
if (parameters == null) {
throw new NullPointerException("illegal parameters");
}
if (req == null) {
throw new NullPointerException("illegal servlet request");
}
if (resp == null) {
throw new NullPointerException("illegal servlet response");
}
resp.setContentType(ResultsOutputFormat.getResultsOutputFormat(parameters.getParameterValue("outputFormat", "json")).getContentType());
if (parameters.containsKey("fetchData")) {
URL url;
URLConnection c;
try {
url = new URL(parameters.getParameterValue("fetchData").replaceAll(" ", "+"));
System.out.println(url);
c = url.openConnection();
// StringBuilder sb = new StringBuilder();
// BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
// String inputLine;
// while ((inputLine = in.readLine()) != null) {
// sb.append(inputLine);
// }
// in.close();
// System.out.println(sb.toString());
}
catch (MalformedURLException e) {
throw new IllegalArgumentException("Attempt to use a malformed URL: "+parameters.getParameterValue("fetchJSON"), e);
}
c.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; Trombone)");
InputStream is = null;
try {
is = c.getInputStream();
c.setReadTimeout(60000);
resp.setContentType(c.getContentType());
// if (parameters.containsKey("format")) {
// String format = parameters.getParameterValue("format").toUpperCase();
// if (format.equals("XML")) {
// resp.setContentType("application/xml;charset=UTF-8");
// } else if (format.equals("JSON")) {
// resp.setContentType("application/json;charset=UTF-8");
// }
// }
IOUtils.copy(is, resp.getWriter());
resp.flushBuffer();
}
finally {
if (is!=null) {
is.close();
}
}
}
else if (parameters.containsKey("fetchJSON")) {
URL url;
URLConnection c;
try {
url = new URL(parameters.getParameterValue("fetchJSON").replaceAll(" ", "+"));
System.out.println(url);
c = url.openConnection();
c.setReadTimeout(0);
}
catch (MalformedURLException e) {
throw new IllegalArgumentException("Attempt to use a malformed URL: "+parameters.getParameterValue("fetchJSON"), e);
}
c.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; Trombone)");
// c.setReadTimeout(readTimeoutMilliseconds);
// c.setConnectTimeout(connectTimeoutMilliseconds);
InputStream is = null;
try {
is = c.getInputStream();
//application/json
resp.setContentType("application/json;charset=UTF-8");
IOUtils.copy(is, resp.getWriter());
resp.flushBuffer();
}
finally {
if (is!=null) {
is.close();
}
}
}
else if (parameters.containsKey("template")) {
parameters.setParameter("outputFormat", "xml"); // we need xml for transformation
final Writer xmlResultsWriter = new StringWriter();
runTromboneController(parameters, xmlResultsWriter);
Source xml = new StreamSource(new StringReader(xmlResultsWriter.toString()));
Source xslt = XslTransformer.getTemplateSource(parameters.getParameterValue("template"), this.getServletConfig().getServletContext());
FlexibleParameters xslParameters = new FlexibleParameters();
xslParameters.setParameter("tromboneUrl", req.getRequestURL().toString());
for (Map.Entry<String, String[]> param : ((Map<String, String[]>) req.getParameterMap()).entrySet()) {
if (this.hiddenParameters.contains(param.getKey()) == true) { // skip hidden parameter
continue;
}
xslParameters.setParameter(param.getKey(), param.getValue());
}
XslTransformer.transform(xslParameters, xml, xslt, resp.getWriter());
}
else if (parameters.getParameterValue("outputFormat", "").toUpperCase().equals("ZIP")) {
resp.setHeader("Content-Disposition", "filename=" + parameters.getParameterValue("zipFilename", "VoyantCorpusDownload.zip"));
OutputStream outputStream = resp.getOutputStream();
final Controller controller = new Controller(storage, parameters);
try {
controller.run(outputStream);
}
catch (Exception e) {
this.log("ERROR: "+e.getLocalizedMessage(), e);
this.log(generateLogMessageForFailedRequest(parameters, this.hiddenParameters));
resp.setStatus(500);
resp.sendError(500, "Unable to produce ZIP file.\n"+e.getMessage());
}
outputStream.flush();
outputStream.close();
}
else {
// we set a permissive control to data to allow calls from elsewhere this may need to be monitored
resp.setHeader("Access-Control-Allow-Origin", "*");
Writer writer = resp.getWriter();
runTromboneController(parameters, resp.getWriter());
writer.flush();
writer.close();
}
}
private void runTromboneController(FlexibleParameters parameters, Writer writer) throws IOException {
if (parameters == null) {
throw new NullPointerException("illegal parameters");
}
if (writer == null) {
throw new NullPointerException("illegal writer");
}
// intercept to see if we have a notebook in resources
if (parameters.getParameterValue("tool", "").equals("notebook.NotebookManager") && parameters.getParameterValue("action", "").equals("load") && parameters.getParameterValue("id","").trim().isEmpty()==false) {
File file = new File(getServletContext().getRealPath("/resources/spyral/notebooks"), parameters.getParameterValue("id")+".html");
if (file.exists()) {
String string = FileUtils.readFileToString(file);
parameters.setParameter("data", string);
parameters.removeParameter("id"); // we can't overwrite this, so make sure to remove it
}
}
final Controller controller = new Controller(storage, parameters, writer);
controller.run();
}
private String getTemplatePath(FlexibleParameters parameters) {
if (parameters == null) {
throw new NullPointerException("illegal parameters");
}
String templatePath = parameters.getParameterValue("template");
if (templatePath.contains("/") == false) {
templatePath = getServletContext().getRealPath("/resources/xsl/"+templatePath);
}
if (templatePath.endsWith(".xsl") == false) {
templatePath += ".xsl";
}
return templatePath;
}
private static String generateLogMessageForUnprocessableParameters(Set<Map.Entry<String, String[]>> rawParameters, Set<String> hiddenParameters) {
if (rawParameters == null) {
throw new NullPointerException("illegal parameters");
}
if (rawParameters.isEmpty()) {
return "(No parameters specified.)";
}
else {
final StringBuilder sb = new StringBuilder("Parameters:\n");
for (Map.Entry<String, String[]> param : rawParameters) {
appendRequestParameter(sb.append("\t"), param.getKey(), param.getValue(), hiddenParameters);
}
return sb.toString();
}
}
private static String generateLogMessageForSuccessfulRequest(FlexibleParameters parameters, HttpServletRequest req) {
if (parameters == null) {
throw new NullPointerException("illegal parameters");
}
if (req == null) {
throw new NullPointerException("illegal servlet request");
}
final StringBuilder sb = new StringBuilder("TOOL: ");
if (parameters.containsKey("tool") == true) {
final String[] tools = parameters.getParameterValues("tool");
for (int i=0, len=tools.length ; i < len ; i++) {
sb.append(tools[i]);
if (i+1 < len) {
sb.append(",");
}
}
}
else {
sb.append("CorpusSummary");
}
if (parameters.containsKey("corpus")) {
sb.append("; CORPUS: ").append(parameters.getParameterValue("corpus"));
}
final Calendar now = Calendar.getInstance();
sb.append("; TIME: ").append(DateFormat.getInstance().format(now.getTime())).append(" (").append(now.getTimeInMillis()).append(")");
sb.append("; REQUEST: ").append(req.getRemoteHost()).append(" (").append(req.getRemoteAddr()).append(")");
return sb.toString();
}
private static String generateLogMessageForFailedRequest(FlexibleParameters parameters, Set<String> hiddenParameters) {
if (parameters == null) {
throw new NullPointerException("illegal parameters");
}
final StringBuilder sb = new StringBuilder("Parameters:\n");
for (String key : parameters.getKeys()) {
appendRequestParameter(sb.append("\t"), key, parameters.getParameterValues(key), hiddenParameters);
}
return sb.toString();
}
private static void appendRequestParameter(StringBuilder sb, String key, String[] values, Set<String> hiddenParameters) {
if (sb == null) {
throw new NullPointerException("illegal StringBuilder");
}
if (key == null) {
throw new NullPointerException("illegal key");
}
if (values == null) {
throw new NullPointerException("illegal values");
}
if (hiddenParameters == null) {
throw new NullPointerException("illegal hidden parameters");
}
sb.append(key).append(": ");
if (hiddenParameters.contains(key) == true) { // bail if we shouldn't show this
sb.append(" (hidden)");
}
else if (values.length == 1) { // 1 key, 1 value
sb.append(cleanParameterValue(values[0]));
}
else { // 1 key, multiple values
sb.append("[");
for (int i=0, len=values.length, mlen=values.length-1 ; i < len ; i++) {
sb.append(cleanParameterValue(values[i]));
if (i < mlen) {
sb.append("; ");
}
}
sb.append("]");
}
sb.append("\n");
}
private static String cleanParameterValue(String parameterValue) {
if (parameterValue == null) {
throw new NullPointerException("illegal value");
}
parameterValue = parameterValue.replaceAll("\\s+", " ");
if (parameterValue.length() > 100) {
parameterValue = parameterValue.substring(0, 100) + "…";
}
return parameterValue;
}
public static boolean hasVoyantServerResource(String resource) {
return Files.exists(getVoyantServerResourcePath(resource));
}
public static String getVoyantServerResource(String resource) throws IOException {
return new String(Files.readAllBytes(getVoyantServerResourcePath(resource)), Charset.forName("UTF-8"));
}
private static Path getVoyantServerResourcePath(String resource) {
// make file from resource to get filename only (avoid traversal vulnerability)
return Paths.get(System.getProperty("java.io.tmpdir"), "voyant-server", new File(resource).getName());
}
}

@ -0,0 +1,184 @@
package org.voyanttools.voyant;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Calendar;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.xml.transform.TransformerException;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.voyanttools.trombone.util.FlexibleParameters;
/**
* @author Stéfan Sinclair
*/
public class Voyant {
/**
* Pre-process the request. At the moment this will look if there's a referer,
* and if so but no input or corpus parameters are provided, it will redirect
* to the same URL but with the referer as input.
* @param request
* @param response
* @return true if preProcessing has resulted in a redirect
* @throws Exception
*/
public static boolean preProcess(HttpServletRequest request, HttpServletResponse response) throws Exception {
final String method = request.getMethod();
if (method==null) {return false;}
final FlexibleParametersFactory flexibleParametersFactory = new FlexibleParametersFactory(request.getSession().getServletContext());
final FlexibleParameters params = flexibleParametersFactory.getInstance(request);
// if we have a POST request, we need to create the corpus before redirecting
if (method.equals("POST") && request.getParameter("noRedirect") == null) {
return handlePostAndRedirect(request, response, params);
}
// if we have a GET request, we need to check for a useReferer parameter
else if (method.equals("GET")) {
return handleRefererAndRedirect(request, response, params);
}
return false;
}
public static String getBaseUrlString(HttpServletRequest request) {
StringBuilder sb = new StringBuilder("//").append(request.getServerName());
int serverPort = request.getServerPort();
if (serverPort!=80 && serverPort!=443) {
sb.append(":").append(serverPort);
}
String contextPath = request.getContextPath();
if (contextPath.isEmpty()==false) {
sb.append(contextPath);
}
sb.append("/");
return sb.toString();
}
/**
* The only time we should be here is when we have a post method to Voyant that includes input and that
* needs to be processed to create a new corpus, and then redirect to the URL with the corpus.
* @param request
* @param response
* @param params
* @return
* @throws IOException
* @throws TransformerException
* @throws ServletException
*/
private static boolean handlePostAndRedirect(HttpServletRequest request,
HttpServletResponse response, FlexibleParameters params) throws IOException, TransformerException, ServletException {
PostedInputResponseWrapper postedInputResponseWrapper = new PostedInputResponseWrapper(response);
request.getRequestDispatcher("/trombone").include(new PostedInputRequestWrapper(request, params), postedInputResponseWrapper);
String responseString = postedInputResponseWrapper.toString();
JSONObject obj= (JSONObject) JSONValue.parse(responseString);
JSONObject builder = (JSONObject) obj.get("stepEnabledCorpusCreator");
String corpusId = (String) builder.get("storedId");
final StringBuilder uri = new StringBuilder("./?corpus=").append(corpusId);
response.sendRedirect(uri.toString());
return true;
}
private static boolean handleRefererAndRedirect(HttpServletRequest request,
HttpServletResponse response, FlexibleParameters params) throws IOException {
// only do this if we have a referer
String referer = request.getHeader("referer");
if ((referer == null) || (referer.isEmpty() == true)) {
return false;
}
// only continue if we have useReferer parameter
if (params.getParameterBooleanValue("useReferer") == false) {return false;}
if ((params.containsKey("input") == false) && (params.containsKey("corpus") == false)) {
params.removeParameter("useReferer");
if (params.getParameterBooleanValue("forceUpdate") == true) {
referer = referer + String.valueOf(Calendar.getInstance().getTimeInMillis());
}
params.addParameter("input", referer);
final StringBuilder uri = new StringBuilder("./?"); // hoping this works
uri.append(params.getAsQueryString());
response.sendRedirect(uri.toString());
return true;
}
return false;
}
static class PostedInputRequestWrapper extends HttpServletRequestWrapper {
private final String TOOL = "corpus.CorpusCreator";
private FlexibleParameters params;
private PostedInputRequestWrapper(HttpServletRequest request, FlexibleParameters params) {
super(request);
this.params = params;
}
@Override
public Map<String,String[]> getParameterMap() {
// we need to create a new map because some servlets provide an unmodifiable map
Map<String, String[]> map = new HashMap<String, String[]>();
Enumeration<String> e = getParameterNames();
while (e.hasMoreElements()) {
String name = e.nextElement();
map.put(name, getParameterValues(name));
}
return map;
}
@Override
public Enumeration<String> getParameterNames() {
Set<String> names = new HashSet<String>();
names.addAll(params.getKeys());
if (!names.contains("tool")) {names.add("tool");}
return Collections.enumeration(names);
}
@Override
public String getParameter(String name) {
return name.equals("tool") ? TOOL : params.getParameterValue(name);
}
@Override
public String[] getParameterValues(String name) {
return name.equals("tool") ? new String[]{getParameter("tool")} : params.getParameterValues(name);
}
}
private static class PostedInputResponseWrapper extends HttpServletResponseWrapper {
private StringWriter stringWriter;
private PrintWriter writer;
private PostedInputResponseWrapper(HttpServletResponse response) {
super(response);
stringWriter = new StringWriter();
writer = new PrintWriter(stringWriter);
}
@Override
public PrintWriter getWriter() {
return writer;
}
@Override
public String toString() {
// writer.flush();
writer.flush();
return stringWriter.toString();
}
}
}

@ -0,0 +1,55 @@
package org.voyanttools.voyant;
import java.io.File;
import java.io.Writer;
import javax.servlet.ServletContext;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.voyanttools.trombone.util.FlexibleParameters;
/**
* @author Stéfan Sinclair, Cyril Briquet
*/
public class XslTransformer {
static void transform(Source xml, Source xslt, Writer writer) throws TransformerException {
transform(new FlexibleParameters(), xml, xslt, writer);
}
static void transform(FlexibleParameters parameters, Source xml, Source xslt, Writer writer) throws TransformerException {
System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
final TransformerFactory transformerFactory = TransformerFactory.newInstance();
final Transformer transformer = transformerFactory.newTransformer(xslt);
for (String key : parameters.getKeys()) {
final String[] vals = parameters.getParameterValues(key);
transformer.setParameter(key, vals.length == 1 ? vals[0] : vals);
}
transformer.transform(xml, new StreamResult(writer));
}
static Source getTemplatePath(String template, File defaultDirectory) {
String templatePath = template;
if (templatePath.contains("/") == false) {
templatePath = new File(defaultDirectory, templatePath).toString();
}
if (templatePath.endsWith(".xsl") == false) {
templatePath += ".xsl";
}
return new StreamSource(templatePath);
}
public static Source getTemplateSource(String template, ServletContext servletContext) {
String path = servletContext.getRealPath("/resources/xsl");
return getTemplatePath(template, new File(path));
}
}

@ -0,0 +1,193 @@
# BUBBLELINES
resources/bubblelines/Bubblelines.js
# KNOTS
resources/knots/Knots.js
# CIRRUS
resources/cirrus/html5/Cirrus.js
resources/cirrus/html5/Word.js
resources/cirrus/html5/WordController.js
# WORDTREE
resources/doubletree/DoubleTree.js
resources/doubletree/Trie.js
# TERMSRADIO
resources/termsradio/TermsRadio.js
# UTILS
app/util/Assignable.js
app/util/Api.js
app/util/Localization.js
app/util/Colors.js
app/util/Deferrable.js
app/util/DetailedError.js
app/util/ResponseError.js
app/util/SparkLine.js
app/util/Toolable.js
app/util/Transferable.js
app/util/Variants.js
app/util/Downloadable.js
app/util/Storage.js
app/util/DiacriticsRemover.js
app/notebook/util/Show.js
app/notebook/util/Embed.js
# MODELS
app/data/model/AnalysisToken.js
app/data/model/Context.js
app/data/model/CorpusFacet.js
app/data/model/CorpusCollocate.js
app/data/model/CorpusTerm.js
app/data/model/CorpusNgram.js
app/data/model/Dimension.js
app/data/model/Document.js
app/data/model/DocumentEntity.js
app/data/model/DocumentQueryMatch.js
app/data/model/DocumentTerm.js
app/data/model/PrincipalComponent.js
app/data/model/RelatedTerm.js
app/data/model/StatisticalAnalysis.js
app/data/model/Token.js
app/data/model/TermCorrelation.js
# STORES
app/data/store/VoyantStore.js
app/data/store/CAAnalysis.js
app/data/store/Contexts.js
app/data/store/CorpusCollocates.js
app/data/store/CorpusFacets.js
app/data/store/CorpusTerms.js
app/data/store/DocumentQueryMatches.js
app/data/store/DocumentTerms.js
app/data/store/DocumentEntities.js
app/data/store/Documents.js
app/data/store/PCAAnalysis.js
app/data/store/DocSimAnalysis.js
app/data/store/CorpusNgrams.js
app/data/store/RelatedTerms.js
app/data/store/TermCorrelations.js
app/data/store/Tokens.js
app/data/store/TSNEAnalysis.js
app/data/store/NotebookFacets.js
# TABLES
app/data/util/Table.js
app/data/util/NetworkGraph.js
app/data/util/Geonames.js
# CORPUS (here because store is needed)
app/data/model/Corpus.js
# WIDGETS
app/widget/CodeEditor.js
app/widget/CorpusSelector.js
app/widget/ListEditor.js
app/widget/StopListOption.js
app/widget/QuerySearchField.js
app/widget/TotalPropertyStatus.js
app/widget/DocumentSelector.js
app/widget/CorpusDocumentSelector.js
app/widget/DownloadFilenameBuilder.js
app/widget/DownloadFileFormat.js
app/widget/DownloadOptions.js
app/widget/FontFamilyOption.js
app/widget/ColorPaletteOption.js
app/widget/VoyantChart.js
app/widget/LiveSearchGrid.js
app/widget/ProgressMonitor.js
app/widget/VoyantTableTransform.js
app/widget/CategoriesBuilder.js
app/widget/VoyantNetworkGraph.js
app/widget/ReaderGraph.js
# PANELS
app/panel/Panel.js
app/panel/VoyantTabPanel.js
# we need facet after panel but before catalogue
app/widget/Facet.js
app/panel/Bubbles.js
app/panel/Bubblelines.js
app/panel/Catalogue.js
app/panel/Cirrus.js
app/panel/CollocatesGraph.js
app/panel/Contexts.js
app/panel/CorpusCollocates.js
app/panel/CorpusTermSummary.js
app/panel/Correlations.js
app/panel/CorpusCreator.js
app/panel/DreamScape.js
app/panel/Knots.js
app/panel/Phrases.js
app/panel/CorpusTerms.js
app/panel/DocumentTerms.js
app/panel/Documents.js
app/panel/DocumentsFinder.js
app/panel/Embedder.js
app/panel/Fountain.js
app/panel/RezoViz.js
app/panel/Loom.js
app/panel/MicroSearch.js
app/panel/Mandala.js
app/panel/MicroOcp.js
app/panel/Reader.js
app/panel/SimpleDocReader.js
app/panel/ScatterPlot.js
app/panel/StreamGraph.js
app/panel/Summary.js
app/panel/TextualArc.js
app/panel/TopicContexts.js
app/panel/TermsBerry.js
app/panel/TermsRadio.js
app/panel/Trends.js
app/panel/NoTool.js
app/panel/VoyantFooter.js
app/panel/VoyantHeader.js
app/panel/CorpusSet.js
app/panel/ScatterSet.js
app/panel/Subset.js
app/panel/CollocatesSet.js
app/panel/BubblelinesSet.js
app/panel/CustomSet.js
app/panel/Veliza.js
app/panel/WordTree.js
app/panel/WordWall.js
app/panel/Topics.js
app/panel/Via.js
# NOTEBOOKS
app/notebook/editor/button/Add.js
app/notebook/editor/button/Edit.js
app/notebook/editor/button/Export.js
app/notebook/editor/button/Counter.js
app/notebook/editor/button/MoveDown.js
app/notebook/editor/button/MoveUp.js
app/notebook/editor/button/Remove.js
app/notebook/editor/button/Metadata.js
app/notebook/editor/button/Movement.js
app/notebook/editor/button/Run.js
app/notebook/editor/button/RunAll.js
app/notebook/editor/button/RunUntil.js
app/notebook/editor/EditorWrapper.js
app/notebook/editor/CodeEditor.js
app/notebook/editor/CodeEditorWrapper.js
app/notebook/editor/TextEditor.js
app/notebook/editor/TextEditorWrapper.js
app/notebook/storage/github/OctokitWrapper.js
app/notebook/storage/github/ReposBrowser.js
app/notebook/storage/github/FileSaver.js
app/notebook/storage/github/GitHubDialogs.js
app/notebook/storage/voyant/StorageDialogs.js
app/notebook/Catalogue.js
app/notebook/Notebook.js
# APPS
app/VoyantApp.js
app/VoyantCorpusApp.js
app/VoyantCorpusToolsetApp.js
app/VoyantDefaultApp.js
app/VoyantDocumentToolsetApp.js
app/VoyantNotebookApp.js
app/VoyantToolApp.js

@ -0,0 +1,3 @@
/docs
/json
.#webclasspath

@ -0,0 +1,3 @@
Manifest-Version: 1.0
Class-Path:

@ -0,0 +1,3 @@
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="maxFormContentSize">100000000</Set> <!-- should be 100MB -->
</Configure>

@ -0,0 +1,140 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<context-param>
<param-name>version</param-name>
<param-value>2.4</param-value>
</context-param>
<context-param>
<param-name>build</param-name>
<param-value>M55</param-value>
</context-param>
<servlet>
<servlet-name>tool</servlet-name>
<jsp-file>/tool/index.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>catalogue</servlet-name>
<url-pattern>/catalogue/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>catalogue</servlet-name>
<jsp-file>/catalogue/index.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>microocp</servlet-name>
<url-pattern>/microocp/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>microocp</servlet-name>
<jsp-file>/microocp/index.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>tool</servlet-name>
<url-pattern>/tool/*</url-pattern>
</servlet-mapping>
<!-- we changed from spiral to spyral, we'll redirect in spyral -->
<servlet-mapping>
<servlet-name>spiral</servlet-name>
<url-pattern>/spiral/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>spiral</servlet-name>
<jsp-file>/spyral/index.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>spyral-oauth</servlet-name>
<url-pattern>/spyral/oauth</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>spyral-oauth</servlet-name>
<jsp-file>/spyral/oauth/index.jsp</jsp-file>
<init-param>
<param-name>oauthprops</param-name>
<param-value>oauth.properties</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spyral-oauth-callback</servlet-name>
<url-pattern>/spyral/oauth/callback</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>spyral-oauth-callback</servlet-name>
<servlet-class>org.voyanttools.voyant.SpyralAuth</servlet-class>
<init-param>
<param-name>oauthprops</param-name>
<param-value>oauth.properties</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spyral-cookie</servlet-name>
<url-pattern>/spyral/cookie</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>spyral-cookie</servlet-name>
<jsp-file>/spyral/cookie/index.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>spyral</servlet-name>
<url-pattern>/spyral/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>spyral</servlet-name>
<jsp-file>/spyral/index.jsp</jsp-file>
</servlet>
<!-- this is to handle a bad URL in Hermeneutica the book -->
<servlet-mapping>
<servlet-name>collocatesgraph</servlet-name>
<url-pattern>/CollocatesGraph/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>collocatesgraph</servlet-name>
<jsp-file>/tool/index.jsp</jsp-file>
</servlet>
<!-- available from http://localhost:8080/trombone?param=...&param=...&param=... -->
<servlet>
<servlet-name>trombone</servlet-name>
<servlet-class>org.voyanttools.voyant.Trombone</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>trombone</servlet-name>
<url-pattern>/trombone</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- make sure that Javascript is sent as UTF-8 (Jetty does this but Tomcat doesn't) -->
<mime-mapping>
<extension>js</extension>
<mime-type>application/javascript;charset=UTF-8</mime-type>
</mime-mapping>
<!-- universally set encoding for UTF-8 (simpliflies jsp includes)-->
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
</web-app>

@ -0,0 +1,412 @@
/*
Ext.promise.Deferred adapted from:
[DeftJS](https://github.com/deftjs/deftjs5)
Copyright (c) 2012-2014 [DeftJS Framework Contributors](http://deftjs.org)
Open source under the [MIT License](http://en.wikipedia.org/wiki/MIT_License).
*/
/**
* Promises represent a future value; i.e., a value that may not yet be available.
*
* Users should **not** create instances of this class directly. Instead user code should
* use `new {@link Ext.Promise}()` or `new {@link Ext.Deferred}()` to create and manage
* promises. If the browser supports the standard `Promise` constructor, this class will
* not be used by `Ext.Promise`. This class will always be used by `Ext.Deferred` in order
* to provide enhanced capabilities beyond standard promises.
*
* A Promise's `{@link #then then()}` method is used to specify onFulfilled and onRejected
* callbacks that will be notified when the future value becomes available. Those callbacks
* can subsequently transform the value that was resolved or the reason that was rejected.
* Each call to `then` returns a new Promise of that transformed value; i.e., a Promise
* that is resolved with the callback return value or rejected with any error thrown by
* the callback.
*
* ## Basic Usage
*
* this.companyService.loadCompanies().then(
* function (records) {
* // Do something with result.
* },
* function (error) {
* // Do something on failure.
* }).
* always(function () {
* // Do something whether call succeeded or failed
* });
*
* The above code uses the `Promise` returned from the `companyService.loadCompanies()`
* method and uses `then()` to attach success and failure handlers. Finally, an `always()`
* method call is chained onto the returned promise. This specifies a callback function
* that will run whether the underlying call succeeded or failed.
*
* See `{@link Ext.Deferred}` for an example of using the returned Promise.
*
* [1]: http://wiki.ecmascript.org/doku.php?id=harmony:specification_drafts#april_14_2015_rev_38_final_draft
*
* @since 6.0.0
*/
Ext.define('Ext.promise.Promise', function (ExtPromise) {
var Deferred;
return {
requires: [
'Ext.promise.Deferred'
],
statics: {
/**
* @property CancellationError
* @static
* The type of `Error` propagated by the `{@link #method-cancel}` method. If
* the browser provides a native `CancellationError` then that type is used. If
* not, a basic `Error` type is used.
*/
CancellationError: Ext.global.CancellationError || Error,
_ready: function () {
// Our requires are met, so we can cache Ext.promise.Deferred
Deferred = Ext.promise.Deferred;
},
/**
* Returns a new Promise that will only resolve once all the specified
* `promisesOrValues` have resolved.
*
* The resolution value will be an Array containing the resolution value of each
* of the `promisesOrValues`.
*
* The public API's to use instead of this method are `{@link Ext.Promise#all}`
* and `{@link Ext.Deferred#all}`.
*
* @param {Mixed[]/Ext.promise.Promise[]/Ext.promise.Promise} promisesOrValues An
* Array of values or Promises, or a Promise of an Array of values or Promises.
* @return {Ext.promise.Promise} A Promise of an Array of the resolved values.
*
* @static
* @private
*/
all: function (promisesOrValues) {
//<debug>
if (!(Ext.isArray(promisesOrValues) || ExtPromise.is(promisesOrValues))) {
Ext.raise('Invalid parameter: expected an Array or Promise of an Array.');
}
//</debug>
return ExtPromise.when(promisesOrValues).then(function (promisesOrValues) {
var deferred = new Deferred(),
remainingToResolve = promisesOrValues.length,
results = new Array(remainingToResolve),
index, promiseOrValue, resolve, i, len;
if (!remainingToResolve) {
deferred.resolve(results);
}
else {
resolve = function (item, index) {
return ExtPromise.when(item).then (function (value) {
results[index] = value;
if (!--remainingToResolve) {
deferred.resolve(results);
}
return value;
}, function (reason) {
return deferred.reject(reason);
});
};
for (index = i = 0, len = promisesOrValues.length; i < len; index = ++i) {
promiseOrValue = promisesOrValues[index];
if (index in promisesOrValues) {
resolve(promiseOrValue, index);
}
else {
remainingToResolve--;
}
}
}
return deferred.promise;
});
},
/**
* Determines whether the specified value is a Promise (including third-party
* untrusted Promises or then()-ables), based on the Promises/A specification
* feature test.
*
* @param {Mixed} value A potential Promise.
* @return {Boolean} `true` if the given value is a Promise, otherwise `false`.
* @static
* @private
*/
is: function (value) {
return (Ext.isObject(value) || Ext.isFunction(value)) &&
Ext.isFunction(value.then);
},
/**
* Rethrows the specified Error on the next turn of the event loop.
* @static
* @private
*/
rethrowError: function (error) {
Ext.asap(function () {
throw error;
});
},
/**
* Returns a new Promise that either
*
* * Resolves immediately for the specified value, or
* * Resolves or rejects when the specified promise (or third-party Promise or
* then()-able) is resolved or rejected.
*
* The public API's to use instead of this method are `{@link Ext.Promise#resolve}`
* and `{@link Ext.Deferred#resolved}`.
*
* @param {Mixed} promiseOrValue A Promise (or third-party Promise or then()-able)
* or value.
* @return {Ext.Promise} A Promise of the specified Promise or value.
*
* @static
* @private
*/
when: function (value) {
var deferred = new Ext.promise.Deferred();
deferred.resolve(value);
return deferred.promise;
}
},
/**
* @property {Ext.promise.Deferred} Reference to this promise's
* `{@link Ext.promise.Deferred Deferred}` instance.
*
* @readonly
* @private
*/
owner: null,
/**
* NOTE: {@link Ext.promise.Deferred Deferreds} are the mechanism used to create new
* Promises.
* @param {Ext.promise.Deferred} owner The owning `Deferred` instance.
*
* @private
*/
constructor: function (owner) {
this.owner = owner;
},
/**
* Attaches onFulfilled and onRejected callbacks that will be notified when the future
* value becomes available.
*
* Those callbacks can subsequently transform the value that was fulfilled or the error
* that was rejected. Each call to `then` returns a new Promise of that transformed
* value; i.e., a Promise that is fulfilled with the callback return value or rejected
* with any error thrown by the callback.
*
* @param {Function} onFulfilled Optional callback to execute to transform a
* fulfillment value.
* @param {Function} onRejected Optional callback to execute to transform a rejection
* reason.
* @param {Function} onProgress Optional callback function to be called with progress
* updates.
* @param {Object} scope Optional scope for the callback(s).
* @return {Ext.promise.Promise} Promise that is fulfilled with the callback return
* value or rejected with any error thrown by the callback.
*/
then: function (onFulfilled, onRejected, onProgress, scope) {
var ref;
if (arguments.length === 1 && Ext.isObject(arguments[0])) {
ref = arguments[0];
onFulfilled = ref.success;
onRejected = ref.failure;
onProgress = ref.progress;
scope = ref.scope;
}
if (scope) {
if (onFulfilled) {
onFulfilled = Ext.Function.bind(onFulfilled, scope);
}
if (onRejected) {
onRejected = Ext.Function.bind(onRejected, scope);
}
if (onProgress) {
onProgress = Ext.Function.bind(onProgress, scope);
}
}
return this.owner.then(onFulfilled, onRejected, onProgress);
},
/**
* Attaches an onRejected callback that will be notified if this Promise is rejected.
*
* The callback can subsequently transform the reason that was rejected. Each call to
* `otherwise` returns a new Promise of that transformed value; i.e., a Promise that
* is resolved with the original resolved value, or resolved with the callback return
* value or rejected with any error thrown by the callback.
*
* @param {Function} onRejected Callback to execute to transform a rejection reason.
* @param {Object} scope Optional scope for the callback.
* @return {Ext.promise.Promise} Promise of the transformed future value.
*/
otherwise: function (onRejected, scope) {
var ref;
if (arguments.length === 1 && Ext.isObject(arguments[0])) {
ref = arguments[0];
onRejected = ref.fn;
scope = ref.scope;
}
if (scope != null) {
onRejected = Ext.Function.bind(onRejected, scope);
}
return this.owner.then(null, onRejected);
},
/**
* Attaches an onCompleted callback that will be notified when this Promise is completed.
*
* Similar to `finally` in `try... catch... finally`.
*
* NOTE: The specified callback does not affect the resulting Promise's outcome; any
* return value is ignored and any Error is rethrown.
*
* @param {Function} onCompleted Callback to execute when the Promise is resolved or
* rejected.
* @param {Object} scope Optional scope for the callback.
* @return {Ext.promise.Promise} A new "pass-through" Promise that is resolved with
* the original value or rejected with the original reason.
*/
always: function (onCompleted, scope) {
var ref;
if (arguments.length === 1 && Ext.isObject(arguments[0])) {
ref = arguments[0];
onCompleted = ref.fn;
scope = ref.scope;
}
if (scope != null) {
onCompleted = Ext.Function.bind(onCompleted, scope);
}
return this.owner.then(function (value) {
debugger
try {
onCompleted();
}
catch (e) {
ExtPromise.rethrowError(e);
}
return value;
}, function (reason) {
try {
onCompleted();
}
catch (e) {
ExtPromise.rethrowError(e);
}
throw reason;
});
},
/**
* Terminates a Promise chain, ensuring that unhandled rejections will be rethrown as
* Errors.
*
* One of the pitfalls of interacting with Promise-based APIs is the tendency for
* important errors to be silently swallowed unless an explicit rejection handler is
* specified.
*
* For example:
*
* promise.then(function () {
* // logic in your callback throws an error and it is interpreted as a
* // rejection. throw new Error("Boom!");
* });
*
* // The Error was not handled by the Promise chain and is silently swallowed.
*
* This problem can be addressed by terminating the Promise chain with the done()
* method:
*
* promise.then(function () {
* // logic in your callback throws an error and it is interpreted as a
* // rejection. throw new Error("Boom!");
* }).done();
*
* // The Error was not handled by the Promise chain and is rethrown by done() on
* // the next tick.
*
* The `done()` method ensures that any unhandled rejections are rethrown as Errors.
*/
done: function () {
this.owner.then(null, ExtPromise.rethrowError);
},
/**
* Cancels this Promise if it is still pending, triggering a rejection with a
* `{@link #CancellationError}` that will propagate to any Promises originating from
* this Promise.
*
* NOTE: Cancellation only propagates to Promises that branch from the target Promise.
* It does not traverse back up to parent branches, as this would reject nodes from
* which other Promises may have branched, causing unintended side-effects.
*
* @param {Error} reason Cancellation reason.
*/
cancel: function (reason) {
if (reason == null) {
reason = null;
}
this.owner.reject(new this.self.CancellationError(reason));
},
/**
* Logs the resolution or rejection of this Promise with the specified category and
* optional identifier. Messages are logged via all registered custom logger functions.
*
* @param {String} identifier An optional identifier to incorporate into the
* resulting log entry.
*
* @return {Ext.promise.Promise} A new "pass-through" Promise that is resolved with
* the original value or rejected with the original reason.
*/
log: function (identifier) {
if (identifier == null) {
identifier = '';
}
return this._owner.then(function (value) {
Ext.log("" + (identifier || 'Promise') + " resolved with value: " + value);
return value;
}, function (reason) {
Ext.log("" + (identifier || 'Promise') + " rejected with reason: " + reason);
throw reason;
});
}
}},
function (ExtPromise) {
ExtPromise._ready();
});

@ -0,0 +1,217 @@
Ext.define('Voyant.VoyantApp', {
extend: 'Ext.app.Application',
mixins: ['Voyant.util.Deferrable','Voyant.util.Localization','Voyant.util.Api','Voyant.util.Colors'],
requires: ['Voyant.util.ResponseError'],
name: 'VoyantApp',
statics: {
i18n: {
},
api: {
palette: 'default',
categories: 'auto',
lang: undefined,
debug: undefined
}
},
config: {
baseUrl: undefined,
tromboneUrl: undefined,
categoriesManager: undefined
},
constructor: function(config) {
this.setBaseUrl(this.config.baseUrl);
// set the Trombone URL from the baseURL // TODO: maybe allow this to be overridden
this.setTromboneUrl(this.config.baseUrl+'trombone');
// set the application for the Corpus so that we can use a simple constructor
Voyant.application = this;
this.mixins['Voyant.util.Api'].constructor.apply(this, arguments);
this.mixins['Voyant.util.Colors'].constructor.apply(this, arguments);
this.setCategoriesManager(new Spyral.Categories());
// inheritance/mixin hack
// var catProps = Object.getOwnPropertyNames(categories).concat(Object.getOwnPropertyNames(Object.getPrototypeOf(categories)));
// catProps.forEach(function(propName) {
// if (this[propName] === undefined) {
// if (typeof categories[propName] === 'function') {
// this[propName] = categories[propName].bind(this);
// } else {
// this[propName] = categories[propName];
// }
// }
// }, this)
this.getCategoriesManager().addFeature('color');
this.getCategoriesManager().addFeature('font', '"Palatino Linotype", "Book Antiqua", Palatino, serif');
// call the parent constructor
this.callParent(arguments);
// override Voyant.util.Colors methods to add palette api param
var _getColor = this.getColor;
this.getColor = function(index, returnHex) {
return _getColor.apply(this, [this.getApiParam('palette'), index, returnHex]);
}
var _getColorForTerm = this.getColorForTerm;
this.getColorForTerm = function(term, returnHex) {
return _getColorForTerm.apply(this, [this.getApiParam('palette'), term, returnHex]);
}
},
getBaseUrl: function() {
var baseUrl = this.callParent();
return baseUrl.indexOf("//")==0 ? location.protocol+baseUrl : baseUrl;
},
getBaseUrlFull: function() {
return window.location.origin+this.getBaseUrl(); // maybe doesn't work in all browsers?
},
getRelativeUrl: function() {
var url = window.location.pathname.substring(this.getBaseUrl().length);
var relative = "";
for (var i=0, len=url.split("/").length-1; i<len; i++) {
relative+="../"
}
return relative;
},
getTools: function() {
return [{type: 'maximize'},{type: 'help'}]
},
launch: function() {
Ext.tip.QuickTipManager.init();
Ext.apply(Ext.tip.QuickTipManager.getQuickTip(), {
showDelay: 50 // shorten the delay before showing
});
this.callParent(arguments);
},
tromboneCall: function(config) {
var config = config ? config : {};
Ext.applyIf(config, {
url: this.getTromboneUrl()
});
if (!config.success && !config.failure && !config.callback) {
Ext.applyIf(config, {
url: this.getTromboneUrl(),
scope: this,
callback: function(response, success, options) {
this.dispatchEvent(config.tool+"Loaded", response, success, options)
}
});
};
Ext.Ajax.request(config);
},
getViewport: function() {
return Ext.ComponentQuery.query('viewport')[0];
},
dispatchEvent: function(eventName, src) {
var viewport = this.getViewport();
var panels = viewport.query("panel,chart");
var isHeard = false;
// tell the app
if (this.hasListener && this.hasListener(eventName)) {
this.fireEvent.apply(this, arguments);
isHeard = true
}
// tell the panels, except the current one
for (var i=0; i<panels.length; i++) {
if (panels[i].hasListener && panels[i].hasListener(eventName)) {
if (src && src.getId && panels[i].getId && src.getId()==panels[i].getId()) {
continue; // don't send to self
}
isHeard = true;
panels[i].fireEvent.apply(panels[i], arguments);
}
}
if (!isHeard) {
// let the application know that we have an unhandledEvent
var args = ["unhandledEvent", src, eventName];
for (var i=2; i<arguments.length; i++) {args.push(arguments[i])}
this.fireEvent.apply(this, args);
}
},
showResponseError: function(config, response) {
this.showError(Ext.create("Voyant.util.ResponseError", {msg: (Ext.isString(config) ? config : config.msg), response: response}))
},
showError: function(config, response) {
if (config instanceof Voyant.util.ResponseError) {
config = {
message: config.getMsg()+"<p class='error'>\n"+config.getError()+" … "+
"<a href='#' onclick=\"window.open('').document.write(unescape('<pre>"+escape(config.getDetails())+"</pre>')); return false;\">more</a></p>"
}
} else if (config instanceof Ext.data.operation.Operation) {
return this.showError(Ext.create("Voyant.util.ResponseError", config.getError()))
} else {
if (Ext.isString(config)) {
config = {message: config}
} else if (Ext.isObject(config)) {
if (config.responseText) {
// rebundle as error (without nice message)
return this.showResponseError(config.statusText, config);
} else if (config.statusText) {
return this.showResponseError(config.statusText, config)
}
}
// maybe handle other forms
}
Ext.applyIf(config, {
title: this.localize("error"),
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.ERROR,
autoScroll: true
})
Ext.Msg.show(config);
},
getToolConfigFromToolXtype: function(xtype) {
cls = Ext.ClassManager.getByAlias("widget."+xtype);
return {
xtype: xtype,
title: this._localizeClass(cls, "title"),
tooltip: { // this needs to be an object for compatibility (other configs can be changed)
text: this._localizeClass(cls, "helpTip")
},
glyph: cls && cls.glyph ? cls.glyph : 'xf12e@FontAwesome'
};
},
/**
* Opens a URL in a new window (handling the case when popup windows aren't allowed).
* @param {String} url The URL to open.
* @private
*/
openUrl: function(url) {
var win = window.open(url);
if (!win) { // popup blocked
Ext.Msg.show({
title: "Popup Blocked",
buttonText: {ok: "Close"},
icon: Ext.MessageBox.INFO,
message: "A popup window was blocked. <a href='"+url+"' target='_blank' class='link'>Click here</a> to open the new window.",
buttons: Ext.Msg.OK
});
}
}
});

@ -0,0 +1,347 @@
Ext.define('Voyant.VoyantCorpusApp', {
extend: 'Voyant.VoyantApp',
name: 'VoyantCorpusApp',
requires: ['Voyant.panel.CorpusSet','Voyant.data.model.Corpus','Voyant.panel.VoyantHeader', 'Voyant.panel.VoyantFooter', 'Voyant.panel.CorpusCreator', 'Voyant.panel.Cirrus', 'Voyant.panel.Summary', 'Voyant.panel.DreamScape', 'Voyant.panel.CorpusTerms', 'Voyant.panel.Reader', 'Voyant.panel.Documents', 'Voyant.panel.Trends', 'Voyant.panel.Contexts', 'Voyant.panel.DocumentTerms','Voyant.panel.CorpusCollocates','Voyant.panel.CollocatesGraph','Voyant.panel.Phrases','Voyant.panel.ScatterPlot','Voyant.panel.TopicContexts','Voyant.panel.TermsRadio','Voyant.panel.TermsBerry'],
statics: {
i18n: {
},
api: {
toolFlow: undefined
}
},
constructor: function() {
this.mixins['Voyant.util.Api'].constructor.apply(this, arguments);
this.callParent(arguments);
},
config: {
corpus: undefined,
corpusAccess: undefined,
moreTools: [{
i18n: 'moreToolsScaleCorpus',
glyph: 'xf065@FontAwesome',
items: ['cirrus','corpusterms','bubblelines','correlations','corpuscollocates','dreamscape','loom','mandala','microsearch','streamgraph','phrases','documents','summary','trends','scatterplot','termsradio','topics','veliza','wordtree']
},{
i18n: 'moreToolsScaleDocument',
glyph: 'xf066@FontAwesome',
items: ['bubbles','cirrus','contexts','documentterms','reader','textualarc','trends','knots','topics']
},{
i18n: 'moreToolsTypeViz',
glyph: 'xf06e@FontAwesome',
items: ['cirrus','bubblelines','bubbles','collocatesgraph','dreamscape','loom','knots','mandala','microsearch','streamgraph','scatterplot','textualarc','trends','termsberry','termsradio','wordtree']
},{
i18n: 'moreToolsTypeGrid',
glyph: 'xf0ce@FontAwesome',
items: ['corpusterms','corpuscollocates','correlations','phrases','contexts','documentterms','documents','topics']
},{
i18n: 'moreToolsTypeOther',
glyph: 'xf035@FontAwesome',
items: ['reader','summary','veliza']
}]
},
launch: function(config) {
this.callParent(arguments);
if (this.hasQueryToLoad()) {
var queryParams = Ext.Object.fromQueryString(document.location.search);
if (!queryParams.corpus && this.getCorpusId && this.getCorpusId()) {
queryParams.corpus = this.getCorpusId();
}
if (config && config.useCache) { // for large corpora
queryParams.useCache = config.useCache;
}
this.loadCorpusFromParams(queryParams);
if (queryParams.palette) {
if (queryParams.palette.indexOf(",")>-1) { // treat as inline
var palette = Ext.decode(queryParams.palette);
this.addColorPalette(queryParams.palette, palette);
} else {
this.loadColorPaletteForCorpus(queryParams.corpus, queryParams.palette);
}
}
} else {
var viewport = this.getViewport();
if (viewport) {
var corpuscreator = viewport.down("corpuscreator")
if (corpuscreator) {
var toast = corpuscreator.toastInfo({
html: this.localize('didYouKnowText'),
title: this.localize('didYouKnow'),
anchor: corpuscreator.down("textareafield"),
align: 'tr',
listeners: {
beforeclose: {
fn: function() {
this.getHeader().getTools().forEach(function(tool) {
if (tool.type=="gear" || tool.type=='help') {
tool.getEl().frame("#ff0000", 1, { duration: 3000 })
}
});
},
scope: corpuscreator
}
}
});
}
}
}
},
loadCorpusFromParams: function(params) {
var me = this;
var view = me.getViewport()
view.mask(this.localize("fetchingCorpus"));
if (params.archive) { // fix a few URLs we know about
if (Ext.isString(params.archive)) {params.archive=[params.archive]}
params.archive = params.archive.map(function(archive) {
return archive.replace('/blogs.sub.uni-hamburg.de/hup/lhn/', '/wikis.sub.uni-hamburg.de/lhn/index.php/')
.replace('/hup.sub.uni-hamburg.de/', '/wikis.sub.uni-hamburg.de/')
})
}
this.validateCorpusLoadParams(params);
new Voyant.data.model.Corpus(params).then(function(corpus) {
view.unmask();
me.setCorpus(corpus);
if (me.validateCorpusAccess()) {
me.dispatchEvent('loadedCorpus', this, corpus);
}
}).otherwise(function() {
view.unmask();
})
},
validateCorpusLoadParams: function(params) {
// leave untouched by default, this can be overridden
},
validateCorpusAccess: function() {
var me = this, view = me.getViewport(), corpus = this.getCorpus();
if (corpus && corpus.requiresPassword() && !me.getViewport().query("panel").every(function(panel) {
return !panel.isConsumptive
})) {
var noPasswordAccess = corpus.getNoPasswordAccess();
var passWin = Ext.create('Ext.window.Window', {
title: me.localize('passwordRequiredTitle'),
layout: 'fit',
items: {
padding: 10,
flex: 1,
width: 300,
layout: {
type: 'vbox',
align: 'stretch'
},
items: [
{
html: '<p>'+me.localize('passwordRequiredMessage')+'</p>' + (noPasswordAccess=='NONCONSUMPTIVE' ? '<p>'+me.localize('nonConsumptiveMessage')+"</p>" : "")+'</p>'
},{
xtype: 'textfield',
fieldLabel: me.localize('password')
}
],
bbar: {
// ui: 'footer',
layout: {pack: 'center'},
items: [{
text: me.localize('passwordValidateButton'),
ui: 'default',
handler: function() {
var password = passWin.query("textfield")[0].getValue().trim();
if (password.length==0) {
me.showError({
message: me.localize('noPasswordGiven')
})
return;
}
passWin.mask();
Ext.Ajax.request({
url: me.getTromboneUrl(),
params: {
corpus: corpus.getId(),
passwordForSession: password
},
method: 'POST',
success: function(result, request) {
passWin.unmask();
var access = result.responseText;
if (access=="ADMIN" || access=="ACCESS") {
passWin.close();
view.unmask();
me.setCorpusAccess(access);
me.dispatchEvent('loadedCorpus', this, corpus);
}
else {
me.showError({
message: me.localize('badPassword')
})
}
},
failure: function(result, request) {
passWin.unmask();
me.showError({
message: me.localize('passwordValidationError')
})
}
});
}
},{
text: me.localize('nonConsumptiveButton'),
hidden: corpus.getNoPasswordAccess()=='NONE',
handler: function() {
passWin.mask();
Ext.Ajax.request({
url: me.getTromboneUrl(),
params: {
corpus: corpus.getId(),
passwordForSessionRemove: true
},
method: 'POST',
callback: function(result, request) { // do this even if request fails
passWin.unmask();
passWin.close();
view.unmask();
me.dispatchEvent('loadedCorpus', me, corpus);
}
});
}
}]
}
}
}).show();
return false;
} else {
return true
}
},
hasQueryToLoad: function(params) {
if (!params) {
params = Ext.Object.fromQueryString(document.location.search);
}
return params.corpus || params.input || (this.getCorpusId && this.getCorpusId()); // TODO: should this include "archive" from V1?
},
loadColorPaletteForCorpus: function(corpusId, paletteId) {
Ext.Ajax.request({
url: this.getTromboneUrl(),
params: {
tool: 'resource.StoredResource',
retrieveResourceId: paletteId,
corpus: corpusId
},
success: function(response, req) {
var json = Ext.util.JSON.decode(response.responseText);
var value = json.storedResource.resource;
var palette = Ext.decode(value);
this.addColorPalette(paletteId, palette);
},
failure: function(response) {
this.setApiParam('palette', undefined);
},
scope: this
});
},
loadCategoryData: function(id) {
return this.getCategoriesManager().load(id, {
trombone: Voyant.application.getTromboneUrl()
});
},
saveCategoryData: function(data) {
return this.getCategoriesManager().save({}, {
trombone: Voyant.application.getTromboneUrl()
});
},
listeners: {
loadedCorpus: function(src, corpus) {
this.setCorpus(corpus);
// let's load the categories based on the corpus
if (this.getApiParam("categories")) {
this.loadCategoryData(this.getApiParam("categories")).then(function() {
// assign colors
for (var category in this.getCategoriesManager().getCategories()) {
var color = this.getCategoriesManager().getCategoryFeature(category, 'color');
if (color !== undefined) {
var rgb = this.hexToRgb(color);
var terms = this.getCategoriesManager().getCategoryTerms(category);
for (var i = 0; i < terms.length; i++) {
this.setColorForTerm(terms[i], rgb);
}
}
}
}.bind(this));
}
this.on("unhandledEvent", function(src, eventName, data) {
var url = this.getBaseUrl() + '?corpus='+corpus.getAliasOrId();
var api = this.getModifiedApiParams() || {}; // use application, not tool
delete api.view; // make sure we show default view
if (eventName=='termsClicked') {
// data can be a simple array of terms or an array of term objects
if (Ext.isArray(data) && "term" in data[0] && "docIndex" in data[0]) {
let termsObj = {};
let docIndObj = {};
data.forEach(function(datum) {
termsObj[datum.term]=true;
docIndObj[datum.docIndex]=true;
})
api.query=Object.keys(termsObj);
api.docIndex=Object.keys(docIndObj);
} else {
api.query=data;
}
}
else if (eventName=='documentsClicked') {
var docIndex = [];
if (data.forEach) {
data.forEach(function(doc) {
docIndex.push(doc.getIndex())
})
}
api.docIndex=docIndex
}
else if (eventName=='corpusTermsClicked') {
if (data.map) {
api.query = data.map(function(corpusTerm) {return corpusTerm.getTerm()});
}
}
else if (eventName=='documentTermsClicked') {
if (data.map) {
api.query = data.map(function(documentTerm) {return documentTerm.getTerm()});
api.docIndex = data.map(function(documentTerm) {return documentTerm.getDocIndex()});
}
}
else {
if (console) {console.warn("Unhandled event: "+eventName, data)}
return;
}
if (api.toolFlow) {
var toolFlow = Ext.Array.from(api.toolFlow.split(","));
api.view = toolFlow.shift();
if (toolFlow.length>0) {
api.toolFlow = toolFlow.join(",");
} else {
delete api.toolFlow
}
}
url += "&"+Ext.Object.toQueryString(api)
this.openUrl(url)
})
}
}
});

@ -0,0 +1,49 @@
Ext.define('Voyant.panel.DocumentClusters', {
extend: 'Ext.panel.Panel',
alias: 'widget.documentclusters',
title: "Document Clusters"
})
// extend: 'Ext.panel.Panel',
// alias: 'widget.rezoviz',
// title: "RezoViz"
//})
Ext.define('Voyant.VoyantCorpusToolsetApp', {
extend : 'Voyant.VoyantCorpusApp',
requires: ['Voyant.panel.Contexts','Voyant.panel.CollocatesGraph','Voyant.panel.Trends'],
name : 'VoyantCorpusToolsetApp',
launch: function() {
Ext.create('Ext.container.Viewport', {
layout: 'border',
items: [{
region: 'south',
xtype: 'voyantfooter'
}, {
xtype: 'tabpanel',
region: 'center',
split: true,
items: [{
xtype: 'cirrus',
collapsible: true
},{
xtype: 'corpusterms',
collapsible: true
},{
xtype: 'documents',
collapsible: true
},{
xtype: 'rezoviz',
collapsible: true
},{
xtype: 'trends',
collapsible: true
},{
xtype: 'documentclusters',
collapsible: true
}],
flex: 6
}]
});
this.callParent(arguments);
}
});

@ -0,0 +1,107 @@
Ext.define('Voyant.VoyantDefaultApp', {
extend : 'Voyant.VoyantCorpusApp',
mixins: ['Voyant.util.Api'],
name : 'VoyantDefaultApp',
constructor: function() {
this.mixins['Voyant.util.Api'].constructor.apply(this, arguments);
this.callParent(arguments);
},
statics: {
i18n: {
},
api: {
view: 'corpusset',
stopList: 'auto',
panels: undefined,
rtl: undefined
}
},
listeners: {
loadedCorpus: function(src, corpus) {
this.viewport.down('voyantheader').collapse();
this.viewport.down('#toolsContainer').setActiveItem(1);
var corpusId = this.getCorpusId && this.getCorpusId() ? this.getCorpusId() : undefined;
if (window.history.pushState && !corpusId) {
// add the corpusId to the url
var corpusId = corpus.getAliasOrId();
var queryParams = Ext.Object.fromQueryString(document.location.search);
var url = this.getBaseUrl()+'?corpus='+corpusId;
for (var key in queryParams) {
if (key !== 'corpus') {
var vals = Ext.isString(queryParams[key]) ? [queryParams[key]] : queryParams[key];
if (Ext.isArray(vals)) {
vals.forEach(function(val) {
url += '&'+key+'='+val;
})
}
}
}
window.history.pushState({
corpus: corpusId
}, 'Corpus: '+corpusId, url);
}
}
},
getViewComponent: function() {
return this.viewport.down('#toolsContainer-main')
},
launch: function() {
var queryParams = Ext.Object.fromQueryString(document.location.search) || {};
var view = this.getApiParam('view', 'CorpusSet');
var xtype = view.toLowerCase();
if (!Ext.ClassManager.getByAlias("widget."+xtype) || queryParams.noskin) {
Ext.Msg.show({
title: this.localize('noViewErrorTitle'),
message: new Ext.Template(this.localize(queryParams.noskin ? 'noViewKnownErrorTpl' : 'noViewErrorTpl')).apply({
view: queryParams.noskin ? queryParams.noskin : view,
additional: queryParams.noskin && queryParams.noskin == 'convert' ? this.localize(queryParams.noskin+'SkinMsg') : ''
}),
buttons: Ext.Msg.OK,
icon: Ext.Msg.ERROR
});
xtype = 'corpusset'; // switch to default view
}
var SPLIT_SIZE = 5;
this.viewport = Ext.create('Ext.container.Viewport', {
layout: 'border',
rtl: (this.getApiParam('rtl')!==undefined || Voyant.util.Localization.LANGUAGE=="ar" || Voyant.util.Localization.LANGUAGE=="he"),
items: [{
xtype: 'voyantheader',
region: 'north'
},{
region: 'south',
xtype: 'voyantfooter'
},{
region: 'center',
layout: 'card',
itemId: 'toolsContainer',
activeItem: 0,
items: [{
xtype : 'container',
layout: {
type: 'vbox',
pack: 'center',
align: 'center'
},
items: [{
xtype: 'corpuscreator'
},{
xtype: 'container',
width: 800,
html: "<div id='voyantIs' style='font-style: italic; text-align: center; margin-top: 10px;'><div>"+this.localize('voyantIs')+"</div>" + (this.localize('translatedBy').indexOf("English") == -1 ? "<div>"+this.localize('translatedBy')+"</div>" : "") +
(this.getCorpusCreatorText && this.getCorpusCreatorText().trim().length>0 ? "<div id='corpusCreatorText'>"+this.getCorpusCreatorText()+"</div>" : "")
}]
},{
layout: 'fit',
itemId: 'toolsContainer-main',
items: {
xtype: xtype
}
}]
}]
});
this.callParent(arguments);
}
});

@ -0,0 +1,44 @@
Ext.define('Voyant.panel.MoreLikeThis', {
extend: 'Ext.panel.Panel',
alias: 'widget.morelikethis',
title: "More Like this"
})
Ext.define('Voyant.VoyantDocumentToolsetApp', {
extend : 'Voyant.VoyantCorpusApp',
requires: ['Voyant.panel.Contexts','Voyant.panel.CollocatesGraph','Voyant.panel.Trends'],
name : 'VoyantDocumentToolsetApp',
launch: function() {
Ext.create('Ext.container.Viewport', {
layout: 'border',
items: [{
region: 'south',
xtype: 'voyantfooter'
}, {
xtype: 'tabpanel',
region: 'center',
split: true,
items: [{
xtype: 'cirrus',
collapsible: true
},{
xtype: 'documentterms',
collapsible: true
},{
xtype: 'contexts',
collapsible: true
},{
xtype: 'collocatesgraph',
collapsible: true
},{
xtype: 'trends',
collapsible: true
},{
xtype: 'morelikethis',
collapsible: true
}],
flex: 6
}]
});
this.callParent(arguments);
}
});

@ -0,0 +1,18 @@
Ext.define('Voyant.VoyantNotebookApp', {
extend : 'Voyant.VoyantApp',
requires: ['Voyant.panel.VoyantFooter','Voyant.notebook.Notebook','Voyant.data.model.Corpus','Voyant.notebook.util.Show'],
name : 'VoyantNotebookApp',
launch: function() {
Ext.create('Ext.container.Viewport', {
layout: 'border',
items: [{
xtype: 'notebook',
region: 'center'
},{
xtype: 'voyantfooter',
region: 'south'
}]
});
this.callParent(arguments);
}
});

@ -0,0 +1,68 @@
Ext.define('Voyant.VoyantToolApp', {
extend : 'Voyant.VoyantCorpusApp',
name : 'VoyantToolApp',
statics: {
api: {
minimal: undefined,
embeddedApiId: undefined
}
},
launch: function() {
var items = [], me = this;
if (!this.getApiParam('minimal')) {
items.push({
region: 'south',
xtype: 'voyantfooter'
})
};
items.push({
region: 'center',
layout: 'fit',
itemId: 'toolcontainer',
items: {
xtype: this.getApiParam('embeddedApiId') ? 'container' : this.getTool()
},
listeners: {
afterrender: function(container) {
if (me.getApiParam('embeddedApiId')) {
var dfd = me.getDeferred(this);
container.mask(this.localize('loadingConfiguration'));
Ext.Ajax.request({
url: me.getTromboneUrl(),
params: {
tool: 'resource.StoredResource',
retrieveResourceId: this.getApiParam('embeddedApiId')
}
}).then(function(response) {
dfd.resolve();
var json = Ext.util.JSON.decode(response.responseText);
var configString = decodeURIComponent(json.storedResource.resource);
var config = Ext.decode(configString);
var tool = Ext.create({xtype: me.getTool()});
tool.setApiParams(config);
container.unmask();
container.remove(container.down('container'));
container.add(tool);
if (config.corpus) {
me.loadCorpusFromParams(config);
}
}).otherwise(function(response) {
if (me.getTargetEl) {
Voyant.notebook.util.Show.TARGET = me.getTargetEl();
showError(response);
}
Voyant.application.showError(response);
dfd.reject();
})
}
},
scope: this
}
});
Ext.create('Ext.container.Viewport', {
layout: 'border',
items: items
});
this.callParent(arguments);
}
});

@ -0,0 +1,12 @@
Ext.define('Voyant.data.model.AnalysisToken', {
extend: 'Ext.data.Model',
idProperty: 'term',
fields: [
{name: 'term'},
{name: 'rawFreq', type: 'int'},
{name: 'relativeFreq', type: 'number'},
{name: 'cluster', type: 'int'},
{name: 'clusterCenter', type: 'boolean'},
{name: 'vector'}
]
});

@ -0,0 +1,22 @@
Ext.define('Voyant.data.model.Context', {
extend: 'Ext.data.Model',
fields: [
{name: 'id'},
{name: 'docIndex', 'type': 'int'},
{name: 'position', 'type': 'int'},
{name: 'docId'},
{name: 'left'},
{name: 'keyword'},
{name: 'term'},
{name: 'right'}
],
getDocIndex: function() {return this.get("docIndex")},
getLeft: function() {return this.get("left")},
getMiddle: function() {return this.get("middle")},
getHighlightedMiddle: function() {return "<span class='keyword'>"+this.getMiddle()+"</span>"},
getRight: function() {return this.get("right")},
getPosition: function() {return this.get("position")},
getHighlightedContext: function() {return this.getLeft()+this.getHighlightedMiddle()+this.getRight();}
});

File diff suppressed because it is too large Load Diff

@ -0,0 +1,16 @@
Ext.define('Voyant.data.model.CorpusCollocate', {
extend: 'Ext.data.Model',
fields: [
{name: 'term'},
{name: 'rawFreq', type: 'int'},
{name: 'contextTerm'},
{name: 'contextTermRawFreq', type: 'int'}
],
getTerm: function() {return this.getKeyword()},
getRawFreq: function() {return this.getKeywordRawFreq()},
getKeyword: function() {return this.get('term');},
getKeywordRawFreq: function() {return this.get('rawFreq');},
getContextTerm: function() {return this.get('contextTerm');},
getContextTermRawFreq: function() {return this.get('contextTermRawFreq');}
});

@ -0,0 +1,18 @@
Ext.define('Voyant.data.model.CorpusFacet', {
extend: 'Ext.data.Model',
idProperty: 'label',
fields: [
{name: 'facet'},
{name: 'label'},
{name: 'inDocumentsCount', type: 'int'}
],
getLabel: function() {
return this.get('label')
},
getFacet: function() {
return this.get('facet')
},
getInDocumentsCount: function() {
return this.get('inDocumentsCount')
}
});

@ -0,0 +1,10 @@
Ext.define('Voyant.data.model.CorpusNgram', {
extend: 'Ext.data.Model',
fields: [
{name: 'term'},
{name: 'length', type: 'int'},
{name: 'rawFreq', type: 'int'},
{name: 'distributions'}
],
getTerm: function() {return this.get('term');}
});

@ -0,0 +1,55 @@
/*
* Corpus Term
*/
Ext.define('Voyant.data.model.CorpusTerm', {
extend: 'Ext.data.Model',
idProperty: 'term', // should be unique
fields: [
{name: 'id'},
{name: 'rawFreq', type: 'int'},
{name: 'inDocumentsCount', type: 'int'},
{name: 'relativeFreq', type: 'float'},
{name: 'relativePeakedness', type: 'float'},
{name: 'relativeSkewness', type: 'float'},
{name: 'comparisonRelativeFreqDifference', type: 'float'},
{name: 'distributions'},
{name: 'typeTokenRatio-lexical', type: 'float', calculate: function(data) {
return data['typesCount-lexical']/data['tokensCount-lexical'];
}}
],
/**
* Get the term.
* @returns {String} Returns the term.
*/
getTerm: function() {
return this.get('term');
},
/**
* Get the term's raw frequency.
* @returns {Number} Returns the term's frequency.
*/
getRawFreq: function() {
return parseInt(this.get('rawFreq'));
},
getInDocumentsCount: function() {
return parseInt(this.get('inDocumentsCount'));
},
getDistributions: function() {
return this.get('distributions');
},
/**
* Show a one line summary of this term.
*/
show: function(config) {
show(this.getString(config))
},
getString: function() {
return this.getTerm()+": "+this.getRawFreq();
}
});

@ -0,0 +1,6 @@
Ext.define('Voyant.data.model.Dimension', {
extend: 'Ext.data.Model',
fields: [
{name: 'percentage', type: 'number'}
]
});

@ -0,0 +1,336 @@
Ext.define('Voyant.data.model.Document', {
extend: 'Ext.data.Model',
//requires: ['Voyant.data.store.DocumentTerms'],
fields: [
{name: 'corpus'},
{name: 'id'},
{name: 'author'},
{name: 'pubDate'},
{name: 'publisher'},
{name: 'pubPlace'},
{name: 'keyword'},
{name: 'collection'},
{name: 'index', type: 'int'},
{name: 'tokensCount-lexical', type: 'int'},
{name: 'typesCount-lexical', type: 'int'},
{name: 'typeTokenRatio-lexical', type: 'float', calculate: function(data) {
return data['typesCount-lexical']/data['tokensCount-lexical'];
}},
{name: 'lastTokenStartOffset-lexical', type: 'int'},
{name: 'title'},
{name: 'language', convert: function(data) {return Ext.isEmpty(data) ? '' : data;}},
{name: 'sentencesCount', type: 'int'},
{name: 'averageWordsPerSentence', type: 'float', calculate: function(data) {
return data['sentencesCount'] ? data['tokensCount-lexical'] / data['sentencesCount'] : 0;
}},
{name: 'css', type: 'string'}
],
getLexicalTokensCount: function() {
return this.get('tokensCount-lexical')
},
getLexicalTypeTokenRatio: function() {
return this.get('typeTokenRatio-lexical')
},
loadDocumentTerms: function(config) {
if (this.then) {
return Voyant.application.getDeferredNestedPromise(this, arguments);
} else {
var dfd = Voyant.application.getDeferred(this);
config = config || {};
if (Ext.isNumber(config)) {
config = {limit: config};
}
Ext.applyIf(config, {
limit: 0
})
var documentTerms = this.getDocumentTerms();
documentTerms.load({
params: config,
callback: function(records, operation, success) {
if (success) {
dfd.resolve(documentTerms)
} else {
dfd.reject(operation)
}
}
})
return dfd.promise
}
},
loadTokens: function(config) {
if (this.then) {
return Voyant.application.getDeferredNestedPromise(this, arguments);
} else {
var dfd = Voyant.application.getDeferred(this);
config = config || {};
if (Ext.isNumber(config)) {
config = {limit: config};
}
Ext.applyIf(config, {
limit: 0
})
var tokens = this.getTokens({});
tokens.load({
params: config,
callback: function(records, operation, success) {
if (success) {
dfd.resolve(tokens)
} else {
dfd.reject(operation)
}
}
})
return dfd.promise
}
},
getTokens: function(config) {
if (this.then) {
return Voyant.application.getDeferredNestedPromise(this, arguments);
} else {
config = config || {};
Ext.applyIf(config, {
proxy: {}
});
Ext.applyIf(config.proxy, {
extraParams: {}
})
Ext.applyIf(config.proxy.extraParams, {
docIndex: this.get('index')
})
Ext.apply(config, {
docId: this.get('id')
});
return this.get('corpus').getTokens(config);
}
},
getDocumentTerms: function(config) {
if (this.then) {
return Voyant.application.getDeferredNestedPromise(this, arguments);
} else {
config = config || {};
Ext.applyIf(config, {
proxy: {}
});
Ext.applyIf(config.proxy, {
extraParams: {}
})
Ext.applyIf(config.proxy.extraParams, {
docIndex: this.get('index')
})
if (config.corpus) {
return config.corpus.getDocumentTerms(config);
}
return this.get('corpus').getDocumentTerms(config); // FIXME: when does this happen?
}
},
getIndex: function() {
return this.get('index');
},
getId: function() {
return this.get('id');
},
getFullLabel: function() {
var author = this.getAuthor();
return this.getTitle() + (author ? "("+author+")" : ''); // TODO: complete full label
},
getTitle: function() {
var title = this.get('title');
if (title === undefined) title = '';
title = Ext.isArray(title) ? title.join("; ") : title;
title = title.trim().replace(/\s+/g, ' '); // remove excess whitespace
return title;
},
getTruncated: function(string, max) {
if (string.length > max) {
// maybe a file or URL?
var slash = string.lastIndexOf("/");
if (slash>-1) {
string = string.substr(slash+1);
}
if (string.length>max) {
var space = string.indexOf(" ", max-5);
if (space < 0 || space > max) {
space = max;
}
string = string.substring(0, space) + "…";
}
}
return string;
},
getShortTitle: function() {
var title = this.getTitle();
title = title.replace(/\.(html?|txt|xml|docx?|pdf|rtf|\/)$/,'');
title = title.replace(/^(the|a|le|l'|un|une)\s/,'');
return this.getTruncated(title, 25);
},
getTinyTitle: function() {
return this.getTruncated(this.getShortTitle(), 10);
},
getShortLabel: function() {
var author = this.getAuthor(25);
return (parseInt(this.getIndex())+1) + ') <i>' + this.getShortTitle() + "</i>" +(author ? " ("+author+")" : '')
},
getTinyLabel: function() {
return (parseInt(this.getIndex())+1) + ') ' + this.getTinyTitle();
},
getPubDate: function() {
return this.get("pubDate");
},
getPublisher: function() {
return this.get("publisher");
},
getPubPlace: function() {
return this.get("pubPlace");
},
getKeyword: function() {
return this.getMultiple("keyword");
},
getCollection: function() {
return this.getMultiple("collection");
},
getAuthor: function(max) {
this.getMultiple("author")
},
getMultiple: function(field, max) {
var val = this.get(field) || "";
val = Ext.isArray(val) ? val.join("; ") : val;
val = val.trim().replace(/\s+/g, ' ');
return max ? this.getTruncated(val, max) : val;
},
getCorpusId: function() {
return this.get('corpus').getAliasOrId();
},
isPlainText: function() {
if (this.get("extra.Content-Type") && new RegExp("plain","i").test(this.get("extra.Content-Type"))) {
return true
}
return false;
},
getAverageWordsPerSentence: function() {
return this.get("averageWordsPerSentence");
},
show: function() {
show(this.getFullLabel())
},
getCorpus: function() {
return this.get('corpus');
},
getText: function(config) {
if (this.then) {
return Voyant.application.getDeferredNestedPromise(this, arguments);
} else {
var dfd = Voyant.application.getDeferred(this);
config = config || {};
Ext.apply(config, {
tool: 'corpus.DocumentTokens',
corpus: this.getCorpusId()
})
this.getTokens(config).then(function(tokens) {
dfd.resolve(tokens);
});
return dfd.promise
}
},
getPlainText: function(config) {
if (this.then) {
return Voyant.application.getDeferredNestedPromise(this, arguments);
} else {
config = config || {};
Ext.apply(config, {
outputFormat: "text",
template: "docTokens2text",
noOthers: true
});
return this.getText();
}
},
getLemmasArray: function(config) {
config = config || {};
config.docId = this.getId();
return this.getCorpus().getLemmasArray(config);
// if (this.then) {
// return Voyant.application.getDeferredNestedPromise(this, arguments);
// } else {
// config = config || {};
// Ext.apply(config, {
// docId: this.getId()
// });
// return this.getCorpus().getLemmasArray(config);
// }
},
getEntities: function(config) {
config = config || {};
Ext.applyIf(config, {
proxy: {}
});
Ext.applyIf(config.proxy, {
extraParams: {}
})
Ext.applyIf(config.proxy.extraParams, {
docIndex: this.get('index')
})
return Ext.create("Voyant.data.store.DocumentEntities", Ext.apply(config, {corpus: this.getCorpus(), docId: this.getId()}));
},
loadEntities: function(config) {
var me = this;
if (this.then) {
return Voyant.application.getDeferredNestedPromise(this, arguments);
} else {
var dfd = Voyant.application.getDeferred(this);
this.getEntities().load({
params: config,
callback: function(records, operation, success) {
if (success) {
dfd.resolve(records)
} else {
dfd.reject(operation.error.response);
}
}
})
return dfd.promise
}
},
getCSS: function() {
return this.get('css') || this.get('parent_css');
}
});

@ -0,0 +1,14 @@
Ext.define('Voyant.data.model.DocumentEntity', {
extend: 'Ext.data.Model',
fields: [
{name: 'term'},
{name: 'docIndex', 'type': 'int'},
{name: 'rawFreq', type: 'int'},
{name: 'type'},
{name: 'positions'}
],
getTerm: function() {return this.get('term');},
getDocIndex: function() {return this.get('docIndex')},
getRawFreq: function() {return this.get('rawFreq')},
getPositions: function() {return this.get('positions')}
});

@ -0,0 +1,12 @@
Ext.define('Voyant.data.model.DocumentQueryMatch', {
extend: 'Ext.data.Model',
fields: [
{name: 'id'},
{name: 'count', 'type': 'int'},
{name: 'query'},
{name: 'distributions'}
],
getCount: function() {return this.get('count')},
getDistributions: function() {return this.get("distributions")},
getDocIds: function() {return this.get("docIds")}
});

@ -0,0 +1,20 @@
Ext.define('Voyant.data.model.DocumentTerm', {
extend: 'Ext.data.Model',
fields: [
{name: 'id'},
{name: 'term'},
{name: 'docIndex', 'type': 'int'},
{name: 'docId'},
{name: 'rawFreq', type: 'int'},
{name: 'relativeFreq', type: 'float'},
{name: 'tfidf', type: 'float'},
{name: 'zscore', type: 'float'},
{name: 'zscoreRatio', type: 'float'},
{name: 'distributions'}
],
getTerm: function() {return this.get('term');},
getDocIndex: function() {return this.get('docIndex')},
getRawFreq: function() {return this.get('rawFreq')},
getRelativeFreq: function() {return this.get('relativeFreq')},
getDistributions: function() {return this.get('distributions')}
});

@ -0,0 +1,7 @@
Ext.define('Voyant.data.model.PrincipalComponent', {
extend: 'Ext.data.Model',
fields: [
{name: 'eigenValue', type: 'number'},
{name: 'eigenVectors'}
]
});

@ -0,0 +1,38 @@
/*
* Related Term
*/
Ext.define('Voyant.data.model.RelatedTerm', {
extend: 'Ext.data.Model',
fields: [
{name: 'source'},
{name: 'target'},
{name: 'rawFreq', type: 'int'}
],
/**
* Get the source term.
* @returns {String} Returns the term.
*/
getSource: function() {
return this.get('source');
},
/**
* Get the source term.
* @returns {String} Returns the term.
*/
getTarget: function() {
return this.get('target');
},
/**
* Show a one line summary of this term.
*/
show: function(config) {
show(this.getString(config))
},
getString: function() {
return this.getSource()+"-"+this.getTarget();
}
});

@ -0,0 +1,39 @@
Ext.define('Voyant.data.model.StatisticalAnalysis', {
extend: 'Ext.data.Model',
requires: ['Voyant.data.model.PrincipalComponent', 'Voyant.data.model.Dimension', 'Voyant.data.model.AnalysisToken'],
fields: [
{name: 'id'}
// ,{name: 'dimensions', reference: 'Voyant.data.model.Dimension'}
// ,{name: 'tokens', reference: 'Voyant.data.model.AnalysisToken'}
]
// alternative access methods to "reference" or "hasMany"
,getPrincipalComponents: function() {
var pcs = [];
this.data.principalComponents.forEach(function(pc) {
pcs.push(Ext.create('Voyant.data.model.PrincipalComponent', pc));
});
return pcs;
}
,getDimensions: function() {
var dimensions = [];
this.data.dimensions.forEach(function(dim) {
dimensions.push(Ext.create('Voyant.data.model.Dimension', {percentage: dim}));
});
return dimensions;
}
,getTokens: function() {
var tokens = [];
this.data.tokens.forEach(function(tok) {
tokens.push(Ext.create('Voyant.data.model.AnalysisToken', tok));
});
return tokens;
}
// ,hasMany: [{
// name: 'dimensions', model: 'Voyant.data.model.Dimension'
// },{
// name: 'tokens', model: 'Voyant.data.model.AnalysisToken'
// }]
});

@ -0,0 +1,43 @@
/*
* Related Term
*/
Ext.define('Voyant.data.model.TermCorrelation', {
extend: 'Ext.data.Model',
fields: [
{name: 'source'},
{name: 'target'},
{name: 'correlation', type: 'float'},
{name: 'significance', type: 'float'},
{name: 'source-term', calculate: function(data) {return data.source.term}},
{name: 'target-term', calculate: function(data) {return data.target.term}},
{name: 'source-distributions', calculate: function(data) {return data.source.distributions}},
{name: 'target-distributions', calculate: function(data) {return data.target.distributions}}
],
/**
* Get the source term.
* @returns {String} Returns the term.
*/
getSource: function() {
return this.get('source');
},
/**
* Get the source term.
* @returns {String} Returns the term.
*/
getTarget: function() {
return this.get('target');
},
/**
* Show a one line summary of this term.
*/
show: function(config) {
show(this.getString(config))
},
getString: function() {
return this.getSource()+"-"+this.getTarget();
}
});

@ -0,0 +1,57 @@
Ext.define('Voyant.data.model.Token', {
extend: 'Ext.data.Model',
fields: [
{name: 'id'},
{name: 'docId'},
{name: 'docIndex', type: 'int'},
{name: 'token'},
{name: 'rawFreq'},
{name: 'tokenType'},
{name: 'position', type: 'int'},
{name: 'startOffset', type: 'int'},
{name: 'endOffset', type: 'int'}
],
statics: {
getInfoFromElement: function(arg) {
if (arg && arg.getId) {
var parts = arg.getId().split("_");
return {
docIndex: parseInt(parts[1]),
position: parseInt(parts[2])
};
}
}
},
isWord: function() {
return this.getTokenType()=='lexical'; // maybe something else later?
},
isStopword: function() {
return this.get("stopword")=="true";
},
getTokenType: function() {
return this.get("tokenType");
},
getId: function() {
return ["",this.getDocIndex(),this.getPosition()].join("_");
},
getDocIndex: function() {
return this.get("docIndex");
},
getDocId: function() {
return this.get("docId");
},
getTerm: function() {
return this.get("term");
},
getTermWithLineSpacing: function(isPlainText) {
var term = this.getTerm().replace(/<\/?\w+\b.*?>/g, "<br /><br />").replace(/>\s+</g,"><").replace(/<br \/><br \/>(<br \/>)+/g,"<br \/><br \/>");
if (isPlainText) {term = term.replace(/(\r\n|\r|\n)\s*/g,"<br />");};
return term;
},
getPosition: function() {
return this.get("position");
},
getDocumentRawFreq: function() {
return this.get("rawFreq");
}
});

@ -0,0 +1,33 @@
Ext.define('Voyant.data.store.CAAnalysisMixin', {
mixins: ['Voyant.data.store.VoyantStore'],
embeddable: ['Voyant.panel.ScatterPlot'],
model: 'Voyant.data.model.StatisticalAnalysis',
constructor : function(config) {
this.mixins['Voyant.data.store.VoyantStore'].constructor.apply(this, [config, {
'proxy.extraParams.tool': 'corpus.CA',
'proxy.reader.rootProperty': 'correspondenceAnalysis',
'proxy.reader.totalProperty': 'correspondenceAnalysis.totalTerms'
}])
config.proxy.extraParams.withDistributions = true;
}
});
Ext.define('Voyant.data.store.CAAnalysis', {
extend: 'Ext.data.Store',
mixins: ['Voyant.data.store.CAAnalysisMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.CAAnalysisMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});
Ext.define('Voyant.data.store.CAAnalysisBuffered', {
extend: 'Ext.data.BufferedStore',
mixins: ['Voyant.data.store.CAAnalysisMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.CAAnalysisMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});

@ -0,0 +1,31 @@
Ext.define('Voyant.data.store.ContextsMixin', {
mixins: ['Voyant.data.store.VoyantStore'],
model: 'Voyant.data.model.Context',
constructor : function(config) {
this.mixins['Voyant.data.store.VoyantStore'].constructor.apply(this, [config, {
'proxy.extraParams.tool': 'corpus.DocumentContexts',
'proxy.reader.rootProperty': 'documentContexts.contexts',
'proxy.reader.totalProperty': 'documentContexts.total'
}])
}
});
Ext.define('Voyant.data.store.Contexts', {
extend: 'Ext.data.Store',
mixins: ['Voyant.data.store.ContextsMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.ContextsMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});
Ext.define('Voyant.data.store.ContextsBuffered', {
extend: 'Ext.data.BufferedStore',
mixins: ['Voyant.data.store.ContextsMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.ContextsMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});

@ -0,0 +1,31 @@
Ext.define('Voyant.data.store.CorpusCollocatesMixin', {
mixins: ['Voyant.data.store.VoyantStore'],
model: 'Voyant.data.model.CorpusCollocate',
constructor : function(config) {
this.mixins['Voyant.data.store.VoyantStore'].constructor.apply(this, [config, {
'proxy.extraParams.tool': 'corpus.CorpusCollocates',
'proxy.reader.rootProperty': 'corpusCollocates.collocates',
'proxy.reader.totalProperty': 'corpusCollocates.total'
}])
}
});
Ext.define('Voyant.data.store.CorpusCollocates', {
extend: 'Ext.data.Store',
mixins: ['Voyant.data.store.CorpusCollocatesMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.CorpusCollocatesMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});
Ext.define('Voyant.data.store.CorpusCollocatesBuffered', {
extend: 'Ext.data.BufferedStore',
mixins: ['Voyant.data.store.CorpusCollocatesMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.CorpusCollocatesMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});

@ -0,0 +1,31 @@
Ext.define('Voyant.data.store.CorpusFacetsMixin', {
mixins: ['Voyant.data.store.VoyantStore'],
model: Voyant.data.model.CorpusFacet,
constructor : function(config) {
this.mixins['Voyant.data.store.VoyantStore'].constructor.apply(this, [config, {
'proxy.extraParams.tool': 'corpus.CorpusFacets',
'proxy.reader.rootProperty': 'corpusFacets.facets',
'proxy.reader.totalProperty': 'corpusFacets.total'
}])
}
});
Ext.define('Voyant.data.store.CorpusFacets', {
extend: 'Ext.data.Store',
mixins: ['Voyant.data.store.CorpusFacetsMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.CorpusFacetsMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});
Ext.define('Voyant.data.store.CorpusFacetsBuffered', {
extend: 'Ext.data.BufferedStore',
mixins: ['Voyant.data.store.CorpusFacetsMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.CorpusFacetsMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});

@ -0,0 +1,31 @@
Ext.define('Voyant.data.store.CorpusNgramsMixin', {
mixins: ['Voyant.data.store.VoyantStore'],
model: 'Voyant.data.model.CorpusNgram',
constructor : function(config) {
this.mixins['Voyant.data.store.VoyantStore'].constructor.apply(this, [config, {
'proxy.extraParams.tool': 'corpus.CorpusNgrams',
'proxy.reader.rootProperty': 'corpusNgrams.ngrams',
'proxy.reader.totalProperty': 'corpusNgrams.total'
}])
}
});
Ext.define('Voyant.data.store.CorpusNgrams', {
extend: 'Ext.data.Store',
mixins: ['Voyant.data.store.CorpusNgramsMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.CorpusNgramsMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});
Ext.define('Voyant.data.store.CorpusNgramsBuffered', {
extend: 'Ext.data.BufferedStore',
mixins: ['Voyant.data.store.CorpusNgramsMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.CorpusNgramsMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});

@ -0,0 +1,70 @@
Ext.define('Voyant.data.store.CorpusTermsMixin', {
mixins: ['Voyant.data.store.VoyantStore'],
model: Voyant.data.model.CorpusTerm,
// statics: {
// i18n: {
// getString: "This store has {0} terms with a total of {1} occurrences."
// }
// },
constructor : function(config) {
this.mixins['Voyant.data.store.VoyantStore'].constructor.apply(this, [config, {
'proxy.extraParams.tool': 'corpus.CorpusTerms',
'proxy.reader.rootProperty': 'corpusTerms.terms',
'proxy.reader.totalProperty': 'corpusTerms.total'
}])
},
show: function(config) {
show(this.getString(config))
}
});
/*
* Corpus Terms store.
*/
Ext.define('Voyant.data.store.CorpusTerms', {
extend: 'Ext.data.Store',
mixins: ['Voyant.data.store.CorpusTermsMixin'],
model: Voyant.data.model.CorpusTerm,
/**
* @method each
* Iterate over each {@link Voyant.data.model.CorpusTerm corpus term} in this store.
*
* new Corpus("Hello Voyant!").loadCorpusTerms().then(function(corpusTerms) {
* corpusTerms.each(function(corpusTerm) {
* corpusTerm.show();
* });
* });
*
* @param {function} function The function to call for each corpus term.
*/
/**
* @method show
* Shows a one line summary of the corpus terms.
*
* new Corpus("Hello Voyant!").loadCorpusTerms().then(function(corpusTerms) {
* corpusTerms.show();
* });
*/
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.CorpusTermsMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});
Ext.define('Voyant.data.store.CorpusTermsBuffered', {
extend: 'Ext.data.BufferedStore',
mixins: ['Voyant.data.store.CorpusTermsMixin'],
model: Voyant.data.model.CorpusTerm,
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.CorpusTermsMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});

@ -0,0 +1,32 @@
Ext.define('Voyant.data.store.DocSimAnalysisMixin', {
mixins: ['Voyant.data.store.VoyantStore'],
model: 'Voyant.data.model.StatisticalAnalysis',
constructor : function(config) {
this.mixins['Voyant.data.store.VoyantStore'].constructor.apply(this, [config, {
'proxy.extraParams.tool': 'corpus.DocumentSimilarity',
'proxy.reader.rootProperty': 'documentSimilarity',
'proxy.reader.totalProperty': 'documentSimilarity.total'
}])
config.proxy.extraParams.withDistributions = true;
}
});
Ext.define('Voyant.data.store.DocSimAnalysis', {
extend: 'Ext.data.Store',
mixins: ['Voyant.data.store.DocSimAnalysisMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.DocSimAnalysisMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});
Ext.define('Voyant.data.store.DocSimAnalysisBuffered', {
extend: 'Ext.data.BufferedStore',
mixins: ['Voyant.data.store.DocSimAnalysisMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.DocSimAnalysisMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});

@ -0,0 +1,31 @@
Ext.define('Voyant.data.store.DocumentEntitiesMixin', {
mixins: ['Voyant.data.store.VoyantStore'],
model: 'Voyant.data.model.DocumentEntity',
constructor : function(config) {
this.mixins['Voyant.data.store.VoyantStore'].constructor.apply(this, [config, {
'proxy.extraParams.tool': 'corpus.DocumentEntities',
'proxy.reader.rootProperty': 'documentEntities.entities',
'proxy.reader.totalProperty': 'documentEntities.total'
}])
}
});
Ext.define('Voyant.data.store.DocumentEntities', {
extend: 'Ext.data.Store',
mixins: ['Voyant.data.store.DocumentEntitiesMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.DocumentEntitiesMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});
Ext.define('Voyant.data.store.DocumentEntitiesBuffered', {
extend: 'Ext.data.BufferedStore',
mixins: ['Voyant.data.store.DocumentEntitiesMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.DocumentEntitiesMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});

@ -0,0 +1,32 @@
Ext.define('Voyant.data.store.DocumentQueryMatchesMixin', {
mixins: ['Voyant.data.store.VoyantStore'],
model: 'Voyant.data.model.DocumentQueryMatch',
constructor : function(config) {
this.mixins['Voyant.data.store.VoyantStore'].constructor.apply(this, [config, {
'proxy.extraParams.tool': 'corpus.DocumentsFinder',
'proxy.reader.rootProperty': 'documentsFinder.queries',
'proxy.reader.totalProperty': undefined,
'proxy.reader.metaProperty': 'documentsFinder.corpus'
}])
}
});
Ext.define('Voyant.data.store.DocumentQueryMatches', {
extend: 'Ext.data.Store',
mixins: ['Voyant.data.store.DocumentQueryMatchesMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.DocumentQueryMatchesMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});
Ext.define('Voyant.data.store.DocumentQueryMatchesBuffered', {
extend: 'Ext.data.BufferedStore',
mixins: ['Voyant.data.store.DocumentQueryMatchesMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.DocumentQueryMatchesMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});

@ -0,0 +1,31 @@
Ext.define('Voyant.data.store.DocumentTermsMixin', {
mixins: ['Voyant.data.store.VoyantStore'],
model: 'Voyant.data.model.DocumentTerm',
constructor : function(config) {
this.mixins['Voyant.data.store.VoyantStore'].constructor.apply(this, [config, {
'proxy.extraParams.tool': 'corpus.DocumentTerms',
'proxy.reader.rootProperty': 'documentTerms.terms',
'proxy.reader.totalProperty': 'documentTerms.total'
}])
}
});
Ext.define('Voyant.data.store.DocumentTerms', {
extend: 'Ext.data.Store',
mixins: ['Voyant.data.store.DocumentTermsMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.DocumentTermsMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});
Ext.define('Voyant.data.store.DocumentTermsBuffered', {
extend: 'Ext.data.BufferedStore',
mixins: ['Voyant.data.store.DocumentTermsMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.DocumentTermsMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});

@ -0,0 +1,56 @@
Ext.define('Voyant.data.store.DocumentsMixin', {
mixins: ['Voyant.data.store.VoyantStore'],
model: 'Voyant.data.model.Document',
statics: {
i18n: {
}
},
sorters: {
property: 'index',
direction: 'ASC'
},
remoteSort: true,
constructor : function(config) {
this.mixins['Voyant.data.store.VoyantStore'].constructor.apply(this, [config, {
'proxy.extraParams.tool': 'corpus.DocumentsMetadata',
'proxy.reader.rootProperty': 'documentsMetadata.documents',
'proxy.reader.totalProperty': 'documentsMetadata.total'
}])
},
listeners: {
load: function(store, records, successful, opts) {
if (successful) {
var corpus = store.getCorpus();
records.forEach(function(record) {
record.set('corpus', corpus);
});
}
}
},
getDocument: function(config) {
return Ext.isNumber(config) ? this.getAt(config) : this.getById(config);
}
});
Ext.define('Voyant.data.store.Documents', {
extend: 'Ext.data.Store',
mixins: ['Voyant.data.store.DocumentsMixin'],
model: 'Voyant.data.model.Document',
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.DocumentsMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});
Ext.define('Voyant.data.store.DocumentsBuffered', {
extend: 'Ext.data.BufferedStore',
mixins: ['Voyant.data.store.DocumentsMixin'],
model: 'Voyant.data.model.Document',
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.DocumentsMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});

@ -0,0 +1,61 @@
Ext.define('Voyant.data.model.NotebookFacet', {
extend: 'Ext.data.Model',
idProperty: 'label',
fields: [
{name: 'facet'},
{name: 'label'},
{name: 'inDocumentsCount', type: 'int'}
],
getLabel: function() {
return this.get('label')
},
getFacet: function() {
return this.get('facet')
},
getInDocumentsCount: function() {
return this.get('inDocumentsCount')
}
});
Ext.define('Voyant.data.store.NotebookFacetsMixin', {
mixins: ['Voyant.data.store.VoyantStore'],
model: Voyant.data.model.NotebookFacet,
constructor : function(config) {
if (config.facet) {
if (config.proxy === undefined) {
config.proxy = {};
}
if (config.proxy.extraParams === undefined) {
config.proxy.extraParams = {};
}
config.proxy.extraParams.facet = config.facet;
config.proxy.extraParams.noCache = 1;
delete config.facet;
}
this.mixins['Voyant.data.store.VoyantStore'].constructor.apply(this, [config, {
'proxy.extraParams.tool': 'notebook.CatalogueFacets',
'proxy.reader.rootProperty': 'catalogue.facets',
'proxy.reader.totalProperty': 'catalogue.total'
}])
}
});
Ext.define('Voyant.data.store.NotebookFacets', {
extend: 'Ext.data.Store',
mixins: ['Voyant.data.store.NotebookFacetsMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.NotebookFacetsMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});
Ext.define('Voyant.data.store.NotebookFacetsBuffered', {
extend: 'Ext.data.BufferedStore',
mixins: ['Voyant.data.store.NotebookFacetsMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.NotebookFacetsMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});

@ -0,0 +1,33 @@
Ext.define('Voyant.data.store.PCAAnalysisMixin', {
mixins: ['Voyant.data.store.VoyantStore'],
embeddable: ['Voyant.panel.ScatterPlot'],
model: 'Voyant.data.model.StatisticalAnalysis',
constructor : function(config) {
this.mixins['Voyant.data.store.VoyantStore'].constructor.apply(this, [config, {
'proxy.extraParams.tool': 'corpus.PCA',
'proxy.reader.rootProperty': 'pcaAnalysis',
'proxy.reader.totalProperty': 'pcaAnalysis.totalTerms'
}])
config.proxy.extraParams.withDistributions = true;
}
});
Ext.define('Voyant.data.store.PCAAnalysis', {
extend: 'Ext.data.Store',
mixins: ['Voyant.data.store.PCAAnalysisMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.PCAAnalysisMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});
Ext.define('Voyant.data.store.PCAAnalysisBuffered', {
extend: 'Ext.data.BufferedStore',
mixins: ['Voyant.data.store.PCAAnalysisMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.PCAAnalysisMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});

@ -0,0 +1,31 @@
Ext.define('Voyant.data.store.RelatedTermsMixin', {
mixins: ['Voyant.data.store.VoyantStore'],
model: 'Voyant.data.model.RelatedTerm',
constructor : function(config) {
this.mixins['Voyant.data.store.VoyantStore'].constructor.apply(this, [config, {
'proxy.extraParams.tool': 'corpus.SemanticGraph',
'proxy.reader.rootProperty': 'semanticGraph.edges',
'proxy.reader.totalProperty': 'semanticGraph.total'
}])
}
});
Ext.define('Voyant.data.store.RelatedTerms', {
extend: 'Ext.data.Store',
mixins: ['Voyant.data.store.RelatedTermsMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.RelatedTermsMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});
Ext.define('Voyant.data.store.RelatedTermsBuffered', {
extend: 'Ext.data.BufferedStore',
mixins: ['Voyant.data.store.RelatedTermsMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.RelatedTermsMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});

@ -0,0 +1,34 @@
Ext.define('Voyant.data.store.TSNEAnalysisMixin', {
mixins: ['Voyant.data.store.VoyantStore'],
embeddable: ['Voyant.panel.ScatterPlot'],
model: 'Voyant.data.model.StatisticalAnalysis',
constructor : function(config) {
this.mixins['Voyant.data.store.VoyantStore'].constructor.apply(this, [config, {
'proxy.extraParams.tool': 'corpus.TSNE',
'proxy.reader.rootProperty': 'tsneAnalysis',
'proxy.reader.totalProperty': 'tsneAnalysis.totalTerms'
}])
config.proxy.extraParams.withDistributions = true;
config.proxy.extraParams.noCache = 1;
}
});
Ext.define('Voyant.data.store.TSNEAnalysis', {
extend: 'Ext.data.Store',
mixins: ['Voyant.data.store.TSNEAnalysisMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.TSNEAnalysisMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});
Ext.define('Voyant.data.store.TSNEAnalysisBuffered', {
extend: 'Ext.data.BufferedStore',
mixins: ['Voyant.data.store.TSNEAnalysisMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.TSNEAnalysisMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});

@ -0,0 +1,32 @@
Ext.define('Voyant.data.store.TermCorrelationsMixin', {
mixins: ['Voyant.data.store.VoyantStore'],
model: 'Voyant.data.model.TermCorrelation',
constructor : function(config) {
this.mixins['Voyant.data.store.VoyantStore'].constructor.apply(this, [config, {
'proxy.extraParams.tool': 'corpus.CorpusTermCorrelations',
'proxy.extraParams.withDistributions': 'true',
'proxy.reader.rootProperty': 'termCorrelations.correlations',
'proxy.reader.totalProperty': 'termCorrelations.total'
}])
}
});
Ext.define('Voyant.data.store.TermCorrelations', {
extend: 'Ext.data.Store',
mixins: ['Voyant.data.store.TermCorrelationsMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.TermCorrelationsMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});
Ext.define('Voyant.data.store.TermCorrelationsBuffered', {
extend: 'Ext.data.BufferedStore',
mixins: ['Voyant.data.store.TermCorrelationsMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.TermCorrelationsMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});

@ -0,0 +1,31 @@
Ext.define('Voyant.data.store.TokensMixin', {
mixins: ['Voyant.data.store.VoyantStore'],
model: 'Voyant.data.model.Token',
constructor : function(config) {
this.mixins['Voyant.data.store.VoyantStore'].constructor.apply(this, [config, {
'proxy.extraParams.tool': 'corpus.DocumentTokens',
'proxy.reader.rootProperty': 'documentTokens.tokens',
'proxy.reader.totalProperty': 'documentTokens.total'
}])
}
});
Ext.define('Voyant.data.store.Tokens', {
extend: 'Ext.data.Store',
mixins: ['Voyant.data.store.TokensMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.TokensMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});
Ext.define('Voyant.data.store.TokensBuffered', {
extend: 'Ext.data.BufferedStore',
mixins: ['Voyant.data.store.TokensMixin'],
constructor : function(config) {
config = config || {};
this.mixins['Voyant.data.store.TokensMixin'].constructor.apply(this, [config])
this.callParent([config]);
}
});

@ -0,0 +1,137 @@
Ext.define('Voyant.data.store.VoyantStore', {
mixins: ['Voyant.util.Localization','Voyant.notebook.util.Embed'],
config: {
corpus: undefined,
parentPanel: undefined
},
constructor: function(config, extras) {
var me = this;
config = config || {};
Ext.applyIf(config, {
remoteSort: true,
autoLoad: false,
// listeners: {
// beforeload: function(store, operation) {
// var parent = this.getParentPanel();
// if (parent !== undefined) {
// var params = parent.getApiParams();
// operation = operation ? (operation===1 ? {} : operation) : {};
// operation.params = operation.params || {};
// for (var key in params) {
// operation.params[key] = params[key];
// }
// }
// }
// },
// scope: this,
// define buffered configuration even if ignored when this isn't a buffered store
pagePurgeCount : 0, // don't purge any data
pageSize : 100, // each request is more intenstive, so do fewer of them then default
leadingBufferZone : 200 // stay two pages ahead
});
config.proxy = config.proxy || {};
Ext.applyIf(config.proxy, {
type: 'ajax',
url: Voyant.application.getTromboneUrl(),
actionMethods: {read: 'POST'},
reader: {
type: 'json',
rootProperty: extras['proxy.reader.rootProperty'],
totalProperty: extras['proxy.reader.totalProperty'],
metaProperty: extras['proxy.reader.metaProperty'] || 'metaData'
},
simpleSortMode: true,
listeners: {
exception: function(proxy, request, operation) {
if (me.parentPanel && me.parentPanel.showError) {
// FIXME: this should probably send the request, not the operation
me.parentPanel.showError(operation)
}
}
}
})
config.proxy.extraParams = config.proxy.extraParams || {};
Ext.applyIf(config.proxy.extraParams, {
tool: extras['proxy.extraParams.tool']
});
if (config.parentPanel !== undefined) {
Ext.applyIf(config.proxy.extraParams, {
forTool: config.parentPanel.xtype
});
this.setParentPanel(config.parentPanel);
config.parentPanel.on("loadedCorpus", function(src, corpus) {
this.setCorpus(corpus);
}, this);
config.listeners = config.listeners || {};
config.listeners.beforeload = {
fn: function(store, operation) {
var parent = this.getParentPanel(), proxy = store.getProxy();
if (parent !== undefined) {
var params = parent.getApiParams();
operation = operation ? (operation===1 ? {} : operation) : {};
operation.params = operation.params || {};
// unset any previously set extra params (only applies with proxy and buffered store)
if (proxy && this.isBufferedStore) {
Ext.Array.from(this.previouslySetExtraParams).forEach(function(key) {
proxy.setExtraParam(key, undefined);
});
this.previouslySetExtraParams = [];
}
for (var key in params) {
/* TODO NOT SURE ABOUT THIS
// don't sent stopList when there's a query
if (key=="stopList" && "query" in params && params.query) {continue;}
*/
if (proxy && this.isBufferedStore) { // also set proxy for automatic buffering calls
this.previouslySetExtraParams.push(key);
proxy.setExtraParam(key, params[key]);
}
operation.params[key] = params[key];
}
}
},
scope: this
}
}
Ext.apply(this, config);
},
setCorpus: function(corpus) {
if (corpus && this.getProxy && this.getProxy()) {
this.getProxy().setExtraParam('corpus', Ext.isString(corpus) ? corpus : corpus.getId());
}
this.callParent(arguments);
},
getString: function(config) {
var count = this.getCount();
return "This store contains "+this.getCount()+" items"+(count>0 ? " with these fields: "+this.getAt(0).getFields().map(function(field) {return field.getName()}).join(", ") : "")+"."
},
embed: function(cmp, config) {
if (!config && Ext.isObject(cmp)) {
config = cmp;
cmp = this.embeddable[0];
}
config = config || {};
var data = [];
this.each(function(record) {
data.push(record.data);
}, this);
Ext.apply(config, {
storeJson: JSON.stringify({
storeClass: Ext.getClassName(this),
storeData: data
})
});
embed.call(this, cmp, config);
}
});

@ -0,0 +1,147 @@
Ext.define('Voyant.data.util.Geonames', {
mixins: ['Voyant.util.Localization'],
statics: {
i18n: {
}
},
config: {
data: {},
queries: undefined,
corpus: undefined,
isIncrementalLoadingOccurrences: false,
previousParams: {}
},
constructor: function(config, opts) {
config = config || {};
this.callParent([config]);
this.setCorpus(config.corpus);
},
load: function(params, dfd) {
this.setPreviousParams(params);
dfd = dfd || Voyant.application.getDeferred(this);
var me = this, localParams = {
corpus: this.getCorpus().getAliasOrId(),
queries: this.getQueries(),
tool: 'corpus.Dreamscape',
limit: 200
};
Ext.apply(localParams, params || {});
if (!params.noOverwrite) {
me.setData({});
}
Ext.Ajax.request({
url: Voyant.application.getTromboneUrl(),
params: localParams,
scope: this
}).then(function(response) {
var data = Ext.JSON.decode(response.responseText);
if (data && data.dreamscape && data.dreamscape.progress) {
new Voyant.widget.ProgressMonitor({
progress: data.dreamscape.progress,
maxMillisSinceStart: 1000*60*60, // an hour (!)
tool: 'corpus.Dreamscape',
success: function() {
me.load.call(me, params, dfd);
},
failure: function(responseOrProgress) {
Voyant.application.showResponseError(me.localize("failedToFetchGeonames"), responseOrProgress);
},
scope: me
});
}
if (data && data.dreamscape && !data.dreamscape.progress) {
if (!params.noOverwrite) {
me.setData(data.dreamscape);
}
dfd.resolve(data);
}
}, function(response) {
Voyant.application.showResponseError(me.localize('failedToFetchGeonames'), response);
});
return dfd.promise;
},
getCitiesCount: function() {
return Object.keys(this.getData().locations.locations).length;
},
getTotalCitiesCount: function() {
return this.getData().locations.total;
},
hasMoreCities: function() {
return this.getCitiesCount()<this.getTotalCitiesCount();
},
eachCity: function(fn, scope, max) {
var locations = this.getData().locations.locations, orderedLocations = [];
for (var id in locations) { // create a sortable list with id
orderedLocations.push(Ext.apply(locations[id], {id: id}))
}
orderedLocations.sort(function(c1, c2) { // order by rawFreq (count)
return c1.rawFreq == c2.rawFreq ? c1.label - c2.label : c2.rawFreq - c1.rawFreq;
});
if (max && orderedLocations.length>max) {orderedLocations = orderedLocations.slice(0,max)}
orderedLocations.forEach(function(location) {fn.call(scope, location);});
},
getConnectionsCount: function() {
return this.getData().connections.connections.length;
},
getTotalConnectionsCount: function() {
return this.getData().connections.total;
},
eachConnection: function(fn, scope, max) {
var connections = this.getData().connections.connections,
locations = this.getData().locations.locations;
orderedConnections = [];
for (var i=0, len=connections.length; i<len; i++) {
fn.call(scope, {
source: Ext.apply({id: connections[i].source}, locations[connections[i].source]),
target: Ext.apply({id: connections[i].target}, locations[connections[i].target]),
rawFreq: connections[i].rawFreq
});
if (i>max) {break;}
}
},
getConnectionOccurrence: function(index) {
if (!this.getData().locations) {return undefined;}
var connectionOccurrencesData = this.getData().connectionOccurrences,
connectionOccurrences = connectionOccurrencesData.connectionOccurrences;
locations = this.getData().locations.locations;
if (!this.getIsIncrementalLoadingOccurrences() && connectionOccurrences.length<connectionOccurrencesData.total && index+100>connectionOccurrences.length) {
this.setIsIncrementalLoadingOccurrences(true);
var me = this;
var params = {};
Ext.apply(params, this.getPreviousParams);
Ext.apply(params, {
start: connectionOccurrences.length,
noOverwrite: true,
suppressLocations: true,
suppressConnections: true
});
this.load(params).then(function(data) {
me.setIsIncrementalLoadingOccurrences(false);
me.getData().connectionOccurrences.connectionOccurrences = connectionOccurrences.concat(data.dreamscape.connectionOccurrences.connectionOccurrences);
})
}
if (connectionOccurrences && connectionOccurrences[index]) {
var occurrence = connectionOccurrences[index];
occurrence.index = index;
Ext.apply(occurrence.source, locations[occurrence.source.location]);
Ext.apply(occurrence.target, locations[occurrence.target.location]);
return occurrence;
}
return null;
},
getAllConnectionOccurrences: function(sourceId, targetId) {
debugger
// TODO return all occurences of connection with given source and target, including those not loaded yet
var occurences = [];
for (var i = 0; i < this.getTotalConnectionsCount(); i++) {
var occurence = this.getConnectionOccurrence(i);
if (occurence && occurence.target.id == targetId && occurence.source.id == sourceId) {
occurences.push(occurence);
}
}
return occurences
}
});

@ -0,0 +1,84 @@
/*
* @class NetworkGraph
*
* A NetworkGraph can facilitate working with network graph data structures, as well as
* displaying results (especially with {@link #embed} and {@link show}).
* Here's a simple example showing the Zipf-Law distribution of the top 20 frequency terms.
*
* new Corpus("austen").loadCorpusTerms(20).then(function(corpusTerms) {
* var table = new VoyantTable({rowKey: 0}); // use first column as row key
* corpusTerms.each(function(corpusTerm) {
* table.addRow([corpusTerm.getTerm(), corpusTerm.getRawFreq()]);
* });
* table.embed("voyantchart"); // graph table as line chart
* });
*/
Ext.define('Voyant.data.util.NetworkGraph', {
alternateClassName: ["NetworkGraph"],
mixins: ['Voyant.notebook.util.Embed','Voyant.notebook.util.Show'],
embeddable: ["Voyant.widget.VoyantNetworkGraph"],
config: {
/**
* @private
*/
edges: [],
/**
* @private
*/
nodes: []
},
constructor: function(config, opts) {
config = config || {};
this.setEdges(Ext.Array.from(config.edges));
this.setNodes(Ext.Array.from(config.nodes));
this.callParent([config]);
},
addEdge: function(src, target, value) {
this.getEdges().push(Ext.isObject(src) ? src : {source: src, target: target, value: value});
},
getNode: function(term) {
return Ext.Array.binarySearch(this.getNodes(), term, undefined, undefined, function(lhs, rhs) {
return (lhs.term < rhs.term) ? -1 : ((lhs.term > rhs.term) ? 1 : 0);
})
},
embed: function(cmp, config) {
if (!config && Ext.isObject(cmp)) {
config = cmp;
cmp = this.embeddable[0];
}
config = config || {};
var json = {
edges: this.getEdges(),
nodes: this.getNodes(),
config: config
};
if (config.limit && json.edges.length>config.limit) {
json.edges = json.edges.slice(0, config.limit);
var terms = {};
json.edges.forEach(function(edge) {
terms["_"+edge.source] = true;
terms["_"+edge.target] = true;
})
var nodes = [];
json.nodes.forEach(function(node) {
if ("_"+node.term in terms) {
nodes.push(node);
}
});
json.nodes = nodes;
}
Ext.apply(config, {
jsonData: JSON.stringify(json)
})
embed.call(this, cmp, config);
},
getString: function(config) {
config = config || {};
return this.getEdges().map(function(edge) {edge.source+"-"+edge.target}).join("; ");
}
});

@ -0,0 +1,483 @@
/*
* @class VoyantTable
* A VoyantTable can facilitate working with tabular data structures, as well as
* displaying results (especially with {@link #embed} and {@link show}).
* Here's a simple example showing the Zipf-Law distribution of the top 20 frequency terms.
*
* new Corpus("austen").loadCorpusTerms(20).then(function(corpusTerms) {
* var table = new VoyantTable({rowKey: 0}); // use first column as row key
* corpusTerms.each(function(corpusTerm) {
* table.addRow([corpusTerm.getTerm(), corpusTerm.getRawFreq()]);
* });
* table.embed("voyantchart"); // graph table as line chart
* });
*/
Ext.define('Voyant.data.table.Table', {
alternateClassName: ["VoyantTable"],
mixins: ['Voyant.notebook.util.Embed','Voyant.notebook.util.Show'],
embeddable: ['Voyant.widget.VoyantTableTransform','Voyant.widget.VoyantChart','Voyant.widget.CodeEditor'],
config: {
/**
* @private
*/
rows: [],
/**
* @private
*/
headers: [],
/**
* @private
*/
rowsMap: {},
/**
* @private
*/
headersMap: {},
/**
* Specifies that a specific header should serve as row key.
*
*/
rowKey: undefined,
/**
* @private
*/
model: undefined
},
clone: function() {
var table = new VoyantTable();
table.setRows(Ext.clone(this.getRows()));
table.setHeaders(Ext.clone(this.getHeaders()))
table.setRowsMap(Ext.clone(this.getRowsMap()))
table.setHeadersMap(Ext.clone(this.getHeadersMap()))
table.setRowKey(Ext.clone(this.getRowKey()))
return table;
},
constructor: function(config, opts) {
config = config || {};
if (config.fromBlock) {
var data = Voyant.notebook.Notebook.getDataFromBlock(config.fromBlock);
if (data) {
data = data.trim();
config.rows = [];
data.split(/\n+/).forEach(function(line,i) {
var cells = line.split("\t");
if (i==0 && !config.noHeaders) {
config.headers = cells
} else {
config.rows.push(cells)
}
})
}
} else if (config.count && Ext.isArray(config.count)) {
// create counts
var freqs = {};
config.count.forEach(function(item) {freqs[item] = freqs[item] ? freqs[item]+1 : 1;});
// sort counts
var counts = [];
for (var key in freqs) {counts.push([key, freqs[key]])}
counts.sort(function(a,b) {return b[1] - a[1]});
if (config.limit && counts.length>config.limit) {
counts.splice(config.limit);
}
if (config.orientation && config.orientation=="horizontal") {
config.headers = counts.map(function(item) {return item[0]});
config.rows = [counts.map(function(item) {return item[1]})];
} else {
config.headers = config.headers ? config.headers : ["Item","Count"];
config.rows = counts;
}
} else if (config.isStore || config.store) {
var store = config.store ? config.store : config;
if (opts && opts.headers) {
config.headers = opts.headers;
} else {
// store.getModel() doesn't seem to work (for CorpusTerms at least)
// so instead we'll try looking at the first record to get headers
var record = store.getAt(0);
if (record) { // don't know what to do if this fails?
config.headers = record.getFields().map(function(field) {return field.getName()});
}
}
// now we get rows
config.rows = [];
store.each(function(record) {
var data = record.getData();
var cells = config.headers.map(function(header) {return data[header]}); // only from headers
config.rows.push(cells);
}, this);
}
// not sure why config isn't working
if (!config.rows && Ext.isArray(config)) {
config.rows = config;
}
if (!this.getHeaders()) {
if (!config.headers && !config.noHeaders && config.rows) {
this.setHeaders(config.rows.shift())
} else {
this.setHeaders(Ext.Array.from(config.headers));
}
}
this.setRows(Ext.Array.from(config.rows));
this.setRowKey(config.rowKey ? config.rowKey : this.getHeaders()[0]);
// if we have no headers, use the index as header
if (this.getHeaders().length==0) {
var firstRow = this.getRow(0, false);
if (firstRow) {
this.setHeaders(firstRow.map(function(cell, i) {return i}));
}
}
var headersMap = {};
this.getHeaders().forEach(function(header, i) {
headersMap[header] = i;
});
this.setHeadersMap(headersMap);
this.reMapRows();
this.callParent();
},
addRow: function(row) {
if (Ext.isArray(row))
if (Ext.isObject(row)) {
var len = this.getRows().length;
for (var key in row) {
this.updateCell(len, key, row[key])
}
} else if (Ext.isArray(row)) {
this.getRows().push(row);
var header = this.getColumnIndex(this.getRowKey());
if (header!==undefined && row[header]!==undefined) {
this.getRowsMap()[row[header]] = this.getRows().length-1;
}
}
},
eachRecord: function(fn, scope) {
var item, i=0, len=this.getRows().length;
for (; i<len; i++) {
item = this.getRecord(i);
if (fn.call(scope || item, item, i, len) === false) {
break;
}
}
},
eachRow: function(fn, asMap, scope) {
var item, i=0, len=this.getRows().length;
for (; i<len; i++) {
item = this.getRow(i, asMap);
if (fn.call(scope || item, item, i, len) === false) {
break;
}
}
},
getRow: function(index, asMap) {
var r = this.getRowIndex(index);
if (asMap) {
var row = {};
var headers = this.getHeaders();
Ext.Array.from(this.getRows()[r]).forEach(function(item, i) {
row[headers[i] || i] = item;
}, this);
return row;
} else {
return this.getRows()[r];
}
},
getRecord: function(index) {
if (this.model) {return new this.model(this.getRow(index, true))}
},
mapRows: function(fn, asMap, scope) {
var rows = [];
this.eachRow(function(row, i) {
// if (Object.keys(row).length>0) {
rows.push(fn.call(scope || this, row, i))
// }
}, asMap, this)
return rows;
},
/**
* Update the cell value at the specified row and column.
*
* This will create the row and column as needed. If there's an existing value in the cell,
* it will be added to the new value, unless the `replace` argument is set to true.
*
* @param {Number/String} row The cell's row.
* @param {Number/String} column The cell's column.
* @param {Mixed} value The cell's value.
* @param {boolean} [replace] Replace the current value (if it exists), otherwise
* the value is added to any current value (which is the default behaviour).
*/
updateCell: function(row, column, value, replace) {
var rows = this.getRows();
var r = Ext.isNumber(row) ? row : this.getRowIndex(row);
var c = this.getColumnIndex(column);
if (rows[r]===undefined) {rows[r]=[]}
if (rows[r][c]===undefined || replace) {rows[r][c]=value}
else {rows[r][c]+=value}
// add to rowsMap if this is the header
if (this.getHeaders()[c]===this.getRowKey()) {
this.getRowsMap()[column] = r;
}
},
getRowIndex: function(key) {
if (Ext.isNumber(key)) {return key;}
if (Ext.isString(key)) {
var rowsMap = this.getRowsMap();
if (!(key in rowsMap)) {
rowsMap[key] = this.getRows().length;
this.getRows().push(new Array(this.getHeaders().length))
}
return rowsMap[key];
}
},
getColumnIndex: function(column) {
var headers = this.getHeaders();
if (Ext.isNumber(column)) {
if (headers[column]===undefined) {
headers[column]=column;
this.getRows().forEach(function(row) {
row.splice(column, 0, undefined);
});
}
return column;
} else if (Ext.isString(column)) {
if (!(column in this.getHeadersMap())) {
// we don't have this column yet, so create it and expand rows
this.getHeaders().push(column);
this.getHeadersMap()[column] = this.getHeaders().length-1
this.getRows().forEach(function(row) {
row.push(undefined)
});
}
return this.getHeadersMap()[column]
}
},
getColumnHeader: function(column) {
var c = this.getColumnIndex(column);
return this.getHeaders()[c];
},
/**
* Compute the sum of the values in the column.
*
* @param {Number/String} column The column index (as a number) or key (as a string).
*/
getColumnSum: function(column) {
return Ext.Array.sum(this.getColumnValues(column, true));
},
/**
* Compute the sum of the values in the column.
*
* @param {Number/String} column The column index (as a number) or key (as a string).
*/
getColumnMean: function(column) {
return Ext.Array.mean(this.getColumnValues(column, true));
},
/**
* Get the largest value in the array.
*
* @param {Number/String} column The column index (as a number) or key (as a string).
*/
getColumnMax: function(column) {
return Ext.Array.max(this.getColumnValues(column, true));
},
/**
* Get the smallest value in the array.
*
* @param {Number/String} column The column index (as a number) or key (as a string).
*/
getColumnMin: function(column) {
return Ext.Array.min(this.getColumnValues(column, true));
},
getColumnValues: function(column, clean) {
var c = this.getColumnIndex(column), vals = [];
this.eachRow(function(row) {
vals.push(row[c]);
});
if (clean) {return Ext.Array.clean(vals)}
else {return vals;}
},
/**
* @private
*/
reMapRows: function() {
var rowKey = this.getRowKey();
var rowsMap = {}
this.eachRow(function(row, i) {
if (rowKey in row) {
rowsMap[row[rowKey]] = i;
}
}, true);
this.setRowsMap(rowsMap)
},
sortByColumn: function(columns) {
var rows = this.getRows(),
sortColumnsIndices = Ext.Array.from(columns).map(function(column) {
if (Ext.isObject(column)) {
for (key in column) {
return {
index: this.getColumnIndex(key),
direction: column[key].indexOf("asc")>-1 ? 'asc' : 'desc'
}
}
} else {
return {
index: this.getColumnIndex(column),
direction: "desc"
}
}
}, this);
rows.sort(function(a, b) {
for (var i=0, len=sortColumnsIndices.length; i<len; i++) {
var header = sortColumnsIndices[i].index
if (a[header]!=b[header]) {
if (sortColumnsIndices[i].direction=='asc') {return a[header] > b[header] ? 1 : -1}
else {return a[header] > b[header] ? -1 : 1}
}
}
});
this.reMapRows();
return this;
},
loadCorrespondenceAnalysis: function(config) {
return this._doAnalysisLoad('table.CA', 'Voyant.data.store.CAAnalysis', config);
},
loadPrincipalComponentAnalysis: function(config) {
return this._doAnalysisLoad('table.PCA', 'Voyant.data.store.PCAAnalysis', config);
},
loadTSNEAnalysis: function(config) {
return this._doAnalysisLoad('table.TSNE', 'Voyant.data.store.TSNEAnalysis', config);
},
_doAnalysisLoad: function(tool, storeType, config) {
if (this.then) {
return Voyant.application.getDeferredNestedPromise(this, arguments);
} else {
config = config || {};
var dfd = Voyant.application.getDeferred(this);
Ext.apply(config, {
columnHeaders: true,
rowHeaders: true,
tool: tool,
analysisInput: this.toTsv(),
inputFormat: 'tsv'
});
var store = Ext.create(storeType, {noCorpus: true});
store.load({
params: config,
callback: function(records, operation, success) {
if (success) {
dfd.resolve(store, records)
} else {
dfd.reject(operation.error.response);
}
}
})
return dfd.promise
}
},
embed: function(cmp, config) {
if (!config && Ext.isObject(cmp)) {
config = cmp;
cmp = this.embeddable[0];
}
config = config || {};
var columnHeaders = Ext.Array.from(config.headers || this.getHeaders()).map(function(header) {return this.getColumnHeader(header);}, this);
var json = {
rowkey: this.getRowKey(),
config: config,
headers: columnHeaders
};
if ("headers" in config) {
var columnIndices = Ext.Array.from(config.headers).map(function(header) {return this.getColumnIndex(header);}, this);
var rows = [];
this.getRows().forEach(function(row) {
rows.push(columnIndices.map(function(i) {
return row[i]
}))
})
Ext.apply(json, {
rows: rows
})
} else {
Ext.apply(json, {
rows: this.getRows()
})
}
Ext.apply(config, {
tableJson: JSON.stringify(json)
});
delete config.axes;
delete config.series;
embed.call(this, cmp, config);
},
toTsv: function(config) {
var tsv = this.getHeaders().join("\t");
this.getRows().forEach(function(row, i) {
if (config && Ext.isNumber(config) && i>config) {return;}
tsv += "\n"+row.map(function(cell) {
return Ext.isString(cell) ? cell.replace(/(\n|\t)/g, "") : cell;
}).join("\t");
})
return tsv;
},
getString: function(config) {
config = config || {};
var table = "<table class='voyant-table' style='"+(config.width ? ' width: '+config.width : '')+"' id='"+(config.id ? config.id : Ext.id())+"'>";
var headers = this.getHeaders();
if (headers.length) {
table+="<thead><tr>";
for (var i=0, len = headers.length; i<len; i++) {
table+="<th>"+headers[i]+"</th>";
}
table+="</tr></thead>";
}
table+="<tbody>";
for (var i=0, len = Ext.isNumber(config) ? config : this.getRows().length; i<len; i++) {
var row = this.getRow(i);
if (row && Ext.isArray(row)) {
table+="<tr>";
row.forEach(function(cell) {
table+="<td>"+cell+"</td>";
})
table+="</tr>";
}
}
table+="</tbody></table>";
return table;
}
});

@ -0,0 +1,269 @@
Ext.define('Voyant.notebook.Catalogue', {
extend: 'Ext.Component',
requires: ['Voyant.widget.Facet','Voyant.data.store.NotebookFacets'],
mixins: ['Voyant.util.Localization'],
alias: 'widget.notebookcatalogue',
statics: {
i18n: {
title: 'Notebooks Catalogue',
browse: 'Browse Notebooks',
keywords: 'Keywords',
author: 'Author',
language: 'Language',
license: 'License',
search: 'Search',
noResults: 'No matching notebooks',
suggested: 'Suggested Notebooks',
load: 'Load Selected Notebook'
}
},
window: undefined,
store: undefined,
template: undefined,
config: {
facets: {}
},
constructor: function() {
this.store = Ext.create('Ext.data.JsonStore', {
fields: [
{name: 'id'},
{name: 'author'},
{name: 'title'},
{name: 'description'},
{name: 'keywords'},
{name: 'language'},
{name: 'license'},
{name: 'created', type: 'date'},
{name: 'modified', type: 'date'},
{name: 'version'}
]
});
this.template = new Ext.XTemplate(
'<tpl for=".">',
'<div class="catalogue-notebook">',
'<div class="id">{id}</div>',
'<div class="title nowrap" title="{title}">{title}</div>',
'<div class="author nowrap"><i class="fa fa-user" aria-hidden="true"></i> {author}</div>',
'<div class="dates"><span class="date"><i class="fa fa-clock-o" aria-hidden="true"></i> {[Ext.Date.format(values.modified, "M j Y")]}</span></div>',
'</div>',
'</tpl>'
);
this.callParent(arguments);
},
initComponent: function(config) {
this.callParent(arguments);
},
showWindow: function() {
if (this.window === undefined) {
this.window = Ext.create('Ext.window.Window', {
title: this.localize('title'),
width: 800,
height: 675,
modal: true,
layout: 'border',
items: [{
xtype: 'panel',
region: 'center',
flex: 2,
border: true,
layout: {
type: 'vbox',
align: 'stretch'
},
items: [{
xtype: 'toolbar',
height: 30,
layout: {
type: 'hbox',
pack: 'center'
},
items: [{xtype:'tbspacer', flex: .1},{
xtype: 'textfield',
itemId: 'queryfield',
emptyText: this.localize('search'),
flex: .8,
enableKeyEvents: true,
triggers: {
search: {
cls: 'fa-trigger form-fa-search-trigger',
handler: function(cmp) {
// var query = cmp.getValue();
// if (query.trim().length > 0) {
// this.getNotebooks([query]);
// }
this.getNotebooks();
},
scope: this
}
},
listeners: {
keyup: function(cmp, e) {
if (e.getCharCode() === 13) {
this.getNotebooks();
}
},
scope: this
}
},{xtype:'tbspacer', flex: .1}]
},{
xtype: 'dataview',
flex: 1,
width: '100%',
padding: 10,
scrollable: 'vertical',
itemId: 'catalogue',
store: this.store,
tpl: this.template,
itemSelector: 'div.catalogue-notebook',
overItemCls: 'catalogue-notebook-over',
selectedItemCls: 'catalogue-notebook-selected',
listeners: {
itemdblclick: function(view, record, el) {
this.fireEvent('notebookSelected', this, record.get('id'));
},
scope: this
}
}]
},{
xtype: 'panel',
region: 'west',
collapsible: true,
title: this.localize('browse'),
flex: 1,
itemId: 'facets',
layout: {
type: 'accordion',
animate: false,
multi: true,
align: 'stretch',
hideCollapseTool: true
},
defaults: {
xtype: 'facet',
flex: 1
},
items: [{
title: this.localize('keywords'),
facet: 'facet.keywords',
store: Ext.create('Voyant.data.store.NotebookFacets', {
facet: 'facet.keywords'
})
},{
title: this.localize('author'),
facet: 'facet.author',
store: Ext.create('Voyant.data.store.NotebookFacets', {
facet: 'facet.author'
})
},{
title: this.localize('language'),
facet: 'facet.language',
store: Ext.create('Voyant.data.store.NotebookFacets', {
facet: 'facet.language'
})
},{
title: this.localize('license'),
facet: 'facet.license',
store: Ext.create('Voyant.data.store.NotebookFacets', {
facet: 'facet.license'
})
}]
},{
xtype: 'panel',
region: 'east',
collapsible: true,
collapsed: true,
title: this.localize('suggested'),
flex: 1,
items: [{
}]
}],
closeAction: 'hide',
buttons: [{
text: this.localize('load'),
handler: function(but) {
var record = this.window.down('#catalogue').getSelection()[0]
if (record !== undefined) {
this.fireEvent('notebookSelected', this, record.get('id'))
}
},
scope: this
}]
});
this.window.query('#facets > facet').forEach(function(facetCmp) {
facetCmp.getSelectionModel().on('selectionchange', this._handleFacetSelection.bind(this, facetCmp.facet))
facetCmp.getStore().load();
}, this);
} else {
// reset
this.setFacets({});
this.window.query('#facets > facet').forEach(function(facetCmp) {
facetCmp.getSelectionModel().deselectAll();
});
this.window.down('#queryfield').setValue('');
this.window.down('#catalogue').getSelectionModel().deselectAll();
this.store.removeAll();
}
this.window.show();
},
hideWindow: function() {
if (this.window !== undefined) {
this.window.close();
}
},
_handleFacetSelection: function(facet, model, selected) {
var labels = [];
selected.forEach(function(model) {
labels.push({facet: facet, label: model.getLabel ? model.getLabel() : model.getTerm()})
})
this.getFacets()[facet] = labels;
this.getNotebooks();
},
getNotebooks: function(queries) {
if (!queries) {
queries = [];
var facets = this.getFacets();
for (facet in facets) {
facets[facet].forEach(function(label) {
queries.push(label.facet+":"+label.label);
})
}
var queryfieldstring = this.window.down('#queryfield').getValue();
if (queryfieldstring.trim().length > 0) {
queries.push(queryfieldstring);
}
return this.getNotebooks(queries);
}
if (queries.length === 0) {
this.window.down('#catalogue').getSelectionModel().deselectAll();
this.store.removeAll();
return;
}
this.window.down('#catalogue').mask('Loading');
this.window.down('#catalogue').getSelectionModel().deselectAll();
var me = this;
Spyral.Load.trombone({
tool: 'notebook.NotebookFinder',
query: queries,
noCache: 1
}).then(function(json) {
me.window.down('#catalogue').unmask();
me.store.loadRawData(json.catalogue.notebooks);
me.store.sort('modified', 'DESC');
}).catch(function(err) {
me.window.unmask()
});
}
});

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

@ -0,0 +1,155 @@
Ext.define("Voyant.notebook.editor.CodeEditor", {
extend: "Ext.Component",
alias: "widget.notebookcodeeditor",
mixins: ["Voyant.util.Localization",'Voyant.notebook.util.Embed'],
embeddable: ["Voyant.notebook.editor.CodeEditor"],
cls: 'notebook-code-editor',
config: {
theme: 'ace/theme/chrome',
mode: 'ace/mode/javascript',
content: '',
docs: undefined,
isChangeRegistered: false,
editor: undefined,
editedTimeout: undefined,
lines: 0
},
statics: {
i18n: {
},
api: {
content: undefined
}
},
constructor: function(config) {
this.callParent(arguments);
},
listeners: {
boxready: function() {
var me = this;
var editor = ace.edit(Ext.getDom(this.getEl()));
editor.$blockScrolling = Infinity;
editor.getSession().setUseWorker(true);
editor.setTheme(this.getTheme());
editor.getSession().setMode(this.getMode());
editor.setOptions({
minLines: 6,
maxLines: Infinity, // this.getMode().indexOf("javascript")>-1 ? Infinity : 10,
autoScrollEditorIntoView: true,
scrollPastEnd: true
});
editor.setHighlightActiveLine(false);
editor.setHighlightGutterLine(false);
editor.renderer.setShowPrintMargin(false);
// editor.renderer.setShowGutter(false);
editor.setValue(this.getContent() ? this.getContent() : "" /*this.localize('emptyText')*/);
editor.clearSelection();
editor.on("focus", function() {
setTimeout(function() {
me.getEditor().setHighlightGutterLine(true);
}, 100); // slight delay to avoid selecting a range of text, caused by showing the gutter while mouse is still pressed
}, this);
editor.on("change", function(ev, editor) {
var lines = editor.getSession().getScreenLength();
if (lines!=me.getLines()) {
me.up('notebookcodeeditorwrapper').setSize({height: lines*editor.renderer.lineHeight+editor.renderer.scrollBar.getWidth()})
me.setLines(lines);
}
if (me.getIsChangeRegistered()==false) {
me.setIsChangeRegistered(true);
var wrapper = me.up('notebookcodeeditorwrapper');
if (wrapper) {
wrapper.setIsRun(false);
var notebook = wrapper.up("notebook");
if (notebook) {notebook.setIsEdited(true);}
}
} else {
if (!me.getEditedTimeout()) { // no timeout, so set it to 30 seconds
me.setEditedTimeout(setTimeout(function() {
me.setIsChangeRegistered(false);
}, 30000));
}
}
}, this);
editor.on("blur", function() {
me.getEditor().setHighlightGutterLine(false);
});
editor.commands.addCommand({
name: 'run',
bindKey: {win: "Shift-Enter", mac: "Shift-Enter"}, // additional bindings like alt/cmd-enter don't seem to work
exec: function(editor) {
var wrapper = me.up('notebookcodeeditorwrapper');
if (wrapper) {
wrapper.run();
}
}
});
editor.commands.addCommand({
name: 'rununtil',
bindKey: {win: "Command-Shift-Enter", mac: "Command-Shift-Enter"}, // additional bindings like alt/cmd-enter don't seem to work
exec: function(editor) {
var wrapper = me.up('notebookcodeeditorwrapper');
var notebook = wrapper.up("notebook");
notebook.runUntil(wrapper);
}
});
this.setEditor(editor);
ace.config.loadModule('ace/ext/tern', function (module) {
me.getEditor().setOptions({
/**
* Either `true` or `false` or to enable with custom options pass object that
* has options for tern server: http://ternjs.net/doc/manual.html#server_api
* If `true`, then default options will be used
*/
enableTern: {
/* http://ternjs.net/doc/manual.html#option_defs */
defs: me.docs ? ['browser', 'ecma5', me.docs] : ['ecma5', 'browser'],
plugins: {
doc_comment: {
fullDocs: true
}
},
/**
* (default is true) If web worker is used for tern server.
* This is recommended as it offers better performance, but prevents this from working in a local html file due to browser security restrictions
*/
useWorker: true
},
/**
* when using tern, it takes over Ace's built in snippets support.
* this setting affects all modes when using tern, not just javascript.
*/
enableSnippets: false,
/**
* when using tern, Ace's basic text auto completion is enabled still by default.
* This settings affects all modes when using tern, not just javascript.
* For javascript mode the basic auto completion will be added to completion results if tern fails to find completions or if you double tab the hotkey for get completion (default is ctrl+space, so hit ctrl+space twice rapidly to include basic text completions in the result)
*/
enableBasicAutocompletion: false
});
});
},
removed: function(cmp, container) {
if (cmp.getEditor()) {
cmp.getEditor().destroy();
}
}
},
switchModes: function(mode) {
this.setMode('ace/mode/'+mode);
this.getEditor().getSession().setMode(this.getMode());
// this.getEditor().setOptions({maxLines: this.getMode().indexOf("javascript")>-1 ? Infinity : 10});
},
getValue: function() {
return this.getEditor().getValue();
}
})

@ -0,0 +1,637 @@
Ext.define("Voyant.notebook.editor.CodeEditorWrapper", {
extend: "Voyant.notebook.editor.EditorWrapper",
requires: ["Voyant.notebook.editor.CodeEditor","Voyant.notebook.editor.button.Run","Voyant.notebook.editor.button.RunAll"],
alias: "widget.notebookcodeeditorwrapper",
cls: 'notebook-code-wrapper',
statics: {
i18n: {
runMultiple: "Run multiple cells",
runUntil: "Run up to here",
runUntilTip: "Run previous code blocks and this one.",
runFrom: "Run from here onwards",
runFromTip: "Run this and following code blocks.",
codeMode: "select from several formats for this cell",
codeModeTitle: "Code Mode",
codeModeTip: "Select from multiple code formats for this cell.",
configureTip: "Configuration Options",
autoExecuteOnLoad: "auto-run this cell on page load",
ok: "OK",
cancel: "Cancel"
},
configWin: undefined,
getConfigWindow: function(codeEditorInstance) {
if (this.configWin === undefined) {
this.configWin = new Ext.Window({
title: codeEditorInstance.localize('codeModeTitle'),
closeAction: 'hide',
layout: 'fit',
width: 240,
items: [{
xtype: 'form',
layout: {
type: 'vbox',
align: 'stretch'
},
bodyPadding: 10,
items: [{
xtype: 'fieldset',
title: codeEditorInstance.localize("modeCode"),
items: [{
xtype : 'radiofield',
boxLabel : codeEditorInstance.localize('modeJavascript'),
name : 'codeMode',
inputValue: 'javascript',
flex : 1,
listeners: {
change: function(cmp, newval, oldval) {
var autoExecCheck = cmp.up().queryById('autoExecute');
autoExecCheck.setHidden(!newval);
if (!newval) {
autoExecCheck.setValue(false);
}
}
}
},{
xtype: 'checkbox',
boxLabel: codeEditorInstance.localize('autoExecuteOnLoad'),
name: 'autoExecute',
itemId: 'autoExecute'
}]
},{
xtype: 'fieldset',
title: codeEditorInstance.localize("modeData"),
items: [{
items: {
xtype : 'radiofield',
boxLabel : codeEditorInstance.localize('modeJson'),
name : 'codeMode',
inputValue: 'json',
flex : 1
}
},{
items: {
xtype : 'radiofield',
boxLabel : codeEditorInstance.localize('modeText'),
name : 'codeMode',
inputValue: 'text',
flex : 1
}
},/*{
items: {
xtype : 'radiofield',
boxLabel : codeEditorInstance.localize('modeCsv'),
name : 'codeMode',
inputValue: 'csv',
flex : 1
}
},{
items: {
xtype : 'radiofield',
boxLabel : codeEditorInstance.localize('modeTsv'),
name : 'codeMode',
inputValue: 'tsv',
flex : 1
}
},*/{
items: {
xtype : 'radiofield',
boxLabel : codeEditorInstance.localize('modeHtml'),
name : 'codeMode',
inputValue: 'html',
flex : 1
}
},{
items: {
xtype : 'radiofield',
boxLabel : codeEditorInstance.localize('modeXml'),
name : 'codeMode',
inputValue: 'xml',
flex : 1
}
}]
}]
}],
buttons: [{
text: codeEditorInstance.localize('ok'),
itemId: 'ok'
},{
text: codeEditorInstance.localize('cancel'),
handler: function(btn) {
btn.up('window').close();
},
scope: this
}]
})
}
// set form values
var mode = codeEditorInstance.getMode();
this.configWin.down('radiofield[name=codeMode][inputValue="'+mode+'"]').setValue(true);
this.configWin.down('checkbox#autoExecute').setValue(codeEditorInstance.getAutoExecute());
// set ok handler
this.configWin.down('button#ok').setHandler(function(btn) {
var win = btn.up('window');
var form = win.down('form');
if (form.isDirty()) {
var values = form.getValues();
codeEditorInstance.switchModes(values.codeMode);
codeEditorInstance.setAutoExecute(values.autoExecute === 'on');
codeEditorInstance.down('button#config').toggleCls("autoExecute", values.autoExecute === 'on');
codeEditorInstance.up('notebook').setIsEdited(true);
}
win.close();
});
return this.configWin;
}
},
config: {
isRun: false,
autoExecute: false,
mode: 'javascript',
isWarnedAboutPreviousCells: false,
expandResults: true,
emptyResultsHeight: 40,
minimumResultsHeight: 120
},
layout: {
type: 'vbox',
align: 'stretch'
},
height: 150,
border: false,
EMPTY_RESULTS_TEXT: ' ', // text to use when clearing results, prior to running code
constructor: function(config) {
config.mode = config.mode !== undefined ? config.mode : this.config.mode;
var runnable = config.mode.indexOf('javascript') > -1;
this.editor = Ext.create("Voyant.notebook.editor.CodeEditor", {
content: Ext.Array.from(config.input).join("\n"),
docs: config.docs,
mode: 'ace/mode/'+config.mode
});
Ext.apply(this, {
dockedItems: [{
xtype: 'toolbar',
dock: 'left',
defaults: {
textAlign: 'left'
},
items: [
{
xtype: 'notebookwrapperadd'
},{
xtype: 'notebookwrapperrun',
hidden: !runnable,
listeners: {
click: {
fn: this.run,
scope: this
}
}
},{
glyph: 'xf050@FontAwesome',
tooltip: this.localize("runMultiple"),
itemId: 'runMultiple',
// xtype: 'notebookwrapperrununtil',
hidden: !runnable,
listeners: {
click: {
fn: function(btn, ev) {
Ext.create('Ext.menu.Menu', {
items: [{
text: this.localize("runUntil"),
tooltip: this.localize("runUntilTip"),
glyph: 'xf049@FontAwesome',
handler: function() {
this.up('notebook').runUntil(this);
},
scope: this
},{
text: this.localize("runFrom"),
tooltip: this.localize("runFromTip"),
glyph: 'xf050@FontAwesome',
handler: function() {
this.up('notebook').runFrom(this);
},
scope: this
}]
}).showAt(ev.pageX, ev.pageY)
},
scope: this
}
}
},{
xtype: 'button',
itemId: 'config',
glyph: 'xf013@FontAwesome',
tooltip: this.localize("configureTip"),
cls: config.autoExecute ? "autoExecute" : "",
handler: function(btn, ev) {
Voyant.notebook.editor.CodeEditorWrapper.getConfigWindow(this).show();
},
scope: this
},{
xtype: "notebookwrapperexport",
hidden: runnable
}
]
},{
xtype: 'toolbar',
dock: 'right',
items: [{
xtype: 'notebookwrappercounter',
order: config.order,
name: config.cellId
},{
xtype: 'notebookwrapperremove'
},{
xtype: 'notebookwrappermoveup'
},{
xtype: 'notebookwrappermovedown'
}
]
}],
items: [this.editor]
});
if (config.uiHtml !== undefined) {
this.items.push(this._getUIComponent(config.uiHtml))
}
this.results = this._getResultsComponent(Ext.Array.from(config.output).join(""), config);
this.results.setVisible(runnable);
this.items.push(this.results);
this.callParent(arguments);
},
initComponent: function(config) {
var me = this;
me.on("afterrender", function() {
this.getTargetEl().on("resize", function(el) {
me._setResultsHeight();
var height = 20;
me.items.each(function(item) {height+=item.getHeight();})
me.setSize({height: height});
});
}, this);
me.callParent(arguments);
},
switchModes: function(mode) {
this.setMode(mode);
this.editor.switchModes(mode);
var runnable = mode.indexOf('javascript') > -1;
this.down('notebookwrapperrun').setVisible(runnable);
this.down('notebookwrapperexport').setVisible(!runnable);
this.queryById("runMultiple").setVisible(runnable);
this.results.setVisible(runnable);
},
/**
* Run the code in this editor.
* @param {boolean} forceRun True to force the code to run, otherwise a check is performed to see if previous editors have already run.
*/
run: function(forceRun) {
if (this.editor.getMode()==='ace/mode/javascript') { // only run JS
if (forceRun===true || this.getIsWarnedAboutPreviousCells()) {
return this._run();
} else {
// this code was for checking if previous cells hadn't been run, but it didn't seem worthwhile
var notebook = this.up('notebook');
Ext.Array.each(notebook.query('notebookcodeeditorwrapper'), function(wrapper) {
if (wrapper===this) {this._run(); return false;} // break
if (wrapper.editor && wrapper.editor.getMode() === 'ace/mode/javascript' && wrapper.getIsRun()===false) {
Ext.Msg.confirm(this.localize('previousNotRunTitle'), this.localize('previousNotRun'), function(btnId) {
if (btnId==='yes') {
notebook.runUntil(this);
} else {
this._run();
}
}, this);
this.setIsWarnedAboutPreviousCells(true);
return false;
}
}, this);
}
}
},
_run: function() {
this.results.show(); // make sure it's visible
this.results.update(this.EMPTY_RESULTS_TEXT); // clear out the results
this.results.mask('working…'); // mask results
var code = this.editor.getValue();
Voyant.notebook.util.Show.TARGET = this.results.getResultsEl(); // this is for output
Voyant.notebook.Notebook.currentBlock = this; // this is to tie back in to the block
Voyant.notebook.Notebook.currentNotebook.setCurrentBlock(this);
var result;
try {
// I'd like to be able to run this in another scope/context, but it
// doesn't seem possible for the type of code that's being run
result = eval.call(window, code);
}
catch (e) {
this.results.unmask();
Voyant.notebook.util.Show.showError(e);
this.getTargetEl().fireEvent('resize');
return e;
}
this.setIsRun(true);
if (result!==undefined) {
if (result.then && result.catch && result.finally) {
var me = this;
result.then(function(result) {
me.results.unmask();
if (result!==undefined) {
me._showResult(result);
}
}).catch(function(err) {
me.results.unmask();
Voyant.notebook.util.Show.showError(err);
}).finally(function() {
Ext.defer(function() {this.getTargetEl().fireEvent('resize')}, 50, me);
})
} else {
this.results.unmask();
this._showResult(result);
this.getTargetEl().fireEvent('resize');
}
} else {
this.results.unmask();
this.getTargetEl().fireEvent('resize');
}
return result;
},
_getResultsComponent: function(html, config) {
var me = this;
var isExpanded = config.expandResults === undefined ? me.config.expandResults : config.expandResults;
var height = me.config.emptyResultsHeight;
return Ext.create('Ext.Container', {
itemId: 'parent',
cls: 'notebook-code-results',
height: height,
layout: {
type: 'vbox',
align: 'stretch'
},
items: [{
xtype: 'container',
flex: 1,
layout: {
type: 'absolute'
},
items: [{
xtype: 'component',
itemId: 'results',
x: 0,
y: 0,
anchor: '100%',
height: '100%',
html: html
},{
xtype: 'toolbar',
itemId: 'buttons',
hidden: true,
x: 0,
y: 0,
style: { background: 'none', paddingTop: '0px', pointerEvents: 'none' },
defaults: { style: { pointerEvents: 'auto'} },
items: ['->',{
itemId: 'expandButton',
glyph: isExpanded ? 'xf066@FontAwesome' : 'xf065@FontAwesome',
tooltip: isExpanded ? 'Contract Results' : 'Expand Results',
handler: function() {
me.results.doExpandContract();
}
},{
xtype: 'notebookwrapperexport',
exportType: 'output'
},{
glyph: 'xf014@FontAwesome',
tooltip: 'Remove Results',
handler: function() {
me.clearResults();
}
}]
}]
},{
xtype: 'component',
itemId: 'expandWidget',
height: 20,
hidden: isExpanded ? true : false,
style: {textAlign: 'center', fontSize: '26px', cursor: 'pointer', borderTop: '1px solid #DDD'},
html: '&#8943;',
listeners: {
afterrender: function(cmp) {
cmp.getEl().on('click', function() {
me.results.doExpandContract();
})
}
}
}],
getValue: function() {
var resultEl = this.getResultsEl().dom.cloneNode(true);
var output = resultEl.innerHTML;
return output;
},
getResultsEl: function() {
return this.down('#results').getEl();
},
doExpandContract: function() {
var expandButton = me.results.down('#expandButton');
if (me.getExpandResults()) {
me.setExpandResults(false);
expandButton.setTooltip('Expand Results');
expandButton.setGlyph('xf065@FontAwesome');
} else {
me.setExpandResults(true);
expandButton.setTooltip('Contract Results');
expandButton.setGlyph('xf066@FontAwesome');
}
me.getTargetEl().fireEvent('resize');
},
// override update method and call it on results child instead
update: function() {
var results = this.down('#results');
results.update.apply(results, arguments);
},
listeners: {
afterrender: function(cmp) {
cmp.getEl().on('mouseover', function(event, el) {
cmp.down('#buttons').setVisible(true);
});
cmp.getEl().on('mouseout', function(event, el) {
cmp.down('#buttons').setVisible(false);
});
}
}
});
},
_getUIComponent: function(html) {
return Ext.create('Ext.Component', {
align: 'stretch',
cls: 'notebook-code-ui',
padding: '20 10',
html: html,
getValue: function() {
const el = this.getTargetEl()
const resultEl = el.dom.cloneNode(true);
let output = resultEl.innerHTML;
return output;
}
});
},
_showResult: function(result) {
// check for pre-existing content (such as from highcharts) and if it exists don't update
if (this.results.getResultsEl().dom.innerHTML === this.EMPTY_RESULTS_TEXT) {
if (result.toString) {result = result.toString()}
if (result && result.then) {
var me = this;
result.then(out => {
me.results.update(out);
return out;
})
} else {
this.results.update(result);
}
}
},
/**
* Set the height of the results component
*/
_setResultsHeight: function() {
var height = this._measureResultsHeight();
var resultsEl = this.results.getResultsEl();
var expandWidget = this.results.down('#expandWidget');
if (this.getExpandResults()) {
expandWidget.hide();
this.results.setHeight(Math.max(height, this.getEmptyResultsHeight()));
resultsEl.removeCls('collapsed');
} else {
height = Math.min(Math.max(height, this.getEmptyResultsHeight()), this.getMinimumResultsHeight());
if (height < this.getMinimumResultsHeight()) {
expandWidget.hide();
} else {
expandWidget.show();
}
this.results.setHeight(height);
resultsEl.addCls('collapsed');
}
},
_measureResultsHeight: function() {
if (this.results.paddingHeight === undefined) {
// compute and store parent padding, which we'll need when determining proper height
var computedStyle = window.getComputedStyle(this.results.getEl().dom);
this.results.paddingHeight = parseFloat(computedStyle.getPropertyValue('padding-top'))+parseFloat(computedStyle.getPropertyValue('padding-bottom'));
}
var resultsEl = this.results.getResultsEl();
var resultsChildHeight = undefined;
if (resultsEl.dom.childElementCount > 0) {
// child might be taller than the results el (e.g. in the case of highcharts)
resultsChildHeight = resultsEl.getFirstChild().getHeight() + this.results.paddingHeight;
} else if (resultsEl.dom.firstChild !== null && resultsEl.dom.firstChild.nodeType === Node.TEXT_NODE) {
// calculate text height
var textHeight = Ext.util.TextMetrics.measure(resultsEl, resultsEl.dom.firstChild.data, resultsEl.getWidth()).height;
resultsChildHeight = textHeight + this.results.paddingHeight;
} else {
// no results?
resultsChildHeight = this.getEmptyResultsHeight();
}
return resultsChildHeight;
},
clearResults: function() {
this.results.show();
var panel = this.results.el.down('.x-panel');
if (panel) {
var id = panel.id;
var cmp = Ext.getCmp(id);
if (cmp) {
cmp.destroy();
} else {
panel.destroy();
}
} else if (this.results.getResultsEl().dom.hasAttribute('data-highcharts-chart')) {
var chartId = this.results.getResultsEl().dom.id;
var highchart = undefined;
Highcharts.charts.forEach(function(chart) {
if (chart !== undefined && chart.renderTo.id === chartId) {
highchart = chart;
}
})
if (highchart) {
highchart.destroy();
// remove highcharts style changes from results element
var resultsDom = this.results.getResultsEl().dom;
resultsDom.style.height = '100%';
resultsDom.style.overflow = '';
} else {
console.warn('tried to destroy highchart but could not', chartId);
}
} else {
this.results.update(' ');
}
this.getTargetEl().fireEvent('resize');
},
tryToUnmask: function() {
if (Spyral && Spyral.promises) {
Ext.defer(this.tryToUnmask, 20, this);
}
if (Voyant.application.getDeferredCount()===0) {
for (var key in window) {
if (typeof window[key] == 'object' && window[key] && key!="opener" && window[key].isFulfilled && window[key].isFulfilled()) {
window[key] = window[key].valueOf();
}
}
this.results.unmask();
if (this.results.getTargetEl().getHtml().trim().length===0) {
this.results.hide();
}
this.getTargetEl().fireEvent('resize');
}
else {
Ext.defer(this.tryToUnmask, 20, this);
}
},
getContent: function() {
var toReturn = {
input: this.editor.getValue(),
mode: this.getMode()
}
if (toReturn.mode==='javascript') {
toReturn.output = this.results.getValue();
var ui = this.down('component[cls="notebook-code-ui"]');
if (ui !== null) {
toReturn.ui = ui.getValue();
}
}
return toReturn;
},
setContentAndMode: function(content, mode, config) {
debugger
this.editor.setContent(content);
this.switchModes(mode || "javascript")
}
})

@ -0,0 +1,54 @@
Ext.define("Voyant.notebook.editor.EditorWrapper", {
extend: "Ext.panel.Panel",
mixins: ["Voyant.util.Localization"],
requires: ["Voyant.notebook.editor.button.Movement","Voyant.notebook.editor.button.Add"],
alias: "widget.notebookeditorwrapper",
cls: "notebook-editor-wrapper",
config: {
cellId: undefined,
content: '',
isEditing: false
},
border: false,
bodyBorder: false,
initComponent: function() {
this.setCellId(this.config.cellId);
this.on("afterrender", function(){
this.getDockedItems().forEach(function(tb) {
tb.getTargetEl().setVisibilityMode(Ext.dom.Element.VISIBILITY);
});
this.setActiveMode(false);
this.body.on("click", function() {
this.removeCls("notebook-editor-wrapper-hover");
this.setActiveMode(true); // added for touch devices
}, this);
this.mon(this.getEl(), "mouseover", function() {
this.setActiveMode(true);
}, this);
this.mon(this.getEl(), "mouseout", function() {
this.setActiveMode(false);
}, this);
}, this);
this.callParent(arguments);
},
setActiveMode: function(mode) {
this.getDockedItems().forEach(function(tb) {
if (tb.dock=='right') {
tb.items.each(function(item) {
if (item.hasCls("notebookwrappercounter")==false) {
item.getTargetEl().setVisibility(mode);
}
})
} else {
tb.getTargetEl().setVisibility(mode);
}
}, this);
if (!this.getIsEditing()) {
if (mode) {
this.body.addCls("notebook-editor-wrapper-hover");
} else {
this.body.removeCls("notebook-editor-wrapper-hover");
}
}
}
})

@ -0,0 +1,104 @@
Ext.define("Voyant.notebook.editor.TextEditor", {
extend: "Ext.Component",
mixins: ["Voyant.util.Localization"],
alias: "widget.notebooktexteditor",
cls: 'notebook-text-editor',
config: {
ckeditorConfig : { // when upgrading ckeditor, remember to copy stopediting and inserthtml4x plugins
toolbar: [
{ name: 'basicstyles', items: [ 'Bold', 'Italic', '-', 'RemoveFormat' ] },
{ name: 'paragraph', items: [ 'NumberedList', 'BulletedList', '-', 'Justify', 'Outdent', 'Indent', 'Blockquote', 'JustifyLeft', 'JustifyCenter', 'JustifyRight' ] },
{ name: 'colors', items: [ 'TextColor', 'BGColor' ] },
{ name: 'styles', items: [ 'Styles', 'Format' ] },
{ name: 'links', items: [ 'Link', 'Unlink', 'Anchor'] },
{ name: 'insert', items: [ 'Image', 'Table' ] },
{ name: 'document', items: [ 'inserthtml4x', 'Sourcedialog', 'Stopediting'] }
],
extraPlugins: 'stopediting,sourcedialog,justify,colorbutton,inserthtml4x',
allowedContent: true,
toolbarCanCollapse: false,
startupFocus: true
},
editor: undefined,
isEditRegistered: false,
currentHeight: 0
},
statics: {
i18n: {
}
},
border: false,
constructor: function(config) {
Ext.apply(this, {
html: config.content ? config.content : this.localize("emptyText")
});
this.callParent(arguments);
},
listeners: {
boxready: function(cmp) {
this.getTargetEl().on("click", function(e, t) {
if (t.tagName!="A") {
this.handleClick(cmp);
}
}, this);
},
removed: function(cmp, container) {
// properly remove editor
if (cmp.getEditor()) {
cmp.getEditor().focusManager.blur(true); //focusManager bug workaround, see: https://dev.ckeditor.com/ticket/16825
cmp.getEditor().destroy();
}
}
},
handleClick: function(cmp) {
if (!cmp.getEditor() || (cmp.getEditor() && cmp.getEditor().readOnly)) {
var el = this.getTargetEl();
el.set({contenteditable: true});
this.findParentByType("notebookeditorwrapper").setIsEditing(true);
if (!cmp.getEditor()) {
var editor = CKEDITOR.inline( el.dom, this.getCkeditorConfig() );
// erase contents if it's click to edit (not localized, FIXME
editor.on("focus", function(evt) {
if (this.getTargetEl().dom.innerText==this.localize("emptyText")) {
this.getTargetEl().update('')
}
}, this)
editor.on("blur", function(evt) {
// cmp.setEditor(undefined);
cmp.findParentByType("notebookeditorwrapper").setIsEditing(false).getEl().fireEvent("mouseout");
// el.set({contenteditable: false});
editor.setReadOnly(true);
})
editor.on("change", function() {
var editorHeight = editor.container.$.clientHeight;
if (editorHeight!=this.getCurrentHeight()) {
this.findParentByType("notebookeditorwrapper").setHeight(editorHeight);
this.setCurrentHeight(editor.container.$.clientHeight)
}
if (!this.getIsEditRegistered()) {
this.findParentByType("notebook").setIsEdited(true);
this.setIsEditRegistered(true);
} else {
var me = this; // make sure to allow edits to be auto-saved every 30 seconds
setTimeout(function() {
me.setIsEditRegistered(false);
}, 30000);
}
}, this)
this.setEditor(editor);
} else {
cmp.getEditor().setReadOnly(false);
}
}
},
getContent: function() {
return this.getTargetEl().dom.innerHTML;
}
})

@ -0,0 +1,47 @@
Ext.define("Voyant.notebook.editor.TextEditorWrapper", {
extend: "Voyant.notebook.editor.EditorWrapper",
requires: ["Voyant.notebook.editor.TextEditor","Voyant.notebook.editor.button.Edit"],
alias: "widget.notebooktexteditorwrapper",
cls: 'notebook-text-wrapper',
config: {
content: ''
},
minHeight: 85,
constructor: function(config) {
Ext.apply(this, {
items: [{
xtype: 'notebooktexteditor',
content: Ext.Array.from(config.input).join("")
}],
dockedItems: [{
xtype: 'toolbar',
dock: 'left',
items: [{
xtype: 'notebookwrapperadd'
}
]
},{
xtype: 'toolbar',
dock: 'right',
items: [{
xtype: 'notebookwrappercounter',
order: config.order,
name: config.cellId
},{
xtype: 'notebookwrapperremove'
},{
xtype: 'notebookwrappermoveup'
},{
xtype: 'notebookwrappermovedown'
}
]
}]
});
this.callParent(arguments);
},
getContent: function() {
return this.items.get(0).getContent();
}
})

@ -0,0 +1,22 @@
Ext.define("Voyant.notebook.editor.button.Add", {
extend: "Ext.button.Button",
mixins: ["Voyant.util.Localization"],
alias: 'widget.notebookwrapperadd',
statics: {
i18n: {
}
},
constructor: function(config) {
Ext.apply(this, {
tooltip: this.localize('tip')
})
this.callParent(arguments);
},
glyph: 'xf067@FontAwesome',
textAlign: 'left',
listeners: {
click: function(btn, e) {
this.findParentByType('notebook').fireEvent("notebookWrapperAdd", this.findParentByType("notebookeditorwrapper"), e);
}
}
})

@ -0,0 +1,30 @@
Ext.define("Voyant.notebook.editor.button.Counter", {
extend: "Ext.toolbar.TextItem",
mixins: ["Voyant.util.Localization"],
alias: 'widget.notebookwrappercounter',
statics: {
i18n: {
}
},
config: {
order: 0,
name: undefined
},
cls: 'notebookwrappercounter',
constructor: function(config) {
Ext.apply(this, {
toolTip: this.localize('tip')
})
this.callParent(arguments);
},
setOrder: function(pos) {
this.callParent(arguments);
this.updateHtml();
},
updateHtml: function() {
var pos = this.getOrder()+1;
var lnk = 'spyralcounter_'+pos;
var name = this.getName();
this.setHtml('<a name="'+name+'" href="#'+name+'">'+pos+'</a>');
}
})

@ -0,0 +1,21 @@
Ext.define("Voyant.notebook.editor.button.Edit", {
extend: "Ext.button.Button",
mixins: ["Voyant.util.Localization"],
alias: 'widget.notebookwrapperedit',
statics: {
i18n: {
}
},
constructor: function(config) {
Ext.apply(this, {
toolTip: this.localize('tip')
})
this.callParent(arguments);
},
glyph: 'xf040@FontAwesome',
listeners: {
click: function() {
this.findParentByType('notebook').fireEvent("notebookWrapperEdit", this.findParentByType("notebookeditorwrapper"));
}
}
})

@ -0,0 +1,108 @@
Ext.define("Voyant.notebook.editor.button.Export", {
extend: "Ext.button.Button",
mixins: ["Voyant.util.Localization"],
alias: 'widget.notebookwrapperexport',
statics: {
i18n: {
tip: "Export",
exportTitle: "Export",
exportOpen: "Export content into new window",
exportDownload: "Download file to your machine",
cancelTitle: "Cancel"
},
exportWin: undefined,
getExportWindow: function(instance) {
if (this.exportWin === undefined) {
this.exportWin = Ext.create('Ext.window.Window', {
title: instance.localize("exportTitle"),
closeAction: 'hide',
modal: true,
bodyPadding: 5,
layout: {
type: 'vbox',
align: 'stretch'
},
defaults: {
xtype: 'button'
},
items: [{
itemId: 'open',
text: instance.localize('exportOpen'),
glyph: 'xf08e@FontAwesome'
},{
itemId: 'download',
margin: '5 0 0 0',
preventDefault: false,
text: instance.localize('exportDownload'),
glyph: 'xf019@FontAwesome',
handler: function(btn) {
btn.up('window').close();
}
}],
buttons: [{
text: instance.localize("cancelTitle"),
glyph: 'xf00d@FontAwesome',
handler: function(btn) {
btn.up('window').close();
}
}]
});
}
var wrapper = instance.up("notebookcodeeditorwrapper");
var content = wrapper.getContent();
var fileContent = instance.getExportType() === 'output' ? content.output : content.input;
var filename = wrapper.getCellId()+"."+instance.getFileExtension(content.mode);
var properties = {type: content.mode==="text" || true ? "text/plain" : "text/"+content.mode};
var file;
try {
file = new File([fileContent], filename, properties);
} catch (e) {
file = new Blob([fileContent], properties);
}
this.exportWin.down('#open').setHandler(function(btn) {
var myWindow = window.open();
myWindow.document.write(fileContent);
myWindow.document.close();
myWindow.focus();
btn.up('window').close();
});
this.exportWin.addListener('show', function() {
var url = URL.createObjectURL(file);
this.exportWin.down('#download').getEl().set({
download: filename,
href: url
});
}, this, { single: true });
return this.exportWin;
}
},
constructor: function(config) {
Ext.apply(config, {
tooltip: this.localize('tip')
})
this.callParent(arguments);
},
config: {
exportType: 'input' // what type of content to include in the export: 'input' or 'output'
},
glyph: 'xf08e@FontAwesome',
listeners: {
click: function(cmp) {
Voyant.notebook.editor.button.Export.getExportWindow(cmp).show();
}
},
getFileExtension: function(mode) {
if (
mode === 'text' ||
(mode === 'javascript' && this.getExportType() === 'output') // use txt for javascript results because they could be anything
) {
return 'txt';
} else {
return mode;
}
}
})

@ -0,0 +1,22 @@
Ext.define("Voyant.notebook.editor.button.Metadata", {
extend: "Ext.button.Button",
mixins: ["Voyant.util.Localization"],
alias: 'widget.notebookwrappermetadata',
statics: {
i18n: {
}
},
constructor: function(config) {
Ext.apply(this, {
tooltip: this.localize('tip')
})
this.callParent(arguments);
},
glyph: 'xf02c@FontAwesome',
textAlign: 'left',
listeners: {
click: function(btn, e) {
this.findParentByType('notebook').fireEvent("notebookWrapperMetadata", this.findParentByType("notebookeditorwrapper"), e);
}
}
})

@ -0,0 +1,22 @@
Ext.define("Voyant.notebook.editor.button.MoveDown", {
extend: "Ext.button.Button",
mixins: ["Voyant.util.Localization"],
alias: 'widget.notebookwrappermovedown',
statics: {
i18n: {
}
},
constructor: function(config) {
Ext.apply(this, {
tooltip: this.localize('tip')
})
this.callParent(arguments);
},
glyph: 'xf063@FontAwesome',
textAlign: 'left',
listeners: {
click: function() {
this.findParentByType('notebook').fireEvent("notebookWrapperMoveDown", this.findParentByType("notebookeditorwrapper"));
}
}
})

@ -0,0 +1,22 @@
Ext.define("Voyant.notebook.editor.button.MoveUp", {
extend: "Ext.button.Button",
mixins: ["Voyant.util.Localization"],
alias: 'widget.notebookwrappermoveup',
statics: {
i18n: {
}
},
constructor: function(config) {
Ext.apply(this, {
tooltip: this.localize('tip')
})
this.callParent(arguments);
},
glyph: 'xf062@FontAwesome',
textAlign: 'left',
listeners: {
click: function() {
this.findParentByType('notebook').fireEvent("notebookWrapperMoveUp", this.findParentByType("notebookeditorwrapper"));
}
}
})

@ -0,0 +1,26 @@
Ext.define("Voyant.notebook.editor.button.Movement", {
extend: "Ext.button.Button",
mixins: ["Voyant.util.Localization"],
requires: ["Voyant.notebook.editor.button.MoveUp", "Voyant.notebook.editor.button.MoveDown", "Voyant.notebook.editor.button.Remove"],
alias: 'widget.notebookwrappermovement',
statics: {
i18n: {
}
},
constructor: function(config) {
Ext.apply(this, {
tooltip: this.localize('tip')
})
this.callParent(arguments);
},
glyph: 'xf07d@FontAwesome',
menu: [
{
xtype: 'notebookwrappermoveup'
},{
xtype: 'notebookwrappermovedown'
},{
xtype: 'notebookwrapperremove'
}
]
})

@ -0,0 +1,33 @@
Ext.define("Voyant.notebook.editor.button.Remove", {
extend: "Ext.button.Button",
mixins: ["Voyant.util.Localization"],
alias: 'widget.notebookwrapperremove',
statics: {
i18n: {
}
},
constructor: function(config) {
Ext.apply(this, {
tooltip: this.localize('tip')
})
this.callParent(arguments);
},
glyph: 'xf014@FontAwesome',
textAlign: 'left',
listeners: {
click: function() {
Ext.Msg.show({
buttons: Ext.Msg.OKCANCEL,
icon: Ext.MessageBox.QUESTION,
msg: this.localize("confirmRemove"),
title: this.localize("confirmRemoveTitle"),
fn: function(buttonId) {
if (buttonId=='ok') {
this.findParentByType('notebook').fireEvent("notebookWrapperRemove", this.findParentByType("notebookeditorwrapper"));
}
},
scope: this
})
}
}
})

@ -0,0 +1,15 @@
Ext.define("Voyant.notebook.editor.button.Run", {
extend: "Ext.button.Button",
mixins: ["Voyant.util.Localization"],
alias: 'widget.notebookwrapperrun',
statics: {
i18n: {
}
},
glyph: 'xf04b@FontAwesome',
constructor: function(config) {
config = config || {};
config.tooltip = this.localize('tip');
this.callParent(arguments);
}
})

@ -0,0 +1,15 @@
Ext.define("Voyant.notebook.editor.button.RunAll", {
extend: "Ext.button.Button",
mixins: ["Voyant.util.Localization"],
alias: 'widget.notebookwrapperrunall',
statics: {
i18n: {
}
},
glyph: 'xf04e@FontAwesome',
constructor: function(config) {
config = config || {};
config.tooltip = this.localize('tip');
this.callParent(arguments);
}
})

@ -0,0 +1,15 @@
Ext.define("Voyant.notebook.editor.button.RunUntil", {
extend: "Ext.button.Button",
mixins: ["Voyant.util.Localization"],
alias: 'widget.notebookwrapperrununtil',
statics: {
i18n: {
}
},
glyph: 'xf050@FontAwesome',
constructor: function(config) {
config = config || {};
config.tooltip = this.localize('tip');
this.callParent(arguments);
}
})

@ -0,0 +1,247 @@
Ext.define("Voyant.notebook.github.FileSaver", {
extend: "Ext.container.Container",
xtype: "githubfilesaver",
config: {
currentFile: undefined,
username: undefined
},
octokit: undefined,
saveData: undefined,
constructor: function(config) {
config = config || {};
this.octokit = config.octokit;
this.saveData = config.saveData;
this.setCurrentFile(config.currentFile);
this.callParent(arguments);
},
initComponent: function() {
Ext.apply(this, {
layout: {
type: 'vbox',
pack: 'start',
align: 'stretch'
},
items: [{
xtype: 'githubreposbrowser',
octokit: this.octokit,
itemId: 'repoBrowser',
flex: 1,
listeners: {
nodeSelected: function(src, type, node) {
const form = this.queryById('saveForm').getForm();
const [owner, repo] = src.getRepoId().split('/');
form.setValues({owner, repo});
if (type === 'file') {
const pathComponents = this.getPathComponents(src.getPath());
form.setValues({...pathComponents});
} else if (type === 'folder') {
const folder = src.getPath().replace(/^\//, '');
form.setValues({folder, file: ''});
} else if (type === 'repo') {
form.setValues({folder: '', file: ''});
}
},
nodeDeselected: function(node) {
// loadWin.queryById('load').setDisabled(true);
},
scope: this
}
},{
bodyPadding: '10',
height: 200,
layout: {
type: 'vbox',
pack: 'start'
},
xtype: 'form',
itemId: 'saveForm',
items: [{
html: '<span class="x-panel-header-title-default">Repository Path</span>'
},{
xtype: 'container',
layout: 'hbox',
defaults: {
xtype: 'textfield',
labelAlign: 'top'
},
items: [{
fieldLabel: 'GitHub User',
name: 'owner',
allowBlank: false,
margin: '0 10 0 0'
},{
fieldLabel: 'Repository Name',
allowBlank: false,
name: 'repo'
}]
},{
html: '<span class="x-panel-header-title-default">File Path</span>',
margin: '10 0 0 0',
},{
xtype: 'container',
layout: 'hbox',
defaults: {
xtype: 'textfield',
labelAlign: 'top'
},
items: [{
fieldLabel: 'Folder(s)',
name: 'folder',
allowBlank: true,
margin: '0 10 0 0'
},{
fieldLabel: 'File Name',
allowBlank: false,
name: 'file'
}]
},{
/*
xtype: 'container',
width: '100%',
layout: {
type: 'hbox',
align: 'middle',
pack: 'start'
},
margin: '25 0 0 0',
defaults: {
xtype: 'button'
},
items: [{
text: 'Save',
handler: function () {
this.doSave(false);
},
scope: this,
margin: '0 10 0 0'
}
// ,{
// text: 'Save as Pull Request',
// handler: function () {
// this.doSave(true);
// },
// scope: this
// }
]
},{
*/
itemId: 'status',
html: '',
margin: '15 0 0 0'
}],
listeners: {
validitychange: function(form, valid) {
this.fireEvent('formValidityChange', this, valid);
},
scope: this
}
}],
listeners: {
boxready: function() {
this.initForm();
},
scope: this
}
});
this.callParent(arguments);
},
initForm: function() {
this.octokit.getInfoForAuthenticatedUser().then(function(resp) {
const username = resp.data.login;
this.setUsername(username);
const form = this.queryById('saveForm').getForm();
const currentFile = this.getCurrentFile();
if (currentFile !== undefined) {
const pathComponents = this.getPathComponents(currentFile.path);
form.setValues({
owner: currentFile.owner,
repo: currentFile.repo,
...pathComponents
});
} else {
form.setValues({owner: username});
}
}.bind(this))
},
getPathComponents: function(path) {
const pathComponents = path.split('/');
let file = pathComponents[pathComponents.length-1];
let folder = '';
if (pathComponents.length > 2) {
folder = pathComponents.slice(0, -1).join('/');
}
return {
folder,
file
}
},
doSave: async function(isPR=false) {
const form = this.queryById('saveForm').getForm();
if (form.isValid()) {
const {owner, repo, folder, file} = form.getValues();
let path = file;
if (folder !== '') {
path = folder+'/'+file;
}
this.setStatus('Checking repository');
const repoExists = await this.octokit.doesRepoExist(owner, repo);
if (repoExists) {
this.setStatus('Checking permissions');
const permission = await this.octokit.getPermissionsForUser(owner, repo, this.getUsername());
if (permission === 'none' || permission === 'read') {
this.setStatus('You don\'t have permission to write to this repository', 'error');
} else {
this.setStatus('Checking file');
const branch = 'master';
const content = this.saveData;
const fileData = {owner, repo, branch, path};
const sha = await this.octokit.getLatestFileSHA(fileData);
if (sha !== undefined) {
const message = 'File updated by Spyral';
this.octokit.saveFile(owner, repo, path, content, branch, message, sha).then(function(resp) {
this.setStatus('File updated');
setTimeout(function() {
this.fireEvent('fileSaved', this, fileData);
}.bind(this), 500);
}.bind(this), function(error) {
this.setStatus('Error: '+error.message, 'error');
});
} else {
const message = 'File created by Spyral';
this.octokit.saveFile(owner, repo, path, content, branch, message).then(function(resp) {
this.setStatus('File created');
setTimeout(function() {
this.fireEvent('fileSaved', this, fileData);
}.bind(this), 500);
}.bind(this), function(error) {
this.setStatus('Error: '+error.message, 'error');
});
}
}
} else {
this.setStatus('The specified repository does not exist', 'error');
}
} else {
this.setStatus('Form is not valid', 'error');
}
},
setStatus: function(message, type) {
let cls = '';
if (type && type === 'error') {
cls = 'x-form-invalid-under-default';
}
this.queryById('status').setHtml(`<span class="${cls}">${message}</span>`);
}
});

@ -0,0 +1,224 @@
Ext.define("Voyant.notebook.github.GitHubDialogs", {
extend: "Ext.Component",
requires: ['Voyant.notebook.github.OctokitWrapper','Voyant.notebook.github.ReposBrowser','Voyant.notebook.github.FileSaver'],
alias: "widget.githubdialogs",
config: {
repoType: 'owner',
currentFile: undefined
},
authToken: undefined,
octokitWrapper: undefined,
currentWindow: undefined,
constructor: function(config) {
config = config || {};
this.callParent(arguments);
},
initComponent: function() {
this.callParent(arguments);
},
close: function() {
if (this.currentWindow !== undefined) {
this.currentWindow.close();
this.currentWindow = undefined;
}
},
showAuthenticate: function(callback) {
const parent = this;
let authWin = undefined;
authWin = Ext.create('Ext.window.Window', {
title: 'Authenticate with GitHub',
width: 750,
height: 550,
closable: false,
layout: {
type: 'vbox',
align: 'middle',
pack: 'center'
},
items: [{
html: '<div style="margin-bottom: 10px;">You must authorize Spyral to use GitHub on your behalf.</div>'
},{
xtype: 'button',
text: 'Authorize with GitHub',
handler: function(button) {
function postMessageHandler(event) {
if (event.origin === window.location.origin && event.data === 'oauth_cookie_set') {
window.removeEventListener("message", postMessageHandler, false);
event.source.close();
parent.initOctokitWrapper();
button.up('window').close();
callback.call(parent);
}
}
window.open(Voyant.application.getBaseUrlFull()+'spyral/oauth', '_blank');
window.addEventListener("message", postMessageHandler, false);
}
}],
buttons: [{
text: 'Cancel',
handler: function() {
parent.close();
}
}]
});
authWin.show();
this.currentWindow = authWin;
},
showLoad: function() {
const parent = this;
this.authToken = this.getCookieValue('access-token');
if (this.authToken === '') {
this.showAuthenticate(this.showLoad);
return;
} else if (this.octokitWrapper === undefined) {
this.initOctokitWrapper();
}
let loadWin = undefined;
loadWin = Ext.create('Ext.window.Window', {
title: 'Load from GitHub',
width: 750,
height: 550,
closable: false,
maximizable: true,
layout: 'fit',
items: {
xtype: 'githubreposbrowser',
octokit: this.octokitWrapper,
itemId: 'repoBrowser',
listeners: {
nodeSelected: function(src, type, node) {
if (type === 'file') {
loadWin.queryById('load').setDisabled(false);
} else {
loadWin.queryById('load').setDisabled(true);
}
},
nodeDeselected: function(node) {
loadWin.queryById('load').setDisabled(true);
}
}
},
buttons: [{
text: 'Load Selected',
itemId: 'load',
disabled: true,
handler: function() {
const repoBrowser = loadWin.queryById('repoBrowser');
this.loadFile(repoBrowser.getRepoId(), repoBrowser.getPath());
},
scope: this
},{
text: 'Cancel',
handler: function() {
parent.close();
}
}]
});
loadWin.show();
this.currentWindow = loadWin;
},
showSave: function(data) {
const parent = this;
this.authToken = this.getCookieValue('access-token');
if (this.authToken === '') {
this.showAuthenticate();
return;
} else if (this.octokitWrapper === undefined) {
this.initOctokitWrapper();
}
let saveWin = undefined;
saveWin = Ext.create('Ext.window.Window', {
title: 'Save to GitHub',
width: 750,
height: 650,
closable: false,
maximizable: true,
layout: 'fit',
items: {
xtype: 'githubfilesaver',
octokit: this.octokitWrapper,
currentFile: this.getCurrentFile(),
saveData: data,
itemId: 'fileSaver',
listeners: {
formValidityChange: function(src, valid) {
saveWin.queryById('save').setDisabled(!valid);
},
fileSaved: function(src, fileData) {
parent.fireEvent('fileSaved', parent, fileData);
}
}
},
buttons: [{
text: 'Save',
itemId: 'save',
disabled: true,
handler: function() {
saveWin.queryById('fileSaver').doSave();
},
scope: this
},{
text: 'Cancel',
handler: function() {
parent.close();
parent.fireEvent('saveCancelled', parent);
}
}]
});
saveWin.show();
this.currentWindow = saveWin;
},
getCookieValue: function(cookieName) {
const re = new RegExp('[; ]'+cookieName+'=([^\\s;]*)');
const sMatch = (' '+document.cookie).match(re);
if (cookieName && sMatch) return unescape(sMatch[1]);
return '';
},
initOctokitWrapper: function() {
this.authToken = this.getCookieValue('access-token');
this.octokitWrapper = new Voyant.notebook.github.OctokitWrapper({
authToken: this.authToken
});
},
loadFileFromId: function(id) {
const parts = decodeURIComponent(id).split('/');
if (parts.length >= 3) {
const repoId = parts[0]+'/'+parts[1];
const filePath = parts.slice(2).join('/');
this.loadFile(repoId, filePath);
}
},
loadFile: function(repoId, filePath) {
this.authToken = this.getCookieValue('access-token');
if (this.authToken === '') {
this.showAuthenticate(this.loadFile.bind(this, repoId, filePath));
return;
} else if (this.octokitWrapper === undefined) {
this.initOctokitWrapper();
}
this.octokitWrapper.loadFile(repoId, filePath).then((data) => {
this.setCurrentFile(data);
this.fireEvent('fileLoaded', this, data);
});
}
})

@ -0,0 +1,188 @@
Ext.define("Voyant.notebook.github.OctokitWrapper", {
extend: "Ext.Base",
alias: "octokitwrapper",
octokit: undefined,
constructor: function(config) {
const authToken = config.authToken;
this.octokit = new Octokit({
auth: authToken,
userAgent: 'https://github.com/sgsinclair/Voyant'
});
},
getInfoForAuthenticatedUser: function() {
return this.octokit.users.getAuthenticated();
},
getReposForAuthenticatedUser: function(affiliation='owner', page=0, per_page=10) {
return this.octokit.repos.listForAuthenticatedUser({
affiliation,
page,
per_page
});
},
getReposForUser: function(owner, page=0, per_page=10) {
return this.octokit.search.repos({
q: 'user:'+owner,
page,
per_page
})
},
searchWithinRepositories: function(query, page=0, per_page=10) {
console.log(query);
},
getRepoContents: function(repoId) {
let {owner, repo} = this.parseFullName(repoId);
return this.getBranchSHAs({owner, repo, branch: 'master'}).then(function(resp) {
return this.getTreeContentsRecursively(resp);
}.bind(this));
},
getTreeContentsRecursively: function(params) {
return this.octokit.git.getTree({
owner: params.owner,
repo: params.repo,
tree_sha: params.baseTreeSHA,
recursive: 1,
headers: {
'If-None-Match': '' // cache busting
}
}).then(function (resp) {
return {
...params,
contents: this.unflattenContents(resp.data.tree),
truncated: resp.data.truncated
}
}.bind(this));
},
loadFile: function(repoId, path) {
let {owner, repo} = this.parseFullName(repoId);
let ref = 'master';
return this.octokit.repos.getContents({
owner, repo, ref, path
}).then(function(resp) {
return {
owner, repo, ref, path,
sha: resp.data.sha,
file: atob(resp.data.content)
}
}.bind(this));
},
// SAVING
doesRepoExist: function(owner, repo) {
return this.getRepoContents(owner+'/'+repo).then(function(resp) {
return true;
}.bind(this), function(err) {
console.log(err);
return false;
}.bind(this));
},
getPermissionsForUser: function(owner, repo, username) {
return this.octokit.repos.getCollaboratorPermissionLevel({
owner, repo, username
}).then(function(resp) {
return resp.data.permission;
}.bind(this), function(err) {
return 'none';
}.bind(this));
},
saveFile: async function(owner, repo, path, content, branch, message, sha) {
if (sha === undefined) {
sha = await this.getLatestFileSHA({owner, repo, branch, path})
}
return this.octokit.repos.createOrUpdateFile({owner, repo, path, content: btoa(content), branch, message, sha});
},
// UTILITIES
parseFullName: function(fullName) {
let [owner, repo] = fullName.split('/');
return {owner, repo};
},
getBranchSHAs: function(params) {
return this.octokit.repos.getBranch({
owner: params.owner,
repo: params.repo,
branch: params.branch,
headers: {
'If-None-Match': '' // cache busting
}
}).then((resp) => {
return {
...params,
baseTreeSHA: resp.data.commit.commit.tree.sha,
parentCommitSHA: resp.data.commit.sha
}
})
},
getLatestFileSHA: async function(params) {
const {owner, repo, branch, path} = params
const {data: {data: {repository: {object: result}}}} = await this.octokit.request({
method: 'POST',
url: '/graphql',
query: `{
repository(owner: "${owner}", name: "${repo}") {
object(expression: "${branch}:${path}") {
... on Blob {
oid
}
}
}
}`
}).catch(function(error) {
console.log(error);
});
const sha = result ? result.oid : undefined
return sha
},
unflattenContents: function(flatContents) {
const files = flatContents.filter(file=>file.type==='blob')
var result = {type: 'folder', name: '', path: '', contents: []}
const findSubFolder = (parentFolder, folderNameToFind) => {
const subfolder = parentFolder.contents.find(el => {
return el.type === 'folder' && el.name === folderNameToFind
})
return subfolder;
}
const addSubFolder = (newFolderName, parentFolder) => {
const newSubFolder = {type: 'folder', name: newFolderName, path: `${parentFolder.path}/${newFolderName}`, contents:[]}
parentFolder.contents.push(newSubFolder)
return newSubFolder;
}
const addFile = (newFileName, parentFolder) => {
const newFile = {type: 'file', name: newFileName, path: `${parentFolder.path}/${newFileName}`}
parentFolder.contents.push(newFile)
}
const isFile = (pathSections, currentIndex) => {
return pathSections.length - 1 == currentIndex
}
files.forEach(file=>{
const pathSections = file.path.split('/')
pathSections.reduce(function(parentFolder, pathSection, pathSectionIndex) {
const subFolder = findSubFolder(parentFolder, pathSection)
if (subFolder) {
return subFolder
} else if (isFile(pathSections, pathSectionIndex)) {
return addFile(pathSection, parentFolder)
} else {
return addSubFolder(pathSection, parentFolder)
}
}, result)
})
return result
}
});

@ -0,0 +1,263 @@
Ext.define("Voyant.notebook.github.ReposBrowser", {
extend: "Ext.container.Container",
xtype: "githubreposbrowser",
config: {
repoType: 'owner',
selectedNode: undefined,
repoId: undefined,
path: undefined
},
octokit: undefined,
constructor: function(config) {
config = config || {};
this.octokit = config.octokit;
this.callParent(arguments);
},
initComponent: function() {
Ext.apply(this, {
layout: {
type: 'hbox',
align: 'stretch',
pack: 'start'
},
items: [{
layout: {
type: 'vbox',
align: 'stretch',
pack: 'start'
},
flex: 1,
items: [{
layout: {
type: 'accordion'
},
items: [{
title: 'My Repositories',
frame: true,
items: {
xtype: 'radiogroup',
fieldLabel: 'Show repositories for which I am',
labelAlign: 'top',
layout: 'vbox',
items: [{
boxLabel: 'Owner',
name: 'repoType',
inputValue: 'owner',
checked: true
},{
boxLabel: 'Collaborator',
name: 'repoType',
inputValue: 'collaborator'
},{
boxLabel: 'Organization Member',
name: 'repoType',
inputValue: 'organization_member'
}],
listeners: {
change: function(field, newValues, oldValue) {
this.setRepoType(newValues.repoType);
this.clearTree(true);
this.octokit.getReposForAuthenticatedUser(this.getRepoType(), 0, 100).then((resp) => {
this.addReposToTree(resp.data);
},(error) => {
console.log(error);
})
},
scope: this
}
},
listeners: {
expand: function() {
this.clearTree(true);
this.octokit.getReposForAuthenticatedUser(this.getRepoType(), 0, 100).then((resp) => {
this.addReposToTree(resp.data);
},(error) => {
console.log(error);
})
},
scope: this
}
},{
title: 'Public Repositories',
frame: true,
layout: 'vbox',
items: [{
fieldLabel: 'Limit to user or organization',
labelAlign: 'top',
xtype: 'textfield'
},{
text: 'Search',
xtype: 'button',
handler: function(button) {
let repoOwner = button.prev('textfield').getValue();
if (repoOwner !== '') {
this.clearTree(true);
this.octokit.getReposForUser(repoOwner, 0, 100).then((resp) => {
this.addReposToTree(resp.data.items);
},(error) => {
console.log(error);
})
}
},
scope: this
}],
listeners: {
expand: function() {
this.clearTree();
},
scope: this
}
}]
}
// ,{
// padding: '20 0 0 0',
// items: [{
// fieldLabel: 'Search within repositories',
// labelAlign: 'top',
// xtype: 'textfield'
// },{
// xtype: 'button',
// text: 'Search',
// margin: '0 5 0 0',
// handler: function(button) {
// let query = button.prev('textfield').getValue();
// if (query !== '') {
// this.searchWithinRepositories(query);
// }
// },
// scope: this
// },{
// xtype: 'button',
// text: 'Clear',
// handler: function(button) {
// },
// scope: this
// }]
// }
]
},{
flex: 2,
layout: 'fit',
xtype: 'treepanel',
itemId: 'repoTree',
title: 'Repositories',
scrollable: true,
rootVisible: false,
viewConfig: {
emptyText: 'No results',
listeners: {
afteritemexpand: function(node, index, el) {
if (node.hasChildNodes() === false) {
switch(node.data.type) {
case 'repo':
let tr = el.querySelector('tr');
Ext.fly(tr).addCls('x-grid-tree-loading');
this.octokit.getRepoContents(node.getId()).then(function(resp) {
Ext.fly(tr).removeCls('x-grid-tree-loading');
this.addRepoContentsToNode(node, resp);
}.bind(this))
break;
case 'folder':
break;
}
}
},
itemclick: function(view, node, el) {
this.setSelectedNode(node);
this.fireEvent('nodeSelected', this, node.data.type, node);
},
scope: this
}
},
store: {
root: {
name: 'Root',
children: []
}
}
}],
listeners: {
boxready: function() {
this.down('#repoTree').setLoading(true);
this.octokit.getReposForAuthenticatedUser(this.getRepoType(), 0, 100).then((resp) => {
this.addReposToTree(resp.data);
},(error) => {
console.log(error);
})
}
}
});
this.callParent(arguments);
},
updateSelectedNode: function(node, oldValue) {
if (node !== undefined) {
let repoParent = node;
while (repoParent !== null && repoParent.data.type !== 'repo') {
repoParent = repoParent.parentNode;
}
this.setRepoId(repoParent.getId());
this.setPath(node.getId());
} else {
this.setRepoId(undefined);
this.setPath(undefined);
}
},
clearTree: function(setLoading) {
let repoTree = this.down('#repoTree');
let root = repoTree.getRootNode();
root.removeAll();
repoTree.getView().refresh();
if (setLoading) {
repoTree.setLoading(true);
}
this.setSelectedNode(undefined);
this.fireEvent('nodeDeselected', this);
},
addReposToTree: function(rawRepos) {
let repoTree = this.down('#repoTree');
repoTree.setLoading(false);
let root = repoTree.getRootNode();
let repos = rawRepos.map((repo) => {
return {
id: repo.full_name,
text: repo.full_name,
description: repo.description,
leaf: false,
type: 'repo'
}
});
root.appendChild(repos);
},
addRepoContentsToNode: function(node, octokitResponse) {
function parseContents(content) {
let nodeConfig = {
id: content.path,
text: content.name,
type: content.type,
leaf: content.type === 'file'
};
if (nodeConfig.leaf === false) {
nodeConfig.children = [];
content.contents.forEach((child) => {
nodeConfig.children.push(parseContents(child));
})
}
return nodeConfig;
}
let contents = parseContents(octokitResponse.contents);
node.appendChild(contents.children);
}
})

@ -0,0 +1,192 @@
Ext.define("Voyant.notebook.StorageDialogs", {
extend: "Ext.Component",
requires: [],
alias: "",
config: {
accessCode: undefined
},
constructor: function(config) {
config = config || {};
this.callParent(arguments);
},
initComponent: function() {
this.callParent(arguments);
},
showSave: function(data, metadata, notebookId='') {
const me = this;
const newNotebook = notebookId === '';
const title = newNotebook ? 'Save New Notebook' : 'Overwrite Existing Notebook';
Ext.create('Ext.window.Window', {
title: title,
items: [{
xtype: 'form',
width: 450,
bodyPadding: 5,
plugins: ['datatip'],
listeners: {
beforeshowtip: function(tip, config, msg) {
return !config.currentTarget.el.hasCls('x-form-invalid'); // don't show tooltip if the field is invalid because otherwise the two tips overlap
}
},
layout: 'anchor',
defaults: {
labelAlign: 'right',
labelWidth: 160,
width: 360,
inputAttrTpl: 'spellcheck="false"',
xtype: 'textfield'
},
items: [{
fieldLabel: 'Notebook ID' + (newNotebook ? ' (optional)' : ''),
name: 'notebookId',
value: notebookId,
allowBlank: true,
readOnly: !newNotebook,
tooltip: 'An ID used to identify this notebook. If left blank, one will be generated for you.',
validator: function(val) {
if (val == '') {
return true;
} else if (val.match(/^[\w-]{4,16}$/) === null) {
return 'The ID must be between 4 and 16 alphanumeric characters.'
} else {
return true;
}
}
},{
fieldLabel: 'Access Code',
name: 'accessCode',
allowBlank: false,
value: newNotebook ? this.generateAccessCode() : this.getAccessCode(),
tooltip: 'The Access Code is required to overwrite this notebook.',
validator: function(val) {
if (val.match(/^[\w-]{4,16}$/) === null) {
return 'The access code must be between 4 and 16 alphanumeric characters.'
} else {
return true;
}
}
},{
fieldLabel: 'Email (optional)',
name: 'email',
allowBlank: true,
vtype: 'email',
hidden: !newNotebook,
tooltip: 'An email will be sent to this address with the Notebook URL and Access Code.'
}]
}],
buttons: [{
text: 'Cancel',
ui: 'default-toolbar',
handler: function() {
this.up('window').close();
me.fireEvent('saveCancelled', me);
}
}, " ", {
text: 'Save',
handler: function(button) {
const win = button.up('window');
const form = win.down('form').getForm();
if (form.isValid()) {
const values = form.getValues();
values.data = data;
values.metadata = metadata;
if (newNotebook && values.notebookId !== '') {
me.doesNotebookIdExist(values.notebookId).then(function(exists) {
if (exists) {
form.findField('notebookId').markInvalid('That Notebook ID already exists.');
} else {
me.doSave(values);
win.close();
}
});
} else {
button.setDisabled(true);
me.doSave(values).then(function(didSave) {
button.setDisabled(false);
if (didSave) {
win.close();
} else {
form.findField('accessCode').markInvalid('Invalid access code.');
}
});
}
}
}
}],
listeners: {
close: function() {
me.fireEvent('close', me); // need an additional close event in case the user uses the close tool / esc button
}
}
}).show();
},
doesNotebookIdExist: function(id) {
const dfd = new Ext.Deferred();
Spyral.Load.trombone({
tool: 'notebook.GitNotebookManager',
action: 'exists',
id: id,
noCache: 1
}).then(function(json) {
var exists = json.notebook.data === 'true';
dfd.resolve(exists);
}).catch(function(err) {
console.log(err);
});
return dfd.promise;
},
doSave: function({notebookId, accessCode, email, data, metadata}) {
const me = this;
metadata.id = notebookId;
return Spyral.Load.trombone({
tool: 'notebook.GitNotebookManager',
action: 'save',
id: notebookId,
accessCode: accessCode,
email: email,
data: data,
metadata: JSON.stringify(metadata)
}).then(function(json) {
if (json.notebook.data !== 'true') {
return false;
} else {
me.setAccessCode(accessCode);
const notebookId = json.notebook.id;
me.fireEvent('fileSaved', me, notebookId);
return true;
}
}).catch(function(err) {
me.fireEvent('fileSaved', me, null);
return false;
});
},
generateAccessCode: function() {
const alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
let code = '';
while (code.length < 6) {
if (Math.random() < .3) {
code += Math.floor(Math.random()*9);
} else {
let letter = alphabet[Math.floor(Math.random()*alphabet.length)];
if (Math.random() < .5) {
letter = letter.toUpperCase();
}
code += letter;
}
}
return code;
},
reset: function() {
this.setAccessCode(undefined);
}
})

@ -0,0 +1,157 @@
Ext.define("Voyant.notebook.util.Embed", {
transferable: ['embed'],
embed: function() { // this is for instances
embed.apply(this, arguments);
},
constructor: function(config) {
var me = this;
},
statics: {
i18n: {},
api: {
embeddedParameters: undefined,
embeddedConfig: undefined
},
embed: function(cmp, config) {
if (this.then) {
this.then(function(embedded) {
embed.call(embedded, cmp, config)
})
} else if (Ext.isArray(cmp)) {
Voyant.notebook.util.Show.SINGLE_LINE_MODE=true;
show("<table><tr>");
cmp.forEach(function(embeddable) {
show("<td>");
if (Ext.isArray(embeddable)) {
if (embeddable[0].embeddable) {
embeddable[0].embed.apply(embeddable[0], embeddable.slice(1))
} else {
embed.apply(this, embeddable)
}
} else {
embed.apply(this, embeddable);
}
show("</td>")
})
// for (var i=0; i<arguments.length; i++) {
// var unit = arguments[i];
// show("<td>")
// unit[0].embed.call(unit[0], unit[1], unit[2]);
// show("</td>")
// }
show("</tr></table>")
Voyant.notebook.util.Show.SINGLE_LINE_MODE=false;
return
} else {
// use the default (first) embeddable panel if no panel is specified
if (this.embeddable && (!cmp || Ext.isObject(cmp))) {
// if the first argument is an object, use it as config instead
if (Ext.isObject(cmp)) {config = cmp;}
cmp = this.embeddable[0];
}
if (Ext.isString(cmp)) {
cmp = Ext.ClassManager.getByAlias('widget.'+cmp.toLowerCase()) || Ext.ClassManager.get(cmp);
}
var isEmbedded = false;
if (Ext.isFunction(cmp)) {
var name = cmp.getName();
if (this.embeddable && Ext.Array.each(this.embeddable, function(item) {
if (item==name) {
config = config || {};
var embeddedParams = {};
for (key in Ext.ClassManager.get(Ext.getClassName(cmp)).api) {
if (key in config) {
embeddedParams[key] = config[key]
}
}
if (!embeddedParams.corpus) {
if (Ext.getClassName(this)=='Voyant.data.model.Corpus') {
embeddedParams.corpus = this.getId();
} else if (this.getCorpus) {
var corpus = this.getCorpus();
if (corpus) {
embeddedParams.corpus = this.getCorpus().getId();
}
}
}
Ext.applyIf(config, {
style: 'width: '+(config.width || '90%') + (Ext.isNumber(config.width) ? 'px' : '')+
'; height: '+(config.height || '400px') + (Ext.isNumber(config.height) ? 'px' : '')
});
delete config.width;
delete config.height;
var corpus = embeddedParams.corpus;
delete embeddedParams.corpus;
Ext.applyIf(embeddedParams, Voyant.application.getModifiedApiParams());
var embeddedConfigParamEncodded = Ext.encode(embeddedParams);
var embeddedConfigParam = encodeURIComponent(embeddedConfigParamEncodded);
var iframeId = Ext.id();
var url = Voyant.application.getBaseUrlFull()+"tool/"+name.substring(name.lastIndexOf(".")+1)+'/?';
if (true || embeddedConfigParam.length>1800) {
show('<iframe style="'+config.style+'" id="'+iframeId+'" name="'+iframeId+'"></iframe>');
var dfd = Voyant.application.getDeferred(this);
Ext.Ajax.request({
url: Voyant.application.getTromboneUrl(),
params: {
tool: 'resource.StoredResource',
storeResource: embeddedConfigParam
}
}).then(function(response) {
var json = Ext.util.JSON.decode(response.responseText);
var params = {
minimal: true,
embeddedApiId: json.storedResource.id
}
if (corpus) {
params.corpus = corpus;
}
Ext.applyIf(params, Voyant.application.getModifiedApiParams());
document.getElementById(iframeId).setAttribute("src",url+Ext.Object.toQueryString(params));
dfd.resolve();
}).otherwise(function(response) {
showError(response);
dfd.reject();
})
} else {
show('<iframe src="'+url+embeddedConfigParam+'" style="'+config.style+'" id="'+iframeId+'" name="'+iframeId+'"></iframe>');
}
isEmbedded = true;
return false;
}
}, this)===true) {
Voyant.notebook.util.Embed.showWidgetNotRecognized.call(this);
}
if (!isEmbedded) {
var embedded = Ext.create(cmp, config);
embedded.embed(config);
isEmbedded = true;
}
}
if (!isEmbedded) {
Voyant.notebook.util.Embed.showWidgetNotRecognized.call(this);
}
}
},
showWidgetNotRecognized: function() {
var msg = Voyant.notebook.util.Embed.i18n.widgetNotRecognized;
if (this.embeddable) {
msg += Voyant.notebook.util.Embed.i18n.tryWidget+'<ul>'+this.embeddable.map(function(cmp) {
var widget = cmp.substring(cmp.lastIndexOf(".")+1).toLowerCase()
return "\"<a href='../../docs/#!/guide/"+widget+"' target='voyantdocs'>"+widget+"</a>\""
}).join(", ")+"</ul>"
}
showError(msg)
}
}
})
embed = Voyant.notebook.util.Embed.embed

@ -0,0 +1,93 @@
Ext.define("Voyant.notebook.util.Show", {
transferable: ['show'],
/**
* Shows a one-line summary of this object. For example, for a corpus:
*
* new Corpus("Hello World!").show(true);
*
* @param {boolean} [withID] Includes the corpus ID in parentheses at the end, if true.
*/
show: function(len) { // this is for instances
if (this.then) {
return Voyant.application.getDeferredNestedPromise(this, arguments);
} else {
show.call(this, this.getString ? this.getString(len) : this.toString(), !this.getString && Ext.isNumber(len) ? len : undefined);
}
},
statics: {
show: function(contents, len) {
if (this.then) {
var arg = contents;
this.then(function(val) {
show.call(val, val, arg);
})
} else {
if (contents === undefined) {
return;
}
if (Ext.isArray(contents)) {
var allContents = "";
contents.forEach(function(content) {
allContents += content.getString ? content.getString() : content.toString();
});
contents = allContents;
} else if (Ext.isString(this) || this instanceof String) {
if (Ext.isNumber(contents)) {len = contents;}
contents = this;
}
if (contents.then) { // check if we currently have a promise
return contents.then(function(text) {show(text, len)})
}
if (contents.toHtml) {contents=contents.toHtml()}
else if (contents.getString) {contents=contents.getString()}
else if (contents.toString) {contents=contents.toString()}
// contents = contents.getString ? contents.getString() : contents.toString();
if (contents.then) { // check again to see if we have a promise (like from toString())
contents.then(function(text) {show(text, len)})
} else {
if (len && Ext.isNumber(len)) {contents = contents.substring(0,len)}
if (Voyant.notebook.util.Show.SINGLE_LINE_MODE==false) {contents="<div class='"+Voyant.notebook.util.Show.MODE+"'>"+contents+"</div>";}
Voyant.notebook.util.Show.TARGET.insertHtml('beforeEnd',contents);
}
}
},
showError: function(error, more) {
var mode = Voyant.notebook.util.Show.MODE;
Voyant.notebook.util.Show.MODE='error';
if (this instanceof Voyant.util.ResponseError) {
error = this;
}
if (error instanceof Voyant.util.ResponseError) {
if (console) {console.error(error.getResponse())}
more = error.getResponse().responseText
error = error.getMsg();
}
else {
if (error !== undefined && error.stack && !more) {more=error.stack}
if (more && Ext.isString(more)===false) {more=more.toString()}
}
if (console) {console.error(error)}
if (more) {
if (console) {console.error(more);}
error="<h3>"+error.toString()+"</h3><pre>"+Ext.String.htmlEncode(more)+'</pre>';
}
show(error);
Voyant.notebook.util.Show.MODE = mode;
},
TARGET : null,
MODE: 'info',
SINGLE_LINE_MODE : false
}
});
String.prototype.show = Voyant.notebook.util.Show.show;
var show = Voyant.notebook.util.Show.show;
var showError = Voyant.notebook.util.Show.showError;

@ -0,0 +1,451 @@
// assuming Bubblelines library is loaded by containing page (via voyant.jsp)
Ext.define('Voyant.panel.Bubblelines', {
extend: 'Ext.panel.Panel',
mixins: ['Voyant.panel.Panel'],
alias: 'widget.bubblelines',
statics: {
i18n: {
},
api: {
/**
* @property bins How many "bins" to separate a document into.
* @type Integer
* @private
*/
bins: 50,
/**
* @property query A string to search for in a document.
* @type String
* @private
*/
query: null,
/**
* @property stopList The stop list to use to filter results.
* Choose from a pre-defined list, or enter a comma separated list of words, or enter an URL to a list of stop words in plain text (one per line).
* @type String
* @private
*/
stopList: 'auto',
/**
* @property docId The document ID to restrict results to.
* @type String
* @private
*/
docId: undefined,
/**
* @property docIndex The document index to restrict results to.
* @type Integer
* @private
*/
docIndex: undefined,
/**
* @property maxDocs The maximum number of documents to show.
* @type Integer
* @private
*/
maxDocs: 50
},
glyph: 'xf06e@FontAwesome'
},
config: {
bubblelines: undefined,
termStore: undefined,
docTermStore: undefined,
selectedDocs: undefined,
options: [{xtype: 'stoplistoption'},{xtype: 'categoriesoption'},{xtype: 'colorpaletteoption'}]
},
termTpl: new Ext.XTemplate(
'<tpl for=".">',
'<div class="term" style="color: rgb({color});float: left;padding: 3px;margin: 2px;">{term}</div>',
'</tpl>'
),
constructor: function() {
this.callParent(arguments);
this.mixins['Voyant.panel.Panel'].constructor.apply(this, arguments);
this.on('loadedCorpus', function(src, corpus) {
this.setDocTermStore(corpus.getDocumentTerms({
proxy: {
extraParams: {
withDistributions: 'raw',
withPositions: true
}
},
listeners: {
load: function(store, records, successful, options) {
records.forEach(function(record) {
var termData = this.processTerms(record);
var docId = record.get('docId');
var term = record.get('term');
var termObj = {};
termObj[term] = termData;
this.getBubblelines().addTermsToDoc(termObj, docId);
}, this);
this.getBubblelines().doBubblelinesLayout();
},
scope: this
}
}));
if (this.isVisible() && this.getBubblelines()) {
this.initLoad();
}
}, this);
this.on('activate', function() { // load after tab activate (if we're in a tab panel)
if (this.getCorpus()) {
Ext.Function.defer(this.initLoad, 100, this);
}
}, this);
this.on('query', function(src, query) {
if (query !== undefined && query != '') {
this.getDocTermsFromQuery(query);
}
}, this);
this.on('documentsSelected', function(src, docIds) {
this.setApiParam('docId', docIds);
this.getBubblelines().cache.each(function(d) {
d.hidden = docIds.indexOf(d.id) === -1;
});
this.getBubblelines().drawGraph();
}, this);
this.on('termsClicked', function(src, terms) {
if (src !== this) {
var queryTerms = [];
terms.forEach(function(term) {
if (Ext.isString(term)) {queryTerms.push(term);}
else if (term.term) {queryTerms.push(term.term);}
else if (term.getTerm) {queryTerms.push(term.getTerm());}
});
this.getDocTermsFromQuery(queryTerms);
}
}, this);
this.on('documentTermsClicked', function(src, terms) {
var queryTerms = [];
terms.forEach(function(term) {
if (term.getTerm()) {queryTerms.push(term.getTerm());}
});
this.getDocTermsFromQuery(queryTerms);
}, this);
this.down('#granularity').setValue(parseInt(this.getApiParam('bins')));
},
initComponent: function() {
this.setTermStore(Ext.create('Ext.data.ArrayStore', {
fields: ['term', 'color'],
listeners: {
load: function(store, records, successful, options) {
var termsView = this.down('#termsView');
for (var i = 0; i < records.length; i++) {
var r = records[i];
termsView.select(r, true);
}
},
scope: this
}
}));
Ext.apply(this, {
title: this.localize('title'),
dockedItems: [{
dock: 'bottom',
xtype: 'toolbar',
overflowHandler: 'scroller',
items: [{
xtype: 'querysearchfield'
},{
text: this.localize('clearTerms'),
glyph: 'xf014@FontAwesome',
handler: function() {
this.down('#termsView').getSelectionModel().deselectAll(true);
this.getTermStore().removeAll();
this.setApiParams({query: null});
this.getBubblelines().removeAllTerms();
this.getBubblelines().drawGraph();
},
scope: this
},{
xtype: 'documentselectorbutton'
},{
xtype: 'slider',
itemId: 'granularity',
fieldLabel: this.localize('granularity'),
labelAlign: 'right',
labelWidth: 70,
width: 150,
increment: 10,
minValue: 10,
maxValue: 300,
listeners: {
changecomplete: function(slider, newvalue) {
this.setApiParams({bins: newvalue});
this.getBubblelines().bubbleSpacing = newvalue;
this.reloadTermsData();
},
scope: this
}
},{
xtype: 'checkbox',
boxLabel: this.localize('separateLines'),
boxLabelAlign: 'before',
checked: false,
handler: function(checkbox, checked) {
this.getBubblelines().SEPARATE_LINES_FOR_TERMS = checked;
this.getBubblelines().lastClickedBubbles = {};
this.getBubblelines().setCanvasHeight();
this.getBubblelines().drawGraph();
},
scope: this
}]
}],
border: false,
layout: 'fit',
items: {
layout: {
type: 'vbox',
align: 'stretch'
},
defaults: {border: false},
items: [{
height: 30,
itemId: 'termsView',
xtype: 'dataview',
store: this.getTermStore(),
tpl: this.termTpl,
itemSelector: 'div.term',
overItemCls: 'over',
selectedItemCls: 'selected',
selectionModel: {
mode: 'SIMPLE'
},
// cls: 'selected', // default selected
focusCls: '',
listeners: {
beforeitemclick: function(dv, record, item, index, event, opts) {
event.preventDefault();
event.stopPropagation();
dv.fireEvent('itemcontextmenu', dv, record, item, index, event, opts);
return false;
},
beforecontainerclick: function() {
// cancel deselect all
event.preventDefault();
event.stopPropagation();
return false;
},
selectionchange: function(selModel, selections) {
var dv = this.down('#termsView');
var terms = [];
dv.getStore().each(function(r) {
if (selections.indexOf(r) !== -1) {
terms.push(r.get('term'));
Ext.fly(dv.getNodeByRecord(r)).removeCls('unselected').addCls('selected');
} else {
Ext.fly(dv.getNodeByRecord(r)).removeCls('selected').addCls('unselected');
}
});
for (var index in this.getBubblelines().lastClickedBubbles) {
var lcTerms = this.getBubblelines().lastClickedBubbles[index];
for (var term in lcTerms) {
if (terms.indexOf(term) == -1) {
delete this.getBubblelines().lastClickedBubbles[index][term];
}
}
}
this.getBubblelines().termsFilter = terms;
this.getBubblelines().setCanvasHeight();
this.getBubblelines().drawGraph();
},
itemcontextmenu: function(dv, record, el, index, event) {
event.preventDefault();
event.stopPropagation();
var isSelected = dv.isSelected(el);
var menu = new Ext.menu.Menu({
floating: true,
items: [{
text: isSelected ? this.localize('hideTerm') : this.localize('showTerm'),
handler: function() {
if (isSelected) {
dv.deselect(index);
} else {
dv.select(index, true);
}
},
scope: this
},{
text: this.localize('removeTerm'),
handler: function() {
dv.deselect(index);
var term = this.getTermStore().getAt(index).get('term');
this.getTermStore().removeAt(index);
dv.refresh();
this.getBubblelines().removeTerm(term);
this.getBubblelines().setCanvasHeight();
this.getBubblelines().drawGraph();
},
scope: this
}]
});
menu.showAt(event.getXY());
},
scope: this
}
},{
flex: 1,
xtype: 'container',
autoEl: 'div',
itemId: 'canvasParent',
layout: 'fit',
overflowY: 'auto',
overflowX: 'hidden'
}],
listeners: {
render: function(component) {
var canvasParent = this.down('#canvasParent');
this.setBubblelines(new Bubblelines({
container: canvasParent,
clickHandler: this.bubbleClickHandler.bind(this)
}));
this.getBubblelines().bubbleSpacing = parseInt(this.getApiParam('bins'));
},
afterlayout: function(container) {
if (this.getBubblelines().initialized === false) {
this.getBubblelines().initializeCanvas();
}
},
resize: function(cnt, width, height) {
this.getBubblelines().doBubblelinesLayout();
},
scope: this
}
}
});
this.callParent(arguments);
},
initLoad: function() {
// get doc info
var docIds = [];
this.getCorpus().getDocuments().each(function(doc, index, total) {
var inLimit = index < this.getApiParam('maxDocs');
this.getBubblelines().addDocToCache({
id: doc.getId(),
index: doc.getIndex(),
title: doc.getShortTitle(),
totalTokens: doc.get('tokensCount-lexical'),
terms: {},
hidden: !inLimit
});
if (inLimit) {
docIds.push(doc.getId());
}
}, this);
this.setApiParam('docId', docIds);
// get top terms in corpus
this.getCorpus().getCorpusTerms({autoload: false}).load({
callback: function(records, operation, success) {
var query = [];
records.forEach(function(record, index) {
query.push(record.get('term'));
}, this);
this.getDocTermsFromQuery(query);
},
scope: this,
params: {
limit: this.getApiParam('query') ? undefined : 5,
stopList: this.getApiParams('stopList'),
query: this.getApiParam('query')
}
});
},
/**
* Get the results for the query(s) for each of the corpus documents.
* @param query {String|Array}
*/
getDocTermsFromQuery: function(query) {
if (query) {this.setApiParam('query', query);} // make sure it's set for subsequent calls
if (this.getCorpus() && this.isVisible()) {
this.getDocTermStore().load({params: this.getApiParams()});
}
},
reloadTermsData: function() {
var terms = [];
for (var term in this.getBubblelines().currentTerms) {
terms.push(term);
}
this.getDocTermsFromQuery(terms);
},
filterDocuments: function() {
var docIds = this.getApiParam('docId');
if (docIds == '') {
docIds = [];
this.getCorpus().getDocuments().each(function(item, index) {
docIds.push(item.getId());
});
this.setApiParams({docId: docIds});
}
if (typeof docIds == 'string') docIds = [docIds];
if (docIds == null) {
this.setSelectedDocs(this.getCorpus().getDocuments().clone());
var count = this.getSelectedDocs().getCount();
if (count > 10) {
for (var i = 10; i < count; i++) {
this.getSelectedDocs().removeAt(10);
}
}
docIds = [];
this.getSelectedDocs().eachKey(function(docId, doc) {
docIds.push(docId);
}, this);
this.setApiParams({docId: docIds});
} else {
this.setSelectedDocs(this.getCorpus().getDocuments().filterBy(function(doc, docId) {
return docIds.indexOf(docId) != -1;
}, this));
}
},
processTerms: function(termRecord) {
var termObj;
var term = termRecord.get('term');
var rawFreq = termRecord.get('rawFreq');
var positions = termRecord.get('positions');
if (rawFreq > 0) {
var color = this.getApplication().getColorForTerm(term);
if (this.getTermStore().find('term', term) === -1) {
this.getTermStore().loadData([[term, color]], true);
var index = this.getTermStore().find('term', term);
this.down('#termsView').select(index, true); // manually select since the store's load listener isn't triggered
}
var distributions = termRecord.get('distributions');
termObj = {positions: positions, distributions: distributions, rawFreq: rawFreq, color: color};
} else {
termObj = false;
}
return termObj;
},
bubbleClickHandler: function(data) {
this.getApplication().dispatchEvent('termsClicked', this, data);
}
});

@ -0,0 +1,41 @@
Ext.define('Voyant.panel.BubblelinesSet', {
extend: 'Ext.panel.Panel',
requires: ['Voyant.panel.Bubblelines','Voyant.panel.Contexts', 'Voyant.panel.Reader'],
mixins: ['Voyant.panel.Panel'],
alias: 'widget.bubblelinesset',
statics: {
i18n: {
},
glyph: 'xf17a@FontAwesome'
},
constructor: function(config) {
this.callParent(arguments);
this.mixins['Voyant.panel.Panel'].constructor.apply(this, arguments);
},
layout: 'vbox',
header: false,
items: [{
width: '100%',
height: '100%',
xtype: 'bubblelines',
flex: 5
},{
width: '100%',
height: '100%',
split: {width: 5},
layout: 'hbox',
flex: 4,
defaults: {
width: '100%',
height: '100%',
flex: 1,
frame: true,
border: true
},
items: [{
xtype: 'contexts'
},{
xtype: 'reader'
}]
}]
})

@ -0,0 +1,202 @@
// assuming Bubblelines library is loaded by containing page (via voyant.jsp)
Ext.define('Voyant.panel.Bubbles', {
extend: 'Ext.panel.Panel',
mixins: ['Voyant.panel.Panel'],
alias: 'widget.bubbles',
statics: {
i18n: {
},
api: {
/**
* @property stopList The stop list to use to filter results.
* Choose from a pre-defined list, or enter a comma separated list of words, or enter an URL to a list of stop words in plain text (one per line).
* @type String
* @private
*/
stopList: 'auto',
docIndex: 0,
limit: 100,
audio: false,
speed: 30
},
glyph: 'xf06e@FontAwesome'
},
config: {
options: {xtype: 'stoplistoption'},
audio: false
},
constructor: function() {
this.mixins['Voyant.util.Localization'].constructor.apply(this, arguments);
Ext.apply(this, {
title: this.localize('title'),
html: '<canvas style="width: 100%; height: 100%"></canvas>',
dockedItems: [{
dock: 'bottom',
xtype: 'toolbar',
overflowHandler: 'scroller',
items: [{
xtype: 'documentselectorbutton',
singleSelect: true
},{
xtype: 'slider',
fieldLabel: this.localize('speed'),
labelAlign: 'right',
labelWidth: 40,
width: 100,
increment: 1,
minValue: 1,
maxValue: 60,
value: 30,
listeners: {
render: function(cmp) {
cmp.setValue(parseInt(this.getApiParam("speed")));
if (this.bubbles) {this.bubbles.frameRate(cmp.getValue())}
this.setAudio(cmp.getValue());
Ext.tip.QuickTipManager.register({
target: cmp.getEl(),
text: this.localize('speedTip')
});
},
beforedestroy: function(cmp) {
Ext.tip.QuickTipManager.unregister(cmp.getEl());
},
changecomplete: function(cmp, val) {
this.setApiParam('speed', val);
if (this.bubbles) {this.bubbles.frameRate(val)}
},
scope: this
}
},{
xtype: 'checkbox',
boxLabel: this.localize('sound'),
listeners: {
render: function(cmp) {
cmp.setValue(this.getApiParam("audio")===true || this.getApiParam("audio")=="true");
this.setAudio(cmp.getValue());
Ext.tip.QuickTipManager.register({
target: cmp.getEl(),
text: this.localize('soundTip')
});
},
beforedestroy: function(cmp) {
Ext.tip.QuickTipManager.unregister(cmp.getEl());
},
change: function(cmp, val) {
this.setApiParam('audio', val);
this.setAudio(val);
},
scope: this
}
},{xtype: 'tbfill'}, {
xtype: 'tbtext',
html: this.localize('adaptation') //https://www.m-i-b.com.ar/letters/en/
}]
}]
});
this.callParent(arguments);
this.mixins['Voyant.panel.Panel'].constructor.apply(this, arguments);
this.on('loadedCorpus', function(src, corpus) {
var canvas = this.getTargetEl().dom.querySelector("canvas");
var me = this;
Ext.Ajax.request({
url: this.getBaseUrl()+'resources/voyant/current/bubbles/bubbles.pjs'
}).then(function(data) {
var canvas = me.getTargetEl().dom.querySelector("canvas");
me.bubbles = new Processing(canvas, data.responseText);
me.bubbles.size(me.getTargetEl().getWidth(),me.getTargetEl().getHeight());
me.bubbles.frameRate(me.getApiParam('speed'));
me.bubbles.bindJavascript(me);
me.bubbles.noLoop();
me.loadDocument();
})
}, this);
this.on("resize", function() {
if (this.bubbles) {
this.bubbles.size(this.body.getWidth(),this.body.getHeight());
}
});
this.on("documentselected", function(src, doc) {
this.setApiParam('docIndex', this.getCorpus().getDocument(doc).getIndex());
this.loadDocument();
})
},
setAudio: function(val) {
if (this.gainNode) {this.gainNode.gain.value=val ? 1 : 0;}
this.callParent(arguments)
},
handleCurrentTerm: function(term) {
if (this.oscillator) {this.oscillator.frequency.value = this.terms[term] ? parseInt((this.terms[term]-this.minFreq) * 2000 / (this.maxFreq-this.minFreq)) : 0;}
},
handleDocFinished: function() {
if (this.gainNode) {this.gainNode.gain.value = 0;}
var index = parseInt(this.getApiParam('docIndex'));
if (index+1<this.getCorpus().getDocumentsCount()) {
this.setApiParam('docIndex', index+1);
this.loadDocument();
}
},
loadDocument: function() {
var me = this, doc = this.getCorpus().getDocument(parseInt(this.getApiParam('docIndex')));
// if we're not in a tab panel, set the document title as part of the header
if (!this.up("tabpanel")) {
this.setTitle(this.localize('title') + " <span class='subtitle'>"+doc.getFullLabel()+"</span>");
}
doc.loadDocumentTerms(Ext.apply(this.getApiParams(["stopList"]), {
limit: 100
})).then(function(documentTerms) {
me.terms = {};
documentTerms.each(function(documentTerm) {
me.terms[documentTerm.getTerm()] = documentTerm.getRawFreq();
})
var values = Object.keys(me.terms).map(function(k){return me.terms[k]});
me.minFreq = Ext.Array.min(values);
me.maxFreq = Ext.Array.max(values);
me.getCorpus().loadTokens({whitelist: Object.keys(me.terms), noOthers: true, limit: 0, docIndex: me.getApiParam('docIndex')}).then(function(tokens) {
var words = [];
tokens.each(function(token) {
words.push(token.getTerm().toLowerCase());
})
me.bubbles.setLines([doc.getTitle(),words.join(" ")]);
me.bubbles.loop();
me.oscillator.frequency.value = 150;
me.gainNode.gain.value = me.getAudio() ? 1 : 0;
})
})
},
initComponent: function() {
// make sure to load script
Ext.Loader.loadScript(this.getBaseUrl()+"resources/processingjs/processing.min.js");
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
this.oscillator = audioCtx.createOscillator();
this.gainNode = audioCtx.createGain();
this.oscillator.connect(this.gainNode);
this.gainNode.connect(audioCtx.destination);
this.oscillator.frequency.value = 0;
this.oscillator.start();
this.gainNode.gain.value = 0;
this.callParent(arguments);
}
});

@ -0,0 +1,550 @@
Ext.define('Voyant.panel.Catalogue', {
extend: 'Ext.panel.Panel',
requires: ['Voyant.widget.Facet'],
mixins: ['Voyant.panel.Panel','Voyant.util.Downloadable'],
alias: 'widget.catalogue',
statics: {
i18n: {
},
api: {
config: undefined,
stopList: 'auto',
facet: ['facet.title','facet.author','facet.language'],
title: undefined,
splash: undefined,
reader: "reader"
},
glyph: 'xf1ea@FontAwesome'
},
config: {
facets: {},
matchingDocIds: [],
customResultsHtml: undefined
},
constructor: function(config) {
config = config || {};
this.mixins['Voyant.util.Api'].constructor.apply(this, arguments); // we need api
Ext.apply(this, {
title: this.localize('title'),
layout: 'hbox',
items: [
{
layout: 'vbox',
height: '100%',
align: 'stretch',
itemId: 'facets',
defaults: {
width: 250,
flex: 1,
xtype: 'facet',
margin: 5,
border: true,
frame: true,
includeTools: {
close: {
type: 'close',
tooltip: this.localize('closeFacetTip'),
callback: function(facetCmp) {
delete this.facets[facetCmp.facet]; // remove from facets map
facetCmp.destroy(); // remove this facet
this.updateResults();
},
scope: this
},
add: {
type: 'plus',
tooltip: this.localize('plusFacetTip'),
callback: function() {
this.addFacet();
},
scope: this
}
}
},
items: []
},
{
xtype: 'panel',
html: config.customResultsHtml || '',
flex: 1,
itemId: 'results',
height: '100%',
align: 'stretch',
scrollable: true,
margin: 5,
getCorpus: function() { // for query search field
return this.findParentByType('panel').getCorpus();
},
listeners: {
query: function(src, query) {
this.findParentByType('panel').updateResults(Ext.isString(query) ? [query] : query)
}
},
dockedItems: [{
dock: 'bottom',
xtype: 'toolbar',
overflowHandler: 'scroller',
items: [{
itemId: 'sendToVoyant',
text: this.localize('sendToVoyantButton'),
disabled: true,
handler: function() {
this.mask(this.localize("exportInProgress"));
var catalogue = this;
Ext.Ajax.request({
url: this.getApplication().getTromboneUrl(),
params: {
corpus: this.getCorpus().getId(),
tool: 'corpus.CorpusManager',
keepDocuments: true,
docId: this.getMatchingDocIds()
},
success: function(response, opts) {
catalogue.unmask();
var json = Ext.JSON.decode(response.responseText);
var url = catalogue.getBaseUrl()+"?corpus="+json.corpus.id;
catalogue.openUrl(url);
},
failure: function(response, opts) {
catalogue.unmask();
me.showResponseError("Unable to export corpus: "+catalogue.getCorpus().getId(), response);
}
})
},
scope: this
},{
itemId: 'export',
text: this.localize('downloadButton'),
disabled: true,
handler: function() {
this.mask(this.localize("exportInProgress"));
var catalogue = this;
Ext.Ajax.request({
url: this.getApplication().getTromboneUrl(),
params: {
corpus: this.getCorpus().getId(),
tool: 'corpus.CorpusManager',
keepDocuments: true,
docId: this.getMatchingDocIds()
},
success: function(response, opts) {
catalogue.unmask();
var json = Ext.JSON.decode(response.responseText);
catalogue.downloadFromCorpusId(json.corpus.id);
},
failure: function(response, opts) {
catalogue.unmask();
me.showResponseError("Unable to export corpus: "+catalogue.getCorpus().getId(), response);
}
})
},
scope: this
},{
xtype: 'querysearchfield',
width: 200,
flex: 1
},{
itemId: 'status',
xtype: 'tbtext'
}]
}]
}, {
xtype: this.getApiParam("reader"),
flex: 1,
height: '100%',
align: 'stretch',
header: false
}]
});
this.callParent(arguments);
this.mixins['Voyant.panel.Panel'].constructor.apply(this, arguments);
// create a listener for corpus loading (defined here, in case we need to load it next)
this.on('loadedCorpus', function(src, corpus) {
this.queryById('status').update(new Ext.XTemplate(this.localize('noMatches')).apply([corpus.getDocumentsCount()]))
if (!this.getCustomResultsHtml()) {
if (this.getApiParam("splash")) {
this.setCustomResultsHtml(this.getApiParam("splash"));
this.updateResults();
return;
}
this.setCustomResultsHtml(new Ext.XTemplate(this.localize('noMatches')).apply([corpus.getDocumentsCount()]));
this.updateResults();
Ext.Ajax.request({
url: this.getTromboneUrl(),
params: {
tool: 'resource.StoredResource',
verifyResourceId: 'customhtml-'+corpus.getAliasOrId()
},
success: function(response, req) {
var json = Ext.util.JSON.decode(response.responseText);
if (json && json.storedResource && json.storedResource.id) {
Ext.Ajax.request({
url: this.getTromboneUrl(),
params: {
tool: 'resource.StoredResource',
retrieveResourceId: 'customhtml-'+corpus.getAliasOrId()
},
success: function(response, req) {
var json = Ext.util.JSON.decode(response.responseText);
if (json && json.storedResource && json.storedResource.resource) {
this.setCustomResultsHtml(json.storedResource.resource);
this.updateResults()
}
},
scope: this
})
}
},
scope: this
})
}
});
this.on('afterrender', function(panel) {
var facetsCmp = this.queryById('facets');
this.addFacet({
facet: 'lexical',
includeTools: {add: {
type: 'plus',
tooltip: this.localize('plusFacetTip'),
callback: function() {
this.addFacet();
},
scope: this
}},
store: new Voyant.data.store.CorpusTerms({
parentPanel: this,
proxy: {
extraParams: {
stopList: this.getApiParam("stopList")
}
}
})
}, facetsCmp)
var facets = this.getApiParam('facet');
if (Ext.isString(facets)) {facets = facets.split(",")}
facets.forEach(function(facet) {
this.addFacet({facet: facet}, facetsCmp)
/*
facetCmp.getSelectionModel().on('selectionchange', function(model, selected) {
var labels = [];
selected.forEach(function(model) {
labels.push({facet: model.getFacet(), label: model.getLabel()})
})
panel.getFacets()[facet] = labels;
panel.updateResults();
})
facetCmp.on('query', function(model, selected) {
panel.getFacets()[facetCmp.facet] = [];
panel.updateResults();
})*/
}, this);
/*
facetCmp.getSelectionModel().on('selectionchange', function(model, selected) {
var labels = [];
selected.forEach(function(model) {
labels.push({facet: 'lexical', label: model.getTerm()})
})
panel.getFacets()['lexical'] = labels;
panel.updateResults();
})*/
var title = this.getApiParam("title");
if (title) {this.setTitle(title)}
});
},
addFacet: function(config, facetsCmp) {
if (!config) {
// select first, then add
return this.selectFacet(function(facet) {
this.addFacet({facet: facet})
})
}
facetsCmp = facetsCmp || this.queryById('facets');
var facet = config.facet,
itemTpl = '<span style="font-size: smaller;">(<span class="info-tip" data-qtip="'+this.localize('matchingDocuments')+'">{inDocumentsCount}</span>)</span> {term}'+'<span style="font-size: smaller;"> (<span class="info-tip" data-qtip="'+this.localize('rawFreqs')+'">{rawFreq}</span>)</span>'
var title = this.localize(facet+"Title");
if (title=="["+facet+"Title]") {
title = facet.replace(/^facet\./,"").replace(/^extra./,"");
}
var matchingDocumentsLabel = this.localize('matchingDocuments');
Ext.applyIf(config, {
title: title,
collapsible: true,
facet: facet,
columns: [{
renderer: function(value, metaData, record) {
return '<span style="font-size: smaller;">(<span class="info-tip" data-qtip="'+this.localize('matchingDocuments')+'">'+record.getInDocumentsCount()+"</span>) </span>"+
(record.getLabel ? record.getLabel() : record.getTerm()+'<span style="font-size: smaller;"> (<span class="info-tip" data-qtip="'+this.localize('rawFreqs')+'">'+record.getRawFreq()+"</span>)</span>")
},
flex: 1
}],
bbar: [{
xtype: 'querysearchfield',
width: '100%',
tokenType: facet.replace("facet.", ""),
itemTpl: itemTpl
}],
corpus: this.getCorpus()
})
var facetCmp = facetsCmp.add(config);
facetCmp.getSelectionModel().on('selectionchange', function(model, selected) {
var labels = [];
selected.forEach(function(model) {
labels.push({facet: facetCmp.facet, label: model.getLabel ? model.getLabel() : model.getTerm()})
})
this.getFacets()[facet] = labels;
this.updateResults();
}, this)
facetCmp.on('query', function(model, selected) {
this.getFacets()[facetCmp.facet] = [];
this.updateResults();
}, this)
return facetCmp;
},
updateResults: function(queries) {
var facets = this.getFacets();
if (!queries) {
var queries = [];
for (facet in facets) {
facets[facet].forEach(function(label) {
queries.push(label.facet+":"+label.label);
})
}
if (queries) {
return this.updateResults(queries)
}
}
var results = this.queryById("results").getTargetEl();
var catalogue = this;
results.update(this.getCustomResultsHtml() ? this.getCustomResultsHtml() : new Ext.XTemplate(this.localize('noMatches')).apply([this.getCorpus().getDocumentsCount()]));
this.queryById('status').update(new Ext.XTemplate(this.localize('noMatches')).apply([this.getCorpus().getDocumentsCount()]))
this.queryById('sendToVoyant').setDisabled(true);
this.queryById('export').setDisabled(true);
if (queries && queries.length>0) {
this.mask(this.localize("loading"));
var documentQueryMatches = this.getCorpus().getDocumentQueryMatches();
documentQueryMatches.load({
params: {query: queries, includeDocIds: true},
callback: function(records, operation, success) {
this.unmask();
if (records && records.length>0) {
this.queryById('status').setHtml(records.length)
var list = "<ul>";
var matchingDocIds = [];
records.forEach(function(record) {
record.getDocIds().forEach(function(docId) {
matchingDocIds.push(docId);
var doc = documentQueryMatches.getCorpus().getDocument(docId);
var item = "<li id='"+results.getId()+'_'+docId+"' class='cataloguedoc'>";
item += "<a href='#' class='cataloguedoctitle' data='"+docId+"'>"+doc.getTitle()+"</a>";
for (facet in facets) {
if (facets[facet].length==0) {continue;}
var labelItems = "";
if (facet!='facet.title') {
var suffix = facet.replace(/^.+?\./,"");
var label = doc.get(suffix);
if (label) {
var isArray = Ext.isArray(label);
if (isArray) {
labelItems+="<li>"+suffix+"<ul>"
} else {
label = [label];
}
label.forEach(function(l) {
var isMatch = false;
facets[facet].forEach(function(f) {
if (f.label==l) {isMatch=true}
else if (f.facet.indexOf('facet')==-1) {
f.label.split(/\W+/).forEach(function(part) {
if (part.trim().length>0 && l.toLowerCase().indexOf(part.toLowerCase())>-1) {
isMatch=true;
}
})
}
})
labelItems+="<li>"+(isArray ? '' : suffix.replace('extra.','')+": ")+(isMatch ? '<span class="keyword">'+l+'</span>' : l)+"</li>"
})
if (isArray) {
labelItems+="</ul></li>";
}
}
}
if (labelItems) {
item+="<ul>"+labelItems+"</ul>";
}
}
item += "</li>";
list += item;
})
})
list += "</ul>";
results.update(list);
var me = this;
var lnks = results.query(".cataloguedoctitle");
lnks.forEach(function(lnk) {
Ext.get(lnk).on("click", function(e,el) {
this.dispatchEvent("documentSelected", me, el.getAttribute("data"));
}, me)
});
if (lnks.length==1) {
this.dispatchEvent("documentSelected", me, lnks[0].getAttribute("data"));
}
this.queryById('status').update(new Ext.XTemplate(this.localize('queryMatches')).apply([matchingDocIds.length,this.getCorpus().getDocumentsCount()]))
this.setMatchingDocIds(Ext.Array.clone(matchingDocIds));
if (matchingDocIds.length>0) {
this.queryById('export').setDisabled(false);
this.queryById('sendToVoyant').setDisabled(false);
}
// now try to load some snippets, if need be
if (facets['lexical']) {
var firstDocIds = matchingDocIds.splice(0,5);
this.loadSnippets(firstDocIds, results.first().first());
if (matchingDocIds && matchingDocIds.length>0) {
this.loadSnippets(matchingDocIds); // load the rest
}
}
}
},
scope: this
})
}
},
loadSnippets: function(docIds, elToMask) {
var results = this.queryById("results").getTargetEl();
var facets = this.getFacets();
if (facets['lexical']) {
var queries = facets['lexical'].map(function(label) {return label.facet+":"+label.label});
var contexts = this.getCorpus().getContexts({buffered: false});
if (elToMask) {
elToMask.mask(this.localize("loadingSnippets"));
}
contexts.load({
method: 'POST',
params: {
stripTags: "all",
query: queries,
docId: docIds,
perDocLimit: 3,
limit: 100,
accurateTotalNotNeeded: true
},
scope: this,
callback: function(records, operation, success) {
if (elToMask) {
elToMask.unmask();
}
if (success && Ext.isArray(records) && records.length>0) {
var snippets = {};
records.forEach(function(record) {
if (!snippets[record.getDocIndex()]) {snippets[record.getDocIndex()]=[]}
snippets[record.getDocIndex()].push(record);
})
for (docIndex in snippets) {
var id = this.getCorpus().getDocument(docIndex).getId();
var html = '<li style="list-style-type: none; font-size: smaller;">'+snippets[docIndex].map(function(snippet) {
return snippet.getHighlightedContext();
}).join(" … ")+'</li>'
var docItem = results.down("#"+results.getId()+"_"+id);
if (docItem.query("ul")) {
html="<ul>"+html+"</ul>";
}
docItem.insertHtml('beforeEnd', html)
}
}
}
})
}
},
selectFacet: function(callback) {
if (!this.facetsSelectionStore) {
var keys = {};
this.getCorpus().getDocuments().each(function(doc) {
for (var key in doc.getData()) {
if (key!="corpus" && key.indexOf("parent")!==0 && key.indexOf("-lexical")=="-1") {
keys[key] = true
}
}
});
keys = Object.keys(keys);
keys.sort();
this.facetsSelectionStore = Ext.create('Ext.data.ArrayStore', {
fields: ['text'],
data: keys.map(function(key) {return [key]})
});
}
var existingFacets = {};
this.queryById('facets').items.each(function(cmp) {
existingFacets[cmp.facet]=true;
})
this.facetsSelectionStore.filterBy(function(record) {
return !("facet."+record.get('text') in existingFacets)
})
var win = Ext.create('Ext.window.Window', {
title: this.localize("selectFacet"),
modal: true,
items: {
xtype: 'form',
width: 300,
items: {
xtype: 'combo',
store: this.facetsSelectionStore,
forceSelection: true,
width: 300
},
buttons: [{
text: this.localize("cancel"),
ui: 'default-toolbar',
glyph: 'xf00d@FontAwesome',
flex: 1,
handler: function(btn) {
btn.up('window').close();
}
},{
text: this.localize("select"),
glyph: 'xf00c@FontAwesome',
flex: 1,
handler: function(btn) {
var facet = btn.up('window').down('combo').getValue();
if (!facet) {
return this.showError(this.localize('selectValidFacet'));
} else {
callback.call(this, "facet."+facet);
btn.up('window').close();
}
},
scope: this
}]
},
bodyPadding: 5
}).show()
}
});

@ -0,0 +1,600 @@
// assuming Cirrus library is loaded by containing page (via voyant.jsp)
/**
* Cirrus tool, a wordcloud-like visuaization.
*
* // simple cirrus
* loadCorpus("austen").tool("cirrus");
*
* // define stopwords list and styling
* loadCorpus("austen").tool("cirrus", {
* stopList: 'auto',
* style: 'width: 500px; height: 400px'
* });
*/
Ext.define('Voyant.panel.Cirrus', {
extend: 'Ext.panel.Panel',
mixins: ['Voyant.panel.Panel'],
alias: 'widget.cirrus',
statics: {
i18n: {
},
api: {
/**
* @cfg {String} stopList A comma-separated list of words, a named list or a URL to a plain text list, one word per line.
* @default auto
*
* By default this is set to 'auto' which auto-detects the document's language and loads an appropriate list (if available for that language). Set this to blank to not use the default stopList.
*
* For more information see the <a href="#!/guide/search">Stopwords documentation</a>.
*/
stopList: 'auto',
categories: undefined,
whiteList: undefined, // specify a list of words to use
/**
* @cfg {Number} limit Specify the number of terms to load (which is separate from the number of {@link #visible} terms to show) at a time).
* @default 500
*
* By default this is set to 'auto' which auto-detects the document's language and loads an appropriate list (if available for that language). Set this to blank to not use the default stopList.
*/
limit: 500,
/**
* @cfg {Number} visible Specify the number of terms that are visible at a time.
* @default 50
*/
visible: 50,
terms: undefined,
docId: undefined,
docIndex: undefined,
inlineData: undefined, // format should match CorpusTerm model, only term and rawFreq required
fontFamily: '"Palatino Linotype", "Book Antiqua", Palatino, serif',
cirrusForceFlash: false,
background: '0xffffff',
fade: true,
smoothness: 2,
diagonals: 'none' // all, bigrams, none
},
glyph: 'xf06e@FontAwesome'
},
config: {
/**
* @private
*/
mode: undefined,
/**
* @private
*/
options: [
{xtype: 'stoplistoption'},
{
xtype: 'listeditor',
name: 'whiteList'
},
{xtype: 'categoriesoption'},
// {
// // TODO this field does nothing
// xtype: 'numberfield',
// name: 'label',
// fieldLabel: 'Max words',
// labelAlign: 'right',
// value: 500,
// minValue: 50,
// step: 50,
// listeners: {
// afterrender: function(field) {
// var win = field.up("window");
// if (win && win.panel) {field.setFieldLabel(win.panel.localize("maxTerms"))}
// }
// }
// },
{xtype: 'fontfamilyoption'},
{xtype: 'colorpaletteoption'}
],
/**
* @private
*/
records: undefined,
/**
* @private
*/
terms: undefined,
/**
* @private
*/
cirrusId: undefined,
/**
* @private
*/
visLayout: undefined, // cloud layout algorithm
/**
* @private
*/
vis: undefined, // actual vis
/**
* @private
*/
tip: undefined,
/**
* @private
*/
sizeAdjustment: 100, // amount to multiply a word's relative size by
/**
* @private
*/
minFontSize: 12,
/**
* @private
*/
largestWordSize: 0,
/**
* @private
*/
smallestWordSize: 1000000
},
MODE_CORPUS: 'corpus',
MODE_DOCUMENT: 'mode_document',
layout: 'fit',
/**
* @private
*/
constructor: function(config) {
this.callParent(arguments);
this.mixins['Voyant.panel.Panel'].constructor.apply(this, arguments);
this.getApplication().getCategoriesManager().addFeature('orientation', function() { return ~~(Math.random() * 2) * 90; });
this.setCirrusId(Ext.id(null, 'cirrus_'));
},
initComponent: function (config) {
Ext.apply(this, {
title: this.localize('title'),
dockedItems: [{
dock: 'bottom',
xtype: 'toolbar',
overflowHandler: 'scroller',
items: [{
xtype: 'corpusdocumentselector',
singleSelect: true
},{
fieldLabel: this.localize('visibleTerms'),
labelWidth: 40,
width: 120,
xtype: 'slider',
increment: 25,
minValue: 25,
maxValue: 500,
listeners: {
afterrender: function(slider) {
slider.maxValue = this.getApiParam("limit")
slider.increment = parseInt(slider.maxValue/50)
slider.setValue(this.getApiParam("visible"))
},
changecomplete: function(slider, newvalue) {
this.setApiParams({visible: newvalue});
this.loadFromTermsRecords();
},
scope: this
}
}]
}]
});
this.callParent(arguments);
},
listeners: {
boxready: function() {
this.initVisLayout(); // force in case we've changed fontFamily from options
var dataString = this.getApiParam('inlineData');
if (dataString !== undefined) {
if (dataString.charAt(0)=="[") {
var jsonData = Ext.decode(dataString, true);
} else {
if (dataString.indexOf(":")>-1) {
jsonData = [];
dataString.split(",").forEach(function(term) {
parts = term.split(":");
jsonData.push({
text: parts[0],
rawFreq: parseInt(parts[1])
})
})
} else {
var terms = {}
jsonData = [];
dataString.split(",").forEach(function(term) {
if (term in terms) {
terms[term]++;
} else {
terms[term] = 1;
}
});
for (term in terms) {
jsonData.push({
text: term,
rawFreq: terms[term]
})
}
}
}
if (jsonData !== null && jsonData.length>0) {
this.setApiParam('inlineData', jsonData);
this.setTerms(jsonData);
this.buildFromTerms();
}
}
},
resize: function(panel, width, height) {
if (this.getVisLayout() && this.getCorpus()) {
this.setAdjustedSizes();
var el = this.getLayout().getRenderTarget();
width = el.getWidth();
height = el.getHeight();
el.down('svg').set({width: width, height: height});
if (this.getTerms()) {
this.getVisLayout().size([width, height]).stop().words(this.getTerms()).start();
}
}
},
loadedCorpus: function(src, corpus) {
this.getApplication().getCategoriesManager().addFeature('font', this.getApiParam('fontFamily')); // make sure the default for font is set from the api
this.initVisLayout(); // force in case we've changed fontFamily from options
if (this.getApiParam("docIndex")) {
this.fireEvent("documentSelected", this, corpus.getDocument(this.getApiParam("docIndex")));
} else if (this.getApiParam("docId")) {
this.fireEvent("documentSelected", this, corpus.getDocument(this.getApiParam("docId")));
} else {
this.loadFromCorpus(corpus);
}
},
corpusSelected: function(src, corpus) {
this.loadFromCorpus(corpus);
},
documentSelected: function(src, document) {
if (document) {
var corpus = this.getCorpus();
var document = corpus.getDocument(document);
this.setApiParam('docId', document.getId());
var documentTerms = document.getDocumentTerms({autoload: false, corpus: corpus, pageSize: this.getApiParam("maxVisible"), parentPanel: this});
this.loadFromDocumentTerms(documentTerms);
}
},
ensureCorpusView: function(src, corpus) {
if (this.getMode() != this.MODE_CORPUS) {this.loadFromCorpus(corpus);}
}
},
loadFromCorpus: function(corpus) {
var jsonData = this.getApiParam('inlineData');
if (jsonData === undefined) {
this.setApiParams({docId: undefined, docIndex: undefined});
this.loadFromCorpusTerms(corpus.getCorpusTerms({autoload: false, pageSize: this.getApiParam("maxVisible"), parentPanel: this}));
} else {
// if (jsonData !== undefined) {
// var records = [];
// for (var i = 0; i < jsonData.length; i++) {
// var wordData = jsonData[i];
// wordData.term = wordData.text; // inlineData/CorpusTerm format mismatch
// var record = Ext.create('Voyant.data.model.CorpusTerm', wordData);
// records.push(record);
// }
// this.setRecords(records);
// this.setMode(this.MODE_CORPUS);
// this.loadFromTermsRecords();
// }
}
},
loadFromDocumentTerms: function(documentTerms) {
documentTerms.load({
callback: function(records, operation, success) {
this.setMode(this.MODE_DOCUMENT);
this.setRecords(operation.getRecords()); // not sure why operation.records is different from records
this.loadFromTermsRecords();
},
scope: this,
params: this.getApiParams()
});
},
loadFromCorpusTerms: function(corpusTerms) {
corpusTerms.load({
callback: function(records, operation, success) {
this.setMode(this.MODE_CORPUS);
this.setRecords(operation.getRecords()); // not sure why operation.records is different from records
this.loadFromTermsRecords();
},
scope: this,
params: this.getApiParams()
});
},
loadFromTermsRecords: function() {
var records = this.getRecords();
var visible = this.getApiParam("visible");
if (visible>records.length) {visible=records.length;}
var terms = [];
for (var i=0; i<visible; i++) {
if (records[i].get('rawFreq')>0) {
terms.push({text: records[i].get('term').replace(/"/g,''), rawFreq: records[i].get('rawFreq')});
}
}
this.setTerms(terms);
this.buildFromTerms();
},
initVisLayout: function(forceLayout) {
if (forceLayout || this.getVisLayout() == undefined) {
var cirrusForceFlash = this.getApiParam('cirrusForceFlash');
if (cirrusForceFlash == 'true' || cirrusForceFlash === true) {
this.setApiParam('cirrusForceFlash', true);
var id = this.getCirrusId();
var appVars = {
id: id
};
var keys = ['background','fade','smoothness','diagonals'];
for (var i = 0; i < keys.length; i++) {
appVars[keys[i]] = this.getApiParam(keys[i]);
}
var swfscript = '<script type="text/javascript" src="'+this.getApplication().getBaseUrl()+'resources/swfobject/swfobject.js'+'"></script>';
var cirrusLinks = '<script type="text/javascript">'+
'cirrusClickHandler'+id+' = function(word, value) {\n'+
'\tif (window.console && console.info) console.info(word, value);\n'+
'\tvar cirrusTool = Ext.getCmp("'+this.id+'");\n'+
'\tcirrusTool.dispatchEvent("termsClicked", cirrusTool, [word]);\n'+
'}\n'+
'cirrusLoaded'+id+' = function() {\n'+
'\tif (window.console && console.info) console.info("cirrus flash loaded");\n'+
'}\n'+
'cirrusPNGHandler'+id+' = function(base64String) {\n'+
'\tvar cirrusTool = Ext.getCmp("'+this.id+'");\n'+
'\tcirrusTool.cirrusPNGHandler(base64String);\n'+
'}'+
'</script>';
this.update(swfscript+cirrusLinks, true, function() {
function loadFlash(component) {
if (typeof swfobject !== 'undefined') {
var el = component.getLayout().getRenderTarget();
var width = el.getWidth();
var height = el.getHeight();
var cirrusFlash = component.getApplication().getBaseUrl()+'resources/cirrus/flash/Cirrus.swf';
component.add({
xtype: 'flash',
id: appVars.id,
url: cirrusFlash,
width: width,
height: height,
flashVars: appVars,
flashParams: {
menu: 'false',
scale: 'showall',
allowScriptAccess: 'always',
bgcolor: '#222222',
wmode: 'opaque'
}
});
component.cirrusFlashApp = Ext.get(appVars.id).first().dom;
} else {
setTimeout(loadFlash, 50, component);
}
}
loadFlash(this);
}, this);
} else {
var el = this.getLayout().getRenderTarget();
el.update(""); // make sure to clear existing contents (especially for re-layout)
var width = el.getWidth();
var height = el.getHeight();
this.setVisLayout(
d3.layoutCloud()
.size([width, height])
.overflow(true)
.padding(1)
.rotate(function(d) { return this.getApplication().getCategoriesManager().getFeatureForTerm('orientation', d.text); }.bind(this))
.spiral('archimedean')
.font(function(d) { return this.getApplication().getCategoriesManager().getFeatureForTerm('font', d.text); }.bind(this))
.fontSize(function(d) {return d.fontSize; }.bind(this))
.text(function(d) { return d.text; })
.on('end', this.draw.bind(this))
);
var svg = d3.select(el.dom).append('svg').attr('id',this.getCirrusId()).attr('class', 'cirrusGraph').attr('width', width).attr('height', height);
this.setVis(svg.append('g').attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')'));
if (this.getTip() === undefined) {
this.setTip(Ext.create('Ext.tip.Tip', {}));
}
}
}
},
buildFromTerms: function() {
var terms = this.getTerms();
if (this.rendered && terms) {
if (this.getApiParam('cirrusForceFlash') === true) {
if (this.cirrusFlashApp !== undefined && this.cirrusFlashApp.clearAll !== undefined) {
var words = [];
for (var i = 0; i < terms.length; i++) {
var t = terms[i];
if (!t.text && t.term) {t.text=t.term;}
words.push({word: t.text, size: t.rawFreq, label: t.rawFreq});
}
this.cirrusFlashApp.clearAll();
this.cirrusFlashApp.addWords(words);
this.cirrusFlashApp.arrangeWords();
} else {
Ext.defer(this.buildFromTerms, 50, this);
}
} else {
var minSize = 1000;
var maxSize = -1;
for (var i = 0; i < terms.length; i++) {
var size = terms[i].rawFreq;
if (size < minSize) minSize = size;
if (size > maxSize) maxSize = size;
}
this.setSmallestWordSize(minSize);
this.setLargestWordSize(maxSize);
// set the relative sizes for each word (0.0 to 1.0), then adjust based on available area
this.setRelativeSizes();
this.setAdjustedSizes();
// var fontSizer = d3.scalePow().range([10, 100]).domain([minSize, maxSize]);
this.getVisLayout().words(terms).start();
}
} else {
Ext.defer(this.buildFromTerms, 50, this);
}
},
draw: function(words, bounds) {
var panel = this;
var el = this.getLayout().getRenderTarget();
var width = this.getVisLayout().size()[0];
var height = this.getVisLayout().size()[1];
var scale = bounds ? Math.min(
width / Math.abs(bounds[1].x - width / 2),
width / Math.abs(bounds[0].x - width / 2),
height / Math.abs(bounds[1].y - height / 2),
height / Math.abs(bounds[0].y - height / 2)
) / 2 : 1;
var t = d3.transition().duration(1000);
var nodes = this.getVis().selectAll('text').data(words, function(d) {return d.text;});
nodes.exit().transition(t)
.style('font-size', '1px')
.remove();
var nodesEnter = nodes.enter().append('text')
.text(function(d) { return d.text; })
.attr('text-anchor', 'middle')
.attr('data-freq', function(d) { return d.rawFreq; })
.attr('transform', function(d) { return 'translate(' + [d.x, d.y] + ')rotate(' + d.rotate + ')'; })
.style('font-family', function(d) { return panel.getApplication().getCategoriesManager().getFeatureForTerm('font', d.text); })
.style('fill', function(d) { return panel.getApplication().getColorForTerm(d.text, true); })
.style('font-size', '1px')
.on('click', function(obj) {panel.dispatchEvent('termsClicked', panel, [obj.text]);})
.on('mouseover', function(obj) {
this.getTip().show();
}.bind(this))
.on('mousemove', function(obj) {
var tip = this.getTip();
tip.update(obj.text+': '+obj.rawFreq);
var container = Ext.get(this.getCirrusId()).dom;
var coords = d3.mouse(container);
coords[1] += 30;
tip.setPosition(coords);
}.bind(this))
.on('mouseout', function(obj) {
this.getTip().hide();
}.bind(this));
var nodesUpdate = nodes.merge(nodesEnter);
nodesUpdate.transition(t)
.style('font-family', function(d) { return panel.getApplication().getCategoriesManager().getFeatureForTerm('font', d.text); })
.style('fill', function(d) { return panel.getApplication().getColorForTerm(d.text, true); })
.attr('transform', function(d) { return 'translate(' + [d.x, d.y] + ')rotate(' + d.rotate + ')'; })
.style('font-size', function(d) { return d.fontSize + 'px'; });
this.getVis().transition(t).attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')scale(' + scale + ')');
},
map: function(value, istart, istop, ostart, ostop) {
return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
},
calculateSizeAdjustment: function() {
var terms = this.getTerms();
if (terms !== undefined) {
var el = this.getLayout().getRenderTarget();
var stageArea = el.getWidth() * el.getHeight();
if (stageArea < 100000) this.setMinFontSize(8);
else this.setMinFontSize(12);
var pixelsPerWord = stageArea / terms.length;
var totalWordsSize = 0;
for (var i = 0; i < terms.length; i++) {
var word = terms[i];
var wordArea = this.calculateWordArea(word);
totalWordsSize += wordArea;
}
this.setSizeAdjustment(stageArea / totalWordsSize);
}
},
calculateWordArea: function(word) {
var baseSize = Math.log(word.relativeSize * 10) * Math.LOG10E; // take the relativeSize (0.1 to 1.0), multiply by 10, then get the base-10 log of it
var height = (baseSize + word.relativeSize) / 2; // find the average between relativeSize and the log
var width = 0; //(baseSize / 1.5) * word.text.length;
for (var i = 0; i < word.text.length; i++ ) {
var letter = word.text.charAt(i);
if (letter == 'f' || letter == 'i' || letter == 'j' || letter == 'l' || letter == 'r' || letter == 't') width += baseSize / 3;
else if (letter == 'm' || letter == 'w') width += baseSize / (4 / 3);
else width += baseSize / 1.9;
}
var wordArea = height * width;
return wordArea;
},
setAdjustedSizes: function() {
this.calculateSizeAdjustment();
var terms = this.getTerms();
if (terms !== undefined) {
for (var i = 0; i < terms.length; i++) {
var term = terms[i];
var adjustedSize = this.findNewRelativeSize(term);
term.fontSize = adjustedSize > this.getMinFontSize() ? adjustedSize : this.getMinFontSize();
}
}
},
setRelativeSizes: function() {
var terms = this.getTerms();
if (terms !== undefined) {
for (var i = 0; i < terms.length; i++) {
var word = terms[i];
word.relativeSize = this.map(word.rawFreq, this.getSmallestWordSize(), this.getLargestWordSize(), 0.1, 1);
}
}
},
findNewRelativeSize: function(word) {
var areaMultiplier = this.getSizeAdjustment();
var area = this.calculateWordArea(word) * areaMultiplier;
// given the area = (x+6)*(2*x/3*y), solve for x
var newRelativeSize = (Math.sqrt(6) * Math.sqrt(6 * Math.pow(word.text.length, 2) + area * word.text.length) - 6 * word.text.length) / (2 * word.text.length);
return newRelativeSize;
}
});

@ -0,0 +1,881 @@
Ext.define('Voyant.panel.CollocatesGraph', {
extend: 'Ext.panel.Panel',
mixins: ['Voyant.panel.Panel'],
alias: 'widget.collocatesgraph',
statics: {
i18n: {
},
api: {
query: undefined,
mode: undefined,
limit: 5,
stopList: 'auto',
terms: undefined,
context: 5,
centralize: undefined
},
glyph: 'xf1e0@FontAwesome'
},
config: {
options: [{xtype: 'stoplistoption'},{
xtype: 'categoriesoption'
}],
nodeData: undefined,
linkData: undefined,
visId: undefined,
vis: undefined,
visLayout: undefined,
nodes: undefined,
links: undefined,
zoom: undefined,
dragging: false,
contextMenu: undefined,
currentNode: undefined,
networkMode: undefined,
graphStyle: {
keywordNode: {
normal: {
fill: '#c6dbef',
stroke: '#6baed6'
},
highlight: {
fill: '#9ecae1',
stroke: '#3182bd'
}
},
contextNode: {
normal: {
fill: '#fdd0a2',
stroke: '#fdae6b'
},
highlight: {
fill: '#fd9a53',
stroke: '#e6550d'
}
},
link: {
normal: {
stroke: '#000000',
strokeOpacity: 0.1
},
highlight: {
stroke: '#000000',
strokeOpacity: 0.5
}
}
},
graphPhysics: {
defaultMode: {
damping: 0.4, // 0 = no damping, 1 = full damping
centralGravity: 0.1, // 0 = no grav, 1 = high grav
nodeGravity: -50, // negative = repel, positive = attract
springLength: 100,
springStrength: 0.25, // 0 = not strong, >1 = probably too strong
collisionScale: 1.25 // 1 = default, 0 = no collision
},
centralizedMode: {
damping: 0.4, // 0 = no damping, 1 = full damping
centralGravity: 0.1, // 0 = no grav, 1 = high grav
nodeGravity: -1, // negative = repel, positive = attract
springLength: 200,
springStrength: 1, // 0 = not strong, >1 = probably too strong
collisionScale: 1 // 1 = default, 0 = no collision
}
}
},
DEFAULT_MODE: 0,
CENTRALIZED_MODE: 1,
constructor: function(config) {
this.setNodeData([]);
this.setLinkData([]);
this.setVisId(Ext.id(null, 'links_'));
this.callParent(arguments);
this.mixins['Voyant.panel.Panel'].constructor.apply(this, arguments);
},
initComponent: function() {
var me = this;
Ext.apply(me, {
title: this.localize('title'),
dockedItems: [{
dock: 'bottom',
xtype: 'toolbar',
overflowHandler: 'scroller',
items: [{
xtype: 'querysearchfield'
},{
text: me.localize('clearTerms'),
glyph: 'xf014@FontAwesome',
handler: this.resetGraph,
scope: me
},this.localize('context'),{
xtype: 'slider',
itemId: 'contextSlider',
minValue: 3,
value: 5,
maxValue: 30,
increment: 2,
width: 50,
listeners: {
render: function(slider) {
slider.setValue(this.getApiParam('context'));
},
changecomplete: function(slider, newValue) {
this.setApiParam('context', slider.getValue());
if (this.getNetworkMode() === this.DEFAULT_MODE) {
var terms = this.getNodeData().map(function(node) { return node.term; });
if (terms.length > 0) {
this.setNodeData([]);
this.setLinkData([]);
this.refresh();
this.loadFromQuery(terms);
}
}
},
scope: me
}
}]
}]
});
this.setContextMenu(Ext.create('Ext.menu.Menu', {
renderTo: Ext.getBody(),
items: [{
xtype: 'box',
itemId: 'label',
margin: '5px 0px 5px 5px',
html: ''
},{
xtype: 'menuseparator'
},{
xtype: 'menucheckitem',
text: 'Fixed',
itemId: 'fixed',
listeners: {
checkchange: function(c, checked, e) {
var node = this.getCurrentNode();
if (node !== undefined) {
var data = {
fixed: checked
};
if (checked) {
data.fx = node.x;
data.fy = node.y;
} else {
data.fx = null;
data.fy = null;
}
this.updateDataForNode(node.id, data);
}
},
scope: this
}
},{
xtype: 'button',
text: 'Fetch Collocates',
style: 'margin: 5px;',
handler: function(b, e) {
var node = this.getCurrentNode();
if (node !== undefined) {
if (this.getNetworkMode() === this.CENTRALIZED_MODE) {
this.resetGraph();
this.setNetworkMode(this.DEFAULT_MODE);
this.setApiParam('centralize', undefined);
node.start = 0;
node.limit = this.getApiParam('limit');
}
this.fetchCollocatesForNode(node);
}
},
scope: this
},{
xtype: 'button',
text: 'Centralize',
style: 'margin: 5px;',
handler: function(b, e) {
var node = this.getCurrentNode();
if (node !== undefined) {
this.doCentralize(node.term);
}
this.getContextMenu().hide();
},
scope: this
},{
xtype: 'button',
text: 'Remove',
style: 'margin: 5px;',
handler: function(b, e) {
var node = this.getCurrentNode();
if (node !== undefined) {
this.removeNode(node.id);
}
b.up('menu').hide();
},
scope: this
}]
}));
this.on('loadedCorpus', function(src, corpus) {
if (this.isVisible()) {
this.initLoad();
}
}, this);
this.on('activate', function() { // load after tab activate (if we're in a tab panel)
if (this.getCorpus()) {
if (this.getNodeData().length === 0) { // only initLoad if there isn't already data
Ext.Function.defer(this.initLoad, 100, this);
}
}
}, this);
this.on('query', function(src, query) {this.loadFromQuery(query);}, this);
this.on('resize', function(panel, width, height) {
var vis = Ext.get(this.getVisId());
if (vis) {
var el = this.body;//this.getLayout().getRenderTarget();
var elHeight = el.getHeight();
var elWidth = el.getWidth();
vis.el.dom.setAttribute('width', elWidth);
vis.el.dom.setAttribute('height', elHeight);
this.getVisLayout()
.force('x', d3.forceX(elWidth/2))
.force('y', d3.forceY(elHeight/2));
// .alpha(0.5).restart(); // restarting physics messes up zoomToFit
Ext.Function.defer(this.zoomToFit, 100, this);
// this.zoomToFit();
}
}, this);
me.callParent(arguments);
},
initLoad: function() {
this.initGraph();
this.setNetworkMode(this.DEFAULT_MODE);
if (this.getApiParam('centralize')) {
this.setNetworkMode(this.CENTRALIZED_MODE);
var term = this.getApiParam('centralize');
this.doCentralize(term);
} else {
var limit = 3;
var query = this.getApiParam('query');
if (query !== undefined) {
limit = Ext.isArray(query) ? query.length : query.split(',').length;
}
this.getCorpus().getCorpusTerms({autoLoad: false}).load({
params: {
limit: limit,
query: query,
stopList: this.getApiParam('stopList'),
categories: this.getApiParam("categories")
},
callback: function(records, operation, success) {
if (success) {
this.loadFromCorpusTermRecords(records);
}
},
scope: this
});
}
},
loadFromQuery: function(query) {
if (Ext.isArray(query) && query.length==0) {
this.setApiParam("query", undefined);
this.resetGraph();
return;
}
this.setApiParams({
mode: 'corpus',
query: query
});
var params = this.getApiParams();
params.noCache=true;
(Ext.isString(query) ? [query] : query).forEach(function(q) {
this.getCorpus().getCorpusCollocates({autoLoad: false}).load({
params: Ext.apply(Ext.clone(params), {query: q}),
callback: function(records, operations, success) {
if (success) {
this.loadFromCorpusCollocateRecords(records);
}
},
scope: this
});
}, this);
},
loadFromCorpusTermRecords: function(corpusTerms) {
if (Ext.isArray(corpusTerms) && corpusTerms.length>0) {
var terms = [];
corpusTerms.forEach(function(corpusTerm) {
terms.push(corpusTerm.getTerm());
});
this.loadFromQuery(terms);
}
},
loadFromCorpusCollocateRecords: function(records, keywordId) {
if (Ext.isArray(records)) {
var start = this.getApiParam('limit');
var el = this.getLayout().getRenderTarget();
var cX = el.getWidth()/2;
var cY = el.getHeight()/2;
var existingKeys = {};
this.getNodeData().forEach(function(item) {
existingKeys[item.id] = true;
}, this);
var newNodes = [];
var newLinks = [];
records.forEach(function(corpusCollocate, index) {
var term = corpusCollocate.getTerm();
var contextTerm = corpusCollocate.getContextTerm();
var termFreq = corpusCollocate.getKeywordRawFreq();
var contextFreq = corpusCollocate.getContextTermRawFreq();
var termValue = termFreq;
var contextValue = contextFreq;
if (this.getNetworkMode() === this.CENTRALIZED_MODE) {
termValue = 0;
contextValue = Math.log(contextFreq);
}
var termEntry = undefined;
var contextTermEntry = undefined;
if (index == 0) { // only process keyword once
if (keywordId === undefined) keywordId = this.idGet(term);
if (existingKeys[keywordId] !== undefined) {
this.updateDataForNode(keywordId, {
title: term+' ('+termFreq+')',
type: 'keyword',
value: termValue
});
} else {
existingKeys[keywordId] = true;
termEntry = {
id: keywordId,
term: term,
title: term+' ('+termFreq+')',
type: 'keyword',
value: termValue,
start: start,
fixed: false,
x: cX,
y: cY
};
newNodes.push(termEntry);
}
}
if (term != contextTerm) {
var contextId = this.idGet(contextTerm);
if (existingKeys[contextId] !== undefined) {
} else {
existingKeys[contextId] = true;
contextTermEntry = {
id: contextId,
term: contextTerm,
title: contextTerm+' ('+contextFreq+')',
type: 'context',
value: contextValue,
start: 0,
fixed: false,
x: cX,
y: cY
};
newNodes.push(contextTermEntry);
}
var existingLink = null;
var linkData = this.getLinkData();
for (var i = 0; i < linkData.length; i++) {
var link = linkData[i];
if ((link.source.id == keywordId && link.target.id == contextId) || (link.source.id == contextId && link.target.id == keywordId)) {
existingLink = link;
break;
}
}
var linkValue = corpusCollocate.getContextTermRawFreq();
if (existingLink === null) {
newLinks.push({source: keywordId, target: contextId, value: linkValue, id: keywordId+'-'+contextId});
} else if (existingLink.value < linkValue) {
// existingLink.value = linkValue;
}
}
}, this);
this.setNodeData(this.getNodeData().concat(newNodes));
this.setLinkData(this.getLinkData().concat(newLinks));
this.refresh();
}
},
idGet: function(term) {
return term.replace(/\W/g, '_');
},
updateDataForNode: function(nodeId, dataObj) {
var data = this.getNodeData();
for (var i = 0; i < data.length; i++) {
if (data[i].id === nodeId) {
Ext.apply(data[i], dataObj);
break;
}
}
},
removeNode: function(nodeId, removeOrphans) {
var data = this.getNodeData();
for (var i = 0; i < data.length; i++) {
if (data[i].id === nodeId) {
data.splice(i, 1);
break;
}
}
data = this.getLinkData();
for (var i = data.length-1; i >= 0; i--) {
if (data[i].source.id === nodeId || data[i].target.id === nodeId) {
data.splice(i, 1);
}
}
this.setApiParam("query", Ext.Array.remove(Ext.Array.from(this.getApiParam("query")), nodeId));
if (removeOrphans) {
// TODO
}
this.refresh();
},
doCentralize: function(term) {
this.setApiParam("centralize",term);
this.resetGraph();
this.setNetworkMode(this.CENTRALIZED_MODE);
var data = {
id: this.idGet(term),
term: term,
title: term+' ('+1+')',
type: 'keyword',
value: 1000,
start: 0
};
this.setNodeData([data]);
this.refresh();
var centralizeLimit = 150;
var limit = this.getApiParam('limit');
this.setApiParam('limit', centralizeLimit);
this.fetchCollocatesForNode(data);
this.setApiParam('limit', limit);
},
// called by setNetworkMode
applyNetworkMode: function(mode) {
if (this.getVisLayout()) {
if (mode === this.DEFAULT_MODE) {
var physics = this.getGraphPhysics().defaultMode;
this.getVisLayout()
.velocityDecay(physics.damping)
.force('link', d3.forceLink().id(function(d) { return d.id; }).distance(physics.springLength).strength(physics.springStrength))
.force('charge', d3.forceManyBody().strength(physics.nodeGravity))
.force('collide', d3.forceCollide(function(d) { return Math.sqrt(d.bbox.width * d.bbox.height) * physics.collisionScale; }));
this.getVisLayout().force('x').strength(physics.centralGravity);
this.getVisLayout().force('y').strength(physics.centralGravity);
} else {
var physics = this.getGraphPhysics().centralizedMode;
this.getVisLayout()
.velocityDecay(physics.damping)
.force('link', d3.forceLink().id(function(d) { return d.id; }).distance(physics.springLength).strength(physics.springStrength))
.force('charge', d3.forceManyBody().strength(function(d) {
if (d.type === 'keyword') {
return -10000;
} else {
return 0;
}
}))
.force('collide', d3.forceCollide(function(d) {
if (d.type === 'keyword') {
return d.value;
} else {
return Math.sqrt(d.bbox.width * d.bbox.height) * physics.collisionScale;
}
}));
this.getVisLayout().force('x').strength(physics.centralGravity);
this.getVisLayout().force('y').strength(physics.centralGravity);
}
}
return mode; // need to return mode for it to actually be set
},
initGraph: function() {
var el = this.getLayout().getRenderTarget();
el.update('');
var width = el.getWidth();
var height = el.getHeight();
this.setVisLayout(d3.forceSimulation()
.force('x', d3.forceX(width/2))
.force('y', d3.forceY(height/2))
.on('tick', function() {
this.getLinks()
.attr('x1', function(d) { return d.source.x; })
.attr('y1', function(d) { return d.source.y; })
.attr('x2', function(d) { return d.target.x; })
.attr('y2', function(d) { return d.target.y; });
// this.getLinks().attr('d', function(d) {
// return 'M' + d[0].x + ',' + d[0].y
// + 'S' + d[1].x + ',' + d[1].y
// + ' ' + d[2].x + ',' + d[2].y;
// });
this.getNodes().attr('transform', function(d) {
var x = d.x;
var y = d.y;
if (this.getNetworkMode() === this.DEFAULT_MODE || d.type !== 'keyword') {
x -= d.bbox.width*0.5;
y -= d.bbox.height*0.5;
} else {
}
return 'translate('+x+','+y+')';
}.bind(this));
if (!this.getDragging() && this.getVisLayout().alpha() < 0.075) {
this.getVisLayout().alpha(-1); // trigger end event
}
}.bind(this))
.on('end', function() {
Ext.Function.defer(this.zoomToFit, 100, this);
}.bind(this))
);
var svg = d3.select(el.dom).append('svg').attr('id',this.getVisId()).attr('class', 'linksGraph').attr('width', width).attr('height', height);
var g = svg.append('g');
var zoom = d3.zoom()
.scaleExtent([1/4, 4])
.on('zoom', function() {
g.attr('transform', d3.event.transform);
});
this.setZoom(zoom);
svg.call(zoom);
svg.on('click', function() {
this.getContextMenu().hide();
}.bind(this));
this.setLinks(g.append('g').attr('class', 'links').selectAll('.link'));
this.setNodes(g.append('g').attr('class', 'nodes').selectAll('.node'));
this.setVis(g);
},
resetGraph: function() {
this.setNodeData([]);
this.setLinkData([]);
this.setNetworkMode(this.DEFAULT_MODE); // ? there was another version of this function without this
this.refresh();
},
refresh: function() {
var me = this;
var nodeData = this.getNodeData();
var linkData = this.getLinkData();
// var nodeMap = d3.map(nodeData, function(d) { return d.id; });
// var bilinks = [];
// linkData.forEach(function(link) {
// var s = link.source = nodeMap.get(link.source);
// var t = link.target = nodeMap.get(link.target);
// var i = {};
// nodeData.push(i);
// linkData.push({source: s, target: i}, {source: i, target: t});
// bilinks.push([s,i,t]);
// });
var link = this.getLinks().data(linkData, function(d) { return d.id; });
link.exit().remove();
var linkEnter = link.enter().append('line')
.attr('class', 'link')
.attr('id', function(d) { return d.id; })
.on('mouseover', me.linkMouseOver.bind(me))
.on('mouseout', me.linkMouseOut.bind(me))
.on('click', function(data) {
d3.event.stopImmediatePropagation();
d3.event.preventDefault();
this.dispatchEvent('termsClicked', this, ['"'+data.source.term+' '+data.target.term+'"~'+this.getApiParam('context')]);
}.bind(me))
// .style('fill', 'none')
.style('cursor', 'pointer')
.style('stroke-width', function(d) {
if (me.getNetworkMode() === me.DEFAULT_MODE) {
return Math.max(1, Math.min(15, Math.sqrt(d.value)));
} else {
return 1;
}
});
this.setLinks(linkEnter.merge(link));
var node = this.getNodes().data(nodeData, function(d) { return d.id; });
node.exit().remove();
var nodeEnter = node.enter().append('g')
.attr('class', function(d) { return 'node '+d.type; })
.attr('id', function(d) { return d.id; })
.on('mouseover', me.nodeMouseOver.bind(me))
.on('mouseout', me.nodeMouseOut.bind(me))
.on('click', function(data) {
d3.event.stopImmediatePropagation();
d3.event.preventDefault();
this.dispatchEvent('termsClicked', this, [data.term]);
}.bind(me))
.on('dblclick', function(data) {
d3.event.stopImmediatePropagation();
d3.event.preventDefault();
this.fetchCollocatesForNode(data);
}.bind(me))
.on('contextmenu', function(d, i) {
d3.event.preventDefault();
// me.getTip().hide();
var menu = me.getContextMenu();
menu.queryById('label').setHtml(d.term);
menu.queryById('fixed').setChecked(d.fixed);
menu.showAt(d3.event.pageX+10, d3.event.pageY-50);
})
.call(d3.drag()
.on('start', function(d) {
me.setDragging(true);
if (!d3.event.active) me.getVisLayout().alpha(0.3).restart();
d.fx = d.x;
d.fy = d.y;
d.fixed = true;
})
.on('drag', function(d) {
me.getVisLayout().alpha(0.3); // don't let simulation end while the user is dragging
d.fx = d3.event.x;
d.fy = d3.event.y;
if (me.isMasked()) {
if (!me.isOffCanvas(d3.event.x, d3.event.y)) {
me.unmask();
}
} else if (me.isOffCanvas(d3.event.x, d3.event.y)) {
me.mask(me.localize('releaseToRemove'));
}
})
.on('end', function(d) {
me.setDragging(false);
// if (!d3.event.active) me.getVisLayout().alpha(0);
if (d.fixed != true) {
d.fx = null;
d.fy = null;
}
if (me.isOffCanvas(d3.event.x, d3.event.y)) {
me.unmask();
me.mask(me.localize('cleaning'));
me.removeNode(d.id);
me.unmask();
}
})
);
nodeEnter.append('title').text(function(d) { return d.title; });
if (this.getNetworkMode() === this.DEFAULT_MODE) {
nodeEnter.append('rect')
.style('stroke-width', 1)
.style('stroke-opacity', 1);
} else {
nodeEnter.filter(function(d) { return d.type === 'keyword'; }).append('circle')
.style('stroke-width', 1)
.style('stroke-opacity', 1);
}
nodeEnter.append('text')
.attr('font-family', function(d) { return me.getApplication().getCategoriesManager().getFeatureForTerm('font', d.term); })
.attr('font-size', function(d) { return Math.max(10, Math.sqrt(d.value)); })
.text(function(d) { return d.term; })
.each(function(d) { d.bbox = this.getBBox(); }) // set bounding box for later use
.style('cursor', 'pointer')
.style('user-select', 'none')
.attr('dominant-baseline', 'middle');
this.setNodes(nodeEnter.merge(node));
if (this.getNetworkMode() === this.DEFAULT_MODE) {
this.getVis().selectAll('rect')
.attr('width', function(d) { return d.bbox.width+16; })
.attr('height', function(d) { return d.bbox.height+8; })
.attr('rx', function(d) { return Math.max(2, d.bbox.height * 0.2); })
.attr('ry', function(d) { return Math.max(2, d.bbox.height * 0.2); })
.call(this.applyNodeStyle.bind(this));
this.getVis().selectAll('text')
.attr('dx', 8)
.attr('dy', function(d) { return d.bbox.height*0.5+4; });
} else {
this.getVis().selectAll('circle')
.attr('r', function(d) { return Math.min(150, d.bbox.width); })
.call(this.applyNodeStyle.bind(this));
this.getVis().selectAll('text')
.attr('dx', function(d) {
if (d.type === 'keyword') {
return -d.bbox.width*0.5;
} else {
return 8;
}
})
.attr('dy', function(d) {
if (d.type === 'keyword') {
return 0;
} else {
return d.bbox.height*0.5+4;
}
});
}
this.getVis().selectAll('line').call(this.applyLinkStyle.bind(this));
this.getVisLayout().nodes(nodeData);
this.getVisLayout().force('link').links(linkData);
this.getVisLayout().alpha(1).restart();
},
isOffCanvas: function(x, y) {
var vis = Ext.get(this.getVisId());
return x < 0 || y < 0 || x > vis.getWidth() || y > vis.getHeight();
},
zoomToFit: function(paddingPercent, transitionDuration) {
var bounds = this.getVis().node().getBBox();
var width = bounds.width;
var height = bounds.height;
var midX = bounds.x + width/2;
var midY = bounds.y + height/2;
var svg = this.getVis().node().parentElement;
var svgRect = svg.getBoundingClientRect();
var fullWidth = svgRect.width;
var fullHeight = svgRect.height;
var scale = (paddingPercent || 0.8) / Math.max(width/fullWidth, height/fullHeight);
var translate = [fullWidth/2 - scale*midX, fullHeight/2 - scale*midY];
if (width<1) {return} // FIXME: something strange with spyral
d3.select(svg)
.transition()
.duration(transitionDuration || 500)
.call(this.getZoom().transform, d3.zoomIdentity.translate(translate[0],translate[1]).scale(scale));
},
applyNodeStyle: function(sel, nodeState) {
var state = nodeState === undefined ? 'normal' : nodeState;
sel.style('fill', function(d) { var type = d.type+'Node'; return this.getGraphStyle()[type][state].fill; }.bind(this));
sel.style('stroke', function(d) { var type = d.type+'Node'; return this.getGraphStyle()[type][state].stroke; }.bind(this));
},
applyLinkStyle: function(sel, linkState) {
var state = linkState === undefined ? 'normal' : linkState;
sel.style('stroke', function(d) { return this.getGraphStyle().link[state].stroke; }.bind(this));
sel.style('stroke-opacity', function(d) { return this.getGraphStyle().link[state].strokeOpacity; }.bind(this));
},
linkMouseOver: function(d) {
this.getVis().selectAll('line').call(this.applyLinkStyle.bind(this));
this.getVis().select('#'+d.id).call(this.applyLinkStyle.bind(this), 'highlight');
},
linkMouseOut: function(d) {
this.getVis().selectAll('line').call(this.applyLinkStyle.bind(this));
},
nodeMouseOver: function(d) {
this.setCurrentNode(d);
this.getVis().selectAll('rect').call(this.applyNodeStyle.bind(this));
this.getLinks().each(function(link) {
var id;
if (link.source.id == d.id) {
id = link.target.id;
} else if (link.target.id == d.id) {
id = link.source.id;
}
if (id !== undefined) {
this.getVis().select('#'+id+' rect').call(this.applyNodeStyle.bind(this), 'highlight');
this.getVis().select('#'+link.id).call(this.applyLinkStyle.bind(this), 'highlight');
}
}.bind(this));
this.getVis().select('#'+d.id+' rect')
.style('stroke-width', 3)
.call(this.applyNodeStyle.bind(this), 'highlight');
},
nodeMouseOut: function(d) {
if (!this.getContextMenu().isVisible()) {
this.setCurrentNode(undefined);
}
this.getVis().selectAll('rect')
.style('stroke-width', 1)
.call(this.applyNodeStyle.bind(this));
this.getVis().selectAll('line')
.call(this.applyLinkStyle.bind(this));
},
fetchCollocatesForNode: function(d) {
var limit = this.getApiParam('limit');
var query = this.getApiParam("query");
var query = Ext.Array.from(this.getApiParam("query"));
Ext.Array.include(query, d.term)
this.setApiParam("query", query);
var corpusCollocates = this.getCorpus().getCorpusCollocates({autoLoad: false});
corpusCollocates.load({
params: Ext.apply(this.getApiParams(), {query: d.term, start: d.start, limit: limit}),
callback: function(records, operation, success) {
if (success) {
this.updateDataForNode(d.id, {
start: d.start+limit
});
this.loadFromCorpusCollocateRecords(records, d.id);
}
},
scope: this
});
}
});

@ -0,0 +1,56 @@
Ext.define('Voyant.panel.CollocatesSet', {
extend: 'Ext.panel.Panel',
requires: ['Voyant.panel.ScatterPlot','Voyant.panel.Documents', 'Voyant.panel.Trends', 'Voyant.panel.Contexts'],
mixins: ['Voyant.panel.Panel'],
alias: 'widget.collocatesset',
statics: {
i18n: {
},
glyph: 'xf17a@FontAwesome'
},
constructor: function(config) {
this.callParent(arguments);
this.mixins['Voyant.panel.Panel'].constructor.apply(this, arguments);
},
layout: 'vbox',
header: false,
items: [{
layout: 'hbox',
align: 'stretch',
width: '100%',
height: '100%',
flex: 2,
defaults: {
width: '100%',
height: '100%',
flex: 1,
frame: true,
border: true
},
items: [{
xtype: 'corpusterms'
},{
xtype: 'documentterms'
},{
xtype: 'corpuscollocates'
}]
},{
width: '100%',
height: '100%',
split: {width: 5},
layout: 'hbox',
flex: 3,
defaults: {
width: '100%',
height: '100%',
flex: 1,
frame: true,
border: true
},
items: [{
xtype: 'contexts'
},{
xtype: 'collocatesgraph'
}]
}]
})

@ -0,0 +1,310 @@
Ext.define('Voyant.panel.Contexts', {
extend: 'Ext.grid.Panel',
mixins: ['Voyant.panel.Panel'],
requires: ['Voyant.data.store.Contexts'],
alias: 'widget.contexts',
isConsumptive: true,
statics: {
i18n: {
},
api: {
query: undefined,
docId: undefined,
docIndex: undefined,
stopList: 'auto',
context: 5,
expand: 50
},
glyph: 'xf0ce@FontAwesome'
},
config: {
options: [{xtype: 'stoplistoption'},{xtype: 'categoriesoption'}]
},
constructor: function() {
this.callParent(arguments);
this.mixins['Voyant.panel.Panel'].constructor.apply(this, arguments);
},
initComponent: function() {
var me = this;
Ext.apply(me, {
title: this.localize('title'),
emptyText: this.localize("emptyText"),
store : Ext.create("Voyant.data.store.ContextsBuffered", {
parentPanel: this,
proxy: {
extraParams: {
stripTags: "all"
}
}
// sortOnLoad: true,
// sorters: {
// property: 'position',
// direction: 'ASC'
// }
}),
selModel: {
type: 'rowmodel',
listeners: {
selectionchange: {
fn: function(sm, selections) {
this.getApplication().dispatchEvent('termLocationClicked', this, selections);
},
scope: this
}
}
},
plugins: [{ // the expander slider assumes there's only one plugin, needs to be updated if changed
ptype: 'rowexpander',
rowBodyTpl : new Ext.XTemplate('')
}],
dockedItems: [{
dock: 'bottom',
xtype: 'toolbar',
overflowHandler: 'scroller',
items: [{
xtype: 'querysearchfield'
}, {
xtype: 'totalpropertystatus'
}, this.localize('context'), {
xtype: 'slider',
minValue: 5,
value: 5,
maxValue: 50,
increment: 5,
width: 50,
listeners: {
render: function(slider) {
slider.setValue(me.getApiParam('context'));
},
changecomplete: function(slider, newValue) {
me.setApiParam("context", slider.getValue());
me.getStore().clearAndLoad({params: me.getApiParams()});
}
}
}, this.localize('expand'), {
xtype: 'slider',
minValue: 5,
value: 5,
maxValue: 500,
increment: 10,
width: 50,
listeners: {
render: function(slider) {
slider.setValue(me.getApiParam('expand'));
},
changecomplete: function(slider, newValue) {
me.setApiParam('expand', newValue);
var view = me.getView();
var recordsExpanded = me.plugins[0].recordsExpanded;
var store = view.getStore();
for (var id in recordsExpanded) {
var record = store.getByInternalId(id);
var row = view.getRow(record);
var expandRow = row.parentNode.childNodes[1];
if (recordsExpanded[id]) {
view.fireEvent("expandbody", row, record, expandRow, {force: true});
} else {
Ext.fly(expandRow).down('.x-grid-rowbody').setHtml('');
}
}
}
}
},{
xtype: 'corpusdocumentselector'
}]
}],
columns: [{
text: this.localize("document"),
toolTip: this.localize("documentTip"),
width: 'autoSize',
dataIndex: 'docIndex',
sortable: true,
renderer: function (value, metaData, record, rowIndex, colIndex, store) {
return store.getCorpus().getDocument(value).getTinyLabel();
}
},{
text: this.localize("left"),
tooltip: this.localize("leftTip"),
align: 'right',
dataIndex: 'left',
sortable: true,
flex: 1
},{
text: this.localize("term"),
tooltip: this.localize("termTip"),
dataIndex: 'term',
sortable: true,
width: 'autoSize'
},{
text: this.localize("right"),
tooltip: this.localize("rightTip"),
dataIndex: 'right',
sortable: true,
flex: 1
},{
text: this.localize("position"),
tooltip: this.localize("positionTip"),
dataIndex: 'position',
sortable: true,
hidden: true,
flex: 1
}],
listeners: {
scope: this,
corpusSelected: function() {
if (this.getStore().getCorpus()) {
this.setApiParams({docId: undefined, docIndex: undefined})
this.getStore().clearAndLoad()
}
},
documentsSelected: function(src, docs) {
var docIds = [];
var corpus = this.getStore().getCorpus();
docs.forEach(function(doc) {
docIds.push(corpus.getDocument(doc).getId())
}, this);
this.setApiParams({docId: docIds, docIndex: undefined})
this.getStore().clearAndLoad()
},
documentSegmentTermClicked: {
fn: function(src, documentSegmentTerm) {
if (!documentSegmentTerm.term) {return;}
params = {query: documentSegmentTerm.term};
if (documentSegmentTerm.docId) {
params.docId = documentSegmentTerm.docId;
}
else {
// default to first document
params.docIndex = documentSegmentTerm.docIndex ? documentSegmentTerm.docIndex : 0;
}
this.setApiParams(params);
if (this.isVisible()) {
this.getStore().clearAndLoad()
}
},
scope: this
},
documentIndexTermsClicked: {
fn: function(src, documentIndexTerms) {
// this isn't quite right, since we want every term associated with a docIndex, but for now it will do
var queriesHash = {};
var queries = [];
var docIndexHash = {};
var docIndex = [];
documentIndexTerms.forEach(function(item) {
if (!queriesHash[item.term]) {
queries.push(item.term);
queriesHash[item.term]=true;
}
if (!docIndexHash[item.docIndex]) {
docIndex.push(item.docIndex);
docIndexHash[item.docIndex]=true;
}
});
this.setApiParams({
docId: undefined,
docIndex: docIndex,
query: queries
});
if (this.isVisible()) {
this.getStore().clearAndLoad({params: this.getApiParams()});
}
},
scope: this
},
afterrender: function(me) {
me.getView().on('expandbody', function( rowNode, record, expandRow, eOpts ) {
if (expandRow.textContent==="" || (eOpts && eOpts.force)) {
var store = Ext.create("Voyant.data.store.Contexts", {
stripTags: "all",
corpus: me.getStore().getCorpus()
});
var data = record.getData();
store.load({
params: {
query: data.query,
docIndex: data.docIndex,
position: data.position,
limit: 1,
context: me.getApiParam('expand')
},
callback: function(records, operation, success) {
if (success && records.length==1) {
data = records[0].getData();
Ext.fly(operation.expandRow).down('.x-grid-rowbody').setHtml(data.left + " <span class='word keyword'>" + data.middle + "</span> " + data.right);
}
},
expandRow: expandRow
});
}
});
}
}
});
me.on("loadedCorpus", function(src, corpus) {
if (this.hasCorpusAccess(corpus)==false) {
this.mask(this.localize('limitedAccess'), 'mask-no-spinner');
}
else {
var corpusTerms = corpus.getCorpusTerms({autoLoad: false});
corpusTerms.load({
callback: function(records, operation, success) {
if (success && records.length>0) {
this.setApiParam("query", [records[0].getTerm()]);
this.getStore().clearAndLoad({params: this.getApiParams()});
}
},
scope: me,
params: {
limit: 1,
query: this.getApiParam("query"),
stopList: this.getApiParam("stopList"),
forTool: 'contexts'
}
});
}
});
me.on("query", function(src, query) {
this.setApiParam('query', query);
this.getStore().clearAndLoad({params: this.getApiParams()});
}, me);
me.on("documentTermsClicked", function(src, documentTerms) {
var documentIndexTerms = [];
documentTerms.forEach(function(documentTerm) {
documentIndexTerms.push({
term: documentTerm.getTerm(),
docIndex: documentTerm.getDocIndex()
});
});
this.fireEvent("documentIndexTermsClicked", this, documentIndexTerms);
});
me.on("termsClicked", function(src, terms) {
var documentIndexTerms = [];
if (Ext.isString(terms)) {terms = [terms];}
terms.forEach(function(term) {
if (term.docIndex !== undefined) {
documentIndexTerms.push({
term: term.term,
docIndex: term.docIndex
});
}
});
if (documentIndexTerms.length > 0) {
this.fireEvent("documentIndexTermsClicked", this, documentIndexTerms);
}
});
me.callParent(arguments);
}
});

@ -0,0 +1,253 @@
Ext.define('Voyant.panel.CorpusCollocates', {
extend: 'Ext.grid.Panel',
mixins: ['Voyant.panel.Panel'],
alias: 'widget.corpuscollocates',
statics: {
i18n: {
},
api: {
stopList: 'auto',
context: 5,
query: undefined,
docId: undefined,
docIndex: undefined,
sort: 'contextTermRawFreq'
},
glyph: 'xf0ce@FontAwesome'
},
config: {
options: [{xtype: 'stoplistoption'},{xtype: 'categoriesoption'}]
},
constructor: function(config) {
this.callParent(arguments);
this.mixins['Voyant.panel.Panel'].constructor.apply(this, arguments);
// create a listener for corpus loading (defined here, in case we need to load it next)
this.on('loadedCorpus', function(src, corpus) {
if (this.isVisible()) {
this.loadFromApis();
}
});
if (config.embedded) {
// var cls = Ext.getClass(config.embedded).getName();
// if (cls=="Voyant.data.store.DocumentTerms" || cls=="Voyant.data.model.Document") {
// this.fireEvent('loadedCorpus', this, config.embedded.getCorpus())
// }
}
else if (config.corpus) {
this.fireEvent('loadedCorpus', this, config.corpus)
}
this.on("corpusTermsClicked", function(src, terms) {
if (this.getStore().getCorpus()) { // make sure we have a corpus
var query = [];
terms.forEach(function(term) {
query.push(term.get("term"));
})
this.setApiParams({
query: query,
docId: undefined,
docIndex: undefined
});
if (this.isVisible()) {
this.loadFromApis();
}
}
});
this.on("documentsClicked", function(src, documents) {
var docIds = [];
documents.forEach(function(doc) {docIds.push(doc.get('id'))});
this.setApiParams({
docId: docIds,
docid: undefined,
query: undefined
})
if (this.isVisible()) {
this.loadFromApis();
}
});
this.on("activate", function() { // load after tab activate (if we're in a tab panel)
if (this.getStore().getCorpus()) {this.loadFromApis()}
}, this)
this.on("query", function(src, query) {
this.setApiParam("query", query);
this.getStore().getProxy().setExtraParam("query", query);
this.loadFromApis();
}, this)
},
loadFromApis: function() {
if (this.getStore().getCorpus()) {
if (this.getApiParam('query')) {
this.getStore().clearAndLoad({params: this.getApiParams()});
}
else {
var corpusTerms = this.getStore().getCorpus().getCorpusTerms({
leadingBufferZone: 0,
autoLoad: false
});
corpusTerms.load({
callback: function(records, operation, success) {
if (success) {
var terms = [];
records.forEach(function(term) {
terms.push(term.getTerm());
})
this.getStore().getProxy().setExtraParam("query", terms);
this.setApiParam('query', terms);
this.loadFromApis();
}
},
scope: this,
params: {
limit: 10,
stopList: this.getApiParam("stopList")
}
});
}
}
},
initComponent: function() {
var me = this;
var store = Ext.create("Voyant.data.store.CorpusCollocatesBuffered", {parentPanel: this});
Ext.apply(me, {
title: this.localize('title'),
emptyText: this.localize("emptyText"),
store : store,
selModel: Ext.create('Ext.selection.CheckboxModel', {
listeners: {
selectionchange: {
fn: function(sm, selections) {
var terms = [];
var context = this.getApiParam("context")
selections.forEach(function(selection) {
terms.push('"'+selection.getKeyword()+" "+selection.getContextTerm()+'"~'+context)
})
this.getApplication().dispatchEvent('termsClicked', this, terms);
},
scope: this
}
}
}),
dockedItems: [{
dock: 'bottom',
xtype: 'toolbar',
overflowHandler: 'scroller',
items: [{
xtype: 'querysearchfield'
}, {
xtype: 'totalpropertystatus'
}, this.localize('context'), {
xtype: 'slider',
minValue: 1,
value: 5,
maxValue: 30,
increment: 2,
width: 50,
listeners: {
render: function(slider) {
slider.setValue(me.getApiParam('context'))
},
changecomplete: function(slider, newValue) {
me.setApiParam("context", slider.getValue());
me.loadFromApis();
}
}
},{
xtype: 'corpusdocumentselector'
}]
}],
columns: [{
text: this.localize("term"),
dataIndex: 'term',
tooltip: this.localize("termTip"),
sortable: true,
flex: 1
},{
text: this.localize("rawFreq"),
dataIndex: 'rawFreq',
tooltip: this.localize("termRawFreqTip"),
sortable: true,
width: 'autoSize',
hidden: true
},{
text: this.localize("contextTerm"),
dataIndex: 'contextTerm',
tooltip: this.localize("contextTermTip"),
flex: 1,
sortable: true
},{
text: this.localize("contextTermRawFreq"),
tooltip: this.localize("contextTermRawFreqTip"),
dataIndex: 'contextTermRawFreq',
width: 'autoSize',
sortable: true
}/*,{
xtype: 'widgetcolumn',
text: this.localize("trend"),
tooltip: this.localize('trendTip'),
width: 120,
dataIndex: 'distributions',
widget: {
xtype: 'sparklineline'
}
}*/],
listeners: {
scope: this,
termsClicked: function(src, terms) {
if (this.getStore().getCorpus()) { // make sure we have a corpus
var queryTerms = [];
terms.forEach(function(term) {
if (Ext.isString(term)) {queryTerms.push(term);}
else if (term.term) {queryTerms.push(term.term);}
else if (term.getTerm) {queryTerms.push(term.getTerm());}
});
if (queryTerms.length > 0) {
this.setApiParams({
docIndex: undefined,
docId: undefined,
query: queryTerms
});
if (this.isVisible()) {
this.loadFromApis();
}
}
}
},
corpusSelected: function() {
if (this.getStore().getCorpus()) {
this.setApiParams({docId: undefined, docIndex: undefined})
this.loadFromApis();
}
},
documentsSelected: function(src, docs) {
var docIds = [];
var corpus = this.getStore().getCorpus();
docs.forEach(function(doc) {
docIds.push(corpus.getDocument(doc).getId())
}, this);
this.setApiParams({docId: docIds, docIndex: undefined});
this.loadFromApis();
}
}
});
me.callParent(arguments);
me.getStore().getProxy().setExtraParam("withDistributions", true);
}
})

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save