Browse Source

Rebuild based on _s (#40)

pull/41/head
Ned Zimmerman 7 years ago committed by GitHub
parent
commit
5e69de9db5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 21
      .editorconfig
  2. 60
      404.php
  3. 347
      LICENSE.md
  4. 134
      README.md
  5. 60
      app/activation.php
  6. 158
      app/admin.php
  7. 159
      app/controllers/App.php
  8. 33
      app/controllers/FrontPage.php
  9. 35
      app/controllers/PageCatalog.php
  10. 79
      app/filters.php
  11. 202
      app/helpers.php
  12. 38
      app/intervention.php
  13. 199
      app/setup.php
  14. 51
      archive.php
  15. 0
      assets/fonts/.gitkeep
  16. 0
      assets/fonts/pressbooks-theme.woff
  17. 0
      assets/images/.gitkeep
  18. 0
      assets/images/banner.jpg
  19. 0
      assets/images/catalog-header.jpg
  20. 0
      assets/images/header.jpg
  21. 0
      assets/images/left-arrow.svg
  22. 0
      assets/images/logo.svg
  23. 0
      assets/images/pb.svg
  24. 0
      assets/images/right-arrow.svg
  25. 0
      assets/scripts/aldine.js
  26. 2
      assets/scripts/customizer.js
  27. 112
      assets/scripts/routes/catalog.js
  28. 16
      assets/scripts/routes/common.js
  29. 6
      assets/scripts/routes/home.js
  30. 0
      assets/scripts/util/Router.js
  31. 0
      assets/scripts/util/camelCase.js
  32. 2
      assets/styles/aldine.scss
  33. 0
      assets/styles/common/_global.scss
  34. 0
      assets/styles/common/_variables.scss
  35. 0
      assets/styles/components/_comments.scss
  36. 0
      assets/styles/components/_forms.scss
  37. 0
      assets/styles/components/_grid.scss
  38. 0
      assets/styles/components/_wp-classes.scss
  39. 0
      assets/styles/layouts/_footer.scss
  40. 0
      assets/styles/layouts/_header.scss
  41. 0
      assets/styles/layouts/_pages.scss
  42. 0
      assets/styles/layouts/_posts.scss
  43. 0
      assets/styles/layouts/_sidebar.scss
  44. 0
      assets/styles/layouts/_tinymce.scss
  45. 0
      assets/styles/layouts/pages/_catalog.scss
  46. 0
      assets/styles/layouts/pages/_front-page.scss
  47. 0
      assets/styles/login.scss
  48. 72
      comments.php
  49. 98
      composer.json
  50. 999
      composer.lock
  51. 31
      config/assets.php
  52. 32
      config/theme.php
  53. 51
      config/view.php
  54. 6
      dist/mix-manifest.json
  55. 1
      dist/scripts/aldine.js
  56. 2
      dist/scripts/customizer.js
  57. 1
      dist/scripts/main.js
  58. 0
      dist/styles/aldine.css
  59. 85
      footer.php
  60. 255
      functions.php
  61. 58
      header.php
  62. 51
      inc/actions/namespace.php
  63. 66
      inc/activation/namespace.php
  64. 185
      inc/customizer/namespace.php
  65. 39
      inc/filters/namespace.php
  66. 146
      inc/helpers/namespace.php
  67. 39
      inc/intervention.php
  68. 8
      inc/tags/namespace.php
  69. 55
      index.php
  70. 186
      languages/aldine.pot
  71. 227
      lib/infusion/Infusion-LICENSE.txt
  72. 212
      lib/infusion/README.md
  73. 344
      lib/infusion/ReleaseNotes.md
  74. 30
      lib/infusion/infusion-uiOptions.js
  75. 1
      lib/infusion/infusion-uiOptions.js.map
  76. 171
      lib/infusion/src/components/slidingPanel/js/SlidingPanel.js
  77. 16
      lib/infusion/src/components/slidingPanel/slidingPanelDependencies.json
  78. 3
      lib/infusion/src/components/tableOfContents/css/TableOfContents.css
  79. 32
      lib/infusion/src/components/tableOfContents/html/TableOfContents.html
  80. 377
      lib/infusion/src/components/tableOfContents/js/TableOfContents.js
  81. 15
      lib/infusion/src/components/tableOfContents/tableOfContentsDependencies.json
  82. 113
      lib/infusion/src/components/textToSpeech/js/MockTTS.js
  83. 288
      lib/infusion/src/components/textToSpeech/js/TextToSpeech.js
  84. 14
      lib/infusion/src/components/textToSpeech/textToSpeechDependencies.json
  85. 312
      lib/infusion/src/components/textfieldSlider/js/TextfieldSlider.js
  86. 18
      lib/infusion/src/components/textfieldSlider/textfieldSliderDependencies.json
  87. 45
      lib/infusion/src/components/uiOptions/js/UIOptions.js
  88. 14
      lib/infusion/src/components/uiOptions/uiOptionsDependencies.json
  89. 69
      lib/infusion/src/framework/core/css/fluid.css
  90. 132
      lib/infusion/src/framework/core/css/fluidDebugging.css
  91. 26
      lib/infusion/src/framework/core/frameworkDependencies.json
  92. BIN
      lib/infusion/src/framework/core/images/debug_tab.png
  93. BIN
      lib/infusion/src/framework/core/images/magnifying_glass.png
  94. 1495
      lib/infusion/src/framework/core/js/DataBinding.js
  95. 2806
      lib/infusion/src/framework/core/js/Fluid.js
  96. 116
      lib/infusion/src/framework/core/js/FluidDOMUtilities.js
  97. 300
      lib/infusion/src/framework/core/js/FluidDebugging.js
  98. 191
      lib/infusion/src/framework/core/js/FluidDocument.js
  99. 2458
      lib/infusion/src/framework/core/js/FluidIoC.js
  100. 266
      lib/infusion/src/framework/core/js/FluidPromises.js
  101. Some files were not shown because too many files have changed in this diff Show More

21
.editorconfig

@ -1,17 +1,24 @@
# This file is for unifying the coding style for different editors and IDEs
# editorconfig.org
# WordPress Coding Standards
# https://make.wordpress.org/core/handbook/coding-standards/
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = tab
[*.php]
indent_size = 4
[*.md]
trim_trailing_whitespace = false
[resources/views/**.php]
[{.jshintrc,*.json,*.yml,*.scss}]
indent_style = space
indent_size = 2
[{*.txt,wp-config-sample.php}]
end_of_line = crlf

60
404.php

@ -0,0 +1,60 @@
<?php
/**
* The template for displaying 404 pages (not found)
*
* @link https://codex.wordpress.org/Creating_an_Error_404_Page
*
* @package Aldine
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<section class="error-404 not-found">
<header class="page-header">
<h1 class="page-title"><?php esc_html_e( 'Oops! That page can&rsquo;t be found.', 'pressbooks-aldine' ); ?></h1>
</header><!-- .page-header -->
<div class="page-content">
<p><?php esc_html_e( 'It looks like nothing was found at this location. Maybe try one of the links below or a search?', 'pressbooks-aldine' ); ?></p>
<?php
get_search_form();
the_widget( 'WP_Widget_Recent_Posts' );
?>
<div class="widget widget_categories">
<h2 class="widget-title"><?php esc_html_e( 'Most Used Categories', 'pressbooks-aldine' ); ?></h2>
<ul>
<?php
wp_list_categories( [
'orderby' => 'count',
'order' => 'DESC',
'show_count' => 1,
'title_li' => '',
'number' => 10,
] );
?>
</ul>
</div><!-- .widget -->
<?php
/* translators: %1$s: smiley */
$archive_content = '<p>' . sprintf( esc_html__( 'Try looking in the monthly archives. %1$s', 'pressbooks-aldine' ), convert_smilies( ':)' ) ) . '</p>';
the_widget( 'WP_Widget_Archives', 'dropdown=1', "after_title=</h2>$archive_content" );
the_widget( 'WP_Widget_Tag_Cloud' );
?>
</div><!-- .page-content -->
</section><!-- .error-404 -->
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_footer();

347
LICENSE.md

@ -1,24 +1,339 @@
Copyright (c) 2017 Pressbooks (Book Oven Inc.)
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
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.
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
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.
Preamble
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
This project is based on work covered by the following copyright and permission notice:
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
this service 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.
Copyright (c) Ben Word and Scott Walkinshaw
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. 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.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE 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.
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
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{description}
Copyright (C) {year} {fullname}
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision 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, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This 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.

134
README.md

@ -2,73 +2,67 @@
[![Build Status](https://travis-ci.org/pressbooks/pressbooks-aldine.svg?branch=dev)](https://travis-ci.org/pressbooks/pressbooks-aldine) [![GitHub Release](https://img.shields.io/github/release/pressbooks/pressbooks-aldine/all.svg)](https://github.com/pressbooks/pressbooks-aldine/releases/latest)
Aldine is the new root theme for [Pressbooks](https://github.com/pressbooks/pressbooks), based on [Sage](https://roots.io/sage/).
## Features
* Sass for stylesheets
* ES6 for JavaScript
* [Webpack](https://webpack.github.io/) for compiling assets, optimizing images, and concatenating and minifying files
* [Browsersync](http://www.browsersync.io/) for synchronized browser testing
* [Laravel Blade](https://laravel.com/docs/5.4/blade) as a templating engine
* [Controller](https://github.com/soberwp/controller) for passing data to Blade templates
## Requirements
Make sure all dependencies have been installed before moving on:
* [PHP](http://php.net/manual/en/install.php) >= 7.0
* [Composer](https://getcomposer.org/download/)
* [WordPress](https://wordpress.org/) >= 4.8.1
* [Pressbooks](https://github.com/pressbooks/pressbooks) >= 4.3
* [Node.js](http://nodejs.org/) >= 6.9.x
* [Yarn](https://yarnpkg.com/en/docs/install)
## Theme installation
Download the [latest zipped release](https://github.com/pressbooks/pressbooks-aldine/releases/latest) to your Pressbooks themes directory (`wp-content/themes` or `app/themes`) and unzip the theme folder.
## Theme structure
```shell
themes/pressbooks-aldine/ # → Theme root
├── app/ # → Theme PHP
│ ├── controllers/ # → Controller files
│ ├── widgets/ # → Custom widget classes
│ ├── admin.php # → Theme customizer setup
│ ├── filters.php # → Theme filters
│ ├── helpers.php # → Helper functions
│ └── setup.php # → Theme setup
│ └── widgets.php # → Widget initialization
├── composer.json # → Autoloading for `app/` files
├── composer.lock # → Composer lock file (never edit)
├── dist/ # → Built theme assets (never edit)
├── functions.php # → Composer autoloader, theme includes
├── index.php # → Never manually edit
├── node_modules/ # → Node.js packages (never edit)
├── package.json # → Node.js dependencies and scripts
├── resources/ # → Theme assets and templates
│ ├── assets/ # → Front-end assets
│ │ ├── config.json # → Settings for compiled assets
│ │ ├── build/ # → Webpack and ESLint config
│ │ ├── fonts/ # → Theme fonts
│ │ ├── images/ # → Theme images
│ │ ├── scripts/ # → Theme JS
│ │ └── styles/ # → Theme stylesheets
│ └── views/ # → Theme templates
│ ├── layouts/ # → Base templates
│ └── partials/ # → Partial templates
├── screenshot.png # → Theme screenshot for WP admin
├── style.css # → Theme meta information
└── vendor/ # → Composer packages (never edit)
```
## Theme development
* Run `yarn` from the theme directory to install dependencies
### Build commands
* `yarn run start` — Compile assets when file changes are made, start Browsersync session
* `yarn run build` — Compile and optimize the files in your assets directory
* `yarn run build:production` — Compile assets for production
**Tags:** publishing, catalog, pressbooks, default-theme
**Requires at least:** 4.9.1
**Tested up to:** 4.9.1
**Stable tag:** 1.0.0-alpha6
**License:** GNU General Public License v2 or later
**License URI:** LICENSE
Aldine is the root theme for Pressbooks.
## Description
Aldine is the root theme for [Pressbooks](https://pressbooks.org), based on [Underscores](https://underscores.me/).
## Installation
1. In your admin panel, go to Appearance > Themes and click the Add New button.
2. Click Upload Theme and Choose File, then select the theme's [.zip file](https://github.com/pressbooks/pressbooks-aldine/releases/latest/). Click Install Now.
3. Click Activate to use your new theme right away.
## Frequently Asked Questions
TK.
## Changelog
### 1.0.0-alpha6
* **[FEATURE]** Add Per Soderlind's WCAG validator to customizer.
* **[FEATURE]** Add Thema subject support.
### 1.0.0-alpha5
* **[CORE ENHANCEMENT]** Configure for use without Pressbooks (see #26).
### 1.0.0-alpha4
* **[CORE ENHANCEMENT]** Save `/dist` folder.
* **[FIX]** Add temporary fix for roots/sage-lib#2.
### 1.0.0-alpha3
* **[CORE ENHANCEMENT]** Move required theme files to root (see #24 and #25).
### 1.0.0-alpha2
* **[CORE ENHANCEMENT]** Optimize activation routine.
* **[FIX]** Remove extra wrapper on catalog and landing pages.
* **[FIX]** Resolve error when activating without active widgets.
### 1.0.0-alpha1
* Basic landing page implementation
* Basic catalog page implementation
* Basic customizer capabilities
## Credits
* Based on [Underscores](https://underscores.me/), (C) 2012-2017 Automattic, Inc., [GPLv2 or later](https://www.gnu.org/licenses/gpl-2.0.html)

60
app/activation.php

@ -1,60 +0,0 @@
<?php
namespace Aldine;
add_action('admin_init', function () {
if (! get_option('pb_aldine_activated')) {
$extra = new \ParsedownExtra();
$about = $extra->text(file_get_contents(get_stylesheet_directory() . '/docs/about.md'));
$help = $extra->text(file_get_contents(get_stylesheet_directory() . '/docs/help.md'));
$default_pages = [
'about' => [
'post_title' => __('About', 'aldine'),
'post_content' => apply_filters('pb_root_about_page_content', $about)
],
'help' => [
'post_title' => __('Help', 'aldine'),
'post_content' => apply_filters('pb_root_help_page_content', $help)
],
'catalog' => [
'post_title' => __('Catalog', 'aldine'),
'post_content' => ''
],
'home' => [
'post_title' => __('Home', 'aldine'),
'post_content' => ''
],
];
// Add our pages
$pages = [];
foreach ($default_pages as $slug => $page) {
$check = get_page_by_path($slug);
if (empty($check)) {
$pages[$slug] = wp_insert_post(array_merge($page, ['post_type' => 'page', 'post_status' => 'publish']));
} else {
$pages[$slug] = $check->ID;
}
}
// Set front page to Home
update_option('show_on_front', 'page');
update_option('page_on_front', $pages['home']);
// Remove content generated by wp_install_defaults
if (! wp_delete_post(1, true)) {
return;
}
if (! wp_delete_post(2, true)) {
return;
}
if (! wp_delete_comment(1, true)) {
return;
}
// Add "pb_aldine_activated" option to enable check above
add_option('pb_aldine_activated', 1);
}
});

158
app/admin.php

@ -1,158 +0,0 @@
<?php
namespace Aldine;
/**
* Theme customizer
*/
add_action('customize_register', function (\WP_Customize_Manager $wp_customize) {
// Add postMessage support
$wp_customize->get_setting('blogname')->transport = 'postMessage';
$wp_customize->selective_refresh->add_partial('blogname', [
'selector' => '.branding h1 a',
'render_callback' => function () {
bloginfo('name');
}
]);
// Add settings
foreach ([
[
'slug' => 'primary',
'hex' => '#b01109',
'label' => __('Primary Color', 'aldine'),
'description' => __('Primary color, used for links and other primary elements.', 'aldine'),
],
[
'slug' => 'accent',
'hex' => '#015d75',
'label' => __('Accent Color', 'aldine'),
'description' => __('Accent color, used for flourishes and secondary elements.', 'aldine'),
],
[
'slug' => 'primary_fg',
'hex' => '#ffffff',
'label' => __('Primary Foreground Color', 'aldine'),
'description' => __('Used for text on a primary background.', 'aldine'),
],
[
'slug' => 'accent_fg',
'hex' => '#ffffff',
'label' => __('Accent Foreground Color', 'aldine'),
'description' => __('Used for text on an accent color background.', 'aldine'),
],
] as $color) {
$wp_customize->add_setting("pb_network_color_{$color['slug']}", [
'type' => 'option',
'default' => $color['hex'],
]);
$wp_customize->add_control(new \WP_Customize_Color_Control(
$wp_customize,
"pb_network_color_{$color['slug']}",
[
'label' => $color['label'],
'section' => 'colors',
'description' => $color['description'],
'settings' => "pb_network_color_{$color['slug']}",
]
));
}
$wp_customize->add_section('pb_network_social', [
'title' => __('Social Media', 'aldine'),
'priority' => 30,
]);
$wp_customize->add_setting('pb_network_facebook', [
'type' => 'option',
'sanitize_callback' => 'esc_url_raw',
]);
$wp_customize->add_control('pb_network_facebook', [
'label' => __('Facebook', 'aldine'),
'section' => 'pb_network_social',
'settings' => 'pb_network_facebook',
]);
$wp_customize->add_setting('pb_network_twitter', [
'type' => 'option',
'sanitize_callback' => 'esc_url_raw',
]);
$wp_customize->add_control('pb_network_twitter', [
'label' => __('Twitter', 'aldine'),
'section' => 'pb_network_social',
'settings' => 'pb_network_twitter',
]);
if (function_exists('pb_meets_minimum_requirements') && pb_meets_minimum_requirements()) {
$wp_customize->add_section('pb_front_page_catalog', [
'title' => __('Front Page Catalog', 'aldine'),
'priority' => 25,
]);
$wp_customize->add_setting('pb_front_page_catalog', [
'type' => 'option',
]);
$wp_customize->add_control('pb_front_page_catalog', [
'label' => __('Show Front Page Catalog', 'aldine'),
'section' => 'pb_front_page_catalog',
'settings' => 'pb_front_page_catalog',
'type' => 'checkbox'
]);
$wp_customize->add_setting('pb_front_page_catalog_title', [
'type' => 'option',
'sanitize_callback' => 'sanitize_text_field'
]);
$wp_customize->add_control('pb_front_page_catalog_title', [
'label' => __('Front Page Catalog Title', 'aldine'),
'section' => 'pb_front_page_catalog',
'settings' => 'pb_front_page_catalog_title',
]);
}
$wp_customize->add_section('pb_network_contact_form', [
'title' => __('Contact Form', 'aldine'),
'priority' => 25,
]);
$wp_customize->add_setting('pb_network_contact_form', [
'type' => 'option',
]);
$wp_customize->add_control('pb_network_contact_form', [
'label' => __('Show Contact Form', 'aldine'),
'section' => 'pb_network_contact_form',
'settings' => 'pb_network_contact_form',
'type' => 'checkbox'
]);
$wp_customize->add_setting('pb_network_contact_form_title', [
'type' => 'option',
'sanitize_callback' => 'sanitize_text_field'
]);
$wp_customize->add_control('pb_network_contact_form_title', [
'label' => __('Contact Form Title', 'aldine'),
'section' => 'pb_network_contact_form',
'settings' => 'pb_network_contact_form_title',
]);
});
/**
* Customizer JS
*/
add_action('customize_preview_init', function () {
wp_enqueue_script('aldine/customizer.js', asset_path('scripts/customizer.js'), ['customize-preview'], null, true);
wp_localize_script('aldine/customizer.js', 'SAGE_DIST_PATH', get_theme_file_uri() . '/dist/');
});
add_action('customize_controls_enqueue_scripts', function () {
$handle = 'wcag-validate-customizer-color-contrast';
$src = get_theme_file_uri() .
'/lib/customizer-validate-wcag-color-contrast/customizer-validate-wcag-color-contrast.js';
$deps = [ 'customize-controls' ];
wp_enqueue_script($handle, $src, $deps);
$exports = [
'validate_color_contrast' => [
'pb_network_color_primary_fg' => [ 'pb_network_color_primary' ],
'pb_network_color_accent_fg' => [ 'pb_network_color_accent' ],
],
];
wp_scripts()->add_data(
$handle,
'data',
sprintf('var _validateWCAGColorContrastExports = %s;', wp_json_encode($exports))
);
});

159
app/controllers/App.php

@ -1,159 +0,0 @@
<?php
namespace Aldine;
use Sober\Controller\Controller;
class App extends Controller
{
public function siteLogo()
{
$custom_logo_id = get_theme_mod('custom_logo');
if (has_custom_logo()) {
return wp_get_attachment_image($custom_logo_id, 'original');
} else {
return file_get_contents(get_theme_file_path() . '/dist/' . asset_dir('images/logo.svg'));
}
}
public function siteName()
{
return get_bloginfo('name');
}
public function networkFacebook()
{
return get_option('pb_network_facebook');
}
public function networkTwitter()
{
return get_option('pb_network_twitter');
}
public static function networkFooter($index)
{
if ($index === 2) {
if (get_option('pb_network_facebook')
|| get_option('pb_network_twitter')
|| is_active_sidebar("network-footer-block-$index")
) {
return $index;
} else {
return 'empty';
}
}
return (is_active_sidebar("network-footer-block-$index")) ?
$index :
'empty';
}
public static function title()
{
if (is_home()) {
if ($home = get_option('page_for_posts', true)) {
return get_the_title($home);
}
return __('Latest Posts', 'aldine');
}
if (is_archive()) {
return get_the_archive_title();
}
if (is_search()) {
return sprintf(__('Search Results for %s', 'aldine'), get_search_query());
}
if (is_404()) {
return __('Not Found', 'aldine');
}
return get_the_title();
}
public function contactFormTitle()
{
$title = get_option('pb_network_contact_form_title');
if ($title) {
return $title;
}
return __('Contact Us', 'aldine');
}
public function currentPage()
{
if (is_front_page()) {
return (get_query_var('page')) ? get_query_var('page') : 1;
} else {
return (get_query_var('paged')) ? get_query_var('paged') : 1;
}
}
public function currentSubject()
{
return (get_query_var('subject')) ? get_query_var('subject') : '';
}
public function currentLicense()
{
return (get_query_var('license')) ? get_query_var('license') : '';
}
public function currentOrderBy()
{
return (get_query_var('orderby')) ? get_query_var('orderby') : 'title';
}
public function previousPage()
{
if (is_front_page()) {
$page = (get_query_var('page')) ? get_query_var('page') : 1;
} else {
$page = (get_query_var('paged')) ? get_query_var('paged') : 1;
}
return ($page > 1) ? $page - 1 : 0;
}
public function nextPage()
{
if (is_front_page()) {
$page = (get_query_var('page')) ? get_query_var('page') : 1;
} else {
$page = (get_query_var('paged')) ? get_query_var('paged') : 1;
}
return $page + 1;
}
public static function catalogData($page = 1, $per_page = 10, $orderby = 'title', $license = '', $subject = '')
{
if (function_exists('pb_meets_minimum_requirements') && pb_meets_minimum_requirements()) {
$request = new \WP_REST_Request('GET', '/pressbooks/v2/books');
$request->set_query_params([
'page' => $page,
'per_page' => $per_page,
]);
$response = rest_do_request($request);
$pages = $response->headers['X-WP-TotalPages'];
$data = rest_get_server()->response_to_data($response, true);
$books = [];
foreach ($data as $key => $book) {
$book['title'] = $book['metadata']['name'];
$book['date-published'] = (isset($book['metadata']['datePublished'])) ?
$book['metadata']['datePublished'] :
'';
$book['subject'] = (isset($book['metadata']['about'][0]))
? $book['metadata']['about'][0]['identifier']
: '';
$books[] = $book;
}
if ($orderby === 'latest') {
$books = wp_list_sort($books, $orderby, 'desc');
} else {
$books = wp_list_sort($books, $orderby);
}
return ['pages' => $pages, 'books' => $books];
} else {
return ['pages' => 0, 'books' => []];
}
}
}

33
app/controllers/FrontPage.php

@ -1,33 +0,0 @@
<?php
namespace Aldine;
use Sober\Controller\Controller;
class FrontPage extends Controller
{
public function blockCount()
{
global $_wp_sidebars_widgets;
if (!empty($_wp_sidebars_widgets['front-page-block'])) {
return count($_wp_sidebars_widgets['front-page-block']);
}
return 1;
}
public function latestBooksTitle()
{
$title = get_option('pb_front_page_catalog_title');
if ($title) {
return $title;
}
return __('Our Latest Titles', 'aldine');
}
public function catalogData()
{
$page = (get_query_var('page')) ? get_query_var('page') : 1;
return App::catalogData($page, 3);
}
}

35
app/controllers/PageCatalog.php

@ -1,35 +0,0 @@
<?php
namespace Aldine;
use Sober\Controller\Controller;
class PageCatalog extends Controller
{
public function licenses()
{
if (function_exists('pb_meets_minimum_requirements') && pb_meets_minimum_requirements()) {
$licenses = (new \Pressbooks\Licensing())->getSupportedTypes();
foreach ($licenses as $key => $value) {
$licenses[$key] = preg_replace("/\([^)]+\)/", '', $value['desc']);
}
return $licenses;
} else {
return [];
}
}
public function subjectGroups()
{
return \Pressbooks\Metadata\get_thema_subjects();
}
public function catalogData()
{
$page = (get_query_var('paged')) ? get_query_var('paged') : 1;
$orderby = (get_query_var('orderby')) ? get_query_var('orderby') : 'title';
$subject = (get_query_var('subject')) ? get_query_var('subject') : '';
$license = (get_query_var('license')) ? get_query_var('license') : '';
return App::catalogData($page, 9, $orderby, $license, $subject);
}
}

79
app/filters.php

@ -1,79 +0,0 @@
<?php
namespace Aldine;
/**
* Add <body> classes
*/
add_filter('body_class', function (array $classes) {
/** Add page slug if it doesn't exist */
if (is_single() || is_page() && !is_front_page()) {
if (!in_array(basename(get_permalink()), $classes)) {
$classes[] = basename(get_permalink());
}
}
/** Clean up class names for custom templates */
$classes = array_map(function ($class) {
return preg_replace(['/-blade(-php)?$/', '/^page-template-views/'], '', $class);
}, $classes);
return array_filter($classes);
});
/**
* Add "… Continued" to the excerpt
*/
add_filter('excerpt_more', function () {
return ' &hellip; <a href="' . get_permalink() . '">' . __('Continued', 'aldine') . '</a>';
});
/**
* Template Hierarchy should search for .blade.php files
*/
collect([
'index', '404', 'archive', 'author', 'category', 'tag', 'taxonomy', 'date', 'home',
'frontpage', 'page', 'paged', 'search', 'single', 'singular', 'attachment'
])->map(function ($type) {
add_filter("{$type}_template_hierarchy", __NAMESPACE__.'\\filter_templates');
});
/**
* Render page using Blade
*/
add_filter('template_include', function ($template) {
$data = collect(get_body_class())->reduce(function ($data, $class) use ($template) {
return apply_filters("sage/template/{$class}/data", $data, $template);
}, []);
if ($template) {
echo template($template, $data);
return get_stylesheet_directory().'/index.php';
}
return $template;
}, PHP_INT_MAX);
/**
* Tell WordPress how to find the compiled path of comments.blade.php
*/
add_filter('comments_template', function ($comments_template) {
$comments_template = str_replace(
[get_stylesheet_directory(), get_template_directory()],
'',
$comments_template
);
return template_path(locate_template(["views/{$comments_template}", $comments_template]) ?: $comments_template);
});
/**
* Fix Controller path
*/
add_filter('sober/controller/path', function () {
return get_template_directory() . '/app/controllers';
});
/**
* Remove Admin Bar callback
*/
add_action('admin_bar_init', function () {
remove_action('wp_head', '_admin_bar_bump_cb');
});

202
app/helpers.php

@ -1,202 +0,0 @@
<?php
namespace Aldine;
use Roots\Sage\Container;
/**
* Get the sage container.
*
* @param string $abstract
* @param array $parameters
* @param Container $container
* @return Container|mixed
*/
function sage($abstract = null, $parameters = [], Container $container = null)
{
$container = $container ?: Container::getInstance();
if (!$abstract) {
return $container;
}
return $container->bound($abstract)
? $container->makeWith($abstract, $parameters)
: $container->makeWith("sage.{$abstract}", $parameters);
}
/**
* Get / set the specified configuration value.
*
* If an array is passed as the key, we will assume you want to set an array of values.
*
* @param array|string $key
* @param mixed $default
* @return mixed|\Roots\Sage\Config
* @copyright Taylor Otwell
* @link https://github.com/laravel/framework/blob/c0970285/src/Illuminate/Foundation/helpers.php#L254-L265
*/
function config($key = null, $default = null)
{
if (is_null($key)) {
return sage('config');
}
if (is_array($key)) {
return sage('config')->set($key);
}
return sage('config')->get($key, $default);
}
/**
* @param string $file
* @param array $data
* @return string
*/
function template($file, $data = [])
{
if (remove_action('wp_head', 'wp_enqueue_scripts', 1)) {
wp_enqueue_scripts();
}
return sage('blade')->render($file, $data);
}
/**
* Retrieve path to a compiled blade view
* @param $file
* @param array $data
* @return string
*/
function template_path($file, $data = [])
{
return sage('blade')->compiledPath($file, $data);
}
/**
* @param $asset
* @return string
*/
function asset_path($asset)
{
return fix_path(sage('assets')->getUri('/' . $asset));
}
/**
* @param $asset
* @return string
*/
function asset_dir($asset)
{
return fix_path(sage('assets')->get('/' . $asset));
}
/**
* @param string|string[] $templates Possible template files
* @return array
*/
function filter_templates($templates)
{
$paths = apply_filters('sage/filter_templates/paths', [
'views',
'resources/views'
]);
$paths_pattern = "#^(" . implode('|', $paths) . ")/#";
return collect($templates)
->map(function ($template) use ($paths_pattern) {
/** Remove .blade.php/.blade/.php from template names */
$template = preg_replace('#\.(blade\.?)?(php)?$#', '', ltrim($template));
/** Remove partial $paths from the beginning of template names */
if (strpos($template, '/')) {
$template = preg_replace($paths_pattern, '', $template);
}
return $template;
})
->flatMap(function ($template) use ($paths) {
return collect($paths)
->flatMap(function ($path) use ($template) {
return [
"{$path}/{$template}.blade.php",
"{$path}/{$template}.php",
"{$template}.blade.php",
"{$template}.php",
];
});
})
->filter()
->unique()
->all();
}
/**
* @param string|string[] $templates Relative path to possible template files
* @return string Location of the template
*/
function locate_template($templates)
{
return \locate_template(filter_templates($templates));
}
/**
*
* Catch a contact form submission.
*
* @return false | array
*/
function contact_form_submission()
{
if (isset($_POST['submitted'])) {
$output = [];
$name = (isset($_POST['visitor_name'])) ? $_POST['visitor_name'] : false;
$email = (isset($_POST['visitor_email'])) ? $_POST['visitor_email'] : false;
$institution = (isset($_POST['visitor_institution'])) ? $_POST['visitor_institution'] : false;
$message = (isset($_POST['message'])) ? $_POST['message'] : false;
if (!$name) {
$output['message'] = __('Name is required.', 'aldine');
$output['status'] = 'error';
$output['field'] = 'visitor_name';
} elseif (!$email) {
$output['message'] = __('Email is required.', 'aldine');
$output['status'] = 'error';
$output['field'] = 'visitor_email';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$output['message'] = __('Email is invalid.', 'aldine');
$output['status'] = 'error';
$output['field'] = 'visitor_email';
} elseif (!$institution) {
$output['message'] = __('Institution is required.', 'aldine');
$output['status'] = 'error';
$output['field'] = 'visitor_institution';
} elseif (!$message) {
$output['message'] = __('Message is required.', 'aldine');
$output['status'] = 'error';
$output['field'] = 'message';
} else {
$sent = wp_mail(
get_option('admin_email'),
sprintf(__('Contact Form Submission from %s', 'aldine'), $name),
sprintf(
"From: %1\$s <%2\$s>\n%3\$s",
$name,
$email,
strip_tags($message)
),
"From: ${email}\r\nReply-To: ${email}\r\n"
);
if ($sent) {
$output['message'] = __('Your message was sent!', 'aldine');
$output['status'] = 'success';
} else {
$output['message'] = __('Your message could not be sent.', 'aldine');
$output['status'] = 'error';
}
}
return $output;
}
return false;
}
function fix_path($path)
{
return str_replace('/dist//', '/dist/', $path);
}

38
app/intervention.php

@ -1,38 +0,0 @@
<?php
namespace Aldine;
use function \Sober\Intervention\intervention;
if (function_exists('\Sober\Intervention\intervention')) {
intervention('remove-customizer-items', 'static-front-page', 'all');
intervention('remove-emoji');
intervention('remove-howdy', __('Hello,', 'aldine'));
intervention('remove-dashboard-items', ['activity', 'quick-draft']);
intervention('remove-menu-items', [
'posts',
'tools',
'setting-writing',
'setting-reading',
'setting-permalink'
], 'all');
intervention('remove-widgets', [
'pages',
'calendar',
'archives',
'links',
'media-audio',
'meta',
'search',
'categories',
'recent-posts',
'recent-comments',
'rss',
'tag-cloud',
'custom-menu',
'custom-html',
'media-video',
'akismet',
], 'all');
intervention('remove-toolbar-frontend', 'all');
}

199
app/setup.php

@ -1,199 +0,0 @@
<?php
namespace Aldine;
use Roots\Sage\Container;
use Roots\Sage\Assets\JsonManifest;
use Roots\Sage\Template\Blade;
use Roots\Sage\Template\BladeProvider;
/**
* Theme assets
*/
add_action('wp_enqueue_scripts', function () {
$webfonts = 'https://fonts.googleapis.com/css?family=Karla:400,400i,700|Spectral:400,400i,600';
wp_enqueue_style('aldine/webfonts', $webfonts, false, null);
wp_enqueue_style('aldine/main.css', asset_path('styles/main.css'), false, null);
wp_enqueue_script('aldine/main.js', asset_path('scripts/main.js'), ['jquery'], null, true);
wp_localize_script('aldine/main.js', 'SAGE_DIST_PATH', get_theme_file_uri() . '/dist/');
}, 100);
/**
* Theme setup
*/
add_action('after_setup_theme', function () {
/**
* Enable plugins to manage the document title
* @link https://developer.wordpress.org/reference/functions/add_theme_support/#title-tag
*/
add_theme_support('title-tag');
/**
* Register navigation menus
* @link https://developer.wordpress.org/reference/functions/register_nav_menus/
*/
register_nav_menus([
'network-footer-menu' => __('Network Footer Menu', 'aldine')
]);
/**
* Enable custom headers
* @link https://developer.wordpress.org/themes/functionality/custom-headers/
*/
add_theme_support('custom-header', [
'default-image' => asset_path('images/header.jpg'),
'width' => 1920,
'height' => 884,
'default-text-color' => '#000',
]);
/**
* Enable custom logos
* @link https://developer.wordpress.org/themes/functionality/custom-logo/
*/
add_theme_support('custom-logo', [
'height' => 40,
'width' => 265,
'flex-width' => true,
'flex-height' => true,
]);
/**
* Enable post thumbnails
* @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
*/
add_theme_support('post-thumbnails');
/**
* Enable HTML5 markup support
* @link https://developer.wordpress.org/reference/functions/add_theme_support/#html5
*/
add_theme_support('html5', ['caption', 'comment-form', 'comment-list', 'gallery', 'search-form']);
/**
* Enable selective refresh for widgets in customizer
* @link https://developer.wordpress.org/themes/advanced-topics/customizer-api/#theme-support-in-sidebars
*/
add_theme_support('customize-selective-refresh-widgets');
/**
* Use main stylesheet for visual editor
* @see resources/assets/styles/layouts/_tinymce.scss
*/
add_editor_style(asset_path('styles/main.css'));
}, 20);
/**
* Register sidebars
*/
add_action('widgets_init', function () {
$config = [
'before_widget' => '<section class="widget %1$s %2$s">',
'after_widget' => '</section>',
'before_title' => '<h2>',
'after_title' => '</h2>'
];
register_sidebar([
'name' => __('Front Page Content', 'aldine'),
'description' => __(
'Add content for your network&rsquo;s front page here. Currently, only text widgets are supported.',
'aldine'
),
'id' => 'front-page-block',
'before_widget' => '<section class="block %1$s %2$s">',
'after_widget' => '</section>',
'before_title' => '<h2>',
'after_title' => '</h2>'
]);
register_sidebar([
'name' => __('Network Footer Block 1', 'aldine'),
'description' => __(
'Add content for your network&rsquo;s customizeable footer here.
Currently, only text and image widgets are supported.
Content in this widget area will appear in the first row (on mobile) or the first column (on desktops).',
'aldine'
),
'id' => 'network-footer-block-1'
] + $config);
register_sidebar([
'name' => __('Network Footer Block 2', 'aldine'),
'description' => __(
'Add content for your network&rsquo;s customizeable footer here.
Currently, only text and image widgets are supported.
Content in this widget area will appear in the second row (on mobile) or the middle column (on desktop).',
'aldine'
),
'id' => 'network-footer-block-2'
] + $config);
});
/**
* Updates the `$post` variable on each iteration of the loop.
* Note: updated value is only available for subsequently loaded views, such as partials
*/
add_action('the_post', function ($post) {
sage('blade')->share('post', $post);
});
/**
* Setup Sage options
*/
add_action('after_setup_theme', function () {
/**
* Add JsonManifest to Sage container
*/
sage()->singleton('sage.assets', function () {
return new JsonManifest(config('assets.manifest'), config('assets.uri'));
});
/**
* Add Blade to Sage container
*/
sage()->singleton('sage.blade', function (\Illuminate\Container\Container $app) {
$cachePath = config('view.compiled');
if (!file_exists($cachePath)) {
wp_mkdir_p($cachePath);
}
(new BladeProvider($app))->register();
return new Blade($app['view']);
});
/**
* Create @asset() Blade directive
*/
sage('blade')->compiler()->directive('asset', function ($asset) {
return "<?= " . __NAMESPACE__ . "\\asset_path({$asset}); ?>";
});
});
add_action('wp_head', function () {
$primary = get_option('pb_network_color_primary');
$accent = get_option('pb_network_color_accent');
$primary_fg = get_option('pb_network_color_primary_fg');
$accent_fg = get_option('pb_network_color_accent_fg');
$header_text = get_header_textcolor();
if ($primary || $accent || $primary_fg || $accent_fg || $header_text) { ?>
<style type="text/css">:root {
<?php if ($primary) { ?>
--primary: <?= $primary ?>;
<?php }
if ($accent) { ?>
--accent: <?= $accent ?>;
<?php }
if ($primary_fg) { ?>
--primary-fg: <?= $primary_fg ?>;
<?php }
if ($accent_fg) { ?>
--accent-fg: <?= $accent_fg ?>;
<?php }
if ($header_text) { ?>
--header-text: <?= $header_text ?>;
<?php } ?>
}</style>
<?php }
});
add_action('wp_head', function () {
$response = contact_form_submission();
sage('blade')->share('contact_form_response', $response);
});

51
archive.php

@ -0,0 +1,51 @@
<?php
/**
* The template for displaying archive pages
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/
*
* @package Aldine
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<?php
if ( have_posts() ) : ?>
<header class="page-header">
<?php
the_archive_title( '<h1 class="page-title">', '</h1>' );
the_archive_description( '<div class="archive-description">', '</div>' );
?>
</header><!-- .page-header -->
<?php
/* Start the Loop */
while ( have_posts() ) : the_post();
/*
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
the_posts_navigation();
else :
get_template_part( 'template-parts/content', 'none' );
endif; ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_sidebar();
get_footer();

0
resources/assets/fonts/.gitkeep → assets/fonts/.gitkeep

0
resources/assets/fonts/pressbooks-theme.woff → assets/fonts/pressbooks-theme.woff

0
resources/assets/images/.gitkeep → assets/images/.gitkeep

0
resources/assets/images/banner.jpg → assets/images/banner.jpg

Before

Width:  |  Height:  |  Size: 530 KiB

After

Width:  |  Height:  |  Size: 530 KiB

0
resources/assets/images/catalog-header.jpg → assets/images/catalog-header.jpg

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 43 KiB

0
resources/assets/images/header.jpg → assets/images/header.jpg

Before

Width:  |  Height:  |  Size: 176 KiB

After

Width:  |  Height:  |  Size: 176 KiB

0
resources/assets/images/left-arrow.svg → assets/images/left-arrow.svg

Before

Width:  |  Height:  |  Size: 447 B

After

Width:  |  Height:  |  Size: 447 B

0
resources/assets/images/logo.svg → assets/images/logo.svg

Before

Width:  |  Height:  |  Size: 6.6 KiB

After

Width:  |  Height:  |  Size: 6.6 KiB

0
resources/assets/images/pb.svg → assets/images/pb.svg

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

0
resources/assets/images/right-arrow.svg → assets/images/right-arrow.svg

Before

Width:  |  Height:  |  Size: 436 B

After

Width:  |  Height:  |  Size: 436 B

0
resources/assets/scripts/main.js → assets/scripts/aldine.js

2
resources/assets/scripts/customizer.js → assets/scripts/customizer.js

@ -1,5 +1,5 @@
import $ from 'jquery';
wp.customize( 'blogname', value => {
value.bind( to => $( '.brand' ).text( to ) );
value.bind( to => $( '.brand a' ).text( to ) );
} );

112
assets/scripts/routes/catalog.js

@ -0,0 +1,112 @@
const jQueryBridget = require( 'jquery-bridget' );
const Isotope = require( 'isotope-layout' );
export default {
init() {
// JavaScript to be fired on the catalog page
jQueryBridget( 'isotope', Isotope, $ );
let $grid = $( '.books' );
$grid.isotope( {
itemSelector: '.book',
getSortData: {
title: '.title a',
subject: '[data-subject]',
latest: '[data-date-published]',
},
sortAscending: {
title: true,
subject: true,
latest: false,
},
} );
$( '.filters > a' ).click( e => {
e.preventDefault();
$( '.filters' ).toggleClass( 'is-active' );
$( '.filter-groups > div' ).removeClass( 'is-active' );
} );
$( '.filter-groups .subjects > a' ).click( e => {
e.preventDefault();
let id = $( e.currentTarget ).attr( 'href' );
$( `.filter-groups .subjects:not(${id})` ).removeClass( 'is-active' );
$( `.filter-groups ${id}` ).toggleClass( 'is-active' );
} );
$( '.licenses > a' ).click( e => {
e.preventDefault();
let id = $( e.currentTarget ).attr( 'href' );
$( id ).toggleClass( 'is-active' );
} );
$( '.subjects .filter-list a' ).click( e => {
e.preventDefault();
if ( $( e.currentTarget ).hasClass( 'is-active' ) ) {
$( '.subjects .filter-list a' ).removeClass( 'is-active' );
$( '.subjects' ).removeClass( 'has-active-child' );
} else {
$( '.subjects .filter-list a' ).removeClass( 'is-active' );
$( e.currentTarget ).addClass( 'is-active' );
$( '.subjects' ).removeClass( 'has-active-child' );
$( e.currentTarget )
.parent()
.parent()
.parent( '.subjects' )
.addClass( 'has-active-child' );
}
let subjectValue = $( '.subjects .filter-list a.is-active' ).attr(
'data-filter'
);
let licenseValue = $( '.licenses .filter-list a.is-active' ).attr(
'data-filter'
);
if ( typeof licenseValue === 'undefined' ) {
licenseValue = '';
} else {
licenseValue = `[data-license="${licenseValue}"]`;
}
if ( typeof subjectValue === 'undefined' ) {
subjectValue = '';
} else {
subjectValue = `[data-subject="${subjectValue}"]`;
}
$grid.isotope( { filter: `${subjectValue}${licenseValue}` } );
} );
$( '.licenses .filter-list a' ).click( e => {
e.preventDefault();
if ( $( e.currentTarget ).hasClass( 'is-active' ) ) {
$( '.licenses .filter-list a' ).removeClass( 'is-active' );
$( '.licenses' ).removeClass( 'has-active-child' );
} else {
$( '.licenses .filter-list a' ).removeClass( 'is-active' );
$( e.currentTarget ).addClass( 'is-active' );
$( '.licenses' ).addClass( 'has-active-child' );
}
let subjectValue = $( '.subjects .filter-list a.is-active' ).attr(
'data-filter'
);
let licenseValue = $( '.licenses .filter-list a.is-active' ).attr(
'data-filter'
);
if ( typeof licenseValue === 'undefined' ) {
licenseValue = '';
} else {
licenseValue = `[data-license="${licenseValue}"]`;
}
if ( typeof subjectValue === 'undefined' ) {
subjectValue = '';
} else {
subjectValue = `[data-subject="${subjectValue}"]`;
}
$grid.isotope( { filter: `${subjectValue}${licenseValue}` } );
} );
$( '.sort > a' ).click( e => {
e.preventDefault();
$( '.sort' ).toggleClass( 'is-active' );
} );
$( '.sorts a' ).click( e => {
e.preventDefault();
let sortBy = $( e.currentTarget ).attr( 'data-sort' );
$( '.sorts a' ).removeClass( 'is-active' );
$( e.currentTarget ).addClass( 'is-active' );
$grid.isotope( { sortBy: sortBy } );
} );
},
finalize() {},
};

16
assets/scripts/routes/common.js

@ -0,0 +1,16 @@
export default {
init() {
// JavaScript to be fired on all pages
$( 'body' )
.removeClass( 'no-js' )
.addClass( 'js' );
$( '.toggle' ).click( event => {
event.preventDefault();
$( event.currentTarget ).toggleClass( 'toggle--active' );
$( '.banner__navigation' ).toggleClass( 'banner__navigation--visible' );
} );
},
finalize() {
// JavaScript to be fired on all pages, after page specific JS is fired
},
};

6
assets/scripts/routes/home.js

@ -0,0 +1,6 @@
export default {
init() {
// JavaScript to be fired on the home page
},
finalize() {},
};

0
resources/assets/scripts/util/Router.js → assets/scripts/util/Router.js

0
resources/assets/scripts/util/camelCase.js → assets/scripts/util/camelCase.js

2
resources/assets/styles/main.scss → assets/styles/aldine.scss

@ -6,7 +6,7 @@
* Prefix your imports with `~` to grab from node_modules/
* @see https://github.com/webpack-contrib/sass-loader#imports
*/
@import '~aetna/assets/styles/aetna.scss';
@import "~aetna/assets/styles/aetna.scss";
/** Import theme styles */
// @import "common/global";

0
resources/assets/styles/common/_global.scss → assets/styles/common/_global.scss

0
resources/assets/styles/common/_variables.scss → assets/styles/common/_variables.scss

0
resources/assets/styles/components/_comments.scss → assets/styles/components/_comments.scss

0
resources/assets/styles/components/_forms.scss → assets/styles/components/_forms.scss

0
resources/assets/styles/components/_grid.scss → assets/styles/components/_grid.scss

0
resources/assets/styles/components/_wp-classes.scss → assets/styles/components/_wp-classes.scss

0
resources/assets/styles/layouts/_footer.scss → assets/styles/layouts/_footer.scss

0
resources/assets/styles/layouts/_header.scss → assets/styles/layouts/_header.scss

0
resources/assets/styles/layouts/_pages.scss → assets/styles/layouts/_pages.scss

0
resources/assets/styles/layouts/_posts.scss → assets/styles/layouts/_posts.scss

0
resources/assets/styles/layouts/_sidebar.scss → assets/styles/layouts/_sidebar.scss

0
resources/assets/styles/layouts/_tinymce.scss → assets/styles/layouts/_tinymce.scss

0
resources/assets/styles/layouts/pages/_catalog.scss → assets/styles/layouts/pages/_catalog.scss

0
resources/assets/styles/layouts/pages/_front-page.scss → assets/styles/layouts/pages/_front-page.scss

0
resources/assets/styles/login.scss → assets/styles/login.scss

72
comments.php

@ -0,0 +1,72 @@
<?php
/**
* The template for displaying comments
*
* This is the template that displays the area of the page that contains both the current comments
* and the comment form.
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/
*
* @package Aldine
*/
/*
* If the current post is protected by a password and
* the visitor has not yet entered the password we will
* return early without loading the comments.
*/
if ( post_password_required() ) {
return;
}
?>
<div id="comments" class="comments-area">
<?php
// You can start editing here -- including this comment!
if ( have_comments() ) : ?>
<h2 class="comments-title">
<?php
$comment_count = get_comments_number();
if ( 1 === $comment_count ) {
printf(
/* translators: 1: title. */
esc_html_e( 'One thought on &ldquo;%1$s&rdquo;', 'pressbooks-aldine' ),
'<span>' . get_the_title() . '</span>'
);
} else {
printf( // WPCS: XSS OK.
/* translators: 1: comment count number, 2: title. */
esc_html( _nx( '%1$s thought on &ldquo;%2$s&rdquo;', '%1$s thoughts on &ldquo;%2$s&rdquo;', $comment_count, 'comments title', 'pressbooks-aldine' ) ),
number_format_i18n( $comment_count ),
'<span>' . get_the_title() . '</span>'
);
}
?>
</h2><!-- .comments-title -->
<?php the_comments_navigation(); ?>
<ol class="comment-list">
<?php
wp_list_comments( [
'style' => 'ol',
'short_ping' => true,
] );
?>
</ol><!-- .comment-list -->
<?php the_comments_navigation();
// If comments are closed and there are comments, let's leave a little note, shall we?
if ( ! comments_open() ) : ?>
<p class="no-comments"><?php esc_html_e( 'Comments are closed.', 'pressbooks-aldine' ); ?></p>
<?php
endif;
endif; // Check for have_comments().
comment_form();
?>
</div><!-- #comments -->

98
composer.json

@ -1,61 +1,41 @@
{
"name": "pressbooks/pressbooks-aldine",
"type": "wordpress-theme",
"license": "GPL-3",
"description": "Aldine is the new root theme for Pressbooks, based on Sage.",
"homepage": "https://github.com/pressbooks/pressbooks-aldine/",
"authors": [
{
"name": "Pressbooks (Book Oven Inc.)",
"email": "code@pressbooks.com",
"homepage": "https://pressbooks.org"
},
{
"name": "Ben Word",
"email": "ben@benword.com",
"homepage": "https://github.com/retlehs"
},
{
"name": "Scott Walkinshaw",
"email": "scott.walkinshaw@gmail.com",
"homepage": "https://github.com/swalkinshaw"
},
{
"name": "QWp6t",
"email": "hi@qwp6t.me",
"homepage": "https://github.com/qwp6t"
}
],
"keywords": [
"publishing",
"catalog",
"pressbooks",
"default-theme"
],
"support": {
"issues": "https://github.com/pressbooks/pressbooks-aldine/issues",
"forum": "https://discourse.pressbooks.org/"
},
"autoload": {
"psr-4": {
"Aldine\\": "app/"
}
},
"require": {
"php": ">=7",
"composer/installers": "~1.0",
"illuminate/support": "~5.4",
"roots/sage-lib": "~9.0.0-beta.4",
"soberwp/controller": "~9.0.0-beta.4",
"soberwp/intervention": "1.2.0-p",
"erusev/parsedown-extra": "^0.7.1"
},
"require-dev": {
"squizlabs/php_codesniffer": "^2.8.0"
},
"scripts": {
"test": [
"phpcs"
]
}
"name": "pressbooks/pressbooks-aldine",
"type": "wordpress-theme",
"license": "GPL-2.0+",
"description": "Aldine is the root theme for Pressbooks.",
"homepage": "https://github.com/pressbooks/pressbooks-aldine/",
"authors": [
{
"name": "Pressbooks (Book Oven Inc.)",
"email": "code@pressbooks.com",
"homepage": "https://pressbooks.org"
}
],
"keywords": ["publishing", "catalog", "pressbooks", "default-theme"],
"support": {
"issues": "https://github.com/pressbooks/pressbooks-aldine/issues",
"forum": "https://discourse.pressbooks.org/"
},
"require": {
"php": ">=7",
"composer/installers": "~1.0",
"pressbooks/mix": "^2.1",
"soberwp/intervention": "1.2.0-p",
"erusev/parsedown-extra": "^0.7.1"
},
"require-dev": {
"humanmade/coding-standards": "^0.2.1",
"squizlabs/php_codesniffer": "^2.8.0",
"wpreadme2markdown/wp2md": "^3.0"
},
"scripts": {
"test": ["@standards"],
"standards": [
"vendor/bin/phpcs --standard=phpcs.ruleset.xml inc partials *.php"
],
"localize": [
"wp-pot -o=languages/pressbooks-aldine.pot -d=pressbooks-aldine -t 'Pressbooks (Book Oven Inc.) <code@pressbooks.com>' -s '*.php'"
],
"readme": ["vendor/bin/wp2md -i readme.txt -o README.md"]
}
}

999
composer.lock generated

File diff suppressed because it is too large Load Diff

31
config/assets.php

@ -1,31 +0,0 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Assets Manifest
|--------------------------------------------------------------------------
|
| Your asset manifest is used by Sage to assist WordPress and your views
| with rendering the correct URLs for your assets. This is especially
| useful for statically referencing assets with dynamically changing names
| as in the case of cache-busting.
|
*/
'manifest' => get_theme_file_path().'/dist/mix-manifest.json',
/*
|--------------------------------------------------------------------------
| Assets Path URI
|--------------------------------------------------------------------------
|
| The asset manifest contains relative paths to your assets. This URI will
| be prepended when using Sage's asset management system. Change this if
| you are using a CDN.
|
*/
'uri' => get_theme_file_uri().'/dist',
];

32
config/theme.php

@ -1,32 +0,0 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Theme Directory
|--------------------------------------------------------------------------
|
| This is the absolute path to your theme directory.
|
| Example:
| /srv/www/example.com/current/web/app/themes/sage
|
*/
'dir' => get_theme_file_path(),
/*
|--------------------------------------------------------------------------
| Theme Directory URI
|--------------------------------------------------------------------------
|
| This is the web server URI to your theme directory.
|
| Example:
| https://example.com/app/themes/sage
|
*/
'uri' => get_theme_file_uri(),
];

51
config/view.php

@ -1,51 +0,0 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most template systems load templates from disk. Here you may specify
| an array of paths that should be checked for your views.
|
*/
'paths' => [
get_theme_file_path().'/resources/views',
get_parent_theme_file_path().'/resources/views',
],
/*
|--------------------------------------------------------------------------
| Compiled View Path
|--------------------------------------------------------------------------
|
| This option determines where all the compiled Blade templates will be
| stored for your application. Typically, this is within the uploads
| directory. However, as usual, you are free to change this value.
|
*/
'compiled' => wp_upload_dir()['basedir'].'/cache',
/*
|--------------------------------------------------------------------------
| View Namespaces
|--------------------------------------------------------------------------
|
| Blade has an underutilized feature that allows developers to add
| supplemental view paths that may contain conflictingly named views.
| These paths are prefixed with a namespace to get around the conflicts.
| A use case might be including views from within a plugin folder.
|
*/
'namespaces' => [
/* Given the below example, in your views use something like: @include('WC::some.view.or.partial.here') */
// 'WC' => WP_PLUGIN_DIR.'/woocommerce/templates/',
],
];

6
dist/mix-manifest.json vendored

@ -1,5 +1,5 @@
{
"/scripts/main.js": "/scripts/main.js?id=02b42ac2ce995252e0ba",
"/styles/main.css": "/styles/main.css?id=8021de4bdd5014faae77",
"/scripts/customizer.js": "/scripts/customizer.js?id=16bf84cad576a20cf73d"
"/scripts/aldine.js": "/scripts/aldine.js?id=8a707791c89c90b8f4c6",
"/styles/aldine.css": "/styles/aldine.css?id=8021de4bdd5014faae77",
"/scripts/customizer.js": "/scripts/customizer.js?id=f1f1f4225cba4c1b35f2"
}

1
dist/scripts/aldine.js vendored

File diff suppressed because one or more lines are too long

2
dist/scripts/customizer.js vendored

File diff suppressed because one or more lines are too long

1
dist/scripts/main.js vendored

File diff suppressed because one or more lines are too long

0
dist/styles/main.css → dist/styles/aldine.css vendored

85
footer.php

@ -1,6 +1,81 @@
</div>
<?php do_action('get_footer');
echo \Aldine\template('partials/footer');
wp_footer(); ?>
</body>
<?php
/**
* The template for displaying the footer
*
* Contains the closing of the #content div and all content after.
*
* @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
*
* @package Aldine
*/
?>
<?php
$network_facebook = get_option( 'pb_network_facebook' );
$network_twitter = get_option( 'pb_network_twitter' );
$pb_network_contact_form = get_option( 'pb_network_contact_form' );
?>
</div><!-- #content -->
<footer class="footer<?php echo is_front_page() ? ' footer--home' : ' footer--inside' ?>" role="contentinfo">
<div class="footer__inner">
<?php if ( $pb_network_contact_form ) :
include( locate_template( 'partials/contact-form.php' ) );
endif; ?>
<section class="footer__network">
<div class="footer__network__block">
<?php dynamic_sidebar( 'network-footer-block-1' ); ?>
</div>
<div class="footer__network__block">
<?php dynamic_sidebar( 'network-footer-block-2' ); ?>
<div class="social-media">
<?php if ( $network_facebook ) { ?>
<a class="link near-black hover-silver dib h2 w2 mr3" href="<?php echo $network_facebook; ?>" title="<?php printf( __( '%s on Facebook', 'aldine' ), get_bloginfo( 'name', 'display' ) ); ?>">
<svg fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="1.414"><path d="M15.117 0H.883C.395 0 0 .395 0 .883v14.234c0 .488.395.883.883.883h7.663V9.804H6.46V7.39h2.086V5.607c0-2.066 1.262-3.19 3.106-3.19.883 0 1.642.064 1.863.094v2.16h-1.28c-1 0-1.195.476-1.195 1.176v1.54h2.39l-.31 2.416h-2.08V16h4.077c.488 0 .883-.395.883-.883V.883C16 .395 15.605 0 15.117 0" fill-rule="nonzero"/></svg>
</a>
<?php } ?>
<?php if ( $network_twitter ) { ?>
<a class="link near-black hover-silver dib h2 w2 mr3" href="<?php echo $network_twitter; ?>" title="<?php printf( __( '%s on Twitter', 'aldine' ), get_bloginfo( 'name', 'display' ) ); ?>">
<svg fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="1.414"><path d="M16 3.038c-.59.26-1.22.437-1.885.517.677-.407 1.198-1.05 1.443-1.816-.634.375-1.337.648-2.085.795-.598-.638-1.45-1.036-2.396-1.036-1.812 0-3.282 1.468-3.282 3.28 0 .258.03.51.085.75C5.152 5.39 2.733 4.084 1.114 2.1.83 2.583.67 3.147.67 3.75c0 1.14.58 2.143 1.46 2.732-.538-.017-1.045-.165-1.487-.41v.04c0 1.59 1.13 2.918 2.633 3.22-.276.074-.566.114-.865.114-.21 0-.416-.02-.617-.058.418 1.304 1.63 2.253 3.067 2.28-1.124.88-2.54 1.404-4.077 1.404-.265 0-.526-.015-.783-.045 1.453.93 3.178 1.474 5.032 1.474 6.038 0 9.34-5 9.34-9.338 0-.143-.004-.284-.01-.425.64-.463 1.198-1.04 1.638-1.7z" fill-rule="nonzero"/></svg>
</a>
<?php } ?>
</div>
</div>
<div class="network-footer__block network-footer__menu">
<?php wp_nav_menu( 'network-footer-menu' ); ?>
</div>
</section>
<section class="footer__pressbooks">
<a class="footer__pressbooks__icon" href="https://pressbooks.com" title="Pressbooks">
<?php // TODO ?>
<svg class="icon--svg">
<use xlink:href="#icon-pressbooks" />
</svg>
</a>
<div class="footer__pressbooks__links">
<h1 class="footer__pressbooks__links__title"><a href="https://pressbooks.com"><?php printf( __( 'Powered by %s', 'pressbooks-book' ), '<span class="pressbooks">Pressbooks</span>' ); ?></a></h1>
<ul class="footer__pressbooks__links__list">
<li><a href="https://pressbooks.org"><?php _e( 'Open Source', 'pressbooks-book' ); ?></a> |</li>
<li><a href="https://pressbooks.com/for-academia"><?php _e( 'Open Textbooks', 'pressbooks-book' ); ?></a> |</li>
<li><a href="https://pressbooks.com"><?php _e( 'Open Book Publishing', 'pressbooks-book' ); ?></a> |</li>
<li><a href="https://pressbooks.com/about"><?php _e( 'Learn More', 'pressbooks-book' ); ?></a> </li>
</ul>
</div>
<div class="footer__pressbooks__social">
<a class="icon icon-facebook" href="https://facebook.com/pressbooks2" title="<?php _e( 'Pressbooks on Facebook', 'pressbooks-book' ); ?>"> </a>
<a class="icon icon-twitter" href="https://twitter.com/intent/follow?screen_name=pressbooks" title="<?php _e( 'Pressbooks on Twitter', 'pressbooks-book' ); ?>"> </a>
</div>
</section>
</div><!-- .container -->
</footer><!-- .footer -->
<?php get_template_part( 'content', 'accessibility-toolbar' ); ?>
<?php wp_footer(); ?>
</body>
</html>

255
functions.php

@ -1,97 +1,198 @@
<?php
/**
* Do not edit anything in this file unless you know what you're doing
*/
use Roots\Sage\Config;
use Roots\Sage\Container;
/**
* Helper function for prettying up errors
* @param string $message
* @param string $subtitle
* @param string $title
* Aldine functions and definitions
*
* @link https://developer.wordpress.org/themes/basics/theme-functions/
*
* @package Aldine
*/
$sage_error = function ($message, $subtitle = '', $title = '') {
$title = $title ?: __('Sage &rsaquo; Error', 'aldine');
$footer = '<a href="https://roots.io/sage/docs/">roots.io/sage/docs/</a>';
$message = "<h1>{$title}<br><small>{$subtitle}</small></h1><p>{$message}</p><p>{$footer}</p>";
wp_die($message, $title);
};
/**
* Ensure compatible version of PHP is used
* Ensure dependencies are loaded
*/
if (version_compare('7', phpversion(), '>=')) {
$sage_error(__('You must be using PHP 7 or greater.', 'aldine'), __('Invalid PHP version', 'aldine'));
if ( ! class_exists( 'PressbooksMix\\Assets' ) ) {
$composer = get_template_directory() . '/vendor/autoload.php';
if ( ! file_exists( $composer ) ) {
wp_die( sprintf(
'<h1>%1$s</h1><p>%2$s</p>',
__( 'Dependencies Missing', 'aldine' ),
__( 'You must run <code>composer install</code> from the Aldine directory.', 'aldine' )
) );
}
require_once $composer;
}
use PressbooksMix\Assets;
/**
* Ensure compatible version of WordPress is used
*/
if (version_compare('4.7.0', get_bloginfo('version'), '>=')) {
$sage_error(
__('You must be using WordPress 4.7.0 or greater.', 'aldine'),
__('Invalid WordPress version', 'aldine')
);
$includes = [
'actions',
'activation',
'customizer',
'filters',
'helpers',
'tags',
];
foreach ( $includes as $include ) {
require get_template_directory() . "/inc/$include/namespace.php";
}
require get_template_directory() . '/inc/intervention.php';
add_action( 'admin_init', '\\Aldine\\Activation\\create_default_content' );
add_action( 'admin_bar_init', '\\Aldine\\Actions\\remove_admin_bar_callback' );
add_action( 'wp_head', '\\Aldine\\Actions\\output_custom_colors' );
add_filter( 'body_class', '\\Aldine\\Filters\\body_classes' );
add_filter( 'excerpt_more', '\\Aldine\\Filters\\excerpt_more' );
if ( ! function_exists( 'pressbooks_aldine_setup' ) ) :
/**
* Sets up theme defaults and registers support for various WordPress features.
*
* Note that this function is hooked into the after_setup_theme hook, which
* runs before the init hook. The init hook is too late for some features, such
* as indicating support for post thumbnails.
*/
function pressbooks_aldine_setup() {
$assets = new Assets( 'pressbooks-aldine', 'theme' );
$assets->setSrcDirectory( 'assets' )->setDistDirectory( 'dist' );
/*
* Make theme available for translation.
* Translations can be filed in the /languages/ directory.
*/
load_theme_textdomain( 'aldine', get_template_directory() . '/languages' );
/*
* Let WordPress manage the document title.
* By adding theme support, we declare that this theme does not use a
* hard-coded <title> tag in the document head, and expect WordPress to
* provide it for us.
*/
add_theme_support( 'title-tag' );
/*
* Enable support for Post Thumbnails on posts and pages.
*
* @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
*/
add_theme_support( 'post-thumbnails' );
// This theme uses wp_nav_menu() in one location.
register_nav_menus( [
'network-footer-menu' => __( 'Network Footer Menu', 'aldine' ),
] );
/*
* Switch default core markup for search form, comment form, and comments
* to output valid HTML5.
*/
add_theme_support( 'html5', [
'search-form',
'comment-form',
'comment-list',
'gallery',
'caption',
] );
// Set up the WordPress core custom header feature.
add_theme_support( 'custom-header', [
'default-image' => $assets->getPath( 'images/header.jpg' ),
'width' => 1920,
'height' => 884,
'default-text-color' => '#000',
] );
// Add theme support for selective refresh for widgets.
add_theme_support( 'customize-selective-refresh-widgets' );
/**
* Add support for core custom logo.
*
* @link https://codex.wordpress.org/Theme_Logo
*/
add_theme_support( 'custom-logo', [
'height' => 40,
'width' => 265,
'flex-width' => true,
'flex-height' => true,
] );
// Add editor style.
add_editor_style( $assets->getPath( 'styles/editor.css' ) );
}
endif;
add_action( 'after_setup_theme', 'pressbooks_aldine_setup' );
/**
* Ensure dependencies are loaded
* Set the content width in pixels, based on the theme's design and stylesheet.
*
* Priority 0 to make it available to lower priority callbacks.
*
* @global int $content_width
*/
if (!class_exists('Roots\\Sage\\Container')) {
if (!file_exists($composer = __DIR__.'/vendor/autoload.php')) {
$sage_error(
__('You must run <code>composer install</code> from the Sage directory.', 'aldine'),
__('Autoloader not found.', 'aldine')
);
}
require_once $composer;
function pressbooks_aldine_content_width() {
$GLOBALS['content_width'] = apply_filters( 'pressbooks_aldine_content_width', 640 );
}
add_action( 'after_setup_theme', 'pressbooks_aldine_content_width', 0 );
/**
* Sage required files
* Register widget area.
*
* The mapped array determines the code library included in your theme.
* Add or remove files to the array as needed. Supports child theme overrides.
* @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
*/
array_map(function ($file) use ($sage_error) {
$file = "/app/{$file}.php";
if (!locate_template($file, true, true)) {
$sage_error(sprintf(__('Error locating <code>%s</code> for inclusion.', 'aldine'), $file), 'File not found');
}
}, [
'helpers',
'setup',
'filters',
'intervention',
'activation',
'admin',
]);
function pressbooks_aldine_widgets_init() {
$config = [
'before_widget' => '<div class="widget %1$s %2$s">',
'after_widget' => '</div>',
'before_title' => '<h2>',
'after_title' => '</h2>',
];
register_sidebar( [
'name' => __( 'Front Page Content', 'aldine' ),
'description' => __(
'Add content for your network&rsquo;s front page here. Currently, only text widgets are supported.',
'aldine'
),
'id' => 'front-page-block',
'before_widget' => '<div class="block %1$s %2$s">',
'after_widget' => '</div>',
'before_title' => '<h2>',
'after_title' => '</h2>',
] );
register_sidebar( [
'name' => __( 'Network Footer Block 1', 'aldine' ),
'description' => __(
'Add content for your network&rsquo;s customizeable footer here.
Currently, only text and image widgets are supported.
Content in this widget area will appear in the first row (on mobile) or the first column (on desktops).',
'aldine'
),
'id' => 'network-footer-block-1',
] + $config );
register_sidebar( [
'name' => __( 'Network Footer Block 2', 'aldine' ),
'description' => __(
'Add content for your network&rsquo;s customizeable footer here.
Currently, only text and image widgets are supported.
Content in this widget area will appear in the second row (on mobile) or the middle column (on desktop).',
'aldine'
),
'id' => 'network-footer-block-2',
] + $config );
}
add_action( 'widgets_init', 'pressbooks_aldine_widgets_init' );
/**
* Here's what's happening with these hooks:
* 1. WordPress initially detects theme in themes/sage/resources
* 2. Upon activation, we tell WordPress that the theme is actually in themes/sage/resources/views
* 3. When we call get_template_directory() or get_template_directory_uri(), we point it back to themes/sage/resources
*
* We do this so that the Template Hierarchy will look in themes/sage/resources/views for core WordPress themes
* But functions.php, style.css, and index.php are all still located in themes/sage/resources
*
* This is not compatible with the WordPress Customizer theme preview prior to theme activation
*
* get_template_directory() -> /srv/www/example.com/current/web/app/themes/sage/resources
* get_stylesheet_directory() -> /srv/www/example.com/current/web/app/themes/sage/resources
* locate_template()
* ├── STYLESHEETPATH -> /srv/www/example.com/current/web/app/themes/sage/resources/views
* └── TEMPLATEPATH -> /srv/www/example.com/current/web/app/themes/sage/resources
* Enqueue scripts and styles.
*/
Container::getInstance()
->bindIf('config', function () {
return new Config([
'assets' => require __DIR__.'/config/assets.php',
'theme' => require __DIR__.'/config/theme.php',
'view' => require __DIR__.'/config/view.php',
]);
}, true);
function pressbooks_aldine_scripts() {
$assets = new Assets( 'pressbooks-aldine', 'theme' );
$assets->setSrcDirectory( 'assets' )->setDistDirectory( 'dist' );
wp_enqueue_style( 'aldine/style', $assets->getPath( 'styles/aldine.css' ), false, null );
wp_enqueue_style( 'aldine/webfonts', 'https://fonts.googleapis.com/css?family=Karla:400,400i,700|Spectral:400,400i,600', false, null );
wp_enqueue_script( 'aldine/script', $assets->getPath( 'scripts/aldine.js' ), [ 'jquery' ], null, true );
}
add_action( 'wp_enqueue_scripts', 'pressbooks_aldine_scripts' );
add_action( 'customize_register', '\\Aldine\\Customizer\\customize_register' );
add_action( 'customize_preview_init', '\\Aldine\\Customizer\\customize_preview_js' );

58
header.php

@ -1,7 +1,55 @@
<?php
/**
* The header for our theme
*
* This is the template that displays all of the <head> section and everything up until <div id="content">
*
* @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
*
* @package Aldine
*/
?>
<!doctype html>
<html <?php language_attributes(); ?>>
<?= \Aldine\template('partials/head'); ?>
<body <?php body_class(); ?>>
<?php do_action('get_header'); ?>
<?= \Aldine\template('partials/header'); ?>
<div class="wrap container" role="document">
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div id="page" class="site">
<a class="skip-link screen-reader-text" href="#content"><?php esc_html_e( 'Skip to content', 'pressbooks-aldine' ); ?></a>
<header id="masthead" class="site-header" role="banner">
<div class="container">
<a class="toggle" href="#navigation"><?php _e( 'Toggle menu', 'aldine' ); ?><span class="toggle__icon"></span></a>
<a class="banner__brand" href="<?php echo home_url( '/' ); ?>"><span class="clip"><?php echo get_bloginfo( 'name', 'display' ); ?></span></a>
<nav class="banner__navigation" id="navigation">
<?php if ( function_exists( 'pb_meets_minimum_requirements' ) && pb_meets_minimum_requirements() ) : ?>
<a class="banner__navigation--catalog" href="<?php echo home_url( '/catalog' ); ?>">Catalog</a>
<?php endif; ?>
<?php if ( get_option( 'pb_network_contact_form' ) ) : ?>
<a class="banner__navigation--contact" href="#contact">Contact</a>
<?php endif; ?>
<?php if ( ! is_user_logged_in() ) : ?>
<a class="banner__navigation--signin" href="<?php echo wp_login_url(); ?>"><?php _e( 'Sign in', 'aldine' ); ?></a>
<span class="banner__navigation--sep">/</span>
<a class="banner__navigation--signup" href="<?php echo network_home_url( '/wp-signup.php' ); ?>"><?php _e( 'Sign up', 'aldine' ); ?></a>
<?php else : ?>
<a class="banner__navigation--admin" href="<?php echo admin_url(); ?>"><?php _e( 'Admin', 'aldine' ); ?></a>
<span class="banner__navigation--sep">/</span>
<a class="banner__navigation--signout" href="<?php echo wp_logout_url(); ?>"><?php _e( 'Sign out', 'aldine' ); ?></a>
<?php endif; ?>
</nav>
<header class="banner__branding">
<h1><a href="{{ home_url('/' ); ?>"><?php echo get_bloginfo( 'name', 'display' ); ?></a></h1>
<p><?php echo get_bloginfo( 'description', 'display' ); ?></p>
</header>
</div>
</header><!-- #masthead -->
<div id="content" class="site-content">

51
inc/actions/namespace.php

@ -0,0 +1,51 @@
<?php
/**
* @package Aldine
*/
namespace Aldine\Actions;
/**
* Output custom colors as CSS variables.
*
* @return void
*/
function output_custom_colors() {
$colors = [
'primary',
'accent',
'primary_fg',
'accent_fg',
'header_text',
];
$values = [];
foreach ( $colors as $k ) {
$v = get_option( "pb_network_color_$k" );
if ( $v ) {
$values[ $k ] = $v;
}
}
$output = '';
if ( ! empty( $values ) ) {
$output .= '<style type="text/css">:root{';
foreach ( $values as $k => $v ) {
$k = str_replace( '_', '-', $k );
$output .= "--$k:$v;";
}
$output .= '}</style>';
}
echo $output;
}
/**
* Remove Admin Bar callback.
*/
function remove_admin_bar_callback() {
remove_action( 'wp_head', '_admin_bar_bump_cb' );
}

66
inc/activation/namespace.php

@ -0,0 +1,66 @@
<?php
/**
* @package Aldine
*/
namespace Aldine\Activation;
use ParsedownExtra;
function create_default_content() {
if ( ! get_option( 'pb_aldine_activated' ) ) {
$extra = new ParsedownExtra();
$about = $extra->text( file_get_contents( get_stylesheet_directory() . '/docs/about.md' ) );
$help = $extra->text( file_get_contents( get_stylesheet_directory() . '/docs/help.md' ) );
$default_pages = [
'about' => [
'post_title' => __( 'About', 'aldine' ),
'post_content' => apply_filters( 'pb_root_about_page_content', $about ),
],
'help' => [
'post_title' => __( 'Help', 'aldine' ),
'post_content' => apply_filters( 'pb_root_help_page_content', $help ),
],
'catalog' => [
'post_title' => __( 'Catalog', 'aldine' ),
'post_content' => '',
],
'home' => [
'post_title' => __( 'Home', 'aldine' ),
'post_content' => '',
],
];
// Add our pages
$pages = [];
foreach ( $default_pages as $slug => $page ) {
$check = get_page_by_path( $slug );
if ( empty( $check ) ) {
$pages[ $slug ] = wp_insert_post( array_merge( $page, [ 'post_type' => 'page', 'post_status' => 'publish' ] ) );
} else {
$pages[ $slug ] = $check->ID;
}
}
// Set front page to Home
update_option( 'show_on_front', 'page' );
update_option( 'page_on_front', $pages['home'] );
// Remove content generated by wp_install_defaults
if ( ! wp_delete_post( 1, true ) ) {
return;
}
if ( ! wp_delete_post( 2, true ) ) {
return;
}
if ( ! wp_delete_comment( 1, true ) ) {
return;
}
// Add "pb_aldine_activated" option to enable check above
add_option( 'pb_aldine_activated', 1 );
}
}

185
inc/customizer/namespace.php

@ -0,0 +1,185 @@
<?php
/**
* Aldine Theme Customizer
*
* @package Aldine
*/
namespace Aldine\Customizer;
use PressbooksMix\Assets;
/**
* Add postMessage support for site title and description for the Theme Customizer.
*
* @param WP_Customize_Manager $wp_customize Theme Customizer object.
*/
function customize_register( \WP_Customize_Manager $wp_customize ) {
$wp_customize->get_setting( 'blogname' )->transport = 'postMessage';
$wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage';
$wp_customize->get_setting( 'header_textcolor' )->transport = 'postMessage';
if ( isset( $wp_customize->selective_refresh ) ) {
$wp_customize->selective_refresh->add_partial( 'blogname', [
'selector' => '.site-title a',
'render_callback' => __NAMESPACE__ . '\\customize_partial_blogname',
] );
$wp_customize->selective_refresh->add_partial( 'blogdescription', [
'selector' => '.site-description',
'render_callback' => __NAMESPACE__ . '\\customize_partial_blogdescription',
] );
}
foreach ( [
[
'slug' => 'primary',
'hex' => '#b01109',
'label' => __( 'Primary Color', 'aldine' ),
'description' => __( 'Primary color, used for links and other primary elements.', 'aldine' ),
],
[
'slug' => 'accent',
'hex' => '#015d75',
'label' => __( 'Accent Color', 'aldine' ),
'description' => __( 'Accent color, used for flourishes and secondary elements.', 'aldine' ),
],
[
'slug' => 'primary_fg',
'hex' => '#ffffff',
'label' => __( 'Primary Foreground Color', 'aldine' ),
'description' => __( 'Used for text on a primary background.', 'aldine' ),
],
[
'slug' => 'accent_fg',
'hex' => '#ffffff',
'label' => __( 'Accent Foreground Color', 'aldine' ),
'description' => __( 'Used for text on an accent color background.', 'aldine' ),
],
] as $color ) {
$wp_customize->add_setting("pb_network_color_{$color['slug']}", [
'type' => 'option',
'default' => $color['hex'],
]);
$wp_customize->add_control(new \WP_Customize_Color_Control(
$wp_customize,
"pb_network_color_{$color['slug']}",
[
'label' => $color['label'],
'section' => 'colors',
'description' => $color['description'],
'settings' => "pb_network_color_{$color['slug']}",
]
));
}
$wp_customize->add_section('pb_network_social', [
'title' => __( 'Social Media', 'aldine' ),
'priority' => 30,
]);
$wp_customize->add_setting('pb_network_facebook', [
'type' => 'option',
'sanitize_callback' => 'esc_url_raw',
]);
$wp_customize->add_control('pb_network_facebook', [
'label' => __( 'Facebook', 'aldine' ),
'section' => 'pb_network_social',
'settings' => 'pb_network_facebook',
]);
$wp_customize->add_setting('pb_network_twitter', [
'type' => 'option',
'sanitize_callback' => 'esc_url_raw',
]);
$wp_customize->add_control('pb_network_twitter', [
'label' => __( 'Twitter', 'aldine' ),
'section' => 'pb_network_social',
'settings' => 'pb_network_twitter',
]);
if ( function_exists( 'pb_meets_minimum_requirements' ) && pb_meets_minimum_requirements() ) {
$wp_customize->add_section('pb_front_page_catalog', [
'title' => __( 'Front Page Catalog', 'aldine' ),
'priority' => 25,
]);
$wp_customize->add_setting('pb_front_page_catalog', [
'type' => 'option',
]);
$wp_customize->add_control('pb_front_page_catalog', [
'label' => __( 'Show Front Page Catalog', 'aldine' ),
'section' => 'pb_front_page_catalog',
'settings' => 'pb_front_page_catalog',
'type' => 'checkbox',
]);
$wp_customize->add_setting('pb_front_page_catalog_title', [
'type' => 'option',
'sanitize_callback' => 'sanitize_text_field',
]);
$wp_customize->add_control('pb_front_page_catalog_title', [
'label' => __( 'Front Page Catalog Title', 'aldine' ),
'section' => 'pb_front_page_catalog',
'settings' => 'pb_front_page_catalog_title',
]);
}
$wp_customize->add_section('pb_network_contact_form', [
'title' => __( 'Contact Form', 'aldine' ),
'priority' => 25,
]);
$wp_customize->add_setting('pb_network_contact_form', [
'type' => 'option',
]);
$wp_customize->add_control('pb_network_contact_form', [
'label' => __( 'Show Contact Form', 'aldine' ),
'section' => 'pb_network_contact_form',
'settings' => 'pb_network_contact_form',
'type' => 'checkbox',
]);
$wp_customize->add_setting('pb_network_contact_form_title', [
'type' => 'option',
'sanitize_callback' => 'sanitize_text_field',
]);
$wp_customize->add_control('pb_network_contact_form_title', [
'label' => __( 'Contact Form Title', 'aldine' ),
'section' => 'pb_network_contact_form',
'settings' => 'pb_network_contact_form_title',
]);
}
/**
* Render the site title for the selective refresh partial.
*
* @return void
*/
function customize_partial_blogname() {
bloginfo( 'name' );
}
/**
* Render the site tagline for the selective refresh partial.
*
* @return void
*/
function customize_partial_blogdescription() {
bloginfo( 'description' );
}
/**
* Binds JS handlers to make Theme Customizer preview reload changes asynchronously.
*/
function customize_preview_js() {
$assets = new Assets( 'pressbooks-aldine', 'theme' );
$assets->setSrcDirectory( 'assets' )->setDistDirectory( 'dist' );
wp_enqueue_script( 'aldine/customizer', $assets->getPath( 'scripts/customizer.js' ), [ 'customize-preview' ], false, null );
wp_enqueue_script( 'wcag-validate-customizer-color-contrast', get_template_directory_uri() . '/lib/customizer-validate-wcag-color-contrast/customizer-validate-wcag-color-contrast.js', [ 'customize-controls' ] );
$exports = [
'validate_color_contrast' => [
'pb_network_color_primary_fg' => [ 'pb_network_color_primary' ],
'pb_network_color_accent_fg' => [ 'pb_network_color_accent' ],
],
];
wp_scripts()->add_data(
'wcag-validate-customizer-color-contrast',
'data',
sprintf( 'var _validateWCAGColorContrastExports = %s;', wp_json_encode( $exports ) )
);
}

39
inc/filters/namespace.php

@ -0,0 +1,39 @@
<?php
/**
* Aldine Filters
*
* @package Aldine
*/
namespace Aldine\Filters;
/**
* Adds custom classes to the array of body classes.
*
* @see https://github.com/roots/sage/blob/master/app/filters.php
*
* @param array $classes Classes for the body element.
* @return array
*/
function body_classes( array $classes ) {
/** Add page slug if it doesn't exist */
if ( is_single() || is_page() && ! is_front_page() ) {
if ( ! in_array( basename( get_permalink() ), $classes, true ) ) {
$classes[] = basename( get_permalink() );
}
}
/** Clean up class names for custom templates */
$classes = array_map( function ( $class ) {
return preg_replace( [ '/-php$/', '/^page-template-/' ], '', $class );
}, $classes);
return array_filter( $classes );
}
/**
* Customize excerpt.
*/
function excerpt_more() {
return ' &hellip; <a href="' . get_permalink() . '">' . __( 'Continued', 'aldine' ) . '</a>';
}

146
inc/helpers/namespace.php

@ -0,0 +1,146 @@
<?php
/**
* Aldine Helpers
*
* @package Aldine
*/
namespace Aldine\Helpers;
/**
* Get block count.
*
* @return int
*/
function get_block_count() {
global $_wp_sidebars_widgets;
if ( ! empty( $_wp_sidebars_widgets['front-page-block'] ) ) {
return count( $_wp_sidebars_widgets['front-page-block'] );
}
return 1;
}
/**
* Get catalog data.
*
* @param int $page
* @param int $per_page
* @param string $orderby
* @param string $license
* @param string $subject
*/
function get_catalog_data( $page = 1, $per_page = 10, $orderby = 'title', $license = '', $subject = '' ) {
if ( function_exists( 'pb_meets_minimum_requirements' ) && pb_meets_minimum_requirements() ) {
$request = new \WP_REST_Request( 'GET', '/pressbooks/v2/books' );
$request->set_query_params([
'page' => $page,
'per_page' => $per_page,
]);
$response = rest_do_request( $request );
$pages = $response->headers['X-WP-TotalPages'];
$data = rest_get_server()->response_to_data( $response, true );
$books = [];
foreach ( $data as $key => $book ) {
$book['title'] = $book['metadata']['name'];
$book['date-published'] = ( isset( $book['metadata']['datePublished'] ) ) ?
$book['metadata']['datePublished'] :
'';
$book['subject'] = ( isset( $book['metadata']['about'][0] ) )
? $book['metadata']['about'][0]['identifier']
: '';
$books[] = $book;
}
if ( $orderby === 'latest' ) {
$books = wp_list_sort( $books, $orderby, 'desc' );
} else {
$books = wp_list_sort( $books, $orderby );
}
return [ 'pages' => $pages, 'books' => $books ];
} else {
return [ 'pages' => 0, 'books' => [] ];
}
}
/**
* Get licenses for catalog display.
*
* @return array
*/
function get_catalog_licenses() {
if ( class_exists( '\\Pressbooks\\Licensing' ) ) {
$licenses = ( new \Pressbooks\Licensing() )->getSupportedTypes();
foreach ( $licenses as $key => $value ) {
$licenses[ $key ] = preg_replace( '/\([^)]+\)/', '', $value['desc'] );
}
return $licenses;
}
return [];
}
/**
*
* Handler for contact form submissions.
*
* @return false | array
*/
function handle_contact_form_submission() {
if ( ! isset( $_POST['pb_root_contact_form_nonce'] ) || ! wp_verify_nonce( $_POST['pb_root_contact_form_nonce'], 'pb_root_contact_form' ) ) {
return; // Security check failed.
}
if ( isset( $_POST['submitted'] ) ) {
$output = [];
$name = ( isset( $_POST['visitor_name'] ) ) ? $_POST['visitor_name'] : '';
$email = ( isset( $_POST['visitor_email'] ) ) ? $_POST['visitor_email'] : '';
$institution = ( isset( $_POST['visitor_institution'] ) ) ? $_POST['visitor_institution'] : '';
$message = ( isset( $_POST['message'] ) ) ? $_POST['message'] : '';
$output['values'] = [
'visitor_name' => esc_attr( $name ),
'visitor_email' => sanitize_email( $email ),
'visitor_institution' => esc_attr( $institution ),
'message' => esc_textarea( $message ),
];
if ( empty( $name ) ) {
$output['message'] = __( 'Name is required.', 'aldine' );
$output['status'] = 'error';
$output['field'] = 'visitor_name';
} elseif ( empty( $email ) ) {
$output['message'] = __( 'Email is required.', 'aldine' );
$output['status'] = 'error';
$output['field'] = 'visitor_email';
} elseif ( ! filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
$output['message'] = __( 'Email is invalid.', 'aldine' );
$output['status'] = 'error';
$output['field'] = 'visitor_email';
} elseif ( empty( $institution ) ) {
$output['message'] = __( 'Institution is required.', 'aldine' );
$output['status'] = 'error';
$output['field'] = 'visitor_institution';
} elseif ( empty( $message ) ) {
$output['message'] = __( 'Message is required.', 'aldine' );
$output['status'] = 'error';
$output['field'] = 'message';
} else {
$sent = wp_mail(
get_option( 'admin_email' ),
sprintf( __( 'Contact Form Submission from %s', 'aldine' ), $name ),
sprintf(
"From: %1\$s <%2\$s>\nInstitution: %3\$s\n\n%4\$s",
stripslashes( $name ),
$email,
stripslashes( $institution ),
strip_tags( $message )
),
"From: ${email}\r\nReply-To: ${email}\r\n"
);
if ( $sent ) {
$output['message'] = __( 'Your message was sent!', 'aldine' );
$output['status'] = 'success';
} else {
$output['message'] = __( 'Your message could not be sent.', 'aldine' );
$output['status'] = 'error';
}
}
return $output;
}
return;
}

39
inc/intervention.php

@ -0,0 +1,39 @@
<?php
/**
* Admin Interventions
*
* @see https://github.com/soberwp/intervention/
*/
use function \Sober\Intervention\intervention;
intervention( 'remove-customizer-items', 'static-front-page', 'all' );
intervention( 'remove-emoji' );
intervention( 'remove-howdy', __( 'Hello,', 'aldine' ) );
intervention( 'remove-dashboard-items', [ 'activity', 'quick-draft' ] );
intervention( 'remove-menu-items', [
'posts',
'tools',
'setting-writing',
'setting-reading',
'setting-permalink',
], 'all' );
intervention( 'remove-widgets', [
'pages',
'calendar',
'archives',
'links',
'media-audio',
'meta',
'search',
'categories',
'recent-posts',
'recent-comments',
'rss',
'tag-cloud',
'custom-menu',
'custom-html',
'media-video',
'akismet',
], 'all' );
intervention( 'remove-toolbar-frontend', 'all' );

8
inc/tags/namespace.php

@ -0,0 +1,8 @@
<?php
/**
* Aldine Template Tags
*
* @package Aldine
*/
namespace Aldine\Tags;

55
index.php

@ -1,3 +1,56 @@
<?php
/**
* The main template file
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/
*
* @package Aldine
*/
// this file is deliberately blank
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<?php
if ( have_posts() ) :
if ( is_home() && ! is_front_page() ) : ?>
<header>
<h1 class="page-title screen-reader-text"><?php single_post_title(); ?></h1>
</header>
<?php
endif;
/* Start the Loop */
while ( have_posts() ) : the_post();
/*
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
the_posts_navigation();
else :
get_template_part( 'template-parts/content', 'none' );
endif; ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_sidebar();
get_footer();

186
languages/aldine.pot

@ -0,0 +1,186 @@
# Copyright (C) 2017 Automattic
# This file is distributed under the GNU General Public License v2 or later.
msgid ""
msgstr ""
"Project-Id-Version: _s 1.0.0\n"
"Report-Msgid-Bugs-To: https://wordpress.org/tags/_s\n"
"POT-Creation-Date: 2016-12-23 16:00+0100\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"PO-Revision-Date: 2017-MO-DA HO:MI+ZONE\n"
"Last-Translator:\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"X-Generator: grunt-wp-i18n 0.5.4\n"
#: 404.php:17
msgid "Oops! That page can&rsquo;t be found."
msgstr ""
#: 404.php:21
msgid ""
"It looks like nothing was found at this location. Maybe try one of the "
"links below or a search?"
msgstr ""
#: 404.php:30
msgid "Most Used Categories"
msgstr ""
#: 404.php:47
#. translators: %1$s: smiley
msgid "Try looking in the monthly archives. %1$s"
msgstr ""
#: comments.php:34
#. translators: 1: title.
msgid "One thought on &ldquo;%1$s&rdquo;"
msgstr ""
#: comments.php:67
msgid "Comments are closed."
msgstr ""
#: footer.php:18
msgid "https://wordpress.org/"
msgstr ""
#: footer.php:20
#. translators: %s: CMS name, i.e. WordPress.
msgid "Proudly powered by %s"
msgstr ""
#: footer.php:25
#. translators: 1: Theme name, 2: Theme author.
msgid "Theme: %1$s by %2$s."
msgstr ""
#: functions.php:47
msgid "Primary"
msgstr ""
#: functions.php:105
msgid "Sidebar"
msgstr ""
#: functions.php:107
msgid "Add widgets here."
msgstr ""
#: header.php:24
msgid "Skip to content"
msgstr ""
#: header.php:45
msgid "Primary Menu"
msgstr ""
#: inc/template-tags.php:52
#. translators: used between list items, there is a space after the comma
msgid ", "
msgstr ""
#: inc/template-tags.php:55
#. translators: 1: list of categories.
msgid "Posted in %1$s"
msgstr ""
#: inc/template-tags.php:62
#. translators: 1: list of tags.
msgid "Tagged %1$s"
msgstr ""
#: inc/template-tags.php:72
#. translators: %s: post title
msgid "Leave a Comment<span class=\"screen-reader-text\"> on %s</span>"
msgstr ""
#: inc/template-tags.php:89 template-parts/content-page.php:35
#. translators: %s: Name of current post. Only visible to screen readers
msgid "Edit <span class=\"screen-reader-text\">%s</span>"
msgstr ""
#: search.php:21
#. translators: %s: search query.
msgid "Search Results for: %s"
msgstr ""
#: template-parts/content-none.php:14
msgid "Nothing Found"
msgstr ""
#: template-parts/content-none.php:25
#. translators: 1: link to WP admin new post page.
msgid "Ready to publish your first post? <a href=\"%1$s\">Get started here</a>."
msgstr ""
#: template-parts/content-none.php:38
msgid ""
"Sorry, but nothing matched your search terms. Please try again with some "
"different keywords."
msgstr ""
#: template-parts/content-none.php:44
msgid ""
"It seems we can&rsquo;t find what you&rsquo;re looking for. Perhaps "
"searching can help."
msgstr ""
#: template-parts/content-page.php:22 template-parts/content.php:45
msgid "Pages:"
msgstr ""
#: template-parts/content.php:34
#. translators: %s: Name of current post. Only visible to screen readers
msgid "Continue reading<span class=\"screen-reader-text\"> \"%s\"</span>"
msgstr ""
#. Theme Name of the plugin/theme
msgid "_s"
msgstr ""
#. Theme URI of the plugin/theme
msgid "https://underscores.me/"
msgstr ""
#. Description of the plugin/theme
msgid ""
"Hi. I'm a starter theme called <code>_s</code>, or <em>underscores</em>, if "
"you like. I'm a theme meant for hacking so don't use me as a <em>Parent "
"Theme</em>. Instead try turning me into the next, most awesome, WordPress "
"theme out there. That's what I'm here for."
msgstr ""
#. Author of the plugin/theme
msgid "Automattic"
msgstr ""
#. Author URI of the plugin/theme
msgid "https://automattic.com/"
msgstr ""
#: comments.php:40
#. translators: 1: comment count number, 2: title.
msgctxt "comments title"
msgid "%1$s thought on &ldquo;%2$s&rdquo;"
msgid_plural "%1$s thoughts on &ldquo;%2$s&rdquo;"
msgstr[0] ""
msgstr[1] ""
#: inc/template-tags.php:29
#. translators: %s: post date.
msgctxt "post date"
msgid "Posted on %s"
msgstr ""
#: inc/template-tags.php:35
#. translators: %s: post author.
msgctxt "post author"
msgid "by %s"
msgstr ""
#: inc/template-tags.php:59
#. translators: used between list items, there is a space after the comma
msgctxt "list item separator"
msgid ", "
msgstr ""

227
lib/infusion/Infusion-LICENSE.txt

@ -1,227 +0,0 @@
Infusion is available under either the terms of the New BSD license or the
Educational Community License, Version 2.0. As a recipient of Infusion, you may
choose which license to receive this code under (except as noted in per-module
LICENSE files). All modules are Copyright 2011 OCAD University except
where noted otherwise in the code itself, or if the modules reside in a separate
directory, they may contain explicit declarations of copyright in both the
LICENSE file in the directory in which they reside and in the code itself. No
external contributions are allowed under licenses which are fundamentally
incompatible with the ECL or BSD licenses that Infusion is distributed under.
The text of the ECL and BSD licenses is reproduced below.
Educational Community License, Version 2.0
*************************************
Copyright 2011 OCAD University
Educational Community License, Version 2.0, April 2007
The Educational Community License version 2.0 ("ECL") consists of the Apache 2.0
license, modified to change the scope of the patent grant in section 3 to be
specific to the needs of the education communities using this license. The
original Apache 2.0 license can be found at:
http://www.apache.org/licenses/LICENSE-2.0
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, "control" means (i) the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising
permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
"Object" form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
"submitted" means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
2. Grant of Copyright License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
3. Grant of Patent License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed. Any
patent license granted hereby with respect to contributions by an individual
employed by an institution or organization is limited to patent claims where the
individual that is the author of the Work is also the inventor of the patent
claims licensed, and where the organization or institution has the right to
grant such license under applicable grant and research funding agreements. No
other express or implied licenses are granted.
4. Redistribution.
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
1. You must give any other recipients of the Work or Derivative Works a copy
of this License; and
2. You must cause any modified files to carry prominent notices stating that
You changed the files; and
3. You must retain, in the Source form of any Derivative Works that You
distribute, all copyright, patent, trademark, and attribution notices from
the Source form of the Work, excluding those notices that do not pertain to
any part of the Derivative Works; and
4. If the Work includes a "NOTICE" text file as part of its distribution,
then any Derivative Works that You distribute must include a readable copy of
the attribution notices contained within such NOTICE file, excluding those
notices that do not pertain to any part of the Derivative Works, in at least
one of the following places: within a NOTICE text file distributed as part of
the Derivative Works; within the Source form or documentation, if provided
along with the Derivative Works; or, within a display generated by the
Derivative Works, if and wherever such third-party notices normally appear.
The contents of the NOTICE file are for informational purposes only and do
not modify the License. You may add Your own attribution notices within
Derivative Works that You distribute, alongside or as an addendum to the
NOTICE text from the Work, provided that such additional attribution notices
cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
5. Submission of Contributions.
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
6. Trademarks.
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
7. Disclaimer of Warranty.
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
8. Limitation of Liability.
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability.
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS FOR ECL 2.0
The New BSD license
**********************
Copyright 2011 OCAD University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of OCAD University nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
END OF TERMS AND CONDITIONS FOR THE NEW BSD LICENSE

212
lib/infusion/README.md

@ -1,212 +0,0 @@
## What Is Infusion? ##
Infusion is a different kind of JavaScript framework. Our approach is to leave you in control—it's your interface, using your markup, your way. Infusion is accessible and very, very configurable.
Infusion includes:
* an application framework for developing flexible stuff with JavaScript and jQuery
* a collection of accessible UI components
## Where Can I See Infusion Components? ##
<http://fluidproject.org/infusion.html>
## How Do I Get Infusion? ##
* [Download a Release](https://github.com/fluid-project/infusion/releases)
* [Install from NPM](https://www.npmjs.com/package/infusion)
* [Fork on GitHub](https://github.com/fluid-project/infusion)
See [How Do I Create an Infusion Package?](#how-do-i-create-an-infusion-package), for details on creating complete or custom packages of Infusion.
## Where is the Infusion Documentation? ##
Infusion has comprehensive documentation at <http://docs.fluidproject.org/infusion>.
## Who Makes Infusion, and How Can I Help? ##
The Fluid community is an international group of designers, developers, and testers who focus on a common mission: improving the user experience and accessibility of the open web.
The best way to join the Fluid Community is to jump into any of our community activities. Visit our [website](http://fluidproject.org/) for links to our mailing lists, chat room, wiki, etc.
## Where is Infusion Used? ##
Infusion is the cornerstone of a number of Fluid's own projects dedicated to supporting inclusive design on the Web. You can see some of them featured on our [Projects page](http://fluidproject.org/projects.html). Infusion is also used in a variety of third-party applications, which are listed on the [Infusion Integrations](https://wiki.fluidproject.org/display/fluid/Infusion+Integrations) wiki page.
## How Do I Create an Infusion Package? ##
For simplicity and performance reasons, you may wish to create a concatenated, minified file. However, such a file is often difficult to read. To address this, source maps for the minified file are automatically generated to make debugging easier.
### Source Maps ###
Source maps are supported in all of the major browsers: [Chrome](https://developer.chrome.com/devtools/docs/javascript-debugging#source-maps), [Firefox](https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Use_a_source_map),
[IE 11](https://msdn.microsoft.com/library/dn255007#source_maps), and Safari. To make use of them, enable source maps in your debugging environment, and ensure that the source maps are hosted adjacent to the file they are associated with.
#### Source Map Example ####
* From the command line, run `grunt` to create a build of Infusion
* All Infusion packages come with a source map for the concatenated JavaScript file
* In the Infusion package, modify one of the demos to replace the individual javascript includes with a reference to "infusion-all.js"
* The "infusion-all.js" includes a reference to the "infusion-all.js.map" file, which is assumed to be hosted as its sibling
* Open the demo in a browser
* In the browser's debugger ensure that source maps are enabled
* In Firefox open the debugger
* In the debugger options, ensure that "Show Original Sources" is enabled
* see [MDN: Use a source map](https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Use_a_source_map)
* In the debugger you should now be able to view and debug the individual JavaScript files as though they were included separately
### Dependencies ###
* [node.js](http://nodejs.org/)
* [grunt-cli](http://gruntjs.com/)
All other development dependencies will be installed by running the following from the project root:
```bash
npm install
```
### Package Types ###
#### Infusion All Build ####
Will include all of Infusion. The source files packaged along with the single concatenated js file will include all of the demos and unit tests. This is a good choice if you are trying to learn Infusion.
```bash
grunt
```
##### Custom Build #####
Will only include the modules you request, and all of their dependencies, minus any that are explicitly excluded. Unlike the "all" build, none of the demos or tests are included with a custom package.
```bash
grunt custom
```
### Build Options ###
#### --source ####
__value__: true (Boolean)
_the value can be omitted if --source is the last flag specified_
By default all packages are minified. This option will allow you to maintain the readable spacing and comments.
```bash
grunt --source=true
grunt custom --source=true
```
#### --include ####
__value__: "module(s)" (String)
_only available to custom packages_
The `--include` option takes in a comma-separated string of the [Modules](#modules) to be included in a custom package. If omitted, all modules will be included (demos and tests will not be included).
```bash
grunt custom --include="inlineEdit, uiOptions"
```
#### --exclude ####
__value__: "module(s)" (String)
_only available to custom packages_
The exclude option takes in a comma-separated string of the [Modules](#modules) to be excluded from a custom package. The `--exclude` option takes priority over `--include`.
```bash
grunt custom --exclude="jQuery"
grunt custom --include="framework" --exclude="jQuery"
```
#### --name ####
__value__: "custom suffix" (String)
_only available to custom packages_
By default, custom packages are given a name with the form _infusion-custom-<version>.zip_ and the concatenated js file is called _infusion-custom.js_. By supplying the `--name` option, you can replace "custom" with any other valid string you like.
```bash
# this produces infusion-myPackage.js
grunt custom --name="myPackage"
```
### Modules ###
#### Framework Modules ####
* enhancement
* framework
* preferences
* renderer
#### Component Modules ####
* inlineEdit
* overviewPanel
* pager
* progress
* reorderer
* slidingPanel
* tableOfContents
* tabs
* textfieldSlider
* textToSpeech
* tooltip
* uiOptions
* undo
* uploader
#### External Libraries ####
* fastXmlPull
* jQuery
* jQueryUI
* jQueryScrollToPlugin
* jQueryTouchPunchPlugin
* normalize
All of these libraries are already bundled within the Infusion image.
## How Do I Run Tests? ##
There are two options available for running tests. The first option involves using browsers installed on your computer and the second uses browsers available in a VM.
### Run Tests Using Browsers Installed On Your Computer ###
Using this option requires the installation of [Testem](https://github.com/testem/testem/#installation) and then running ``testem ci --file tests/testem.json`` in this directory. Any browsers that Testem finds on your platform will be launched sequentially with each browser running the full Infusion test suite. The results will be returned in your terminal in the [TAP](https://testanything.org/) format. You can use the ``testem launchers`` command to get a list of available browsers.
**Note:** Any browser launched will need to be focused and remain the active window. Some of the tests require focus, and will report errors if they are not focused.
### Run Tests Using Browsers Installed In a VM ###
A [Fedora VM](https://github.com/idi-ops/packer-fedora) can be automatically created using tools provided by the [Prosperity4All Quality Infrastructure](https://github.com/GPII/qi-development-environments/). After meeting the [QI development VM requirements](https://github.com/GPII/qi-development-environments/#requirements) the ``vagrant up`` command can be used to launch a VM which will contain Testem and several browsers. Typing ``grunt tests`` will run the Infusion tests in the VM and the results will be displayed in your terminal.
When this VM is first created Chrome and Firefox will be upgraded to the latest versions available in the Fedora and Google package repositories. The ``vagrant provision`` command can be used at a later time to trigger the browser upgrade and general VM provisioning mechanism.
The benefits of using a VM include the following:
* Does not require testem to be installed on the host machine
* Allows other applications on the host machine to have focus while the tests are run
## Developing with the Preferences Framework ##
Infusion is in the process of switching to use [Stylus](http://learnboost.github.io/stylus/) for CSS pre-processing.
CSS files for the Preferences Framework have been re-written in Stylus. Only Stylus files are pushed into the github repository.
For developing the Preferences Framework, run the following from the project root to compile Stylus files to CSS:
```bash
grunt buildStylus
```
A `watch` task using [grunt-contrib-watch](https://github.com/gruntjs/grunt-contrib-watch) is also supplied to ease Stylus development. This task launches a process that watches all Stylus files in the `src` directory and recompiles them when they are changed. This task can be run using the following command:
```bash
grunt watch:buildStylus
```

344
lib/infusion/ReleaseNotes.md

@ -1,344 +0,0 @@
# Release Notes for Fluid Infusion 2.0.0 #
[Fluid Project](http://fluidproject.org)
[Infusion Documentation](https://github.com/fluid-project/infusion-docs)
## What's New in 2.0.0? ##
See [API Changes from 1.5 to 2.0](http://docs.fluidproject.org/infusion/development/APIChangesFrom1_5To2_0.html) and [Deprecations in 1.5](http://docs.fluidproject.org/infusion/development/DeprecationsIn1_5.html) on the [Infusion Documentation](https://github.com/fluid-project/infusion-docs) site.
For a complete list of Fixes and Improvements see the [Version 2.0](https://issues.fluidproject.org/projects/FLUID/versions/10041) summary in the [JIRA](https://issues.fluidproject.org) issue tracker.
**Note:** Infusion 1.9 was not officially released, but is available as an official branch. It is is available on GitHub at [Infusion 1.9.x](https://github.com/fluid-project/infusion/tree/1.9.x). For a complete list of Fixes and Improvements see the [Version 1.9](https://issues.fluidproject.org/projects/FLUID/versions/10520) summary in the [JIRA](https://issues.fluidproject.org) issue tracker.
### New Features ###
* Constraint-based priorities, supported by `listeners`, `modelListeners`, `modelRelay`, `distributeOptions`, `contextAwareness`, and `components`. This allows the specific order of those items to be configured. (See: [Priorities](http://docs.fluidproject.org/infusion/development/Priorities.html))
* Context Awareness - and things it relies on:
* Global Instantiator
* Every Infusion component, regardless of how it is instantiated, ends up in a single-rooted tree of components
* This enables use of modern IoC features such as model relay and declarative event binding
* Enables use of the root distributeOptions context "/"
* Enables the removal of "demands blocks"
* Useful debugging tip: Watch `fluid.globalInstantiator` in your JS debugging tools to see the structure of your application and its tree.
* `fluid.notImplemented` function for implementing abstract grades
* [Lazy loading for UI Options](http://docs.fluidproject.org/infusion/development/UserInterfaceOptionsAPI.html#lazyload) and instructions for how to use the Preferences Framework with a [zero initial load time](http://docs.fluidproject.org/infusion/development/tutorial-prefsFrameworkMinimalFootprint/MinimalFootprint.html).
* This should assist in improving performance when using the Preferences Framework, particularly for resource intensive sites and applications
* Much faster invokers and boiled listeners (c. 60x faster)
* Support for using Infusion with npm for both Node.js and web-based projects.
* Provides a variety of prebuilt versions of Infusion in the module's `dist` directory.
* Source Maps are generated for the concatenated JavaScript files
* View oriented IoC debugging tools
* Including FluidViewDebugging.js on the page of any Infusion application gives you access to the _IoC View Inspector_. Click on the small cogwheel icon at the bottom right of the page to open a panel which shows the details of the view components and their grades, that are attached to DOM nodes in the browser pane. This interface works similarly to the _DOM Inspector_ familiar from modern web browsers, but is an experimental implementation with an engineer-level UI.
### Removal of Deprecated Features ###
* Manual lifecycle points finalInit, postInit, etc.
* Obsolete syntax for arguments, options, etc.
* `"autoInit"` grade
* Static and dynamic environments, replaced by Global Instantiator
* The old model component hierarchy and "old ChangeApplier" implementation
* `fluid.demands`
* No more distinction between fast and dynamic invokers
* Model Relay specific component grades have been removed, model relay now works with any model grade.
## Obtaining Infusion ##
* [Fork on GitHub](https://github.com/fluid-project/infusion)
* [Download a Build](https://github.com/fluid-project/infusion/releases)
* [NPM](https://www.npmjs.com/package/infusion)
You can create your own custom build of Infusion using the [grunt build script](README.md#how-do-i-create-an-infusion-package).
## Demos ##
Infusion ships with demos of all of the components in action. You can find them in the _**demos**_ folder in the release bundle or on our [build site](http://build.fluidproject.org/).
When running the demos on your local machine, a web server is recommended. Several of the demos make use of AJAX calls; which typically are not allowed by
the browser when run from the local file system.
## License ##
Fluid Infusion is licensed under both the ECL 2.0 and new BSD licenses.
More information is available in our [wiki](http://wiki.fluidproject.org/display/fluid/Fluid+Licensing).
## Third Party Software in Infusion ##
This is a list of publicly available software that is redistributed with Fluid Infusion,
categorized by license:
### Apache 2.0 ###
* [`fluid.load.scripts` is based on Jake Archibald's script loading example](http://www.html5rocks.com/en/tutorials/speed/script-loading/#toc-dom-rescue)
* [Open Sans Light font](http://www.google.com/fonts/specimen/Open+Sans)
### MIT License ###
* [Buzz v1.1.0](http://buzz.jaysalvat.com)
* [Foundation v6.2.3](http://foundation.zurb.com/index.html)
* [HTML5 Boilerplate v4.3](http://html5boilerplate.com/)
* [html5shiv v3.7.2](https://code.google.com/p/html5shiv/)
* [jQuery v3.1.0](http://jquery.com/)
* [jQuery Mockjax v2.2.1](https://github.com/jakerella/jquery-mockjax)
* [jQuery QUnit v1.12.0](http://qunitjs.com)
* [jQuery QUnit Composite v1.0.1](https://github.com/jquery/qunit-composite)
* [jQuery scrollTo v1.4.2](http://flesler.blogspot.com/2007/10/jqueryscrollto.html)
* [jQuery Touch Punch v0.2.2](http://touchpunch.furf.com/)
* [jQuery UI (Core; Interactions: draggable, resizable; Widgets: button, checkboxradio, controlgroup, dialog, mouse, slider, tabs, and tooltip) v1.12.1](http://ui.jquery.com/)
* [jquery.selectbox v0.5 (forked)](https://github.com/fluid-project/jquery.selectbox)
* [jquery.simulate](https://github.com/eduardolundgren/jquery-simulate)
* [Micro Clearfix](http://nicolasgallagher.com/micro-clearfix-hack/)
* [Normalize v4.1.1](https://necolas.github.io/normalize.css/)
### zlib/libpng License ###
* [fastXmlPull is based on XML for Script's Fast Pull Parser v3.1](http://wiki.fluidproject.org/display/fluid/Licensing+for+fastXmlPull.js)
## Documentation ##
Documentation and tutorials can found on the [Infusion Documentation](http://docs.fluidproject.org/infusion/development/) site.
## Supported Browsers ##
Infusion 2.0 was tested with the following browsers:
* Chrome current (version 54)
* Firefox current (versions 49-50)
* Internet Explorer (version 11)
* Microsoft Edge (version 38)
* Safari (version 10)
Additional testing for mobile devices was performed with the following:
* Chrome (Android 6.0.1)
* Safari (iOS 10.1.1)
For more information see the [Fluid Infusion browser support](https://wiki.fluidproject.org/display/fluid/Prior+Browser+Support) wiki page.
### Testing Configurations ####
<table>
<summary>Testing Configurations</summary>
<thead>
<tr>
<th rowspan="2">Testing Task</th>
<th colspan="5">Desktop Browser</th>
<th colspan="2">Mobile Browser</th>
</tr>
<tr>
<th>Chrome</th>
<th>Firefox</th>
<th>IE 11</th>
<th>MS Edge</th>
<th>Safari</th>
<th>Chrome for Android</th>
<th>Safari iOS</th>
</tr>
</thead>
<tbody>
<tr>
<th>Run All Unit Tests</th>
<td>Chrome 54 (macOS 10.12)</td>
<td>Firefox 49 (macOS 10.12)</td>
<td>IE 11 (Win 10)</td>
<td>MS Edge 38 (Win 10)</td>
<td>Safari 10 (macOS 10.12)</td>
<td>Chrome 54 (Android 6.0.1 & 7.0.0)</td>
<td>Safari (iOS 10.1.1)</td>
</tr>
<tr>
<th>Smoke Tests - All Manual Tests</th>
<td>Chrome 54 (macOS 10.11.6)</td>
<td>Firefox 50 (macOS 10.12.1)</td>
<td>IE 11 (Win 8.1)</td>
<td>MS Edge 38 (Win 10)</td>
<td>Safari 10 (macOS 10.12.1)</td>
<td>Chrome 54 (Android 6.0.1)</td>
<td>Safari (iOS 10.1.1)</td>
</tr>
<tr>
<th>Smoke Tests - All Demos</th>
<td>Chrome 54 (macOS 10.12.1)</td>
<td>Firefox 50 (macOS 10.12.1)</td>
<td>IE 11 (Win 8.1)</td>
<td>MS Edge 38 (Win 10)</td>
<td>Safari 10 (macOS 10.12.1)</td>
<td>Chrome 54 (Android 6.0.1)</td>
<td>Safari (iOS 10.1.1)</td>
</tr>
<tr>
<th>Smoke Tests - All Examples</th>
<td>Chrome 54 (macOS 10.12.1)</td>
<td>Firefox 50 (macOS 10.12.1)</td>
<td>IE 11 (Win 8.1)</td>
<td>MS Edge 38 (Win 10)</td>
<td>Safari 10 (macOS 10.12.1)</td>
<td>Chrome 54 (Android 6.0.1)</td>
<td>Safari (iOS 10.1.1)</td>
</tr>
<tr>
<th>Inline Edit QA Test Plan - Simple Text</th>
<td>Chrome 54 (macOS 10.10)</td>
<td>Firefox 49 (openSUSE Linux 42.1)</td>
<td>IE 11 (Win 8.1)</td>
<td>MS Edge 38 (Win 10)</td>
<td>Safari 10 (macOS 10.12)</td>
<td>N/A</td>
<td>N/A</td>
</tr>
<tr>
<th>Keyboard Accessibility QA Test Plan</th>
<td>Chrome 54 (Win 10)</td>
<td>Firefox 49.0.2 (macOS 10.12)</td>
<td>IE 11 (Win 8.1)</td>
<td>MS Edge 38 (Win 10)</td>
<td>Safari 10 (macOS 10.12)</td>
<td>N/A</td>
<td>N/A</td>
</tr>
<tr>
<th>Pager QA Test Plan</th>
<td>Chrome 54 (Win 10)</td>
<td>Firefox 49.0.2 (macOS 10.12)</td>
<td>IE 11 (Win 7)</td>
<td>MS Edge 38 (Win 10)</td>
<td>Safari 10 (macOS 10.12)</td>
<td>N/A</td>
<td>N/A</td>
</tr>
<tr>
<th>Progress QA Test Plan</th>
<td>Chrome 54 (macOS 10.11.6)</td>
<td>Firefox 49.0.2 (macOS 10.12)</td>
<td>IE 11 (Win 7)</td>
<td>MS Edge 38 (Win 10)</td>
<td>Safari 10 (macOS 10.12)</td>
<td>N/A</td>
<td>N/A</td>
</tr>
<tr>
<th>Reorderer QA Test Plan - Image Reorderer</th>
<td>Chrome 54 (Win 10)</td>
<td>Firefox 49.0.2 (macOS 10.12)</td>
<td>IE 11 (Win 7)</td>
<td>MS Edge 38 (Win 10)</td>
<td>Safari 10 (macOS 10.12)</td>
<td>N/A</td>
<td>N/A</td>
</tr>
<tr>
<th>Reorderer QA Test Plan - Layout Reorderer</th>
<td>Chrome 54 (macOS 10.11.6)</td>
<td>Firefox 49.0.2 (macOS 10.12)</td>
<td>IE 11 (Win 7)</td>
<td>MS Edge 38 (Win 10)</td>
<td>Safari 10 (macOS 10.12)</td>
<td>N/A</td>
<td>N/A</td>
</tr>
<tr>
<th>Reorderer QA Test Plan - List Reorderer</th>
<td>Chrome 54 (macOS 10.11.6)</td>
<td>Firefox 49.0.2 (macOS 10.12)</td>
<td>IE 11 (Win 7)</td>
<td>MS Edge 38 (Win 10)</td>
<td>Safari 10 (macOS 10.12)</td>
<td>N/A</td>
<td>N/A</td>
</tr>
<tr>
<th>Reorderer QA Test Plan - Grid Reorderer</th>
<td>Chrome 54 (macOS 10.11.6)</td>
<td>Firefox 49.0.2 (macOS 10.12)</td>
<td>IE 11 (Win 7)</td>
<td>MS Edge 38 (Win 10)</td>
<td>Safari 10 (macOS 10.12)</td>
<td>N/A</td>
<td>N/A</td>
</tr>
<tr>
<th>Preferences Framework QA Test Plan</th>
<td>Chrome 54 (Win 10)</td>
<td>Firefox 49.0.2 (macOS 10.12)</td>
<td>IE 11 (Win 7)</td>
<td>MS Edge 38 (Win 10)</td>
<td>Safari 10 (macOS 10.12)</td>
<td>N/A</td>
<td>N/A</td>
</tr>
<tr>
<th>UI Options QA Test Plan - Separated Panel</th>
<td>Chrome 54 (Win 10)</td>
<td>Firefox 49.0.2 (Win 10)</td>
<td>IE 11 (Win 7)</td>
<td>MS Edge 38 (Win 10)</td>
<td>Safari 10 (macOS 10.12)</td>
<td>N/A</td>
<td>N/A</td>
</tr>
<tr>
<th>Uploader QA Test Plan</th>
<td>Chrome 54 (macOS 10.12.1)</td>
<td>Firefox 49.0.2 (macOS 10.12.1)</td>
<td>IE 11 (Win 10)</td>
<td>MS Edge 38 (Win 10)</td>
<td>Safari 10 (macOS 10.12.1)</td>
<td>N/A</td>
<td>N/A</td>
</tr>
</tbody>
</table>
## Known Issues ##
The Fluid Project uses a [JIRA](http://issues.fluidproject.org) website to track bugs. Some of the known issues in this release are described here:
### Framework ###
* [FLUID-5912: "{arguments}" IoC references in dynamicComponents model block are incorrectly interpreted as implicit model relays](https://issues.fluidproject.org/browse/FLUID-5912)
* [FLUID-5546: Framework fails to deregister listeners to events which are injected from other components](https://issues.fluidproject.org/browse/FLUID-5546)
* [FLUID-5519: Timing of "initial transaction" in new model relay system is problematic](https://issues.fluidproject.org/browse/FLUID-5519)
### Inline Edit ###
* [FLUID-5392: Two clicks required to edit an empty inline edit field](https://issues.fluidproject.org/browse/FLUID-5392)
* [FLUID-1600: Pressing the "Tab" key to exit edit mode places focus on the wrong item](http://issues.fluidproject.org/browse/FLUID-1600)
### Layout Reorderer ###
* [FLUID-3864: Layout Reorderer failed to move portlets back to the first column in three-columns view with keyboard](http://issues.fluidproject.org/browse/FLUID-3864)
* [FLUID-3089: If columns become stacked, can't drag item into lower column](http://issues.fluidproject.org/browse/FLUID-3089)
### Pager ###
[FLUID-6081: VoiceOver on Pager doesn't announce the page number when the focus is on a page link](https://issues.fluidproject.org/browse/FLUID-6081)
### Reorderer ###
* [FLUID-6013: The Grid Reorderer and Image Reorderer are missing ARIA role=row containers](https://issues.fluidproject.org/browse/FLUID-6013)
* [FLUID-5870: Reorderer demo failures on IE 11](https://issues.fluidproject.org/browse/FLUID-5870)
* [FLUID-44737: Focus styling persists after moving focus from Reorderer](https://issues.fluidproject.org/browse/FLUID-4437)
* [FLUID-3925: With no wrapping on, the keyboard movement keystrokes are captured by the browser where a wrap would have occurred.](http://issues.fluidproject.org/browse/FLUID-3925)
### UI Options / Preferences Framework ###
* [FLUID-5928: Schema and Grade version save preferences to different values](https://issues.fluidproject.org/browse/FLUID-5928)
* [FLUID-5372: Increasing font size does not increase width of UIO panel](https://issues.fluidproject.org/browse/FLUID-5372)
* [FLUID-5223: If there's exactly one text field in the prefs editor, pressing enter on most inputs causes the form to submit](http://issues.fluidproject.org/browse/FLUID-5223)
* [FLUID-5218: Prefs editor requires iFrame template to be in the same place as panel templates; it probably shouldn't](http://issues.fluidproject.org/browse/FLUID-5218)
* [FLUID-5066: UIO Integrators shouldn't have to edit Infusion's copy of html templates to add panels, css](http://issues.fluidproject.org/browse/FLUID-5066)
* [FLUID-4491: Line spacing doesn't affect elements that have a line-height style set](http://issues.fluidproject.org/browse/FLUID-4491)
* [FLUID-4394: Separated Panel UI Options' iFrame HTML page (SeparatedPanelFrame.html) doesn't play nice with a concatenated build of Infusion](http://issues.fluidproject.org/browse/FLUID-4394)
### Undo ###
* [FLUID-3697: Undo hard-codes selector classes instead of using user-configured values](http://issues.fluidproject.org/browse/FLUID-3697)
### Uploader ###
* [FLUID-6079: Uploader error, when chosen files are too large, is not read by screenreader](https://issues.fluidproject.org/browse/FLUID-6079)
* [FLUID-6065: The focus remains on the "Browse Files" button with 2 keyboard tabbings in IE 11 and IE Edge](https://issues.fluidproject.org/browse/FLUID-6065)
* [FLUID-6045: The table header scrolls out of view as the file queue is scrolled](https://issues.fluidproject.org/browse/FLUID-6045)
* [FLUID-5737: Uploading size is higher than total size](https://issues.fluidproject.org/browse/FLUID-5737)
* [FLUID-4726: Cannot change uploader's button text through the string options.](https://issues.fluidproject.org/browse/FLUID-4726)

30
lib/infusion/infusion-uiOptions.js

File diff suppressed because one or more lines are too long

1
lib/infusion/infusion-uiOptions.js.map

File diff suppressed because one or more lines are too long

171
lib/infusion/src/components/slidingPanel/js/SlidingPanel.js

@ -1,171 +0,0 @@
/*
Copyright 2011-2015 OCAD University
Copyright 2011 Lucendo Development Ltd.
Copyright 2016 Raising the Floor - International
Licensed under the Educational Community License (ECL), Version 2.0 or the New
BSD license. You may not use this file except in compliance with one these
Licenses.
You may obtain a copy of the ECL 2.0 License and BSD License at
https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt
*/
var fluid_2_0_0 = fluid_2_0_0 || {};
(function ($, fluid) {
"use strict";
/**********************
* Sliding Panel *
*********************/
fluid.defaults("fluid.slidingPanel", {
gradeNames: ["fluid.viewComponent"],
selectors: {
panel: ".flc-slidingPanel-panel",
toggleButton: ".flc-slidingPanel-toggleButton",
toggleButtonLabel: ".flc-slidingPanel-toggleButton"
},
strings: {
showText: "show",
hideText: "hide",
panelLabel: "panel"
},
events: {
onPanelHide: null,
onPanelShow: null,
afterPanelHide: null,
afterPanelShow: null
},
listeners: {
"onCreate.bindClick": {
"this": "{that}.dom.toggleButton",
"method": "click",
"args": ["{that}.togglePanel"]
},
"onCreate.bindModelChange": {
listener: "{that}.applier.modelChanged.addListener",
args: ["isShowing", "{that}.refreshView"]
},
"onCreate.setAriaProps": "{that}.setAriaProps",
"onCreate.setInitialState": {
listener: "{that}.refreshView"
},
"onPanelHide.setText": {
"this": "{that}.dom.toggleButtonLabel",
"method": "text",
"args": ["{that}.options.strings.showText"],
"priority": "first"
},
"onPanelHide.setAriaLabel": {
"this": "{that}.dom.toggleButtonLabel",
"method": "attr",
"args": ["aria-label", "{that}.options.strings.showTextAriaLabel"]
},
"onPanelShow.setText": {
"this": "{that}.dom.toggleButtonLabel",
"method": "text",
"args": ["{that}.options.strings.hideText"],
"priority": "first"
},
"onPanelShow.setAriaLabel": {
"this": "{that}.dom.toggleButtonLabel",
"method": "attr",
"args": ["aria-label", "{that}.options.strings.hideTextAriaLabel"]
},
"onPanelHide.operate": {
listener: "{that}.operateHide"
},
"onPanelShow.operate": {
listener: "{that}.operateShow"
},
"onCreate.setAriaStates": "{that}.setAriaStates"
},
members: {
panelId: {
expander: {
// create an id for panel
// and set that.panelId to the id value
funcName: "fluid.allocateSimpleId",
args: "{that}.dom.panel"
}
}
},
model: {
isShowing: false
},
modelListeners: {
"isShowing": {
funcName: "{that}.setAriaStates",
excludeSource: "init"
}
},
invokers: {
operateHide: {
"this": "{that}.dom.panel",
"method": "slideUp",
"args": ["{that}.options.animationDurations.hide", "{that}.events.afterPanelHide.fire"]
},
operateShow: {
"this": "{that}.dom.panel",
"method": "slideDown",
"args": ["{that}.options.animationDurations.show", "{that}.events.afterPanelShow.fire"]
},
hidePanel: {
func: "{that}.applier.change",
args: ["isShowing", false]
},
showPanel: {
func: "{that}.applier.change",
args: ["isShowing", true]
},
setAriaStates: {
funcName: "fluid.slidingPanel.setAriaStates",
args: ["{that}", "{that}.model.isShowing"]
},
setAriaProps: {
funcName: "fluid.slidingPanel.setAriaProperties",
args: ["{that}", "{that}.panelId"]
},
togglePanel: {
funcName: "fluid.slidingPanel.togglePanel",
args: ["{that}"]
},
refreshView: {
funcName: "fluid.slidingPanel.refreshView",
args: ["{that}"]
}
},
animationDurations: {
hide: 400,
show: 400
}
});
fluid.slidingPanel.togglePanel = function (that) {
that.applier.change("isShowing", !that.model.isShowing);
};
fluid.slidingPanel.refreshView = function (that) {
that.events[that.model.isShowing ? "onPanelShow" : "onPanelHide"].fire();
};
// panelId is passed in to ensure that it is evaluated before this
// function is called.
fluid.slidingPanel.setAriaProperties = function (that, panelId) {
that.locate("toggleButton").attr({
"role": "button",
"aria-controls": panelId
});
that.locate("panel").attr({
"aria-label": that.options.strings.panelLabel,
"role": "group"
});
};
fluid.slidingPanel.setAriaStates = function (that, isShowing) {
that.locate("toggleButton").attr("aria-pressed", isShowing);
that.locate("panel").attr("aria-expanded", isShowing);
};
})(jQuery, fluid_2_0_0);

16
lib/infusion/src/components/slidingPanel/slidingPanelDependencies.json

@ -1,16 +0,0 @@
{
"slidingPanel": {
"name": "Sliding Panel",
"description": "A widget that slides a panel in and out of view.",
"cssFiles": [],
"files": [
"./js/SlidingPanel.js"
],
"dependencies": [
"jQuery",
"jQueryUI",
"normalize",
"framework"
]
}
}

3
lib/infusion/src/components/tableOfContents/css/TableOfContents.css

@ -1,3 +0,0 @@
.fl-tableOfContents-hide-bullet {
list-style-type: none;
}

32
lib/infusion/src/components/tableOfContents/html/TableOfContents.html

@ -1,32 +0,0 @@
<!-- Table of contents template -->
<h2 class="flc-toc-header">Table of Contents Header</h2>
<ul class="flc-toc-levels-level1">
<li class="flc-toc-levels-items1">
<a class="flc-toc-levels-link1" href="">1</a>
<ul class="flc-toc-levels-level2">
<li class="flc-toc-levels-items2">
<a class="flc-toc-levels-link2" href="">2</a>
<ul class="flc-toc-levels-level3">
<li class="flc-toc-levels-items3">
<a class="flc-toc-levels-link3" href="">3</a>
<ul class="flc-toc-levels-level4">
<li class="flc-toc-levels-items4">
<a class="flc-toc-levels-link4" href="">4</a>
<ul class="flc-toc-levels-level5">
<li class="flc-toc-levels-items5">
<a class="flc-toc-levels-link5" href="">5</a>
<ul class="flc-toc-levels-level6">
<li class="flc-toc-levels-items6">
<a class="flc-toc-levels-link6" href="">6</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>

377
lib/infusion/src/components/tableOfContents/js/TableOfContents.js

@ -1,377 +0,0 @@
/*
Copyright 2011-2016 OCAD University
Copyright 2011 Lucendo Development Ltd.
Copyright 2012 Raising the Floor - US
Copyright 2015-2016 Raising the Floor - International
Licensed under the Educational Community License (ECL), Version 2.0 or the New
BSD license. You may not use this file except in compliance with one these
Licenses.
You may obtain a copy of the ECL 2.0 License and BSD License at
https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt
*/
var fluid_2_0_0 = fluid_2_0_0 || {};
(function ($, fluid) {
"use strict";
/******
* ToC *
*******/
fluid.registerNamespace("fluid.tableOfContents");
fluid.tableOfContents.headingTextToAnchorInfo = function (heading) {
var id = fluid.allocateSimpleId(heading);
var anchorInfo = {
id: id,
url: "#" + id
};
return anchorInfo;
};
fluid.tableOfContents.locateHeadings = function (that) {
var headings = that.locate("headings");
fluid.each(that.options.ignoreForToC, function (sel) {
headings = headings.not(sel).not(sel + " :header");
});
return headings;
};
fluid.tableOfContents.refreshView = function (that) {
var headings = that.locateHeadings();
that.anchorInfo = fluid.transform(headings, function (heading) {
return that.headingTextToAnchorInfo(heading);
});
var headingsModel = that.modelBuilder.assembleModel(headings, that.anchorInfo);
that.applier.change("", headingsModel);
that.events.onRefresh.fire();
};
fluid.defaults("fluid.tableOfContents", {
gradeNames: ["fluid.viewComponent"],
components: {
levels: {
type: "fluid.tableOfContents.levels",
createOnEvent: "onCreate",
container: "{tableOfContents}.dom.tocContainer",
options: {
model: {
headings: "{tableOfContents}.model"
},
events: {
afterRender: "{tableOfContents}.events.afterRender"
},
listeners: {
"{tableOfContents}.events.onRefresh": "{that}.refreshView"
},
strings: "{tableOfContents}.options.strings"
}
},
modelBuilder: {
type: "fluid.tableOfContents.modelBuilder"
}
},
model: [],
invokers: {
headingTextToAnchorInfo: "fluid.tableOfContents.headingTextToAnchorInfo",
locateHeadings: {
funcName: "fluid.tableOfContents.locateHeadings",
args: ["{that}"]
},
refreshView: {
funcName: "fluid.tableOfContents.refreshView",
args: ["{that}"]
},
// TODO: is it weird to have hide and show on a component?
hide: {
"this": "{that}.dom.tocContainer",
"method": "hide"
},
show: {
"this": "{that}.dom.tocContainer",
"method": "show"
}
},
strings: {
tocHeader: "Table of Contents"
},
selectors: {
headings: ":header:visible",
tocContainer: ".flc-toc-tocContainer"
},
ignoreForToC: {
tocContainer: "{that}.options.selectors.tocContainer"
},
events: {
onRefresh: null,
afterRender: null,
onReady: {
events: {
"onCreate": "onCreate",
"afterRender": "afterRender"
},
args: ["{that}"]
}
},
listeners: {
"onCreate.refreshView": "{that}.refreshView"
}
});
/*******************
* ToC ModelBuilder *
********************/
fluid.registerNamespace("fluid.tableOfContents.modelBuilder");
fluid.tableOfContents.modelBuilder.toModel = function (headingInfo, modelLevelFn) {
var headings = fluid.copy(headingInfo);
var buildModelLevel = function (headings, level) {
var modelLevel = [];
while (headings.length > 0) {
var heading = headings[0];
if (heading.level < level) {
break;
}
if (heading.level > level) {
var subHeadings = buildModelLevel(headings, level + 1);
if (modelLevel.length > 0) {
modelLevel[modelLevel.length - 1].headings = subHeadings;
} else {
modelLevel = modelLevelFn(modelLevel, subHeadings);
}
}
if (heading.level === level) {
modelLevel.push(heading);
headings.shift();
}
}
return modelLevel;
};
return buildModelLevel(headings, 1);
};
fluid.tableOfContents.modelBuilder.gradualModelLevelFn = function (modelLevel, subHeadings) {
// Clone the subHeadings because we don't want to modify the reference of the subHeadings.
// the reference will affect the equality condition in generateTree(), resulting an unwanted tree.
var subHeadingsClone = fluid.copy(subHeadings);
subHeadingsClone[0].level--;
return subHeadingsClone;
};
fluid.tableOfContents.modelBuilder.skippedModelLevelFn = function (modelLevel, subHeadings) {
modelLevel.push({headings: subHeadings});
return modelLevel;
};
fluid.tableOfContents.modelBuilder.convertToHeadingObjects = function (that, headings, anchorInfo) {
headings = $(headings);
return fluid.transform(headings, function (heading, index) {
return {
level: that.headingCalculator.getHeadingLevel(heading),
text: $(heading).text(),
url: anchorInfo[index].url
};
});
};
fluid.tableOfContents.modelBuilder.assembleModel = function (that, headings, anchorInfo) {
var headingInfo = that.convertToHeadingObjects(headings, anchorInfo);
return that.toModel(headingInfo);
};
fluid.defaults("fluid.tableOfContents.modelBuilder", {
gradeNames: ["fluid.component"],
components: {
headingCalculator: {
type: "fluid.tableOfContents.modelBuilder.headingCalculator"
}
},
invokers: {
toModel: {
funcName: "fluid.tableOfContents.modelBuilder.toModel",
args: ["{arguments}.0", "{modelBuilder}.modelLevelFn"]
},
modelLevelFn: "fluid.tableOfContents.modelBuilder.gradualModelLevelFn",
convertToHeadingObjects: "fluid.tableOfContents.modelBuilder.convertToHeadingObjects({that}, {arguments}.0, {arguments}.1)", // headings, anchorInfo
assembleModel: "fluid.tableOfContents.modelBuilder.assembleModel({that}, {arguments}.0, {arguments}.1)" // headings, anchorInfo
}
});
/*************************************
* ToC ModelBuilder headingCalculator *
**************************************/
fluid.registerNamespace("fluid.tableOfContents.modelBuilder.headingCalculator");
fluid.tableOfContents.modelBuilder.headingCalculator.getHeadingLevel = function (that, heading) {
return that.options.levels.indexOf(heading.tagName) + 1;
};
fluid.defaults("fluid.tableOfContents.modelBuilder.headingCalculator", {
gradeNames: ["fluid.component"],
invokers: {
getHeadingLevel: "fluid.tableOfContents.modelBuilder.headingCalculator.getHeadingLevel({that}, {arguments}.0)" // heading
},
levels: ["H1", "H2", "H3", "H4", "H5", "H6"]
});
/*************
* ToC Levels *
**************/
fluid.registerNamespace("fluid.tableOfContents.levels");
/**
* Create an object model based on the type and ID. The object should contain an
* ID that maps the selectors (ie. level1:), and the object should contain a children
* @param string Accepted values are: level, items
* @param int The current level which is used here as the ID.
*/
fluid.tableOfContents.levels.objModel = function (type, ID) {
var objModel = {
ID: type + ID + ":",
children: []
};
return objModel;
};
/**
* Configure item object when item object has no text, uri, level in it.
* defaults to add a decorator to hide the bullets.
*/
fluid.tableOfContents.levels.handleEmptyItemObj = function (itemObj) {
itemObj.decorators = [{
type: "addClass",
classes: "fl-tableOfContents-hide-bullet"
}];
};
/**
* @param Object that.model, the model with all the headings, it should be in the format of {headings: [...]}
* @param int the current level we want to generate the tree for. default to 1 if not defined.
* @return Object A tree that looks like {children: [{ID: x, subTree:[...]}, ...]}
*/
fluid.tableOfContents.levels.generateTree = function (headingsModel, currentLevel) {
currentLevel = currentLevel || 0;
var levelObj = fluid.tableOfContents.levels.objModel("level", currentLevel);
// FLUID-4352, run generateTree if there are headings in the model.
if (headingsModel.headings.length === 0) {
return currentLevel ? [] : {children: []};
}
// base case: level is 0, returns {children:[generateTree(nextLevel)]}
// purpose is to wrap the first level with a children object.
if (currentLevel === 0) {
var tree = {
children: [
fluid.tableOfContents.levels.generateTree(headingsModel, currentLevel + 1)
]
};
return tree;
}
// Loop through the heading array, which can have multiple headings on the same level
$.each(headingsModel.headings, function (index, model) {
var itemObj = fluid.tableOfContents.levels.objModel("items", currentLevel);
var linkObj = {
ID: "link" + currentLevel,
target: model.url,
linktext: model.text
};
// If level is undefined, then add decorator to it, otherwise add the links to it.
if (!model.level) {
fluid.tableOfContents.levels.handleEmptyItemObj(itemObj);
} else {
itemObj.children.push(linkObj);
}
// If there are sub-headings, go into the next level recursively
if (model.headings) {
itemObj.children.push(fluid.tableOfContents.levels.generateTree(model, currentLevel + 1));
}
// At this point, the itemObj should be in a tree format with sub-headings children
levelObj.children.push(itemObj);
});
return levelObj;
};
/**
* @return Object Returned produceTree must be in {headings: [trees]}
*/
fluid.tableOfContents.levels.produceTree = function (that) {
var tree = fluid.tableOfContents.levels.generateTree(that.model);
// Add the header to the tree
tree.children.push({
ID: "tocHeader",
messagekey: "tocHeader"
});
return tree;
};
fluid.tableOfContents.levels.fetchResources = function (that) {
fluid.fetchResources(that.options.resources, function () {
that.container.append(that.options.resources.template.resourceText);
that.refreshView();
});
};
fluid.defaults("fluid.tableOfContents.levels", {
gradeNames: ["fluid.rendererComponent"],
produceTree: "fluid.tableOfContents.levels.produceTree",
strings: {
tocHeader: "Table of Contents"
},
selectors: {
tocHeader: ".flc-toc-header",
level1: ".flc-toc-levels-level1",
level2: ".flc-toc-levels-level2",
level3: ".flc-toc-levels-level3",
level4: ".flc-toc-levels-level4",
level5: ".flc-toc-levels-level5",
level6: ".flc-toc-levels-level6",
items1: ".flc-toc-levels-items1",
items2: ".flc-toc-levels-items2",
items3: ".flc-toc-levels-items3",
items4: ".flc-toc-levels-items4",
items5: ".flc-toc-levels-items5",
items6: ".flc-toc-levels-items6",
link1: ".flc-toc-levels-link1",
link2: ".flc-toc-levels-link2",
link3: ".flc-toc-levels-link3",
link4: ".flc-toc-levels-link4",
link5: ".flc-toc-levels-link5",
link6: ".flc-toc-levels-link6"
},
repeatingSelectors: ["level1", "level2", "level3", "level4", "level5", "level6", "items1", "items2", "items3", "items4", "items5", "items6"],
model: {
headings: [] // [text: heading, url: linkURL, headings: [ an array of subheadings in the same format]
},
listeners: {
"onCreate.fetchResources": "fluid.tableOfContents.levels.fetchResources"
},
resources: {
template: {
forceCache: true,
url: "../html/TableOfContents.html"
}
},
rendererFnOptions: {
noexpand: true
},
rendererOptions: {
debugMode: false
}
});
})(jQuery, fluid_2_0_0);

15
lib/infusion/src/components/tableOfContents/tableOfContentsDependencies.json

@ -1,15 +0,0 @@
{
"tableOfContents": {
"name": "Table of Contents",
"description": "Present an automatic table of contents from any HTML page.",
"files": [
"./js/TableOfContents.js"
],
"dependencies": [
"jQuery",
"normalize",
"framework",
"renderer"
]
}
}

113
lib/infusion/src/components/textToSpeech/js/MockTTS.js

@ -1,113 +0,0 @@
/*
Copyright 2015 OCAD University
Licensed under the Educational Community License (ECL), Version 2.0 or the New
BSD license. You may not use this file except in compliance with one these
Licenses.
You may obtain a copy of the ECL 2.0 License and BSD License at
https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt
*/
/* global fluid */
(function () {
"use strict";
// Mocks the fluid.textToSpeech component, removing calls to the
// Web Speech API. This will allow for tests to run in browsers
// that don't support the Web Speech API.
fluid.defaults("fluid.mock.textToSpeech", {
gradeNames: ["fluid.textToSpeech"],
members: {
// An archive of all the calls to queueSpeech.
// Will contain an ordered set of objects -- {text: String, options: Object}.
speechRecord: [],
// An archive of all the events fired
// Will contain a key/value pairing where key is the name of the event and the
// value is the number of times the event was fired.
eventRecord: {}
},
listeners: {
"onStart.recordEvent": {
listener: "{that}.recordEvent",
args: ["onStart"]
},
"onStop.recordEvent": {
listener: "{that}.recordEvent",
args: ["onStop"]
},
"onSpeechQueued.recordEvent": {
listener: "{that}.recordEvent",
args: ["onSpeechQueued"]
}
},
invokers: {
queueSpeech: {
funcName: "fluid.mock.textToSpeech.queueSpeech",
args: ["{that}", "{that}.handleStart", "{that}.handleEnd", "{that}.speechRecord", "{arguments}.0", "{arguments}.1", "{arguments}.2"]
},
cancel: {
funcName: "fluid.mock.textToSpeech.cancel",
args: ["{that}", "{that}.handleEnd"]
},
pause: {
"this": null, // TODO: This needs to be removed once FLUID-5714 is fixed
method: null,
func: "{that}.events.onPause.fire"
},
resume: {
"this": null,
method: null,
func: "{that}.events.onResume.fire"
},
getVoices: {
"this": null,
method: null,
funcName: "fluid.identity",
args: []
},
recordEvent: {
funcName: "fluid.mock.textToSpeech.recordEvent",
args: ["{that}.eventRecord", "{arguments}.0"]
}
}
});
fluid.mock.textToSpeech.queueSpeech = function (that, handleStart, handleEnd, speechRecord, text, interrupt, options) {
if (interrupt) {
that.cancel();
}
var record = {
text: text,
interrupt: !!interrupt
};
if (options) {
record.options = options;
}
speechRecord.push(record);
that.queue.push(text);
that.events.onSpeechQueued.fire(text);
// mocking speechSynthesis speak
handleStart();
// using setTimeout to preserve asynchronous behaviour
setTimeout(handleEnd, 0);
};
fluid.mock.textToSpeech.cancel = function (that, handleEnd) {
that.queue = [];
handleEnd();
};
fluid.mock.textToSpeech.recordEvent = function (eventRecord, name) {
eventRecord[name] = (eventRecord[name] || 0) + 1;
};
})();

288
lib/infusion/src/components/textToSpeech/js/TextToSpeech.js

@ -1,288 +0,0 @@
/*
Copyright 2015-2016 OCAD University
Licensed under the Educational Community License (ECL), Version 2.0 or the New
BSD license. You may not use this file except in compliance with one these
Licenses.
You may obtain a copy of the ECL 2.0 License and BSD License at
https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt
Includes code from Underscore.js 1.8.3
http://underscorejs.org
(c) 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
Underscore may be freely distributed under the MIT license.
*/
/* global speechSynthesis, SpeechSynthesisUtterance*/
var fluid_2_0_0 = fluid_2_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.textToSpeech");
/******************************************************************************************* *
* fluid.textToSpeech provides a wrapper around the SpeechSynthesis Interface *
* from the Web Speech API ( https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html ) *
*********************************************************************************************/
fluid.textToSpeech.isSupported = function () {
return !!(window && window.speechSynthesis);
};
/**
* Ensures that TTS is supported in the browser, including cases where the
* feature is detected, but where the underlying audio engine is missing.
* For example in VMs on SauceLabs, the behaviour for browsers which report that the speechSynthesis
* API is implemented is for the `onstart` event of an utterance to never fire. If we don't receive this
* event within a timeout, this API's behaviour is to return a promise which rejects.
*
* @param delay {Number} A time in milliseconds to wait for the speechSynthesis to fire its onStart event
* by default it is 5000ms (5s). This is crux of the test, as it needs time to attempt to run the speechSynthesis.
* @return {fluid.promise} A promise which will resolve if the TTS is supported (the onstart event is fired within the delay period)
* or be rejected otherwise.
*/
fluid.textToSpeech.checkTTSSupport = function (delay) {
var promise = fluid.promise();
if (fluid.textToSpeech.isSupported()) {
// MS Edge speech synthesizer won't speak if the text string is blank,
// so this must contain actual text
var toSpeak = new SpeechSynthesisUtterance("short"); // short text to attempt to speak
toSpeak.volume = 0; // mutes the Speech Synthesizer
// Same timeout as the timeout in the IoC testing framework
var timeout = setTimeout(function () {
fluid.textToSpeech.deferredSpeechSynthesisControl("cancel");
promise.reject();
}, delay || 5000);
toSpeak.onend = function () {
clearTimeout(timeout);
fluid.textToSpeech.deferredSpeechSynthesisControl("cancel");
promise.resolve();
};
fluid.textToSpeech.deferredSpeechSynthesisControl("speak", toSpeak);
} else {
setTimeout(promise.reject, 0);
}
return promise;
};
fluid.defaults("fluid.textToSpeech", {
gradeNames: ["fluid.modelComponent"],
events: {
onStart: null,
onStop: null,
onError: null,
onSpeechQueued: null
},
members: {
queue: []
},
// Model paths: speaking, pending, paused, utteranceOpts, pauseRequested, resumeRequested
model: {
// Changes to the utteranceOpts will only text that is queued after the change.
// All of these options can be overriden in the queueSpeech method by passing in
// options directly there. It is useful in cases where a single instance needs to be
// spoken with different options (e.g. single text in a different language.)
utteranceOpts: {
// text: "", // text to synthesize. avoid as it will override any other text passed in
// lang: "", // the language of the synthesized text
// voice: {} // a WebSpeechSynthesis object; if not set, will use the default one provided by the browser
// volume: 1, // a value between 0 and 1
// rate: 1, // a value from 0.1 to 10 although different synthesizers may have a smaller range
// pitch: 1, // a value from 0 to 2
}
},
modelListeners: {
"speaking": {
listener: "fluid.textToSpeech.speak",
args: ["{that}", "{change}.value"]
},
"pauseRequested": {
listener: "fluid.textToSpeech.requestControl",
args: ["{that}", "pause", "{change}"]
},
"resumeRequested": {
listener: "fluid.textToSpeech.requestControl",
args: ["{that}", "resume", "{change}"]
}
},
invokers: {
queueSpeech: {
funcName: "fluid.textToSpeech.queueSpeech",
args: ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2"]
},
cancel: {
funcName: "fluid.textToSpeech.cancel",
args: ["{that}"]
},
pause: {
changePath: "pauseRequested",
value: true
},
resume: {
changePath: "resumeRequested",
value: true
},
getVoices: {
"this": "speechSynthesis",
"method": "getVoices"
},
handleStart: {
changePath: "speaking",
value: true
},
// The handleEnd method is assumed to be triggered asynchronously
// as it is processed/triggered by the mechanism voicing the utterance.
handleEnd: {
funcName: "fluid.textToSpeech.handleEnd",
args: ["{that}"]
},
handleError: "{that}.events.onError.fire",
handlePause: {
changePath: "paused",
value: true
},
handleResume: {
changePath: "paused",
value: false
}
}
});
// Issue commands to the speechSynthesis interface with deferral (1 ms timeout);
// this makes the wrapper behave better when issuing commands, especially
// play and pause
fluid.textToSpeech.deferredSpeechSynthesisControl = function (control, args) {
setTimeout(function () {
speechSynthesis[control](args);
}, 1);
};
// Throttle implementation adapted from underscore.js 1.8.3; see
// file header for license details
// Returns a version of a function that will only be called max once
// every "wait" MS
fluid.textToSpeech.throttle = function (func, wait, options) {
var timeout, context, args, result;
var previous = 0;
if (!options) {
options = {};
}
var later = function () {
previous = options.leading === false ? 0 : new Date().getTime();
timeout = null;
result = func.apply(context, args);
if (!timeout) {
context = args = null;
}
};
var throttled = function () {
var now = new Date().getTime();
if (!previous && options.leading === false) {
previous = now;
}
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) {
context = args = null;
}
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
throttled.cancel = function () {
clearTimeout(timeout);
previous = 0;
timeout = context = args = null;
};
return throttled;
};
// Throttled version of deferred speech synthesis control
fluid.textToSpeech.throttleControl = fluid.textToSpeech.throttle(fluid.textToSpeech.deferredSpeechSynthesisControl, 100, {leading: false});
fluid.textToSpeech.speak = function (that, speaking) {
that.events[speaking ? "onStart" : "onStop"].fire();
};
fluid.textToSpeech.requestControl = function (that, control, change) {
// If there's a control request (value change to true), clear and
// execute it
if (change.value) {
that.applier.change(change.path, false);
fluid.textToSpeech.throttleControl(control);
}
};
fluid.textToSpeech.handleEnd = function (that) {
that.queue.shift();
var resetValues = {
speaking: false,
pending: false,
paused: false
};
if (that.queue.length) {
that.applier.change("pending", true);
} else if (!that.queue.length) {
var newModel = $.extend({}, that.model, resetValues);
that.applier.change("", newModel);
}
};
fluid.textToSpeech.queueSpeech = function (that, text, interrupt, options) {
if (interrupt) {
that.cancel();
}
var errorFn = function () {
that.handleError(text);
};
var toSpeak = new SpeechSynthesisUtterance(text);
var eventBinding = {
onstart: that.handleStart,
onend: that.handleEnd,
onerror: errorFn,
onpause: that.handlePause,
onresume: that.handleResume
};
$.extend(toSpeak, that.model.utteranceOpts, options, eventBinding);
// Store toSpeak additionally on the queue to help deal
// with premature garbage collection described at https://bugs.chromium.org/p/chromium/issues/detail?id=509488#c11
// this makes the speech synthesis behave much better in Safari in
// particular
that.queue.push({text: text, utterance: toSpeak});
that.events.onSpeechQueued.fire(text);
fluid.textToSpeech.deferredSpeechSynthesisControl("speak", toSpeak);
};
fluid.textToSpeech.cancel = function (that) {
that.queue = [];
fluid.textToSpeech.deferredSpeechSynthesisControl("cancel");
};
})(jQuery, fluid_2_0_0);

14
lib/infusion/src/components/textToSpeech/textToSpeechDependencies.json

@ -1,14 +0,0 @@
{
"textToSpeech": {
"name": "Text To Speech",
"description": "A wrapper around the Web Speech API for Speech Synthesis",
"cssFiles": [],
"files": [
"./js/TextToSpeech.js"
],
"dependencies": [
"jQuery",
"framework"
]
}
}

312
lib/infusion/src/components/textfieldSlider/js/TextfieldSlider.js

@ -1,312 +0,0 @@
/*
Copyright 2013-2016 OCAD University
Licensed under the Educational Community License (ECL), Version 2.0 or the New
BSD license. You may not use this file except in compliance with one these
Licenses.
You may obtain a copy of the ECL 2.0 License and BSD License at
https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt
*/
var fluid_2_0_0 = fluid_2_0_0 || {};
(function ($, fluid) {
"use strict";
/********************
* Textfield Slider *
********************/
fluid.defaults("fluid.textfieldSlider", {
gradeNames: ["fluid.viewComponent", "fluid.contextAware"],
components: {
textfield: {
type: "fluid.textfieldSlider.textfield",
container: "{textfieldSlider}.dom.textfield",
options: {
model: "{textfieldSlider}.model",
range: "{textfieldSlider}.options.range",
ariaOptions: "{textfieldSlider}.options.ariaOptions",
strings: "{textfieldSlider}.options.strings"
}
},
slider: {
container: "{textfieldSlider}.dom.slider",
options: {
model: "{textfieldSlider}.model",
range: "{textfieldSlider}.options.range",
sliderOptions: "{textfieldSlider}.options.sliderOptions",
ariaOptions: "{textfieldSlider}.options.ariaOptions",
strings: "{textfieldSlider}.options.strings"
}
}
},
contextAwareness: {
sliderVariety: {
checks: {
jQueryUI: {
contextValue: "{fluid.prefsWidgetType}",
equals: "jQueryUI",
gradeNames: "fluid.textfieldSlider.jQueryUI"
}
},
defaultGradeNames: "fluid.textfieldSlider.nativeHTML"
}
},
selectors: {
textfield: ".flc-textfieldSlider-field",
slider: ".flc-textfieldSlider-slider"
},
model: {
value: null
},
modelRelay: {
target: "value",
singleTransform: {
type: "fluid.transforms.limitRange",
input: "{that}.model.value",
min: "{that}.options.range.min",
max: "{that}.options.range.max"
}
},
range: {
min: 0,
max: 100
},
ariaOptions: {
// Specified by implementor
// ID of an external label to refer to with aria-labelledby
// attribute
// "aria-labelledby": ""
},
sliderOptions: {
orientation: "horizontal",
step: 1.0
},
strings: {
// Specified by implementor
// text of label to apply to both textfield and slider input
// via aria-label attribute
// "aria-label": ""
}
});
fluid.defaults("fluid.textfieldSlider.nativeHTML", {
components: {
slider: {
type: "fluid.slider.native"
}
}
});
fluid.defaults("fluid.textfieldSlider.jQueryUI", {
components: {
slider: {
type: "fluid.slider.jQuery"
}
}
});
fluid.defaults("fluid.textfieldSlider.textfield", {
gradeNames: ["fluid.viewComponent"],
range: {}, // should be used to specify the min, max range e.g. {min: 0, max: 100}
modelRelay: {
target: "value",
singleTransform: {
type: "fluid.transforms.stringToNumber",
input: "{that}.model.stringValue"
}
},
modelListeners: {
value: {
"this": "{that}.container",
"method": "val",
args: ["{change}.value"]
},
// TODO: This listener is to deal with the issue that, when the input field receives a invalid input such as a string value,
// ignore it and populate the field with the previous value.
// This is an area in which UX has spilled over into our model configuration, which to some extent we should try to prevent.
// Whenever we receive a "change" event or some other similar checkpoint, if these updates occurred any faster, the user would
// be infuriated by being unable to type into the field. This situation doesn't occur at the moment because the change event is
// only fired when users leave the input feild. At the very least, we need to give a namespace to this listener - unfortunately
// the current dataBinding implementation will ignore it. Having this listener here represents an interaction decision rather
// than an implementation decision. This issue needs to be revisited.
stringValue: {
"this": "{that}.container",
"method": "val",
args: ["{that}.model.value"]
}
},
listeners: {
"onCreate.bindChangeEvt": {
"this": "{that}.container",
"method": "change",
"args": ["{that}.setModel"]
},
"onCreate.initTextfieldAttributes": {
"this": "{that}.container",
method: "attr",
args: [{
"aria-labelledby": "{that}.options.ariaOptions.aria-labelledby",
"aria-label": "{that}.options.strings.aria-label"
}]
}
},
invokers: {
setModel: {
changePath: "stringValue",
value: "{arguments}.0.target.value"
}
}
});
// Base slider grade
fluid.defaults("fluid.slider", {
gradeNames: ["fluid.viewComponent"],
range: {} // should be used to specify the min, max range e.g. {min: 0, max: 100}
});
fluid.defaults("fluid.slider.native", {
gradeNames: ["fluid.slider"],
modelRelay: {
target: "value",
singleTransform: {
type: "fluid.transforms.stringToNumber",
input: "{that}.model.stringValue"
}
},
invokers: {
setModel: {
changePath: "stringValue",
value: {
expander: {
"this": "{that}.container",
"method": "val"
}
}
}
},
listeners: {
"onCreate.initSliderAttributes": {
"this": "{that}.container",
method: "attr",
args: [{
"min": "{that}.options.range.min",
"max": "{that}.options.range.max",
"step": "{that}.options.sliderOptions.step",
"type": "range",
"value": "{that}.model.value",
"aria-labelledby": "{that}.options.ariaOptions.aria-labelledby",
"aria-label": "{that}.options.strings.aria-label"
}]
},
"onCreate.bindSlideEvt": {
"this": "{that}.container",
"method": "on",
"args": ["input", "{that}.setModel"]
},
"onCreate.bindRangeChangeEvt": {
"this": "{that}.container",
"method": "on",
"args": ["change", "{that}.setModel"]
}
},
modelListeners: {
"value": [{
"this": "{that}.container",
"method": "val",
args: ["{change}.value"],
// If we don't exclude init, the value can get
// set before onCreate.initSliderAttributes
// sets min / max / step, which messes up the
// initial slider rendering
excludeSource: "init"
}]
}
});
fluid.defaults("fluid.slider.jQuery", {
gradeNames: ["fluid.slider"],
selectors: {
thumb: ".ui-slider-handle"
},
styles: {
handle: "fl-slider-handle",
range: "fl-slider-range"
},
members: {
slider: {
expander: {
"this": "{that}.container",
method: "slider",
args: ["{that}.combinedSliderOptions"]
}
},
combinedSliderOptions: {
expander: {
funcName: "fluid.slider.combineSliderOptions",
args: ["{that}.options.sliderOptions", "{that}.options.range"]
}
}
},
sliderOptions: {
orientation: "horizontal",
step: 1.0,
classes: {
"ui-slider-handle": "{that}.options.styles.handle",
"ui-slider-range": "{that}.options.styles.range"
}
},
invokers: {
setSliderValue: {
"this": "{that}.slider",
"method": "slider",
args: ["value", "{arguments}.0"]
},
setSliderAriaValueNow: {
"this": "{that}.dom.thumb",
"method": "attr",
args: ["aria-valuenow", "{arguments}.0"]
},
setModel: {
changePath: "value",
value: "{arguments}.1.value"
}
},
listeners: {
// This can be removed once the jQuery UI slider has built in ARIA
"onCreate.initSliderAria": {
"this": "{that}.dom.thumb",
method: "attr",
args: [{
role: "slider",
"aria-valuenow": "{that}.combinedSliderOptions.value",
"aria-valuemin": "{that}.combinedSliderOptions.min",
"aria-valuemax": "{that}.combinedSliderOptions.max",
"aria-labelledby": "{that}.options.ariaOptions.aria-labelledby",
"aria-label": "{that}.options.strings.aria-label"
}]
},
"onCreate.bindSlideEvt": {
"this": "{that}.slider",
"method": "on",
"args": ["slide", "{that}.setModel"]
}
},
modelListeners: {
"value": [{
listener: "{that}.setSliderValue",
args: ["{change}.value"]
}, {
listener: "{that}.setSliderAriaValueNow",
args: ["{change}.value"]
}]
}
});
fluid.slider.combineSliderOptions = function (sliderOptions, model, range) {
return $.extend(true, {}, sliderOptions, model, range);
};
})(jQuery, fluid_2_0_0);

18
lib/infusion/src/components/textfieldSlider/textfieldSliderDependencies.json

@ -1,18 +0,0 @@
{
"textfieldSlider": {
"name": "Textfield Slider",
"description": "A synchronized slider and textfield",
"cssFiles": [],
"files": [
"./js/TextfieldSlider.js"
],
"dependencies": [
"jQuery",
"jQueryUI",
"normalize",
"framework",
"enhancement",
"jQueryTouchPunchPlugin"
]
}
}

45
lib/infusion/src/components/uiOptions/js/UIOptions.js

@ -1,45 +0,0 @@
/*
Copyright 2013-2016 OCAD University
Licensed under the Educational Community License (ECL), Version 2.0 or the New
BSD license. You may not use this file except in compliance with one these
Licenses.
You may obtain a copy of the ECL 2.0 License and BSD License at
https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt
*/
var fluid_2_0_0 = fluid_2_0_0 || {};
(function ($, fluid) {
"use strict";
// Gradename to invoke "fluid.uiOptions.prefsEditor"
fluid.prefs.builder({
gradeNames: ["fluid.prefs.auxSchema.starter"]
});
fluid.defaults("fluid.uiOptions.prefsEditor", {
gradeNames: ["fluid.prefs.constructed.prefsEditor"],
lazyLoad: false,
distributeOptions: [{
record: "{that}.options.lazyLoad",
target: "{that separatedPanel}.options.lazyLoad"
}, {
source: "{that}.options.tocTemplate",
target: "{that uiEnhancer}.options.tocTemplate"
}, {
source: "{that}.options.ignoreForToC",
target: "{that uiEnhancer}.options.ignoreForToC"
}],
enhancer: {
distributeOptions: [{
source: "{that}.options.tocTemplate",
target: "{that > fluid.prefs.enactor.tableOfContents}.options.tocTemplate"
}, {
source: "{that}.options.ignoreForToC",
target: "{that > fluid.prefs.enactor.tableOfContents}.options.ignoreForToC"
}]
}
});
})(jQuery, fluid_2_0_0);

14
lib/infusion/src/components/uiOptions/uiOptionsDependencies.json

@ -1,14 +0,0 @@
{
"uiOptions": {
"name": "User Interface Options",
"description": "An instance of a preference editor created by the Infusion Preferences Framework. Users customize their preferences and needs for viewing content.",
"files": [
"./js/UIOptions.js"
],
"dependencies": [
"jQuery",
"framework",
"preferences"
]
}
}

69
lib/infusion/src/framework/core/css/fluid.css

@ -1,69 +0,0 @@
/* focus */
.fl-focus:focus,
.fl-focus :focus {
outline: 2px solid black;
}
/* Container alignment */
.fl-force-right {float:right;}
.fl-force-left {float:left;}
.fl-centered {margin-left:auto; margin-right:auto; display:block;}
/* The following styles are based on 3rd party software */
/*
* The following styles are based on the Micro Clearfix solution:
* http://nicolasgallagher.com/micro-clearfix-hack/
*/
.fl-clearfix:before, .fl-clearfix:after {content:""; display:table;}
.fl-clearfix:after {clear:both;}
/* End of Micro Clearfix based styles */
/*
* The following styles are based on css from HTML5 Boilerplate v4.3:
* http://html5boilerplate.com
*/
/* Hide from both screenreaders and browsers */
.fl-hidden {
display: none !important;
visibility: hidden;
}
/* Hide visually and from screenreaders, but maintain layout */
.fl-hidden-invisible {
visibility: hidden;
}
/* Hide only visually, but have it available for screenreaders */
.fl-hidden-accessible {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
/*
* Extends the .visuallyhidden class to allow the element to be focusable
* when navigated to via the keyboard
*/
.fl-hidden-accessible.fl-focus:active,
.fl-hidden-accessible.fl-focus:focus {
clip: auto;
height: auto;
margin: 0;
overflow: visible;
position: static;
width: auto;
}
/* End of HTML5 Boilerplate based styles */

132
lib/infusion/src/framework/core/css/fluidDebugging.css

@ -1,132 +0,0 @@
.fl-debug-holder {
position: fixed;
bottom: 0;
right: 0;
width: 100%;
height: 0px;
background-color: #dff;
}
.fl-debug-holder-open {
height: 20em;
}
.fl-debug-holder-closed {
height: 0px;
}
.fl-debug-open-pane-trigger {
width: 32px;
height: 32px;
position: absolute;
top: -37px;
right: 5px;
background: url("../images/debug_tab.png");
}
.fl-debug-open-pane-trigger:hover {
background-color: #bbb;
}
.fl-debug-pane {
width: 100%;
height: 100%;
font-family: OpenSans, 'Helvetica Neue', Helvetica, Helvetica, Arial, sans-serif;
font-size: 16px;
color: black;
padding-top: 40px;
overflow-y: scroll;
overflow-x: hidden;
}
.fl-debug-pane thead {
padding-bottom: 2px;
font-weight: bold;
}
.fl-debug-pointer-events-none {
pointer-events: none;
}
.fl-debug-highlightElement {
z-index: 999999;
position: absolute;
width: 100%;
height: 100%;
pointer-events: none;
}
.fl-debug-highlightRoot {
position: absolute;
width: 100%;
height: 100%;
overflow: hidden;
}
.flc-debug-pane-indexel {
width: 2em;
height: 1em;
margin: 0.2em;
border: 2px solid black
}
.fl-debug-inspect-trigger {
width: 32px;
height: 32px;
position: absolute;
top: 5px;
left: 5px;
background: url("../images/magnifying_glass.png");
}
.fl-debug-inspect-trigger:hover {
background-color: #ddd;
}
.fl-debug-inspect-active {
background-color: #aaa;
}
.fl-debug-inspect-active:hover {
background-color: #888;
}
.fl-debug-selector-cell {
text-align: right;
padding-right: 1em;
}
/* See http://stackoverflow.com/questions/14765817/why-does-css-td-width-not-work */
.fl-debug-pane-index {
min-width: 3em;
}
.fl-debug-pane-dom-id {
min-width: 11em;
}
.fl-debug-pane-component-id {
min-width: 11em;
}
.fl-debug-pane-grades {
min-width: 40em;
}
.fl-debug-line {
min-width: 18em;
}
.fl-debug-tooltip {
width: 40em;
font-size: 10px;
position: absolute;
background-color: #FFC;
border: 2px solid #444;
padding: 0.5em;
}
.flc-debug-tooltip-trigger:hover {
background-color: rgba(128, 128, 128, 0.3);
}

26
lib/infusion/src/framework/core/frameworkDependencies.json

@ -1,26 +0,0 @@
{
"framework": {
"name": "Infusion Framework Core",
"description": "A suite of core Infusion framework features, including support for events, views, data binding, and keyboard accessibility. Required by all Fluid components.",
"files": [
"./js/Fluid.js",
"./js/FluidPromises.js",
"./js/FluidDocument.js",
"./js/FluidDOMUtilities.js",
"./js/JavaProperties.js",
"./js/FluidDebugging.js",
"./js/FluidIoC.js",
"./js/DataBinding.js",
"./js/ModelTransformation.js",
"./js/ModelTransformationTransforms.js",
"./js/jquery.keyboard-a11y.js",
"./js/FluidView.js",
"./js/FluidRequests.js",
"./js/ResourceLoader.js"
],
"dependencies": [
"jQuery",
"jQueryUI"
]
}
}

BIN
lib/infusion/src/framework/core/images/debug_tab.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

BIN
lib/infusion/src/framework/core/images/magnifying_glass.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

1495
lib/infusion/src/framework/core/js/DataBinding.js

File diff suppressed because it is too large Load Diff

2806
lib/infusion/src/framework/core/js/Fluid.js

File diff suppressed because it is too large Load Diff

116
lib/infusion/src/framework/core/js/FluidDOMUtilities.js

@ -1,116 +0,0 @@
/*
Copyright 2008-2010 University of Cambridge
Copyright 2008-2009 University of Toronto
Licensed under the Educational Community License (ECL), Version 2.0 or the New
BSD license. You may not use this file except in compliance with one these
Licenses.
You may obtain a copy of the ECL 2.0 License and BSD License at
https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt
*/
var fluid_2_0_0 = fluid_2_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.dom = fluid.dom || {};
// Node walker function for iterateDom.
var getNextNode = function (iterator) {
if (iterator.node.firstChild) {
iterator.node = iterator.node.firstChild;
iterator.depth += 1;
return iterator;
}
while (iterator.node) {
if (iterator.node.nextSibling) {
iterator.node = iterator.node.nextSibling;
return iterator;
}
iterator.node = iterator.node.parentNode;
iterator.depth -= 1;
}
return iterator;
};
/**
* Walks the DOM, applying the specified acceptor function to each element.
* There is a special case for the acceptor, allowing for quick deletion of elements and their children.
* Return "delete" from your acceptor function if you want to delete the element in question.
* Return "stop" to terminate iteration.
* Implementation note - this utility exists mainly for performance reasons. It was last tested
* carefully some time ago (around jQuery 1.2) but at that time was around 3-4x faster at raw DOM
* filtration tasks than the jQuery equivalents, which was an important source of performance loss in the
* Reorderer component. General clients of the framework should use this method with caution if at all, and
* the performance issues should be reassessed when we have time.
*
* @param {Element} node the node to start walking from
* @param {Function} acceptor the function to invoke with each DOM element
* @param {Boolean} allnodes Use <code>true</code> to call acceptor on all nodes,
* rather than just element nodes (type 1)
*/
fluid.dom.iterateDom = function (node, acceptor, allNodes) {
var currentNode = {node: node, depth: 0};
var prevNode = node;
var condition;
while (currentNode.node !== null && currentNode.depth >= 0 && currentNode.depth < fluid.dom.iterateDom.DOM_BAIL_DEPTH) {
condition = null;
if (currentNode.node.nodeType === 1 || allNodes) {
condition = acceptor(currentNode.node, currentNode.depth);
}
if (condition) {
if (condition === "delete") {
currentNode.node.parentNode.removeChild(currentNode.node);
currentNode.node = prevNode;
}
else if (condition === "stop") {
return currentNode.node;
}
}
prevNode = currentNode.node;
currentNode = getNextNode(currentNode);
}
};
// Work around IE circular DOM issue. This is the default max DOM depth on IE.
// http://msdn2.microsoft.com/en-us/library/ms761392(VS.85).aspx
fluid.dom.iterateDom.DOM_BAIL_DEPTH = 256;
/**
* Checks if the specified container is actually the parent of containee.
*
* @param {Element} container the potential parent
* @param {Element} containee the child in question
*/
fluid.dom.isContainer = function (container, containee) {
for (; containee; containee = containee.parentNode) {
if (container === containee) {
return true;
}
}
return false;
};
/** Return the element text from the supplied DOM node as a single String.
* Implementation note - this is a special-purpose utility used in the framework in just one
* position in the Reorderer. It only performs a "shallow" traversal of the text and was intended
* as a quick and dirty means of extracting element labels where the user had not explicitly provided one.
* It should not be used by general users of the framework and its presence here needs to be
* reassessed.
*/
fluid.dom.getElementText = function (element) {
var nodes = element.childNodes;
var text = "";
for (var i = 0; i < nodes.length; ++i) {
var child = nodes[i];
if (child.nodeType === 3) {
text = text + child.nodeValue;
}
}
return text;
};
})(jQuery, fluid_2_0_0);

300
lib/infusion/src/framework/core/js/FluidDebugging.js

@ -1,300 +0,0 @@
/*
Copyright 2007-2010 University of Cambridge
Copyright 2007-2009 University of Toronto
Copyright 2007-2009 University of California, Berkeley
Copyright 2010 OCAD University
Copyright 2010-2011 Lucendo Development Ltd.
Copyright 2012 Raising the Floor - US
Copyright 2014-2015 Raising the Floor - International
Licensed under the Educational Community License (ECL), Version 2.0 or the New
BSD license. You may not use this file except in compliance with one these
Licenses.
You may obtain a copy of the ECL 2.0 License and BSD License at
https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt
*/
var fluid_2_0_0 = fluid_2_0_0 || {};
var fluid = fluid || fluid_2_0_0;
(function ($, fluid) {
"use strict";
/** Render a timestamp from a Date object into a helpful fixed format for debug logs to millisecond accuracy
* @param date {Date} The date to be rendered
* @return {String} A string format consisting of hours:minutes:seconds.millis for the datestamp padded to fixed with
*/
fluid.renderTimestamp = function (date) {
var zeropad = function (num, width) {
if (!width) { width = 2; }
var numstr = (num === undefined ? "" : num.toString());
return "00000".substring(5 - width + numstr.length) + numstr;
};
return zeropad(date.getHours()) + ":" + zeropad(date.getMinutes()) + ":" + zeropad(date.getSeconds()) + "." + zeropad(date.getMilliseconds(), 3);
};
fluid.isTracing = false;
fluid.registerNamespace("fluid.tracing");
fluid.tracing.pathCount = [];
fluid.tracing.summarisePathCount = function (pathCount) {
pathCount = pathCount || fluid.tracing.pathCount;
var togo = {};
for (var i = 0; i < pathCount.length; ++i) {
var path = pathCount[i];
if (!togo[path]) {
togo[path] = 1;
}
else {
++togo[path];
}
}
var toReallyGo = [];
fluid.each(togo, function (el, path) {
toReallyGo.push({path: path, count: el});
});
toReallyGo.sort(function (a, b) {return b.count - a.count;});
return toReallyGo;
};
fluid.tracing.condensePathCount = function (prefixes, pathCount) {
prefixes = fluid.makeArray(prefixes);
var prefixCount = {};
fluid.each(prefixes, function (prefix) {
prefixCount[prefix] = 0;
});
var togo = [];
fluid.each(pathCount, function (el) {
var path = el.path;
if (!fluid.find(prefixes, function (prefix) {
if (path.indexOf(prefix) === 0) {
prefixCount[prefix] += el.count;
return true;
}
})) {
togo.push(el);
}
});
fluid.each(prefixCount, function (count, path) {
togo.unshift({path: path, count: count});
});
return togo;
};
// Exception stripping code taken from https://github.com/emwendelin/javascript-stacktrace/blob/master/stacktrace.js
// BSD licence, see header
fluid.detectStackStyle = function (e) {
var style = "other";
var stackStyle = {
offset: 0
};
if (e.arguments) {
style = "chrome";
} else if (typeof window !== "undefined" && window.opera && e.stacktrace) {
style = "opera10";
} else if (e.stack) {
style = "firefox";
// Detect FireFox 4-style stacks which are 1 level less deep
stackStyle.offset = e.stack.indexOf("Trace exception") === -1 ? 1 : 0;
} else if (typeof window !== "undefined" && window.opera && !("stacktrace" in e)) { //Opera 9-
style = "opera";
}
stackStyle.style = style;
return stackStyle;
};
fluid.obtainException = function () {
try {
throw new Error("Trace exception");
}
catch (e) {
return e;
}
};
var stackStyle = fluid.detectStackStyle(fluid.obtainException());
fluid.registerNamespace("fluid.exceptionDecoders");
fluid.decodeStack = function () {
if (stackStyle.style !== "firefox") {
return null;
}
var e = fluid.obtainException();
return fluid.exceptionDecoders[stackStyle.style](e);
};
fluid.exceptionDecoders.firefox = function (e) {
var delimiter = "at ";
var lines = e.stack.replace(/(?:\n@:0)?\s+$/m, "").replace(/^\(/gm, "{anonymous}(").split("\n");
return fluid.transform(lines, function (line) {
line = line.replace(/\)/g, "");
var atind = line.indexOf(delimiter);
return atind === -1 ? [line] : [line.substring(atind + delimiter.length), line.substring(0, atind)];
});
};
// Main entry point for callers.
fluid.getCallerInfo = function (atDepth) {
atDepth = (atDepth || 3) - stackStyle.offset;
var stack = fluid.decodeStack();
var element = stack && stack[atDepth][0];
if (element) {
var lastslash = element.lastIndexOf("/");
if (lastslash === -1) {
lastslash = 0;
}
var nextColon = element.indexOf(":", lastslash);
return {
path: element.substring(0, lastslash),
filename: element.substring(lastslash + 1, nextColon),
index: element.substring(nextColon + 1)
};
} else {
return null;
}
};
/** Generates a string for padding purposes by replicating a character a given number of times
* @param c {Character} A character to be used for padding
* @param count {Integer} The number of times to repeat the character
* @return A string of length <code>count</code> consisting of repetitions of the supplied character
*/
// UNOPTIMISED
fluid.generatePadding = function (c, count) {
var togo = "";
for (var i = 0; i < count; ++i) {
togo += c;
}
return togo;
};
// Marker so that we can render a custom string for properties which are not direct and concrete
fluid.SYNTHETIC_PROPERTY = {};
// utility to avoid triggering custom getter code which could throw an exception - e.g. express 3.x's request object
fluid.getSafeProperty = function (obj, key) {
var desc = Object.getOwnPropertyDescriptor(obj, key); // supported on all of our environments - is broken on IE8
return desc && !desc.get ? obj[key] : fluid.SYNTHETIC_PROPERTY;
};
function printImpl(obj, small, options) {
function out(str) {
options.output += str;
}
var big = small + options.indentChars, isFunction = typeof(obj) === "function";
if (options.maxRenderChars !== undefined && options.output.length > options.maxRenderChars) {
return true;
}
if (obj === null) {
out("null");
} else if (obj === undefined) {
out("undefined"); // NB - object invalid for JSON interchange
} else if (obj === fluid.SYNTHETIC_PROPERTY) {
out("[Synthetic property]");
} else if (fluid.isPrimitive(obj) && !isFunction) {
out(JSON.stringify(obj));
}
else {
if (options.stack.indexOf(obj) !== -1) {
out("(CIRCULAR)"); // NB - object invalid for JSON interchange
return;
}
options.stack.push(obj);
var i;
if (fluid.isArrayable(obj)) {
if (obj.length === 0) {
out("[]");
} else {
out("[\n" + big);
for (i = 0; i < obj.length; ++i) {
if (printImpl(obj[i], big, options)) {
return true;
}
if (i !== obj.length - 1) {
out(",\n" + big);
}
}
out("\n" + small + "]");
}
}
else {
out("{" + (isFunction ? " Function" : "") + "\n" + big); // NB - Function object invalid for JSON interchange
var keys = fluid.keys(obj);
for (i = 0; i < keys.length; ++i) {
var key = keys[i];
var value = fluid.getSafeProperty(obj, key);
out(JSON.stringify(key) + ": ");
if (printImpl(value, big, options)) {
return true;
}
if (i !== keys.length - 1) {
out(",\n" + big);
}
}
out("\n" + small + "}");
}
options.stack.pop();
}
return;
}
/** Render a complex JSON object into a nicely indented format suitable for human readability.
* @param obj {Object} The object to be rendered
* @param options {Object} An options structure governing the rendering process. This supports the following options:
* <code>indent</code> {Integer} the number of space characters to be used to indent each level of containment (default value: 4)
* <code>maxRenderChars</code> {Integer} rendering the object will cease once this number of characters has been generated
*/
fluid.prettyPrintJSON = function (obj, options) {
options = $.extend({indent: 4, stack: [], output: ""}, options);
options.indentChars = fluid.generatePadding(" ", options.indent);
printImpl(obj, "", options);
return options.output;
};
/**
* Dumps a DOM element into a readily recognisable form for debugging - produces a
* "semi-selector" summarising its tag name, class and id, whichever are set.
*
* @param {jQueryable} element The element to be dumped
* @return A string representing the element.
*/
fluid.dumpEl = function (element) {
var togo;
if (!element) {
return "null";
}
if (element.nodeType === 3 || element.nodeType === 8) {
return "[data: " + element.data + "]";
}
if (element.nodeType === 9) {
return "[document: location " + element.location + "]";
}
if (!element.nodeType && fluid.isArrayable(element)) {
togo = "[";
for (var i = 0; i < element.length; ++i) {
togo += fluid.dumpEl(element[i]);
if (i < element.length - 1) {
togo += ", ";
}
}
return togo + "]";
}
element = $(element);
togo = element.get(0).tagName;
if (element.id) {
togo += "#" + element.id;
}
if (element.attr("class")) {
togo += "." + element.attr("class");
}
return togo;
};
})(jQuery, fluid_2_0_0);

191
lib/infusion/src/framework/core/js/FluidDocument.js

@ -1,191 +0,0 @@
/*
Copyright 2007-2010 University of Cambridge
Copyright 2007-2009 University of Toronto
Copyright 2010-2011 Lucendo Development Ltd.
Copyright 2010-2016 OCAD University
Copyright 2013-2014 Raising the Floor - US
Copyright 2005-2013 jQuery Foundation, Inc. and other contributors
Licensed under the Educational Community License (ECL), Version 2.0 or the New
BSD license. You may not use this file except in compliance with one these
Licenses.
You may obtain a copy of the ECL 2.0 License and BSD License at
https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt
*/
/** This file contains functions which depend on the presence of a DOM document
* but which do not depend on the contents of Fluid.js **/
var fluid_2_0_0 = fluid_2_0_0 || {};
(function ($, fluid) {
"use strict";
// polyfill for $.browser which was removed in jQuery 1.9 and later
// Taken from jquery-migrate-1.2.1.js,
// jQuery Migrate - v1.2.1 - 2013-05-08
// https://github.com/jquery/jquery-migrate
// Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors; Licensed MIT
fluid.uaMatch = function (ua) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || [];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
var matched, browser;
// Don't clobber any existing jQuery.browser in case it's different
if (!$.browser) {
if (!!navigator.userAgent.match(/Trident\/7\./)) {
browser = { // From http://stackoverflow.com/questions/18684099/jquery-fail-to-detect-ie-11
msie: true,
version: 11
};
} else {
matched = fluid.uaMatch(navigator.userAgent);
browser = {};
if (matched.browser) {
browser[matched.browser] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if (browser.chrome) {
browser.webkit = true;
} else if (browser.webkit) {
browser.safari = true;
}
}
$.browser = browser;
}
// Private constants.
var NAMESPACE_KEY = "fluid-scoped-data";
/**
* Gets stored state from the jQuery instance's data map.
* This function is unsupported: It is not really intended for use by implementors.
*/
fluid.getScopedData = function (target, key) {
var data = $(target).data(NAMESPACE_KEY);
return data ? data[key] : undefined;
};
/**
* Stores state in the jQuery instance's data map. Unlike jQuery's version,
* accepts multiple-element jQueries.
* This function is unsupported: It is not really intended for use by implementors.
*/
fluid.setScopedData = function (target, key, value) {
$(target).each(function () {
var data = $.data(this, NAMESPACE_KEY) || {};
data[key] = value;
$.data(this, NAMESPACE_KEY, data);
});
};
/** Global focus manager - makes use of "focusin" event supported in jquery 1.4.2 or later.
*/
var lastFocusedElement = null;
$(document).on("focusin", function (event) {
lastFocusedElement = event.target;
});
fluid.getLastFocusedElement = function () {
return lastFocusedElement;
};
var ENABLEMENT_KEY = "enablement";
/** Queries or sets the enabled status of a control. An activatable node
* may be "disabled" in which case its keyboard bindings will be inoperable
* (but still stored) until it is reenabled again.
* This function is unsupported: It is not really intended for use by implementors.
*/
fluid.enabled = function (target, state) {
target = $(target);
if (state === undefined) {
return fluid.getScopedData(target, ENABLEMENT_KEY) !== false;
}
else {
$("*", target).add(target).each(function () {
if (fluid.getScopedData(this, ENABLEMENT_KEY) !== undefined) {
fluid.setScopedData(this, ENABLEMENT_KEY, state);
}
else if (/select|textarea|input/i.test(this.nodeName)) {
$(this).prop("disabled", !state);
}
});
fluid.setScopedData(target, ENABLEMENT_KEY, state);
}
};
fluid.initEnablement = function (target) {
fluid.setScopedData(target, ENABLEMENT_KEY, true);
};
// This utility is required through the use of newer versions of jQuery which will obscure the original
// event responsible for interaction with a target. This is currently use in Tooltip.js and FluidView.js
// "dead man's blur" but would be of general utility
fluid.resolveEventTarget = function (event) {
while (event.originalEvent && event.originalEvent.target) {
event = event.originalEvent;
}
return event.target;
};
// These function (fluid.focus() and fluid.blur()) serve several functions. They should be used by
// all implementation both in test cases and component implementation which require to trigger a focus
// event. Firstly, they restore the old behaviour in jQuery versions prior to 1.10 in which a focus
// trigger synchronously relays to a focus handler. In newer jQueries this defers to the real browser
// relay with numerous platform and timing-dependent effects.
// Secondly, they are necessary since simulation of focus events by jQuery under IE
// is not sufficiently good to intercept the "focusin" binding. Any code which triggers
// focus or blur synthetically throughout the framework and client code must use this function,
// especially if correct cross-platform interaction is required with the "deadMansBlur" function.
function applyOp(node, func) {
node = $(node);
node.trigger("fluid-" + func);
node.triggerHandler(func);
node[func]();
return node;
}
$.each(["focus", "blur"], function (i, name) {
fluid[name] = function (elem) {
return applyOp(elem, name);
};
});
/* Sets the value to the DOM element and triggers the change event on the element.
* Note: when using jQuery val() function to change the node value, the change event would
* not be fired automatically, it requires to be initiated by the user.
*
* @param node {A jQueryable DOM element} A selector, a DOM node, or a jQuery instance
* @param value {String|Number|Array} A string of text, a number, or an array of strings
* corresponding to the value of each matched element to set in the node
*/
fluid.changeElementValue = function (node, value) {
node = $(node);
node.val(value).change();
};
})(jQuery, fluid_2_0_0);

2458
lib/infusion/src/framework/core/js/FluidIoC.js

File diff suppressed because it is too large Load Diff

266
lib/infusion/src/framework/core/js/FluidPromises.js

@ -1,266 +0,0 @@
/*!
Copyright 2011 unscriptable.com / John Hann
Copyright 2014 Lucendo Development Ltd.
Copyright 2014 Raising the Floor - US
Copyright 2014-2016 Raising the Floor - International
License MIT
*/
var fluid_2_0_0 = fluid_2_0_0 || {};
(function ($, fluid) {
"use strict";
// Light fluidification of minimal promises library. See original gist at
// https://gist.github.com/unscriptable/814052 for limitations and commentary
// This implementation provides what could be described as "flat promises" with
// no support for structured programming idioms involving promise composition.
// It provides what a proponent of mainstream promises would describe as
// a "glorified callback aggregator"
fluid.promise = function () {
var that = {
onResolve: [],
onReject: []
// disposition
// value
};
that.then = function (onResolve, onReject) {
if (onResolve) {
if (that.disposition === "resolve") {
onResolve(that.value);
} else {
that.onResolve.push(onResolve);
}
}
if (onReject) {
if (that.disposition === "reject") {
onReject(that.value);
} else {
that.onReject.push(onReject);
}
}
return that;
};
that.resolve = function (value) {
if (that.disposition) {
fluid.fail("Error: resolving promise ", that,
" which has already received \"" + that.disposition + "\"");
} else {
that.complete("resolve", that.onResolve, value);
}
return that;
};
that.reject = function (reason) {
if (that.disposition) {
fluid.fail("Error: rejecting promise ", that,
"which has already received \"" + that.disposition + "\"");
} else {
that.complete("reject", that.onReject, reason);
}
return that;
};
// PRIVATE, NON-API METHOD
that.complete = function (which, queue, arg) {
that.disposition = which;
that.value = arg;
for (var i = 0; i < queue.length; ++i) {
queue[i](arg);
}
};
return that;
};
/** Any object with a member <code>then</code> of type <code>function</code> passes this test.
* This includes essentially every known variety, including jQuery promises.
*/
fluid.isPromise = function (totest) {
return totest && typeof(totest.then) === "function";
};
/** Coerces any value to a promise
* @param promiseOrValue The value to be coerced
* @return If the supplied value is already a promise, it is returned unchanged. Otherwise a fresh promise is created with the value as resolution and returned
*/
fluid.toPromise = function (promiseOrValue) {
if (fluid.isPromise(promiseOrValue)) {
return promiseOrValue;
} else {
var togo = fluid.promise();
togo.resolve(promiseOrValue);
return togo;
}
};
/** Chains the resolution methods of one promise (target) so that they follow those of another (source).
* That is, whenever source resolves, target will resolve, or when source rejects, target will reject, with the
* same payloads in each case.
*/
fluid.promise.follow = function (source, target) {
source.then(target.resolve, target.reject);
};
/** Returns a promise whose resolved value is mapped from the source promise or value by the supplied function.
* @param source {Object|Promise} An object or promise whose value is to be mapped
* @param func {Function} A function which will map the resolved promise value
* @return {Promise} A promise for the resolved mapped value.
*/
fluid.promise.map = function (source, func) {
var promise = fluid.toPromise(source);
var togo = fluid.promise();
promise.then(function (value) {
var mapped = func(value);
if (fluid.isPromise(mapped)) {
fluid.promise.follow(mapped, togo);
} else {
togo.resolve(mapped);
}
}, function (error) {
togo.reject(error);
});
return togo;
};
/* General skeleton for all sequential promise algorithms, e.g. transform, reduce, sequence, etc.
* These accept a variable "strategy" pair to customise the interchange of values and final return
*/
fluid.promise.makeSequencer = function (sources, options, strategy) {
if (!fluid.isArrayable(sources)) {
fluid.fail("fluid.promise sequence algorithms must be supplied an array as source");
}
return {
sources: sources,
resolvedSources: [], // the values of "sources" only with functions invoked (an array of promises or values)
index: 0,
strategy: strategy,
options: options, // available to be supplied to each listener
returns: [],
promise: fluid.promise() // the final return value
};
};
fluid.promise.progressSequence = function (that, retValue) {
that.returns.push(retValue);
that.index++;
// No we dun't have no tail recursion elimination
fluid.promise.resumeSequence(that);
};
fluid.promise.processSequenceReject = function (that, error) { // Allow earlier promises in the sequence to wrap the rejection supplied by later ones (FLUID-5584)
for (var i = that.index - 1; i >= 0; --i) {
var resolved = that.resolvedSources[i];
var accumulator = fluid.isPromise(resolved) && typeof(resolved.accumulateRejectionReason) === "function" ? resolved.accumulateRejectionReason : fluid.identity;
error = accumulator(error);
}
that.promise.reject(error);
};
fluid.promise.resumeSequence = function (that) {
if (that.index === that.sources.length) {
that.promise.resolve(that.strategy.resolveResult(that));
} else {
var value = that.strategy.invokeNext(that);
that.resolvedSources[that.index] = value;
if (fluid.isPromise(value)) {
value.then(function (retValue) {
fluid.promise.progressSequence(that, retValue);
}, function (error) {
fluid.promise.processSequenceReject(that, error);
});
} else {
fluid.promise.progressSequence(that, value);
}
}
};
// SEQUENCE ALGORITHM APPLYING PROMISES
fluid.promise.makeSequenceStrategy = function () {
return {
invokeNext: function (that) {
var source = that.sources[that.index];
return typeof(source) === "function" ? source(that.options) : source;
},
resolveResult: function (that) {
return that.returns;
}
};
};
// accepts an array of values, promises or functions returning promises - in the case of functions returning promises,
// will assure that at most one of these is "in flight" at a time - that is, the succeeding function will not be invoked
// until the promise at the preceding position has resolved
fluid.promise.sequence = function (sources, options) {
var sequencer = fluid.promise.makeSequencer(sources, options, fluid.promise.makeSequenceStrategy());
fluid.promise.resumeSequence(sequencer);
return sequencer.promise;
};
// TRANSFORM ALGORITHM APPLYING PROMISES
fluid.promise.makeTransformerStrategy = function () {
return {
invokeNext: function (that) {
var lisrec = that.sources[that.index];
lisrec.listener = fluid.event.resolveListener(lisrec.listener);
var value = lisrec.listener(that.returns[that.index], that.options);
return value;
},
resolveResult: function (that) {
return that.returns[that.index];
}
};
};
// Construct a "mini-object" managing the process of a sequence of transforms,
// each of which may be synchronous or return a promise
fluid.promise.makeTransformer = function (listeners, payload, options) {
listeners.unshift({listener:
function () {
return payload;
}
});
var sequencer = fluid.promise.makeSequencer(listeners, options, fluid.promise.makeTransformerStrategy());
sequencer.returns.push(null); // first dummy return from initial entry
fluid.promise.resumeSequence(sequencer);
return sequencer;
};
fluid.promise.filterNamespaces = function (listeners, namespaces) {
if (!namespaces) {
return listeners;
}
return fluid.remove_if(fluid.makeArray(listeners), function (element) {
return element.namespace && !element.softNamespace && !fluid.contains(namespaces, element.namespace);
});
};
/** Top-level API to operate a Fluid event which manages a sequence of
* chained transforms. Rather than being a standard listener accepting the
* same payload, each listener to the event accepts the payload returned by the
* previous listener, and returns either a transformed payload or else a promise
* yielding such a payload.
* @param event {fluid.eventFirer} A Fluid event to which the listeners are to be interpreted as
* elements cooperating in a chained transform. Each listener will receive arguments <code>(payload, options)</code> where <code>payload</code>
* is the (successful, resolved) return value of the previous listener, and <code>options</code> is the final argument to this function
* @param payload {Object|Promise} The initial payload input to the transform chain
* @param options {Object} A free object containing options governing the transform. Fields interpreted at this top level are:
* reverse {Boolean}: <code>true</code> if the listeners are to be called in reverse order of priority (typically the case for an inverse transform)
* filterTransforms {Array}: An array of listener namespaces. If this field is set, only the transform elements whose listener namespaces listed in this array will be applied.
* @return {fluid.promise} A promise which will yield either the final transformed value, or the response of the first transform which fails.
*/
fluid.promise.fireTransformEvent = function (event, payload, options) {
options = options || {};
var listeners = options.reverse ? fluid.makeArray(event.sortedListeners).reverse() :
fluid.makeArray(event.sortedListeners);
listeners = fluid.promise.filterNamespaces(listeners, options.filterNamespaces);
var transformer = fluid.promise.makeTransformer(listeners, payload, options);
return transformer.promise;
};
})(jQuery, fluid_2_0_0);

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

Loading…
Cancel
Save