From 5cc1807471418a0dee843b12c3ab8d5060e317f0 Mon Sep 17 00:00:00 2001 From: Glenn Rice Date: Wed, 18 Jun 2025 07:21:08 -0700 Subject: [PATCH 1/2] Add a workflow to check file formatting. Perltidy is used for Perl files, and prettier for javascript, css, html, yml, and md files. The files are not formatted yet, this commit just adds the infrastructure. --- .editorconfig | 17 +++++ .github/workflows/check-formats.yml | 44 ++++++++++++ .gitignore | 8 +-- .perltidyrc | 22 ++++++ .prettierrc | 8 +++ bin/run-perltidy.pl | 108 ++++++++++++++++++++++++++++ public/package-lock.json | 17 +++++ public/package.json | 5 +- 8 files changed, 222 insertions(+), 7 deletions(-) create mode 100644 .editorconfig create mode 100644 .github/workflows/check-formats.yml create mode 100644 .perltidyrc create mode 100644 .prettierrc create mode 100755 bin/run-perltidy.pl diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..98066f22a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,17 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +max_line_length = 120 +trim_trailing_whitespace = true +indent_style = tab +indent_size = 4 + +[*.{yml,md}] +indent_style = space +indent_size = 2 + +[*.pg] +trim_trailing_whitespace = false diff --git a/.github/workflows/check-formats.yml b/.github/workflows/check-formats.yml new file mode 100644 index 000000000..bedc15a83 --- /dev/null +++ b/.github/workflows/check-formats.yml @@ -0,0 +1,44 @@ +--- +name: Check Formatting of Code Base + +defaults: + run: + shell: bash + +on: + push: + branches-ignore: [main, develop] + pull_request: + +jobs: + perltidy: + name: Check Perl file formatting with perltidy + runs-on: ubuntu-24.04 + container: + image: perl:5.38 + steps: + - name: Checkout code + uses: actions/checkout@v4 + - name: Install dependencies + run: cpanm -n Perl::Tidy@20240903 + - name: Run perltidy + shell: bash + run: | + git config --global --add safe.directory "$GITHUB_WORKSPACE" + shopt -s extglob globstar nullglob + perltidy --pro=./.perltidyrc -b -bext='/' ./**/*.p[lm] ./**/*.t && git diff --exit-code + + prettier: + name: Check JavaScript, style, and HTML file formatting with prettier + runs-on: ubuntu-24.04 + steps: + - name: Checkout code + uses: actions/checkout@v4 + - name: Install Node + uses: actions/setup-node@v4 + with: + node-version: '20' + - name: Install Dependencies + run: cd public && npm ci --ignore-scripts + - name: Check formatting with prettier + run: cd public && npm run prettier-check diff --git a/.gitignore b/.gitignore index 72884bf70..494d3451c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,8 @@ *.DS_Store render_app.conf lib/.pls-tmp-* -lib/WeBWorK/htdocs/tmp/renderer/gif/* -lib/WeBWorK/htdocs/tmp/renderer/images/* -lib/WeBWorK/htdocs/DATA/*.json -lib/WeBWorK/bin/* -webwork-open-problem-library/ -private/ +webwork-open-problem-library +private tmp/* !tmp/.gitkeep logs/* diff --git a/.perltidyrc b/.perltidyrc new file mode 100644 index 000000000..8314b7c17 --- /dev/null +++ b/.perltidyrc @@ -0,0 +1,22 @@ +# PBP .perltidyrc file +-l=120 # Max line width is 120 cols +-et=4 # Use tabs instead of spaces. +-i=4 # Indent level is 4 cols +-ci=4 # Continuation indent is 4 cols +-b # Write the file inline and create a .bak file +-vt=0 # Minimal vertical tightness +-cti=0 # No extra indentation for closing brackets +-pt=2 # Maximum parenthesis tightness +-bt=1 # Medium brace tightness +-sbt=1 # Medium square bracket tightness +-bbt=1 # Medium block brace tightness +-nsfs # No space before semicolons +-nolq # Don't outdent long quoted strings +-mbl=1 # Do not allow multiple empty lines +-ce # Cuddled else +-cb # Cuddled blocks +-nbbc # Do not add blank lines before full length comments +-nbot # No line break on ternary +-nlop # No logical padding (this causes mixed tabs and spaces) +-wn # Weld nested containers +-xci # Extended continuation indentation diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 000000000..b21dab065 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,8 @@ +{ + "arrowParens": "always", + "bracketSpacing": true, + "printWidth": 120, + "semi": true, + "singleQuote": true, + "trailingComma": "none" +} diff --git a/bin/run-perltidy.pl b/bin/run-perltidy.pl new file mode 100755 index 000000000..a4a8f03d6 --- /dev/null +++ b/bin/run-perltidy.pl @@ -0,0 +1,108 @@ +#!/usr/bin/env perl + +=head1 NAME + +run-perltidy.pl -- Run perltidy on the renderer source files. + +=head1 SYNOPSIS + + run-perltidy.pl [options] file1 file2 ... + +=head1 DESCRIPTION + +Run perltidy on the renderer source files. + +=head1 OPTIONS + +For this script to work the .perltidyrc file in the renderer root directory +must be readable. Note that the renderer root directory is automatically +detected. + +This script accepts all of the options that are accepted by perltidy. See the +perltidy documentation for details. + +However, the C<-pro> option is not allowed. This script will use the +.perltidyrc file in the renderer root directory for this option instead. + +In addition the default value of C<-bext> for this script is C<'/'>, which means +that backup files will be created with the C<.bak> extension, and will be +deleted if there are no errors. Note that this behavior may be changed by +passing a different value for the C<-bext> option. + +Note that the C<-v> flag makes this script verbose, and does not output the +perltidy version as it would usually do for perltidy. + +Finally, if no files are passed on the command line, then perltidy will be +executed on all files with the extensions C<.pl>, C<.pm>, or C<.t> in the +renderer directory. If files are passed on the command line, then perltidy +will only be executed on the listed files. + +=cut + +use strict; +use warnings; +use feature 'say'; + +use Perl::Tidy; +use File::Find qw(find); +use Mojo::File qw(curfile); + +my $renderer_root = curfile->dirname->dirname; + +die "Version 20240903 of perltidy is required for this script.\nThe installed version is $Perl::Tidy::VERSION.\n" + unless $Perl::Tidy::VERSION == 20240903; +die "The .perltidyrc file in the renderer root directory is not readable.\n" + unless -r "$renderer_root/.perltidyrc"; + +my $verbose = 0; +my (@args, @files); +for (@ARGV) { + if ($_ eq '-v') { $verbose = 1 } + elsif ($_ =~ /^-/) { push(@args, $_) } + else { push(@files, $_) } +} + +# Validate options that were passed. +my %options; +my $err = Perl::Tidy::perltidy(argv => \@args, dump_options => \%options); +exit $err if $err; +die "The -pro option is not suppored by this script.\n" if defined $options{profile}; + +unshift(@args, '-bext=/') unless defined $options{'backup-file-extension'}; + +if (@files) { + for (@files) { + push(@args, $_); + say "Tidying file: $_" if $verbose; + Perl::Tidy::perltidy(argv => \@args, perltidyrc => "$renderer_root/.perltidyrc"); + pop(@args); + } +} else { + find( + { + wanted => sub { + my $path = $File::Find::name; + my $dir = $File::Find::dir; + my ($name) = $path =~ m|^$dir(?:/(.*))?$|; + $name = '' unless defined $name; + + if (-d $path && $name =~ /^(\.git|\.github|htdocs|\.vscode|PG)$/) { + $File::Find::prune = 1; + return; + } + + return unless $path =~ /\.p[lm]$/ || $path =~ /\.t$/; + + say "Tidying file: $path" if $verbose; + + push(@args, $path); + Perl::Tidy::perltidy(argv => \@args, perltidyrc => "$renderer_root/.perltidyrc"); + pop(@args); + }, + no_chdir => 1 + }, + $renderer_root + ); +} + +1; diff --git a/public/package-lock.json b/public/package-lock.json index 051611c5b..108bb1946 100644 --- a/public/package-lock.json +++ b/public/package-lock.json @@ -20,6 +20,7 @@ "chokidar": "^3.5.3", "cssnano": "^6.0.0", "postcss": "^8.4.21", + "prettier": "^3.5.3", "rtlcss": "^4.0.0", "sass": "^1.57.1", "terser": "^5.16.1", @@ -1789,6 +1790,22 @@ "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", "dev": true }, + "node_modules/prettier": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.5.3.tgz", + "integrity": "sha512-QQtaxnoDJeAkDvDKWCLiwIXkTgRhwYDEQCghU9Z6q03iyek/rxRh/2lC3HB7P8sWT2xC/y5JDctPLBIGzHKbhw==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, "node_modules/readdirp": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", diff --git a/public/package.json b/public/package.json index f1a8c4d18..d97d26ea9 100644 --- a/public/package.json +++ b/public/package.json @@ -4,7 +4,9 @@ "license": "GPL-2.0+", "scripts": { "generate-assets": "node generate-assets", - "prepare": "npm run generate-assets" + "prepare": "npm run generate-assets", + "prettier-format": "prettier --ignore-path=../.gitignore --write \"**/*.{js,css,scss,html}\" \"../**/*.yml\"", + "prettier-check": "prettier --ignore-path=../.gitignore --check \"**/*.{js,css,scss,html}\" \"../**/*.yml\"" }, "repository": { "type": "git", @@ -24,6 +26,7 @@ "chokidar": "^3.5.3", "cssnano": "^6.0.0", "postcss": "^8.4.21", + "prettier": "^3.5.3", "rtlcss": "^4.0.0", "sass": "^1.57.1", "terser": "^5.16.1", From cdba4cfff91a34e2d2dd0da7482a53abc912e4f1 Mon Sep 17 00:00:00 2001 From: Glenn Rice Date: Wed, 18 Jun 2025 07:22:38 -0700 Subject: [PATCH 2/2] Run perltidy and prettier on all files in the renderer codebase. --- .github/workflows/createContainer.yml | 12 +- LICENSE.md | 328 ++++---- README.md | 172 ++-- docs/make_translation_files.md | 1 - k8/Ingress.yml | 32 +- k8/README.md | 1 + lib/RenderApp.pm | 50 +- lib/RenderApp/Controller/IO.pm | 6 +- lib/RenderApp/Controller/Pages.pm | 10 +- lib/RenderApp/Controller/Render.pm | 4 +- lib/RenderApp/Model/Problem.pm | 4 +- lib/WeBWorK/Localize.pm | 34 +- lib/WeBWorK/Utils/LanguageAndDirection.pm | 96 ++- lib/WeBWorK/Utils/Tags.pm | 796 +++++++++--------- public/css/bootstrap.scss | 76 +- public/css/crt-display.css | 367 ++++---- public/css/filebrowser.css | 16 +- public/css/navbar.css | 176 ++-- public/css/opl-flex.css | 62 +- public/css/rtl.css | 1 - public/css/tags.css | 66 +- public/css/twocolumn.css | 112 +-- public/css/typing-sim.css | 62 +- public/generate-assets.js | 83 +- public/index.html | 24 +- public/js/apps/CSSMessage/css-message.js | 34 +- .../js/apps/MathJaxConfig/mathjax-config.js | 37 +- public/js/apps/Problem/problem.js | 92 +- public/js/apps/Problem/submithelper.js | 12 +- public/js/filebrowser.js | 315 +++---- public/js/navbar.js | 204 ++--- public/js/tags.js | 119 +-- 32 files changed, 1754 insertions(+), 1650 deletions(-) diff --git a/.github/workflows/createContainer.yml b/.github/workflows/createContainer.yml index f237093f4..56c73af0f 100644 --- a/.github/workflows/createContainer.yml +++ b/.github/workflows/createContainer.yml @@ -3,26 +3,26 @@ name: Github Packages Release on: push: branches: - - main - - development + - main + - development tags: - - v* + - v* jobs: build: runs-on: ubuntu-latest steps: - # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it + # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - uses: actions/checkout@v2 with: submodules: recursive - + - name: Extract branch/tag name shell: bash run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF##*/})" id: extract_branch - + # make sure you have "Improved Container Support" enabled for both your personal and/or Organization accounts! - uses: pmorelli92/github-container-registry-build-push@2.0.0 name: Build and Publish latest service image diff --git a/LICENSE.md b/LICENSE.md index f288702d2..a5eae1527 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,190 +1,190 @@ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. +Copyright (C) 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. Preamble - The GNU General Public License is a free, copyleft license for +The GNU General Public License is a free, copyleft license for software and other kinds of works. - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the +software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to +any other work released this way by its authors. You can apply it to your programs, too. - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have +To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. - For example, if you distribute copies of such a program, whether +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they know their rights. - Developers that use the GNU GPL protect your rights with two steps: +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and +For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. - Some devices are designed to deny users access to install or run +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we +use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we +products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. - Finally, every program is threatened constantly by software patents. +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that +make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. - The precise terms and conditions for copying, distribution and +The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS - 0. Definitions. +0. Definitions. - "This License" refers to version 3 of the GNU General Public License. +"This License" refers to version 3 of the GNU General Public License. - "Copyright" also means copyright-like laws that apply to other kinds of +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. - To "modify" a work means to copy from or adapt all or part of the work +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the +exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. - A "covered work" means either the unmodified Program or a work based +A "covered work" means either the unmodified Program or a work based on the Program. - To "propagate" a work means to do anything with it that, without +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, +computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. - An interactive user interface displays "Appropriate Legal Notices" +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If +work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. - 1. Source Code. +1. Source Code. - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source +The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source form of a work. - A "Standard Interface" means an interface that either is an official +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. - The "System Libraries" of an executable work include anything, other +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A +implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. - The "Corresponding Source" for a work in object code form means all +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's +control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source +which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. - The Corresponding Source need not include anything that users +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. - The Corresponding Source for a work in source code form is that +The Corresponding Source for a work in source code form is that same work. - 2. Basic Permissions. +2. Basic Permissions. - All rights granted under this License are granted for the term of +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your +content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. - You may make, run and propagate covered works that you do not +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose +in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works +not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 +Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. +3. Protecting Users' Legal Rights From Anti-Circumvention Law. - No covered work shall be deemed part of an effective technological +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. - When you convey a covered work, you waive any legal power to forbid +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or @@ -192,9 +192,9 @@ modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. - 4. Conveying Verbatim Copies. +4. Conveying Verbatim Copies. - You may convey verbatim copies of the Program's source code as you +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any @@ -202,12 +202,12 @@ non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. - You may charge any price or no price for each copy that you convey, +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. - 5. Conveying Modified Source Versions. +5. Conveying Modified Source Versions. - You may convey a work based on the Program, or the modifications to +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: @@ -232,19 +232,19 @@ terms of section 4, provided that you also meet all of these conditions: interfaces that do not display Appropriate Legal Notices, your work need not make them do so. - A compilation of a covered work with other separate and independent +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work +beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. - 6. Conveying Non-Source Forms. +6. Conveying Non-Source Forms. - You may convey a covered work in object code form under the terms +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: @@ -290,75 +290,75 @@ in one of these ways: Source of the work are being offered to the general public at no charge under subsection 6d. - A separable portion of the object code, whose source code is excluded +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. - A "User Product" is either (1) a "consumer product", which means any +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product +actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. - "Installation Information" for a User Product means any methods, +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must +a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. - If you convey an object code work under this section in, or with, or +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply +by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). - The requirement to provide Installation Information does not include a +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a +the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. - Corresponding Source conveyed, and Installation Information provided, +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. - 7. Additional Terms. +7. Additional Terms. - "Additional permissions" are terms that supplement the terms of this +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions +that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. - When you convey a copy of a covered work, you may at your option +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. - Notwithstanding any other provision of this License, for material you +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: @@ -385,74 +385,74 @@ that material) supplement the terms of this License with terms: any liability that these contractual assumptions directly impose on those licensors and authors. - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains +restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. - If you add terms to a covered work in accord with this section, you +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. - Additional terms, permissive or non-permissive, may be stated in the +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. - 8. Termination. +8. Termination. - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). - However, if you cease all violation of this License, then your +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. - Moreover, your license from a particular copyright holder is +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. - Termination of your rights under this section does not terminate the +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently +this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. - 9. Acceptance Not Required for Having Copies. +9. Acceptance Not Required for Having Copies. - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work +You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, +to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. - 10. Automatic Licensing of Downstream Recipients. +10. Automatic Licensing of Downstream Recipients. - Each time you convey a covered work, the recipient automatically +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible +propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. - An "entity transaction" is a transaction transferring control of an +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered +organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could @@ -460,43 +460,43 @@ give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. - 11. Patents. +11. Patents. - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". - A contributor's "essential patent claims" are all patent claims +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For +consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. - Each contributor grants you a non-exclusive, worldwide, royalty-free +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. - In the following three paragraphs, a "patent license" is any express +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a +sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. - If you convey a covered work, knowingly relying on a patent license, +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, @@ -504,13 +504,13 @@ then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have +license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. - If, pursuant to or in connection with a single transaction or +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify @@ -518,10 +518,10 @@ or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. - A patent license is "discriminatory" if it does not include within +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered +specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying @@ -533,73 +533,73 @@ for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. - Nothing in this License shall be construed as excluding or limiting +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. - 12. No Surrender of Others' Freedom. +12. No Surrender of Others' Freedom. - If conditions are imposed on you (whether by court order, agreement or +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a +excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you +not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. - 13. Use with the GNU Affero General Public License. +13. Use with the GNU Affero General Public License. - Notwithstanding any other provision of this License, you have +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this +combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. - 14. Revised Versions of this License. +14. Revised Versions of this License. - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will +The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. - Each version is given a distinguishing version number. If the +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the +Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. - If the Program specifies that a proxy can decide which future +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. - 15. Disclaimer of Warranty. +15. Disclaimer of Warranty. - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +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 +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - 16. Limitation of Liability. +16. Limitation of Liability. - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE @@ -609,9 +609,9 @@ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - 17. Interpretation of Sections 15 and 16. +17. Interpretation of Sections 15 and 16. - If the disclaimer of warranty and limitation of liability provided +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the @@ -622,11 +622,11 @@ copy of the Program in return for a fee. How to Apply These Terms to Your New Programs - If you develop a new program, and you want it to be of the greatest +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 do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. @@ -649,7 +649,7 @@ the "copyright" line and a pointer to where the full notice is found. Also add information on how to contact you by electronic and paper mail. - If the program does terminal interaction, make it output a short +If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) @@ -658,17 +658,17 @@ notice like this when it starts in an interactive mode: under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands +parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". - You should also get your employer (if you work as a programmer) or school, +You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you +The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read . diff --git a/README.md b/README.md index b5b1cd17d..e8d1b65be 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ This is a PG Renderer derived from the WeBWorK2 codebase -* [https://github.com/openwebwork/webwork2](https://github.com/openwebwork/webwork2) +- [https://github.com/openwebwork/webwork2](https://github.com/openwebwork/webwork2) ## DOCKER CONTAINER INSTALL @@ -33,7 +33,7 @@ If you have non-OPL content, it can be mounted as a volume at `/usr/app/private` ``` A default configuration file is included in the container, but it can be overridden by mounting a replacement at the - application root. This is necessary if, for example, you want to run the container in `production` mode. +application root. This is necessary if, for example, you want to run the container in `production` mode. ```bash --mount type=bind,source=/pathToYour/render_app.conf,target=/usr/app/render_app.conf \ @@ -43,63 +43,69 @@ A default configuration file is included in the container, but it can be overrid If using a local install instead of docker: -* Clone the renderer and its submodules: `git clone --recursive https://github.com/openwebwork/renderer` -* Enter the project directory: `cd renderer` -* Install Perl dependencies listed in Dockerfile (CPANMinus recommended) -* clone webwork-open-problem-library into the provided stub ./webwork-open-problem-library - * `git clone https://github.com/openwebwork/webwork-open-problem-library ./webwork-open-problem-library` -* copy `render_app.conf.dist` to `render_app.conf` and make any desired modifications -* copy `conf/pg_config.yml` to `lib/PG/pg_config.yml` and make any desired modifications -* install third party JavaScript dependencies - * `cd public/` - * `npm ci` - * `cd ..` -* install PG JavaScript dependencies - * `cd lib/PG/htdocs` - * `npm ci` -* start the app with `morbo ./script/render_app` or `morbo -l http://localhost:3000 ./script/render_app` if changing +- Clone the renderer and its submodules: `git clone --recursive https://github.com/openwebwork/renderer` +- Enter the project directory: `cd renderer` +- Install Perl dependencies listed in Dockerfile (CPANMinus recommended) +- clone webwork-open-problem-library into the provided stub ./webwork-open-problem-library + - `git clone https://github.com/openwebwork/webwork-open-problem-library ./webwork-open-problem-library` +- copy `render_app.conf.dist` to `render_app.conf` and make any desired modifications +- copy `conf/pg_config.yml` to `lib/PG/pg_config.yml` and make any desired modifications +- install third party JavaScript dependencies + - `cd public/` + - `npm ci` + - `cd ..` +- install PG JavaScript dependencies + - `cd lib/PG/htdocs` + - `npm ci` +- start the app with `morbo ./script/render_app` or `morbo -l http://localhost:3000 ./script/render_app` if changing root url -* access on `localhost:3000` by default or otherwise specified root url +- access on `localhost:3000` by default or otherwise specified root url ## Editor Interface -* point your browser at [`localhost:3000`](http://localhost:3000/) -* select an output format (see below) -* specify a problem path (e.g. `Library/Rochester/setMAAtutorial/hello.pg`) and a problem seed (e.g. `1234`) -* click on "Load" to load the problem source into the editor -* render the contents of the editor (with or without edits) via "Render contents of editor" -* click on "Save" to save your edits to the specified file path +- point your browser at [`localhost:3000`](http://localhost:3000/) +- select an output format (see below) +- specify a problem path (e.g. `Library/Rochester/setMAAtutorial/hello.pg`) and a problem seed (e.g. `1234`) +- click on "Load" to load the problem source into the editor +- render the contents of the editor (with or without edits) via "Render contents of editor" +- click on "Save" to save your edits to the specified file path ![image](https://user-images.githubusercontent.com/3385756/129100124-72270558-376d-4265-afe2-73b5c9a829af.png) ## Server Configuration -Modification of `baseURL` may be necessary to separate multiple services running on `SITE_HOST`, and will be used to extend `SITE_HOST`. The result of this extension will serve as the root URL for accessing the renderer (and any supplementary assets it may need to provide in support of a rendered problem). If `baseURL` is an absolute URL, it will be used verbatim -- userful if the renderer is running behind a load balancer. +Modification of `baseURL` may be necessary to separate multiple services running on `SITE_HOST`, and will be used to +extend `SITE_HOST`. The result of this extension will serve as the root URL for accessing the renderer (and any +supplementary assets it may need to provide in support of a rendered problem). If `baseURL` is an absolute URL, it will +be used verbatim -- userful if the renderer is running behind a load balancer. -By default, `formURL` will further extend `baseURL`, and serve as the form-data target for user interactions with problems rendered by this service. If `formURL` is an absolute URL, it will be used verbatim -- useful if your implementation intends to sit in between the user and the renderer. +By default, `formURL` will further extend `baseURL`, and serve as the form-data target for user interactions with +problems rendered by this service. If `formURL` is an absolute URL, it will be used verbatim -- useful if your +implementation intends to sit in between the user and the renderer. ## Renderer API -Can be accessed by POST to `{SITE_HOST}{baseURL}{formURL}`. +Can be accessed by POST to `{SITE_HOST}{baseURL}{formURL}`. By default, `localhost:3000/render-api`. ### **REQUIRED PARAMETERS** The bare minimum of parameters that must be included are: -* the code for the problem, so, **ONE** of the following (in order of precedence): - * `problemSource` (raw pg source code, _can_ be base64 encoded) - * `sourceFilePath` (relative to OPL `Library/`, `Contrib/`; or in `private/`) - * `problemSourceURL` (fetch the pg source from remote server) -* a "seed" value for consistent randomization - * `problemSeed` (integer) - -| Key | Type | Description | Notes | -| --- | ---- | ----------- | ----- | -| problemSource | string (possibly base64 encoded) | The source code of a problem to be rendered | Takes precedence over `sourceFilePath`. | -| sourceFilePath | string | The path to the file that contains the problem source code | Renderer will automatically adjust `Library/` and `Contrib/` relative to the webwork-open-problem-library root. Path may also begin with `private/` for local, non-OPL content. | -| problemSourceURL | string | The URL from which to fetch the problem source code | Takes precedence over `problemSource` and `sourceFilePath`. A request to this URL is expected to return valid pg source code in base64 encoding. | -| problemSeed | number | The seed that determines the randomization of a problem | | + +- the code for the problem, so, **ONE** of the following (in order of precedence): + - `problemSource` (raw pg source code, _can_ be base64 encoded) + - `sourceFilePath` (relative to OPL `Library/`, `Contrib/`; or in `private/`) + - `problemSourceURL` (fetch the pg source from remote server) +- a "seed" value for consistent randomization + - `problemSeed` (integer) + +| Key | Type | Description | Notes | +| ---------------- | -------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| problemSource | string (possibly base64 encoded) | The source code of a problem to be rendered | Takes precedence over `sourceFilePath`. | +| sourceFilePath | string | The path to the file that contains the problem source code | Renderer will automatically adjust `Library/` and `Contrib/` relative to the webwork-open-problem-library root. Path may also begin with `private/` for local, non-OPL content. | +| problemSourceURL | string | The URL from which to fetch the problem source code | Takes precedence over `problemSource` and `sourceFilePath`. A request to this URL is expected to return valid pg source code in base64 encoding. | +| problemSeed | number | The seed that determines the randomization of a problem | | **ALL** other request parameters are optional. @@ -107,10 +113,10 @@ The bare minimum of parameters that must be included are: The defaults for these parameters are set in `render_app.conf`, but these can be overridden on a per-request basis. -| Key | Type | Default Value | Description | Notes | -| --- | ---- | ------------- | ----------- | ----- | -| baseURL | string | '/' (as set in `render_app.conf`) | the URL for relative paths | | -| formURL | string | '/render-api' (as set in `render_app.conf`) | the URL for form submission | | +| Key | Type | Default Value | Description | Notes | +| ------- | ------ | ------------------------------------------- | --------------------------- | ----- | +| baseURL | string | '/' (as set in `render_app.conf`) | the URL for relative paths | | +| formURL | string | '/render-api' (as set in `render_app.conf`) | the URL for form submission | | ### Display Parameters @@ -118,12 +124,12 @@ The defaults for these parameters are set in `render_app.conf`, but these can be Parameters that control the structure and templating of the response. -| Key | Type | Default Value | Description | Notes | -| --- | ---- | ------------- | ----------- | ----- | -| language | string | en | Language to render the problem in (if supported) | affects the translation of template strings, _not_ actual problem content | -| _format | string | 'html' | Determine how the response is _structured_ ('html' or 'json') | usually 'html' if the user is directly interacting with the renderer, 'json' if your CMS sits between user and renderer | -| outputFormat | string | 'default' | Determines how the problem should be formatted | 'default', 'static', 'PTX', 'raw', or | -| displayMode | string | 'MathJax' | How to prepare math content for display | 'MathJax' or 'ptx' | +| Key | Type | Default Value | Description | Notes | +| ------------ | ------ | ------------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | +| language | string | en | Language to render the problem in (if supported) | affects the translation of template strings, _not_ actual problem content | +| \_format | string | 'html' | Determine how the response is _structured_ ('html' or 'json') | usually 'html' if the user is directly interacting with the renderer, 'json' if your CMS sits between user and renderer | +| outputFormat | string | 'default' | Determines how the problem should be formatted | 'default', 'static', 'PTX', 'raw', or | +| displayMode | string | 'MathJax' | How to prepare math content for display | 'MathJax' or 'ptx' | #### User Interactions @@ -131,56 +137,66 @@ Control how the user is allowed to interact with the rendered problem. Requesting `outputFormat: 'static'` will prevent any buttons from being included in the rendered output, regardless of the following options. -| Key | Type | Default Value | Description | Notes | -| --- | ---- | ------------- | ----------- | ----- | -| hidePreviewButton | number (boolean) | false | "Preview My Answers" is enabled by default | | -| hideCheckAnswersButton | number (boolean) | false | "Submit Answers" is enabled by default | | -| showCorrectAnswersButton | number (boolean) | `isInstructor` | "Show Correct Answers" is disabled by default, enabled if `isInstructor` is true (see below) | | +| Key | Type | Default Value | Description | Notes | +| ------------------------ | ---------------- | -------------- | -------------------------------------------------------------------------------------------- | ----- | +| hidePreviewButton | number (boolean) | false | "Preview My Answers" is enabled by default | | +| hideCheckAnswersButton | number (boolean) | false | "Submit Answers" is enabled by default | | +| showCorrectAnswersButton | number (boolean) | `isInstructor` | "Show Correct Answers" is disabled by default, enabled if `isInstructor` is true (see below) | | #### Content Control what is shown to the user: hints, solutions, attempt results, scores, etc. -| Key | Type | Default Value | Description | Notes | -| --- | ---- | ------------- | ----------- | ----- | -| permissionLevel | number | 0 | **DEPRECATED.** Use `isInstructor` instead. | -| isInstructor | number (boolean) | 0 | Is the user viewing the problem an instructor or not. | Used by PG to determine if scaffolds can be allowed to be open among other things | -| showHints | number (boolean) | 1 | Whether or not to show hints | | -| showSolutions | number (boolean) | `isInstructor` | Whether or not to show the solutions | | -| hideAttemptsTable | number (boolean) | 0 | Hide the table of answer previews/results/messages | If you have a replacement for flagging the submitted entries as correct/incorrect | -| showSummary | number (boolean) | 1 | Determines whether or not to show a summary of the attempt underneath the table | Only relevant if the Attempts Table is shown `hideAttemptsTable: false` (default) | -| showComments | number (boolean) | 0 | Renders author comment field at the end of the problem | | -| showFooter | number (boolean) | 0 | Show version information and WeBWorK copyright footer | | -| includeTags | number (boolean) | 0 | Includes problem tags in the returned JSON | Only relevant when requesting `_format: 'json'` | +| Key | Type | Default Value | Description | Notes | +| ----------------- | ---------------- | -------------- | ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | +| permissionLevel | number | 0 | **DEPRECATED.** Use `isInstructor` instead. | | +| isInstructor | number (boolean) | 0 | Is the user viewing the problem an instructor or not. | Used by PG to determine if scaffolds can be allowed to be open among other things | +| showHints | number (boolean) | 1 | Whether or not to show hints | | +| showSolutions | number (boolean) | `isInstructor` | Whether or not to show the solutions | | +| hideAttemptsTable | number (boolean) | 0 | Hide the table of answer previews/results/messages | If you have a replacement for flagging the submitted entries as correct/incorrect | +| showSummary | number (boolean) | 1 | Determines whether or not to show a summary of the attempt underneath the table | Only relevant if the Attempts Table is shown `hideAttemptsTable: false` (default) | +| showComments | number (boolean) | 0 | Renders author comment field at the end of the problem | | +| showFooter | number (boolean) | 0 | Show version information and WeBWorK copyright footer | | +| includeTags | number (boolean) | 0 | Includes problem tags in the returned JSON | Only relevant when requesting `_format: 'json'` | ## Using JWTs There are three JWT structures that the Renderer uses, each containing its predecessor: -* problemJWT -* sessionJWT -* answerJWT + +- problemJWT +- sessionJWT +- answerJWT ### ProblemJWT -This JWT encapsulates the request parameters described above, under the API heading. Any value set in the JWT cannot be overridden by form-data. For example, if the problemJWT includes `isInstructor: 0`, then any subsequent interaction with the problem rendered by this JWT cannot override this setting by including `isInstructor: 1` in the form-data. +This JWT encapsulates the request parameters described above, under the API heading. Any value set in the JWT cannot be +overridden by form-data. For example, if the problemJWT includes `isInstructor: 0`, then any subsequent interaction with +the problem rendered by this JWT cannot override this setting by including `isInstructor: 1` in the form-data. ### SessionJWT This JWT encapsulates a user's attempt on a problem, including: -* the text and LaTeX versions of each answer entry -* count of incorrect attempts (stopping after a correct attempt, or after `showCorrectAnswers` is used) -* the problemJWT -If stored (see next), this JWT can be submitted as the sole request parameter, and the response will effectively restore the users current state of interaction with the problem (as of their last submission). +- the text and LaTeX versions of each answer entry +- count of incorrect attempts (stopping after a correct attempt, or after `showCorrectAnswers` is used) +- the problemJWT + +If stored (see next), this JWT can be submitted as the sole request parameter, and the response will effectively restore +the users current state of interaction with the problem (as of their last submission). ### AnswerJWT -If the initial problemJWT contains a value for `JWTanswerURL`, this JWT will be generated and sent to the specified URL. The answerJWT is the only content provided to the URL. The renderer is intended to to be user-agnostic. It is recommended that the JWTanswerURL specify the unique identifier for the user/problem combination. (e.g. `JWTanswerURL: 'https://db.yoursite.org/grades-api/:user_problem_id'`) +If the initial problemJWT contains a value for `JWTanswerURL`, this JWT will be generated and sent to the specified URL. +The answerJWT is the only content provided to the URL. The renderer is intended to to be user-agnostic. It is +recommended that the JWTanswerURL specify the unique identifier for the user/problem combination. (e.g. `JWTanswerURL: +'https://db.yoursite.org/grades-api/:user_problem_id'`) For security purposes, this parameter is only accepted when included as part of a JWT. This JWT encapsulates the status of the user's interaction with the problem. -* score -* sessionJWT -The goal here is to update the `JWTanswerURL` with the score and "state" for the user. If you have uses for additional information, please feel free to suggest as a GitHub Issue. +- score +- sessionJWT + +The goal here is to update the `JWTanswerURL` with the score and "state" for the user. If you have uses for additional +information, please feel free to suggest as a GitHub Issue. diff --git a/docs/make_translation_files.md b/docs/make_translation_files.md index a31d5ac9f..9a6dee21f 100644 --- a/docs/make_translation_files.md +++ b/docs/make_translation_files.md @@ -15,4 +15,3 @@ xgettext.pl -o WeBWorK/Localize/standalone.pot -D PG/lib -D PG/macros -D RenderA cd WeBWorK/Localize find . -name '*.po' -exec bash -c "echo \"Updating {}\"; msgmerge -qUN {} standalone.pot" \; ``` - diff --git a/k8/Ingress.yml b/k8/Ingress.yml index 91e4d64d4..ca6915fb1 100644 --- a/k8/Ingress.yml +++ b/k8/Ingress.yml @@ -12,9 +12,9 @@ spec: name: letsencrypt-prod-private-key # Add a single challenge solver, HTTP01 using nginx solvers: - - http01: - ingress: - class: nginx + - http01: + ingress: + class: nginx --- apiVersion: networking.k8s.io/v1 kind: Ingress @@ -25,17 +25,17 @@ metadata: cert-manager.io/cluster-issuer: letsencrypt-prod spec: tls: - - hosts: - - "example.org" - secretName: renderer-kubernetes-tls + - hosts: + - 'example.org' + secretName: renderer-kubernetes-tls rules: - - host: "example.org" - http: - paths: - - pathType: Prefix - path: "/" - backend: - service: - name: wwrenderer - port: - number: 80 + - host: 'example.org' + http: + paths: + - pathType: Prefix + path: '/' + backend: + service: + name: wwrenderer + port: + number: 80 diff --git a/k8/README.md b/k8/README.md index 4577a21a6..2d4da48d7 100644 --- a/k8/README.md +++ b/k8/README.md @@ -1,4 +1,5 @@ #Deploy Renderer to Kubernetes + 1. Install `kubectl`, the [official Kubernetes client](https://kubernetes.io/docs/tasks/tools/install-kubectl/). Use the most recent version of kubectl to ensure you are within one minor version of your cluster's Kubernetes version. 2. Install `doctl`, the official [DigitalOcean command-line tool](https://github.com/digitalocean/doctl), or other cloud platform-specific command-line tool. 3. Install [helm](https://helm.sh/docs/intro/install/), the kubernetes package manager. diff --git a/lib/RenderApp.pm b/lib/RenderApp.pm index 55e71db38..d3d11e3c1 100644 --- a/lib/RenderApp.pm +++ b/lib/RenderApp.pm @@ -87,31 +87,31 @@ sub startup { # Add Cache-Control and Expires headers to static content from webwork2_files if (my $STATIC_EXPIRES = $self->config('STATIC_EXPIRES')) { - $STATIC_EXPIRES = int( $STATIC_EXPIRES ); - my $cache_control_setting = "max-age=$STATIC_EXPIRES"; - my $no_cache_setting = 'max-age=1, no-cache'; - $self->hook(after_dispatch => sub { - my $c = shift; - - # Only process if file requested is under webwork2_files - return unless ($c->req->url->path =~ '^/webwork2_files/'); - - if ($c->req->url->path =~ '/tmp/renderer') { - # Treat problem generated files as already expired. - # They should not be cached. - $c->res->headers->cache_control( $no_cache_setting ); - $c->res->headers->header(Expires => - Mojo::Date->new(time - 86400) # expired 24 hours ago - ); - } else { - # Standard "static" files. - # They can be cached - $c->res->headers->cache_control( $cache_control_setting ); - $c->res->headers->header(Expires => - Mojo::Date->new(time + $STATIC_EXPIRES) - ); - } - }); + $STATIC_EXPIRES = int($STATIC_EXPIRES); + my $cache_control_setting = "max-age=$STATIC_EXPIRES"; + my $no_cache_setting = 'max-age=1, no-cache'; + $self->hook( + after_dispatch => sub { + my $c = shift; + + # Only process if file requested is under webwork2_files + return unless ($c->req->url->path =~ '^/webwork2_files/'); + + if ($c->req->url->path =~ '/tmp/renderer') { + # Treat problem generated files as already expired. + # They should not be cached. + $c->res->headers->cache_control($no_cache_setting); + $c->res->headers->header( + Expires => Mojo::Date->new(time - 86400) # expired 24 hours ago + ); + } else { + # Standard "static" files. + # They can be cached + $c->res->headers->cache_control($cache_control_setting); + $c->res->headers->header(Expires => Mojo::Date->new(time + $STATIC_EXPIRES)); + } + } + ); } # Models diff --git a/lib/RenderApp/Controller/IO.pm b/lib/RenderApp/Controller/IO.pm index 0cea97f5c..c2ec8b6b3 100644 --- a/lib/RenderApp/Controller/IO.pm +++ b/lib/RenderApp/Controller/IO.pm @@ -2,9 +2,9 @@ package RenderApp::Controller::IO; use Mojo::Base -async_await; use Mojo::Base 'Mojolicious::Controller'; use File::Spec::Functions qw(splitdir); -use File::Find qw(find); -use MIME::Base64 qw(decode_base64); -use Mojo::JSON qw(decode_json); +use File::Find qw(find); +use MIME::Base64 qw(decode_base64); +use Mojo::JSON qw(decode_json); use Mojolicious::Validator; use Math::Random::Secure qw( rand ); use Mojo::IOLoop; diff --git a/lib/RenderApp/Controller/Pages.pm b/lib/RenderApp/Controller/Pages.pm index aaad67522..1cfec20ba 100644 --- a/lib/RenderApp/Controller/Pages.pm +++ b/lib/RenderApp/Controller/Pages.pm @@ -2,13 +2,13 @@ package RenderApp::Controller::Pages; use Mojo::Base 'Mojolicious::Controller'; sub twocolumn { - my $c = shift; - $c->render(template=>'pages/twocolumn'); + my $c = shift; + $c->render(template => 'pages/twocolumn'); } sub oplUI { - my $c = shift; - $c->render(template=>'pages/oplUI'); + my $c = shift; + $c->render(template => 'pages/oplUI'); } -1; \ No newline at end of file +1; diff --git a/lib/RenderApp/Controller/Render.pm b/lib/RenderApp/Controller/Render.pm index 77a7da4de..bfae768f3 100644 --- a/lib/RenderApp/Controller/Render.pm +++ b/lib/RenderApp/Controller/Render.pm @@ -1,8 +1,8 @@ package RenderApp::Controller::Render; use Mojo::Base 'Mojolicious::Controller', -async_await; -use Mojo::JSON qw(encode_json decode_json); -use Crypt::JWT qw(encode_jwt decode_jwt); +use Mojo::JSON qw(encode_json decode_json); +use Crypt::JWT qw(encode_jwt decode_jwt); use Time::HiRes qw/time/; use WeBWorK::PreTeXt; diff --git a/lib/RenderApp/Model/Problem.pm b/lib/RenderApp/Model/Problem.pm index 155017871..58b294205 100644 --- a/lib/RenderApp/Model/Problem.pm +++ b/lib/RenderApp/Model/Problem.pm @@ -7,7 +7,7 @@ use Mojo::File; use Mojo::IOLoop; use Mojo::JSON qw( encode_json ); use Mojo::Base -async_await; -use Time::HiRes qw( time ); +use Time::HiRes qw( time ); use MIME::Base64 qw( decode_base64 ); use WeBWorK::RenderProblem; @@ -222,7 +222,7 @@ sub render { } sub success { - my $self = shift; + my $self = shift; $self->{log}->error($self->{exception}) if ($self->{log} && $self->{exception}); my $report = ($self->{_error} =~ /\S/) ? $self->{_error} : 'NO ERRORS'; return 1 unless $self->{_error} =~ /\S/; diff --git a/lib/WeBWorK/Localize.pm b/lib/WeBWorK/Localize.pm index 5805004f8..3bbdd9c19 100644 --- a/lib/WeBWorK/Localize.pm +++ b/lib/WeBWorK/Localize.pm @@ -22,7 +22,7 @@ eval " }); *tense = sub { \$_[1] . ((\$_[2] eq 'present') ? 'ing' : 'ed') }; -" or die "Can't process eval in WeBWorK/Localize.pm: line 35: ". $@; +" or die "Can't process eval in WeBWorK/Localize.pm: line 35: " . $@; package WeBWorK::Localize; @@ -32,13 +32,13 @@ package WeBWorK::Localize; # on perl 5.8.8 sub getLoc { my $lang = shift; - my $lh = WeBWorK::Localize::I18N->get_handle($lang); - return sub {$lh->maketext(@_)}; + my $lh = WeBWorK::Localize::I18N->get_handle($lang); + return sub { $lh->maketext(@_) }; } sub getLangHandle { my $lang = shift; - my $lh = WeBWorK::Localize::I18N->get_handle($lang); + my $lh = WeBWorK::Localize::I18N->get_handle($lang); return $lh; } @@ -46,33 +46,31 @@ sub getLangHandle { # usage: [quant,_1,,,] sub plural { - my($handle, $num, @forms) = @_; + my ($handle, $num, @forms) = @_; - return "" if @forms == 0; - return $forms[2] if @forms > 2 and $num == 0; + return "" if @forms == 0; + return $forms[2] if @forms > 2 and $num == 0; - # Normal case: - return( $handle->numerate($num, @forms) ); + # Normal case: + return ($handle->numerate($num, @forms)); } # this is like [quant] but it also has -1 case # usage: [negquant,_1,,,,] sub negquant { - my($handle, $num, @forms) = @_; + my ($handle, $num, @forms) = @_; - return $num if @forms == 0; + return $num if @forms == 0; - my $negcase = shift @forms; - return $negcase if $num < 0; + my $negcase = shift @forms; + return $negcase if $num < 0; - return $forms[2] if @forms > 2 and $num == 0; - return( $handle->numf($num) . ' ' . $handle->numerate($num, @forms) ); + return $forms[2] if @forms > 2 and $num == 0; + return ($handle->numf($num) . ' ' . $handle->numerate($num, @forms)); } -%Lexicon = ( - '_AUTO' => 1, - ); +%Lexicon = ('_AUTO' => 1,); package WeBWorK::Localize::I18N; use base(WeBWorK::Localize); diff --git a/lib/WeBWorK/Utils/LanguageAndDirection.pm b/lib/WeBWorK/Utils/LanguageAndDirection.pm index 9dcc94815..b56d408db 100644 --- a/lib/WeBWorK/Utils/LanguageAndDirection.pm +++ b/lib/WeBWorK/Utils/LanguageAndDirection.pm @@ -44,20 +44,20 @@ Arabic ("ar") trigger the RTL direction setting. =cut sub get_lang_and_dir { - my $lang = shift; - my $master_lang_setting = "lang=\"en-US\""; # default setting - my $master_dir_setting = ""; # default is NOT set + my $lang = shift; + my $master_lang_setting = "lang=\"en-US\""; # default setting + my $master_dir_setting = ""; # default is NOT set if ($lang eq "en") { - $master_lang_setting = "lang=\"en-US\""; # as in default - } elsif ($lang =~ /^he/i) { # supports also the current "heb" option - # Hebrew - requires RTL direction - $master_lang_setting = "lang=\"he\""; # Hebrew - $master_dir_setting = "dir=\"rtl\""; # RTL + $master_lang_setting = "lang=\"en-US\""; # as in default + } elsif ($lang =~ /^he/i) { # supports also the current "heb" option + # Hebrew - requires RTL direction + $master_lang_setting = "lang=\"he\""; # Hebrew + $master_dir_setting = "dir=\"rtl\""; # RTL } elsif ($lang =~ /^ar/i) { # Hebrew - requires RTL direction - $master_lang_setting = "lang=\"ar\""; # Arabic - $master_dir_setting = "dir=\"rtl\""; # RTL + $master_lang_setting = "lang=\"ar\""; # Arabic + $master_dir_setting = "dir=\"rtl\""; # RTL } else { # use the language setting of the course, with NO direction setting $master_lang_setting = "lang=\"${lang}\""; @@ -91,9 +91,9 @@ In some cases, the return result is empty. =cut sub get_problem_lang_and_dir { - my $pg_flags = shift; + my $pg_flags = shift; my $requested_mode = shift; - my $lang = shift; + my $lang = shift; my %result; @@ -102,19 +102,19 @@ sub get_problem_lang_and_dir { $lang = "en" unless defined($lang); - my $dir = "ltr"; # default + my $dir = "ltr"; # default - if ($lang =~ /^he/i) { # supports also the current "heb" option - # Hebrew - requires RTL direction - $lang = "he"; # Hebrew - standard form - $dir = "rtl"; # RTL + if ($lang =~ /^he/i) { # supports also the current "heb" option + # Hebrew - requires RTL direction + $lang = "he"; # Hebrew - standard form + $dir = "rtl"; # RTL } elsif ($lang =~ /^ar/i) { # Arabic - requires RTL direction - $lang = "ar"; # Arabic - $dir = "rtl"; # RTL + $lang = "ar"; # Arabic + $dir = "rtl"; # RTL } - my @tmp1 = split(':', $requested_mode); + my @tmp1 = split(':', $requested_mode); my $reqMode = $tmp1[0]; my $reqLang = $tmp1[1]; my $reqDir = $tmp1[2]; @@ -126,10 +126,10 @@ sub get_problem_lang_and_dir { if ($reqMode eq "force") { # Requested mode is to force the LANG and DIR attributes regardless of lang data from problem PG code. if ($reqLang ne "") { - $result{lang} = $reqLang; # forced setting + $result{lang} = $reqLang; # forced setting } - $result{dir} = $reqDir; # forced setting - return wantarray ? %result : join("", map { qq{ $_="$result{$_}"} } keys %result); + $result{dir} = $reqDir; # forced setting + return wantarray ? %result : join("", map {qq{ $_="$result{$_}"}} keys %result); } if ($reqMode ne "auto") { @@ -139,8 +139,8 @@ sub get_problem_lang_and_dir { # We are now handling an "auto" setting, so want to handle data from PG - my $pg_lang = "en-US"; # system default - my $pg_dir = "ltr"; # system default + my $pg_lang = "en-US"; # system default + my $pg_dir = "ltr"; # system default # Determine the language code to use if (defined($pg_flags->{language})) { @@ -157,15 +157,16 @@ sub get_problem_lang_and_dir { # we changed the order of precedence here. if (defined($pg_flags->{textdirection})) { # Direction set by PG - $pg_dir = $pg_flags->{textdirection}; + $pg_dir = $pg_flags->{textdirection}; } elsif (defined($pg_flags->{language})) { # Direction not set by PG, # but PG did set the language. # Fallback is to use LTR, except for Hebrew and Arabic. - $pg_dir = "ltr"; # correct for most languages - if (($pg_flags->{language} =~ /^he/i) || - ($pg_flags->{language} =~ /^ar/i)) { - $pg_dir = "rtl"; # should be correct for these languages + $pg_dir = "ltr"; # correct for most languages + if (($pg_flags->{language} =~ /^he/i) + || ($pg_flags->{language} =~ /^ar/i)) + { + $pg_dir = "rtl"; # should be correct for these languages } } elsif ($reqDir ne "") { # We have a request for a direction when PG did not set it @@ -175,7 +176,7 @@ sub get_problem_lang_and_dir { # and PG did NOT set the language. # For SetMaker, we are assuming that a problem without a PG direction # setting should be in LTR mode. - $pg_dir = "ltr"; # correct for most languages + $pg_dir = "ltr"; # correct for most languages # Even for Arabic and Hebrew do NOT change to RTL. # The teacher should add the language and direction setting to @@ -185,20 +186,24 @@ sub get_problem_lang_and_dir { # Make these string all lowercase (just in case) $pg_lang = lc($pg_lang); $pg_dir = lc($pg_dir); - $lang = lc($lang); - $dir = lc($dir); + $lang = lc($lang); + $dir = lc($dir); # We are ALWAYS setting this for this mode. - $result{lang} = $pg_lang; # send the problem language that was selected - - if (($dir eq "rtl") && # Possible hack for RTL direction courses and OPL problems - ($reqDir eq "rtl") && - ! defined($pg_flags->{textdirection}) && # problem does not set the language or - ! defined($pg_flags->{language})) { # the text direction - # In a RTL language course, we may really want to force LTR use for unknown problems. - # that would best be handled by always including the language setting in RTL language - # problems, and using a setting which falls back to LTR when there is no setting from - # the problem (expected on OPL problems). + $result{lang} = $pg_lang; # send the problem language that was selected + + if ( + ($dir eq "rtl") && # Possible hack for RTL direction courses and OPL problems + ($reqDir eq "rtl") + && !defined($pg_flags->{textdirection}) + && # problem does not set the language or + !defined($pg_flags->{language}) + ) + { # the text direction + # In a RTL language course, we may really want to force LTR use for unknown problems. + # that would best be handled by always including the language setting in RTL language + # problems, and using a setting which falls back to LTR when there is no setting from + # the problem (expected on OPL problems). # May want to issue a warning @@ -207,12 +212,11 @@ sub get_problem_lang_and_dir { } # We are ALWAYS setting this for this mode. - $result{dir} = $pg_dir; # override to $pg_dir + $result{dir} = $pg_dir; # override to $pg_dir - return wantarray ? %result : join("", map { qq{ $_="$result{$_}"} } keys %result); + return wantarray ? %result : join("", map {qq{ $_="$result{$_}"}} keys %result); } - =back =cut diff --git a/lib/WeBWorK/Utils/Tags.pm b/lib/WeBWorK/Utils/Tags.pm index 1e1a48d57..4ba0fac2d 100644 --- a/lib/WeBWorK/Utils/Tags.pm +++ b/lib/WeBWorK/Utils/Tags.pm @@ -15,32 +15,33 @@ use IO::File; our @EXPORT = (); our @EXPORT_OK = qw(); -use constant BASIC => qw( DBsubject DBchapter DBsection Date Institution Author MLT MLTleader Level Language Static MO Status ); +use constant BASIC => + qw( DBsubject DBchapter DBsection Date Institution Author MLT MLTleader Level Language Static MO Status ); use constant NUMBERED => qw( TitleText AuthorText EditionText Section Problem ); # KEYWORDS and RESOURCES are treated specially since each takes a list of values -my $basics = join('|', BASIC); +my $basics = join('|', BASIC); my $numbered = join('|', NUMBERED); -my $re = qr/#\s*\b($basics)\s*\(\s*['"]?(.*?)['"]?\s*\)\s*$/; +my $re = qr/#\s*\b($basics)\s*\(\s*['"]?(.*?)['"]?\s*\)\s*$/; sub istagline { - my $line = shift; - return 1 if($line =~ /$re/); - return 1 if($line =~ /#\s*\bKEYWORDS?\s*\(\s*'?(.*?)'?\s*\)/); - return 1 if($line =~ /#\s*\bRESOURCES?\s*\(\s*'?(.*?)'?\s*\)/); - return 1 if($line =~ /#\s*\b($numbered)\d+\s*\(\s*'?(.*?)'?\s*\)/); - return 0; + my $line = shift; + return 1 if ($line =~ /$re/); + return 1 if ($line =~ /#\s*\bKEYWORDS?\s*\(\s*'?(.*?)'?\s*\)/); + return 1 if ($line =~ /#\s*\bRESOURCES?\s*\(\s*'?(.*?)'?\s*\)/); + return 1 if ($line =~ /#\s*\b($numbered)\d+\s*\(\s*'?(.*?)'?\s*\)/); + return 0; } sub isStartDescription { - my $line = shift; - return ($line =~ /DESCRIPTION/) ? 1 : 0; + my $line = shift; + return ($line =~ /DESCRIPTION/) ? 1 : 0; } sub isEndDescription { - my $line = shift; - return ($line =~ /ENDDESCRIPTION/) ? 1 : 0; + my $line = shift; + return ($line =~ /ENDDESCRIPTION/) ? 1 : 0; } # sub kwtidy { @@ -63,456 +64,459 @@ sub isEndDescription { # # my @spl2 = map(kwtidy($_), @spl1); # return(@spl1); # } -my $quote = qr/['"\x{2018}\x{2019}\x{91}\x{92}]/; -my $space = qr/[\s\x{85}]/; -my $kwtidy_qr = qr/^$space*$quote*$space*(.*?)$space*$quote*$space*$/; +my $quote = qr/['"\x{2018}\x{2019}\x{91}\x{92}]/; +my $space = qr/[\s\x{85}]/; +my $kwtidy_qr = qr/^$space*$quote*$space*(.*?)$space*$quote*$space*$/; my $kwcleaner_qr = qr/$quote$space*$quote/; sub trim { - my $s = shift; - $s =~ s/^$space*$quote*$space*//; - $s =~ s/$space*$quote*$space*$//; - return $s; + my $s = shift; + $s =~ s/^$space*$quote*$space*//; + $s =~ s/$space*$quote*$space*$//; + return $s; } sub kwtidy { - my $s = shift; - $s =~ s/$kwtidy_qr/$1/; - $s =~ s/[_\s]/-/g; - $s = lc($s); - return ( $s =~ /\S/ ) ? $s : (); + my $s = shift; + $s =~ s/$kwtidy_qr/$1/; + $s =~ s/[_\s]/-/g; + $s = lc($s); + return ($s =~ /\S/) ? $s : (); } sub keywordcleaner { - my $string = shift; - my @spl1 = split /[;,.]/, $string; - @spl1 = map( { split( $kwcleaner_qr, $_ ) } @spl1 ); - return map( kwtidy($_), @spl1 ); + my $string = shift; + my @spl1 = split /[;,.]/, $string; + @spl1 = map({ split($kwcleaner_qr, $_) } @spl1); + return map(kwtidy($_), @spl1); } sub mergekeywords { - my $self=shift; - my $kws=shift; - if(not defined($self->{keywords})) { - $self->{keywords} = $kws; - return; - } - if(not defined($kws)) { - return; - } - my @kw = @{$self->{keywords}}; - for my $j (@{$kws}) { - my $old = 0; - for my $k (@kw) { - if(lc($k) eq lc($j)) { - $old = 1; - last; - } - } - push @kw, $j unless ($old); - } - $self->{keywords} = \@kw; + my $self = shift; + my $kws = shift; + if (not defined($self->{keywords})) { + $self->{keywords} = $kws; + return; + } + if (not defined($kws)) { + return; + } + my @kw = @{ $self->{keywords} }; + for my $j (@{$kws}) { + my $old = 0; + for my $k (@kw) { + if (lc($k) eq lc($j)) { + $old = 1; + last; + } + } + push @kw, $j unless ($old); + } + $self->{keywords} = \@kw; } # Note on texts, we store them in an array, but the index is one less than on # the corresponding tag. sub isnewtext { - my $self = shift; - my $ti = shift; - for my $j (@{$self->{textinfo}}) { - my $ok = 1; - for my $k ('TitleText', 'EditionText', 'AuthorText') { - if($ti->{$k} ne $j->{$k}) { - $ok = 0; - last; - } - } - return 0 if($ok); - } - return 1; + my $self = shift; + my $ti = shift; + for my $j (@{ $self->{textinfo} }) { + my $ok = 1; + for my $k ('TitleText', 'EditionText', 'AuthorText') { + if ($ti->{$k} ne $j->{$k}) { + $ok = 0; + last; + } + } + return 0 if ($ok); + } + return 1; } sub mergetexts { - my $self=shift; - my $newti=shift; - for my $ti (@$newti) { - if($self->isnewtext($ti)) { - my @tia = @{$self->{textinfo}}; - push @tia, $ti; - $self->{textinfo} = \@tia; - } - } + my $self = shift; + my $newti = shift; + for my $ti (@$newti) { + if ($self->isnewtext($ti)) { + my @tia = @{ $self->{textinfo} }; + push @tia, $ti; + $self->{textinfo} = \@tia; + } + } } # Set a tag with a value sub settag { - my $self = shift; - my $tagname = shift; - my $newval = shift; - my $force = shift; - - if(defined($newval) and ((defined($force) and $force) or $newval) and ((not defined($self->{$tagname})) or ($newval ne $self->{$tagname}))) { - $self->{modified}=1; - $self->{$tagname} = $newval; - } + my $self = shift; + my $tagname = shift; + my $newval = shift; + my $force = shift; + + if (defined($newval) + and ((defined($force) and $force) or $newval) + and ((not defined($self->{$tagname})) or ($newval ne $self->{$tagname}))) + { + $self->{modified} = 1; + $self->{$tagname} = $newval; + } } # Similar, but add a resource to the list sub addresource { - my $self = shift; - my $resc = shift; - - if(not defined($self->{resources})) { - $self->{resources} = [$resc]; - } else { - unless(grep(/^$resc$/, @{$self->{resources}} )) { - push @{$self->{resources}}, $resc; - } - } + my $self = shift; + my $resc = shift; + + if (not defined($self->{resources})) { + $self->{resources} = [$resc]; + } else { + unless (grep(/^$resc$/, @{ $self->{resources} })) { + push @{ $self->{resources} }, $resc; + } + } } sub printtextinfo { - my $textref = shift; - print "{"; - for my $k (keys %{$textref}){ - print "$k -> ".$textref->{$k}.", "; - } - print "}\n"; + my $textref = shift; + print "{"; + for my $k (keys %{$textref}) { + print "$k -> " . $textref->{$k} . ", "; + } + print "}\n"; } sub printalltextinfo { - my $self = shift; - for my $j (@{$self->{textinfo}}) { - printtextinfo $j; - } + my $self = shift; + for my $j (@{ $self->{textinfo} }) { + printtextinfo $j; + } } sub maybenewtext { - my $textno = shift; - my $textinfo = shift ; - return $textinfo if defined($textinfo->[$textno-1]); - # So, not defined yet - $textinfo->[$textno-1] = { TitleText => '', AuthorText =>'', EditionText =>'', - section => '', chapter =>'', problems => [] }; - return $textinfo; + my $textno = shift; + my $textinfo = shift; + return $textinfo if defined($textinfo->[ $textno - 1 ]); + # So, not defined yet + $textinfo->[ $textno - 1 ] = { + TitleText => '', + AuthorText => '', + EditionText => '', + section => '', + chapter => '', + problems => [] + }; + return $textinfo; } sub gettextnos { - my $textinfo = shift; - return grep { defined $textinfo->[$_] } (0..(scalar(@{$textinfo})-1)); + my $textinfo = shift; + return grep { defined $textinfo->[$_] } (0 .. (scalar(@{$textinfo}) - 1)); } sub tidytextinfo { - my $self = shift; - my @textnos = gettextnos($self->{textinfo}); - my $ntxts = scalar(@textnos); - if($ntxts and ($ntxts-1) != $textnos[-1]) { - $self->{modified} = 1; - my @tmptexts = grep{ defined $_ } @{$self->{textinfo}}; - $self->{textinfo} = \@tmptexts; - } + my $self = shift; + my @textnos = gettextnos($self->{textinfo}); + my $ntxts = scalar(@textnos); + if ($ntxts and ($ntxts - 1) != $textnos[-1]) { + $self->{modified} = 1; + my @tmptexts = grep { defined $_ } @{ $self->{textinfo} }; + $self->{textinfo} = \@tmptexts; + } } - # name is a path sub new { - my $class = shift; - my $name = shift; - my $source = shift; - my $self = {}; - - $self->{isplaceholder} = 0; - $self->{modified} = 0; - my $lasttag = 1; - - my ($text, $edition, $textauthor, $textsection, $textproblem); - my $textno; - my $textinfo=[]; - my @lines = (); - - if ($source) { - @lines = split "\n", $source; - } else { - if ( $name !~ /pg$/ && $name !~ /\.pg\.[-a-zA-Z0-9_.@]*\.tmp$/ ) { - warn "Not a pg file"; #print caused trouble with XMLRPC - $self->{file} = undef; - bless( $self, $class ); - return $self; - } - open( IN, '<:encoding(UTF-8)', "$name" ) or die "can not open $name: $!"; - @lines = ; - close IN; - } - - my $lineno = 0; - $self->{file} = $name; - - # Initialize some values - for my $tagname ( BASIC ) { - $self->{$tagname} = ''; - } - $self->{keywords} = []; - $self->{resources} = []; - $self->{description} = []; - my $inDescription = 0; - $self->{Language} = 'en'; # Default to English - - - foreach (@lines) { - $lineno++; - eval { - SWITCH: { - if (/^#+\s*\bDESCRIPTION/i) { - $inDescription = 1; - last SWITCH; - } - if ($inDescription) { - # we cannot assume that all problems have ENDDESCRIPTION - # check if we have a valid tag-line and continue processing if so - if (istagline($_)) { - $inDescription = 0; - } else { - if (/^#+\s*\bENDDESCRIPTION/i) { - $inDescription = 0; - } - elsif (/^#+\s*(.*)/) { - push @{ $self->{description} }, $1; - } - last SWITCH; - } - } - if (/#\s*\bKEYWORDS\((.*)\)/i) { - my @keyword = keywordcleaner($1); - @keyword = grep { not /^\s*'?\s*'?\s*$/ } @keyword; - $self->{keywords} = [@keyword]; - $lasttag = $lineno; - last SWITCH; - } - if (/#\s*\bRESOURCES\((.*)\)/i) { - my @resc = split ',', $1; - s/["'\s]*$//g for (@resc); - s/^["'\s]*//g for (@resc); - @resc = grep { not /^\s*'?\s*'?\s*$/ } @resc; - $self->{resources} = [@resc]; - $lasttag = $lineno; - last SWITCH; - } - if (/$re/) { # Checks all other un-numbered tags - my $tmp1 = $1; - my $tmp = trim($2); - - #$tmp =~ s/'/\'/g; - # $tmp =~ s/\s+$//; - # $tmp =~ s/^\s+//; - $self->{$tmp1} = $tmp; - $lasttag = $lineno; - last SWITCH; - } - - if (/#\s*\bTitleText(\d+)\(\s*'?(.*?)'?\s*\)/) { - $textno = $1; - $text = $2; - $text =~ s/'/\'/g; - if ( $text =~ /\S/ ) { - $textinfo = maybenewtext( $textno, $textinfo ); - $textinfo->[ $textno - 1 ]->{TitleText} = $text; - } - $lasttag = $lineno; - last SWITCH; - } - if (/#\s*\bEditionText(\d+)\(\s*'?(.*?)'?\s*\)/) { - $textno = $1; - $edition = $2; - $edition =~ s/'/\'/g; - if ( $edition =~ /\S/ ) { - $textinfo = maybenewtext( $textno, $textinfo ); - $textinfo->[ $textno - 1 ]->{EditionText} = $edition; - } - $lasttag = $lineno; - last SWITCH; - } - if (/#\s*\bAuthorText(\d+)\(\s*'?(.*?)'?\s*\)/) { - $textno = $1; - $textauthor = $2; - $textauthor =~ s/'/\'/g; - if ( $textauthor =~ /\S/ ) { - $textinfo = maybenewtext( $textno, $textinfo ); - $textinfo->[ $textno - 1 ]->{AuthorText} = $textauthor; - } - $lasttag = $lineno; - last SWITCH; - } - if (/#\s*\bSection(\d+)\(\s*'?(.*?)'?\s*\)/) { - $textno = $1; - $textsection = $2; - $textsection =~ s/'/\'/g; - $textsection =~ s/[^\d\.]//g; - - #print "|$textsection|\n"; - if ( $textsection =~ /\S/ ) { - $textinfo = maybenewtext( $textno, $textinfo ); - if ( $textsection =~ /(\d*?)\.(\d*)/ ) { - $textinfo->[ $textno - 1 ]->{chapter} = $1; - $textinfo->[ $textno - 1 ]->{section} = $2; - } - else { - $textinfo->[ $textno - 1 ]->{chapter} = $textsection; - $textinfo->[ $textno - 1 ]->{section} = -1; - } - } - $lasttag = $lineno; - last SWITCH; - } - if (/#\s*\bProblem(\d+)\(\s*(.*?)\s*\)/) { - $textno = $1; - $textproblem = $2; - $textproblem =~ s/\D/ /g; - my @textproblems = (-1); - @textproblems = split /\s+/, $textproblem; - @textproblems = grep { $_ =~ /\S/ } @textproblems; - if ( scalar(@textproblems) or defined( $textinfo->[$textno] ) ) - { - @textproblems = (-1) unless ( scalar(@textproblems) ); - $textinfo = maybenewtext( $textno, $textinfo ); - $textinfo->[ $textno - 1 ]->{problems} = \@textproblems; - } - $lasttag = $lineno; - last SWITCH; - } - } # end of SWITCH - }; # end of eval error trap - warn "error reading problem $name $!, $@ " if $@; - } #end of while - $self->{textinfo} = $textinfo; - - if (defined($self->{DBchapter}) and $self->{DBchapter} eq 'ZZZ-Inserted Text') { - $self->{isplaceholder} = 1; - } - - - $self->{lasttagline}=$lasttag; - bless($self, $class); - $self->tidytextinfo(); -# $self->printalltextinfo(); - return $self; + my $class = shift; + my $name = shift; + my $source = shift; + my $self = {}; + + $self->{isplaceholder} = 0; + $self->{modified} = 0; + my $lasttag = 1; + + my ($text, $edition, $textauthor, $textsection, $textproblem); + my $textno; + my $textinfo = []; + my @lines = (); + + if ($source) { + @lines = split "\n", $source; + } else { + if ($name !~ /pg$/ && $name !~ /\.pg\.[-a-zA-Z0-9_.@]*\.tmp$/) { + warn "Not a pg file"; #print caused trouble with XMLRPC + $self->{file} = undef; + bless($self, $class); + return $self; + } + open(IN, '<:encoding(UTF-8)', "$name") or die "can not open $name: $!"; + @lines = ; + close IN; + } + + my $lineno = 0; + $self->{file} = $name; + + # Initialize some values + for my $tagname (BASIC) { + $self->{$tagname} = ''; + } + $self->{keywords} = []; + $self->{resources} = []; + $self->{description} = []; + my $inDescription = 0; + $self->{Language} = 'en'; # Default to English + + foreach (@lines) { + $lineno++; + eval { + SWITCH: { + if (/^#+\s*\bDESCRIPTION/i) { + $inDescription = 1; + last SWITCH; + } + if ($inDescription) { + # we cannot assume that all problems have ENDDESCRIPTION + # check if we have a valid tag-line and continue processing if so + if (istagline($_)) { + $inDescription = 0; + } else { + if (/^#+\s*\bENDDESCRIPTION/i) { + $inDescription = 0; + } elsif (/^#+\s*(.*)/) { + push @{ $self->{description} }, $1; + } + last SWITCH; + } + } + if (/#\s*\bKEYWORDS\((.*)\)/i) { + my @keyword = keywordcleaner($1); + @keyword = grep { not /^\s*'?\s*'?\s*$/ } @keyword; + $self->{keywords} = [@keyword]; + $lasttag = $lineno; + last SWITCH; + } + if (/#\s*\bRESOURCES\((.*)\)/i) { + my @resc = split ',', $1; + s/["'\s]*$//g for (@resc); + s/^["'\s]*//g for (@resc); + @resc = grep { not /^\s*'?\s*'?\s*$/ } @resc; + $self->{resources} = [@resc]; + $lasttag = $lineno; + last SWITCH; + } + if (/$re/) { # Checks all other un-numbered tags + my $tmp1 = $1; + my $tmp = trim($2); + + #$tmp =~ s/'/\'/g; + # $tmp =~ s/\s+$//; + # $tmp =~ s/^\s+//; + $self->{$tmp1} = $tmp; + $lasttag = $lineno; + last SWITCH; + } + + if (/#\s*\bTitleText(\d+)\(\s*'?(.*?)'?\s*\)/) { + $textno = $1; + $text = $2; + $text =~ s/'/\'/g; + if ($text =~ /\S/) { + $textinfo = maybenewtext($textno, $textinfo); + $textinfo->[ $textno - 1 ]->{TitleText} = $text; + } + $lasttag = $lineno; + last SWITCH; + } + if (/#\s*\bEditionText(\d+)\(\s*'?(.*?)'?\s*\)/) { + $textno = $1; + $edition = $2; + $edition =~ s/'/\'/g; + if ($edition =~ /\S/) { + $textinfo = maybenewtext($textno, $textinfo); + $textinfo->[ $textno - 1 ]->{EditionText} = $edition; + } + $lasttag = $lineno; + last SWITCH; + } + if (/#\s*\bAuthorText(\d+)\(\s*'?(.*?)'?\s*\)/) { + $textno = $1; + $textauthor = $2; + $textauthor =~ s/'/\'/g; + if ($textauthor =~ /\S/) { + $textinfo = maybenewtext($textno, $textinfo); + $textinfo->[ $textno - 1 ]->{AuthorText} = $textauthor; + } + $lasttag = $lineno; + last SWITCH; + } + if (/#\s*\bSection(\d+)\(\s*'?(.*?)'?\s*\)/) { + $textno = $1; + $textsection = $2; + $textsection =~ s/'/\'/g; + $textsection =~ s/[^\d\.]//g; + + #print "|$textsection|\n"; + if ($textsection =~ /\S/) { + $textinfo = maybenewtext($textno, $textinfo); + if ($textsection =~ /(\d*?)\.(\d*)/) { + $textinfo->[ $textno - 1 ]->{chapter} = $1; + $textinfo->[ $textno - 1 ]->{section} = $2; + } else { + $textinfo->[ $textno - 1 ]->{chapter} = $textsection; + $textinfo->[ $textno - 1 ]->{section} = -1; + } + } + $lasttag = $lineno; + last SWITCH; + } + if (/#\s*\bProblem(\d+)\(\s*(.*?)\s*\)/) { + $textno = $1; + $textproblem = $2; + $textproblem =~ s/\D/ /g; + my @textproblems = (-1); + @textproblems = split /\s+/, $textproblem; + @textproblems = grep { $_ =~ /\S/ } @textproblems; + if (scalar(@textproblems) or defined($textinfo->[$textno])) { + @textproblems = (-1) unless (scalar(@textproblems)); + $textinfo = maybenewtext($textno, $textinfo); + $textinfo->[ $textno - 1 ]->{problems} = \@textproblems; + } + $lasttag = $lineno; + last SWITCH; + } + } # end of SWITCH + }; # end of eval error trap + warn "error reading problem $name $!, $@ " if $@; + } #end of while + $self->{textinfo} = $textinfo; + + if (defined($self->{DBchapter}) and $self->{DBchapter} eq 'ZZZ-Inserted Text') { + $self->{isplaceholder} = 1; + } + + $self->{lasttagline} = $lasttag; + bless($self, $class); + $self->tidytextinfo(); + # $self->printalltextinfo(); + return $self; } sub isplaceholder { - my $self = shift; - return $self->{isplaceholder}; + my $self = shift; + return $self->{isplaceholder}; } sub istagged { - my $self = shift; - #return 1 if (defined($self->{DBchapter}) and $self->{DBchapter} and (not $self->{isplaceholder})); - return 1 if (defined($self->{DBsubject}) and $self->{DBsubject} and (not $self->{isplaceholder})); + my $self = shift; + #return 1 if (defined($self->{DBchapter}) and $self->{DBchapter} and (not $self->{isplaceholder})); + return 1 if (defined($self->{DBsubject}) and $self->{DBsubject} and (not $self->{isplaceholder})); return 0; } # Try to copy in the contents of another Tag object. # Return 1 if ok, 0 if not compatible sub copyin { - my $self = shift; - my $ob = shift; -# for my $j (qw( DBsubject DBchapter DBsection )) { -# if($self->{$j} =~ /\S/ and $ob->{$j} =~ /\S/ and $self->{$j} ne $ob->{$j}) { -# # print "Incompatible $j: ".$self->{$j}." vs ".$ob->{$j} ."\n"; -# return 0; -# } -# } - # Just copy in all basic tags - for my $j (qw( DBsubject DBchapter DBsection MLT MLTleader Level )) { - $self->settag($j, $ob->{$j}) if(defined($ob->{$j})); - } - # Now copy in keywords - $self->mergekeywords($ob->{keywords}); - # Finally, textbooks - $self->mergetexts($ob->{textinfo}); - return 1; + my $self = shift; + my $ob = shift; + # for my $j (qw( DBsubject DBchapter DBsection )) { + # if($self->{$j} =~ /\S/ and $ob->{$j} =~ /\S/ and $self->{$j} ne $ob->{$j}) { + # # print "Incompatible $j: ".$self->{$j}." vs ".$ob->{$j} ."\n"; + # return 0; + # } + # } + # Just copy in all basic tags + for my $j (qw( DBsubject DBchapter DBsection MLT MLTleader Level )) { + $self->settag($j, $ob->{$j}) if (defined($ob->{$j})); + } + # Now copy in keywords + $self->mergekeywords($ob->{keywords}); + # Finally, textbooks + $self->mergetexts($ob->{textinfo}); + return 1; } sub dumptags { - my $self = shift; - my $fh = shift; - if ( $self->{description} ) { - if (ref( $self->{description} ) !~ /ARRAY/) { - warn "TAGS.PM: dumping description, but it wasn't an array..."; - $self->{description} = [$self->{description}]; - } - my @descriptionArray = @{$self->{description}}; - unshift @descriptionArray, "## DESCRIPTION"; - push @descriptionArray, "ENDDESCRIPTION"; - print $fh join("\n## ", @descriptionArray)."\n"; - } - - if ( $self->{keywords} ) { - if (ref( $self->{keywords} ) !~ /ARRAY/) { - warn "TAGS.PM: dumping keywords, but it wasn't an array...\n"; - $self->{keywords} = [ keywordcleaner( $self->{keywords} ) ]; - } else { - @{ $self->{keywords} } = map { kwtidy($_) } @{ $self->{keywords} }; - } - } - - for my $tagname ( BASIC ) { - print $fh "## $tagname(".$self->{$tagname}.")\n" if($self->{$tagname}); - } - my @textinfo = @{$self->{textinfo}}; - my $textno = 0; - for my $ti (@textinfo) { - $textno++; - for my $nw ( NUMBERED ) { - if($nw eq 'Problem') { - print $fh "## $nw$textno('".join(' ', @{$ti->{problems}})."')\n"; - next; - } - if($nw eq 'Section') { - if($ti->{section} eq '-1') { - print $fh "## Section$textno('".$ti->{chapter}."')\n"; - } else { - print $fh "## Section$textno('".$ti->{chapter}.".".$ti->{section}."')\n"; - } - next; - } - print $fh "## $nw$textno('".$ti->{$nw}."')\n"; - } - } - print $fh "## KEYWORDS(".join(',', @{$self->{keywords}}).")\n" if(scalar(@{$self->{keywords}})); - my @resc; - if(scalar(@{$self->{resources}})) { - @resc = @{$self->{resources}}; - s/^/'/g for (@resc); - s/$/'/g for (@resc); - print $fh "## RESOURCES(".join(',', @resc).")\n"; - } + my $self = shift; + my $fh = shift; + if ($self->{description}) { + if (ref($self->{description}) !~ /ARRAY/) { + warn "TAGS.PM: dumping description, but it wasn't an array..."; + $self->{description} = [ $self->{description} ]; + } + my @descriptionArray = @{ $self->{description} }; + unshift @descriptionArray, "## DESCRIPTION"; + push @descriptionArray, "ENDDESCRIPTION"; + print $fh join("\n## ", @descriptionArray) . "\n"; + } + + if ($self->{keywords}) { + if (ref($self->{keywords}) !~ /ARRAY/) { + warn "TAGS.PM: dumping keywords, but it wasn't an array...\n"; + $self->{keywords} = [ keywordcleaner($self->{keywords}) ]; + } else { + @{ $self->{keywords} } = map { kwtidy($_) } @{ $self->{keywords} }; + } + } + + for my $tagname (BASIC) { + print $fh "## $tagname(" . $self->{$tagname} . ")\n" if ($self->{$tagname}); + } + my @textinfo = @{ $self->{textinfo} }; + my $textno = 0; + for my $ti (@textinfo) { + $textno++; + for my $nw (NUMBERED) { + if ($nw eq 'Problem') { + print $fh "## $nw$textno('" . join(' ', @{ $ti->{problems} }) . "')\n"; + next; + } + if ($nw eq 'Section') { + if ($ti->{section} eq '-1') { + print $fh "## Section$textno('" . $ti->{chapter} . "')\n"; + } else { + print $fh "## Section$textno('" . $ti->{chapter} . "." . $ti->{section} . "')\n"; + } + next; + } + print $fh "## $nw$textno('" . $ti->{$nw} . "')\n"; + } + } + print $fh "## KEYWORDS(" . join(',', @{ $self->{keywords} }) . ")\n" if (scalar(@{ $self->{keywords} })); + my @resc; + if (scalar(@{ $self->{resources} })) { + @resc = @{ $self->{resources} }; + s/^/'/g for (@resc); + s/$/'/g for (@resc); + print $fh "## RESOURCES(" . join(',', @resc) . ")\n"; + } } # Write the file sub write { - my $self=shift; - # First read it into an array - open(IN,$self->{file}) or die "can not open $self->{file}: $!"; - my @lines = ; - close(IN); - my $fh = IO::File->new(">".$self->{file}) or die "can not open $self->{file}: $!"; - my ($line, $lineno, $inDescription)=('', 0, 0); - while($line = shift @lines) { - $lineno++; - $self->dumptags($fh) if($lineno == $self->{lasttagline}); - $inDescription = isStartDescription($line) unless $inDescription; - if ($inDescription) { - # do not assume every DESCRIPTION has an ENDDESCRIPTION - if (isEndDescription($line) || istagline($line)) { - $inDescription = 0; - } - next; - } - next if istagline($line); - print $fh $line unless $lineno < $self->{lasttagline}; - } - - $fh->close(); + my $self = shift; + # First read it into an array + open(IN, $self->{file}) or die "can not open $self->{file}: $!"; + my @lines = ; + close(IN); + my $fh = IO::File->new(">" . $self->{file}) or die "can not open $self->{file}: $!"; + my ($line, $lineno, $inDescription) = ('', 0, 0); + while ($line = shift @lines) { + $lineno++; + $self->dumptags($fh) if ($lineno == $self->{lasttagline}); + $inDescription = isStartDescription($line) unless $inDescription; + if ($inDescription) { + # do not assume every DESCRIPTION has an ENDDESCRIPTION + if (isEndDescription($line) || istagline($line)) { + $inDescription = 0; + } + next; + } + next if istagline($line); + print $fh $line unless $lineno < $self->{lasttagline}; + } + + $fh->close(); } 1; diff --git a/public/css/bootstrap.scss b/public/css/bootstrap.scss index 7a5606489..b82db428f 100644 --- a/public/css/bootstrap.scss +++ b/public/css/bootstrap.scss @@ -1,5 +1,5 @@ // Include functions first (so you can manipulate colors, SVGs, calc, etc) -@import "../node_modules/bootstrap/scss/functions"; +@import '../node_modules/bootstrap/scss/functions'; // Variable overrides @@ -22,49 +22,49 @@ $breadcrumb-divider-color: #495057; $breadcrumb-active-color: #495057; // Include the remainder of bootstrap's scss configuration -@import "../node_modules/bootstrap/scss/variables"; -@import "../node_modules/bootstrap/scss/maps"; -@import "../node_modules/bootstrap/scss/mixins"; -@import "../node_modules/bootstrap/scss/utilities"; +@import '../node_modules/bootstrap/scss/variables'; +@import '../node_modules/bootstrap/scss/maps'; +@import '../node_modules/bootstrap/scss/mixins'; +@import '../node_modules/bootstrap/scss/utilities'; // Layout & components -@import "../node_modules/bootstrap/scss/root"; -@import "../node_modules/bootstrap/scss/reboot"; -@import "../node_modules/bootstrap/scss/type"; -@import "../node_modules/bootstrap/scss/images"; -@import "../node_modules/bootstrap/scss/containers"; -@import "../node_modules/bootstrap/scss/grid"; -@import "../node_modules/bootstrap/scss/tables"; -@import "../node_modules/bootstrap/scss/forms"; -@import "../node_modules/bootstrap/scss/buttons"; -@import "../node_modules/bootstrap/scss/transitions"; -@import "../node_modules/bootstrap/scss/dropdown"; -@import "../node_modules/bootstrap/scss/button-group"; -@import "../node_modules/bootstrap/scss/nav"; -@import "../node_modules/bootstrap/scss/navbar"; -@import "../node_modules/bootstrap/scss/card"; -@import "../node_modules/bootstrap/scss/accordion"; -@import "../node_modules/bootstrap/scss/breadcrumb"; -@import "../node_modules/bootstrap/scss/pagination"; -@import "../node_modules/bootstrap/scss/badge"; -@import "../node_modules/bootstrap/scss/alert"; -@import "../node_modules/bootstrap/scss/placeholders"; -@import "../node_modules/bootstrap/scss/progress"; -@import "../node_modules/bootstrap/scss/list-group"; -@import "../node_modules/bootstrap/scss/close"; -@import "../node_modules/bootstrap/scss/toasts"; -@import "../node_modules/bootstrap/scss/modal"; -@import "../node_modules/bootstrap/scss/tooltip"; -@import "../node_modules/bootstrap/scss/popover"; -@import "../node_modules/bootstrap/scss/carousel"; -@import "../node_modules/bootstrap/scss/spinners"; -@import "../node_modules/bootstrap/scss/offcanvas"; +@import '../node_modules/bootstrap/scss/root'; +@import '../node_modules/bootstrap/scss/reboot'; +@import '../node_modules/bootstrap/scss/type'; +@import '../node_modules/bootstrap/scss/images'; +@import '../node_modules/bootstrap/scss/containers'; +@import '../node_modules/bootstrap/scss/grid'; +@import '../node_modules/bootstrap/scss/tables'; +@import '../node_modules/bootstrap/scss/forms'; +@import '../node_modules/bootstrap/scss/buttons'; +@import '../node_modules/bootstrap/scss/transitions'; +@import '../node_modules/bootstrap/scss/dropdown'; +@import '../node_modules/bootstrap/scss/button-group'; +@import '../node_modules/bootstrap/scss/nav'; +@import '../node_modules/bootstrap/scss/navbar'; +@import '../node_modules/bootstrap/scss/card'; +@import '../node_modules/bootstrap/scss/accordion'; +@import '../node_modules/bootstrap/scss/breadcrumb'; +@import '../node_modules/bootstrap/scss/pagination'; +@import '../node_modules/bootstrap/scss/badge'; +@import '../node_modules/bootstrap/scss/alert'; +@import '../node_modules/bootstrap/scss/placeholders'; +@import '../node_modules/bootstrap/scss/progress'; +@import '../node_modules/bootstrap/scss/list-group'; +@import '../node_modules/bootstrap/scss/close'; +@import '../node_modules/bootstrap/scss/toasts'; +@import '../node_modules/bootstrap/scss/modal'; +@import '../node_modules/bootstrap/scss/tooltip'; +@import '../node_modules/bootstrap/scss/popover'; +@import '../node_modules/bootstrap/scss/carousel'; +@import '../node_modules/bootstrap/scss/spinners'; +@import '../node_modules/bootstrap/scss/offcanvas'; // Helpers -@import "../node_modules/bootstrap/scss/helpers"; +@import '../node_modules/bootstrap/scss/helpers'; // Utilities -@import "../node_modules/bootstrap/scss/utilities/api"; +@import '../node_modules/bootstrap/scss/utilities/api'; // Overrides a:not(.btn):focus { diff --git a/public/css/crt-display.css b/public/css/crt-display.css index b65368973..945f0388c 100644 --- a/public/css/crt-display.css +++ b/public/css/crt-display.css @@ -1,161 +1,228 @@ /* http://aleclownes.com/2017/02/01/crt-display.html */ @keyframes flicker { - 0% { - opacity: 0.27861; - } - 5% { - opacity: 0.34769; - } - 10% { - opacity: 0.23604; - } - 15% { - opacity: 0.90626; - } - 20% { - opacity: 0.18128; - } - 25% { - opacity: 0.83891; - } - 30% { - opacity: 0.65583; - } - 35% { - opacity: 0.67807; - } - 40% { - opacity: 0.26559; - } - 45% { - opacity: 0.84693; - } - 50% { - opacity: 0.96019; - } - 55% { - opacity: 0.08594; - } - 60% { - opacity: 0.20313; - } - 65% { - opacity: 0.71988; - } - 70% { - opacity: 0.53455; - } - 75% { - opacity: 0.37288; - } - 80% { - opacity: 0.71428; - } - 85% { - opacity: 0.70419; - } - 90% { - opacity: 0.7003; - } - 95% { - opacity: 0.36108; - } - 100% { - opacity: 0.24387; - } + 0% { + opacity: 0.27861; + } + 5% { + opacity: 0.34769; + } + 10% { + opacity: 0.23604; + } + 15% { + opacity: 0.90626; + } + 20% { + opacity: 0.18128; + } + 25% { + opacity: 0.83891; + } + 30% { + opacity: 0.65583; + } + 35% { + opacity: 0.67807; + } + 40% { + opacity: 0.26559; + } + 45% { + opacity: 0.84693; + } + 50% { + opacity: 0.96019; + } + 55% { + opacity: 0.08594; + } + 60% { + opacity: 0.20313; + } + 65% { + opacity: 0.71988; + } + 70% { + opacity: 0.53455; + } + 75% { + opacity: 0.37288; + } + 80% { + opacity: 0.71428; + } + 85% { + opacity: 0.70419; + } + 90% { + opacity: 0.7003; + } + 95% { + opacity: 0.36108; + } + 100% { + opacity: 0.24387; + } } @keyframes textShadow { - 0% { - text-shadow: 0.4389924193300864px 0 1px rgba(0,30,255,0.5), -0.4389924193300864px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 5% { - text-shadow: 2.7928974010788217px 0 1px rgba(0,30,255,0.5), -2.7928974010788217px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 10% { - text-shadow: 0.02956275843481219px 0 1px rgba(0,30,255,0.5), -0.02956275843481219px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 15% { - text-shadow: 0.40218538552878136px 0 1px rgba(0,30,255,0.5), -0.40218538552878136px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 20% { - text-shadow: 3.4794037899852017px 0 1px rgba(0,30,255,0.5), -3.4794037899852017px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 25% { - text-shadow: 1.6125630401149584px 0 1px rgba(0,30,255,0.5), -1.6125630401149584px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 30% { - text-shadow: 0.7015590085143956px 0 1px rgba(0,30,255,0.5), -0.7015590085143956px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 35% { - text-shadow: 3.896914047650351px 0 1px rgba(0,30,255,0.5), -3.896914047650351px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 40% { - text-shadow: 3.870905614848819px 0 1px rgba(0,30,255,0.5), -3.870905614848819px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 45% { - text-shadow: 2.231056963361899px 0 1px rgba(0,30,255,0.5), -2.231056963361899px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 50% { - text-shadow: 0.08084290417898504px 0 1px rgba(0,30,255,0.5), -0.08084290417898504px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 55% { - text-shadow: 2.3758461067427543px 0 1px rgba(0,30,255,0.5), -2.3758461067427543px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 60% { - text-shadow: 2.202193051050636px 0 1px rgba(0,30,255,0.5), -2.202193051050636px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 65% { - text-shadow: 2.8638780614874975px 0 1px rgba(0,30,255,0.5), -2.8638780614874975px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 70% { - text-shadow: 0.48874025155497314px 0 1px rgba(0,30,255,0.5), -0.48874025155497314px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 75% { - text-shadow: 1.8948491305757957px 0 1px rgba(0,30,255,0.5), -1.8948491305757957px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 80% { - text-shadow: 0.0833037308038857px 0 1px rgba(0,30,255,0.5), -0.0833037308038857px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 85% { - text-shadow: 0.09769827255241735px 0 1px rgba(0,30,255,0.5), -0.09769827255241735px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 90% { - text-shadow: 3.443339761481782px 0 1px rgba(0,30,255,0.5), -3.443339761481782px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 95% { - text-shadow: 2.1841838852799786px 0 1px rgba(0,30,255,0.5), -2.1841838852799786px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } - 100% { - text-shadow: 2.6208764473832513px 0 1px rgba(0,30,255,0.5), -2.6208764473832513px 0 1px rgba(255,0,80,0.3), 0 0 3px; - } + 0% { + text-shadow: + 0.4389924193300864px 0 1px rgba(0, 30, 255, 0.5), + -0.4389924193300864px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 5% { + text-shadow: + 2.7928974010788217px 0 1px rgba(0, 30, 255, 0.5), + -2.7928974010788217px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 10% { + text-shadow: + 0.02956275843481219px 0 1px rgba(0, 30, 255, 0.5), + -0.02956275843481219px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 15% { + text-shadow: + 0.40218538552878136px 0 1px rgba(0, 30, 255, 0.5), + -0.40218538552878136px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 20% { + text-shadow: + 3.4794037899852017px 0 1px rgba(0, 30, 255, 0.5), + -3.4794037899852017px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 25% { + text-shadow: + 1.6125630401149584px 0 1px rgba(0, 30, 255, 0.5), + -1.6125630401149584px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 30% { + text-shadow: + 0.7015590085143956px 0 1px rgba(0, 30, 255, 0.5), + -0.7015590085143956px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 35% { + text-shadow: + 3.896914047650351px 0 1px rgba(0, 30, 255, 0.5), + -3.896914047650351px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 40% { + text-shadow: + 3.870905614848819px 0 1px rgba(0, 30, 255, 0.5), + -3.870905614848819px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 45% { + text-shadow: + 2.231056963361899px 0 1px rgba(0, 30, 255, 0.5), + -2.231056963361899px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 50% { + text-shadow: + 0.08084290417898504px 0 1px rgba(0, 30, 255, 0.5), + -0.08084290417898504px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 55% { + text-shadow: + 2.3758461067427543px 0 1px rgba(0, 30, 255, 0.5), + -2.3758461067427543px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 60% { + text-shadow: + 2.202193051050636px 0 1px rgba(0, 30, 255, 0.5), + -2.202193051050636px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 65% { + text-shadow: + 2.8638780614874975px 0 1px rgba(0, 30, 255, 0.5), + -2.8638780614874975px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 70% { + text-shadow: + 0.48874025155497314px 0 1px rgba(0, 30, 255, 0.5), + -0.48874025155497314px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 75% { + text-shadow: + 1.8948491305757957px 0 1px rgba(0, 30, 255, 0.5), + -1.8948491305757957px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 80% { + text-shadow: + 0.0833037308038857px 0 1px rgba(0, 30, 255, 0.5), + -0.0833037308038857px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 85% { + text-shadow: + 0.09769827255241735px 0 1px rgba(0, 30, 255, 0.5), + -0.09769827255241735px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 90% { + text-shadow: + 3.443339761481782px 0 1px rgba(0, 30, 255, 0.5), + -3.443339761481782px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 95% { + text-shadow: + 2.1841838852799786px 0 1px rgba(0, 30, 255, 0.5), + -2.1841838852799786px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } + 100% { + text-shadow: + 2.6208764473832513px 0 1px rgba(0, 30, 255, 0.5), + -2.6208764473832513px 0 1px rgba(255, 0, 80, 0.3), + 0 0 3px; + } } .crt::after { - content: " "; - display: block; - position: absolute; - top: 0; - left: 0; - bottom: 0; - right: 0; - background: rgba(18, 16, 16, 0.1); - opacity: 0; - z-index: 2; - pointer-events: none; - animation: flicker 0.15s infinite; + content: ' '; + display: block; + position: absolute; + top: 0; + left: 0; + bottom: 0; + right: 0; + background: rgba(18, 16, 16, 0.1); + opacity: 0; + z-index: 2; + pointer-events: none; + animation: flicker 0.15s infinite; } .crt::before { - content: " "; - display: block; - position: absolute; - top: 0; - left: 0; - bottom: 0; - right: 0; - background: linear-gradient(rgba(18, 16, 16, 0) 50%, rgba(0, 0, 0, 0.25) 50%), linear-gradient(90deg, rgba(255, 0, 0, 0.06), rgba(0, 255, 0, 0.02), rgba(0, 0, 255, 0.06)); - z-index: 2; - background-size: 100% 2px, 3px 100%; - pointer-events: none; + content: ' '; + display: block; + position: absolute; + top: 0; + left: 0; + bottom: 0; + right: 0; + background: + linear-gradient(rgba(18, 16, 16, 0) 50%, rgba(0, 0, 0, 0.25) 50%), + linear-gradient(90deg, rgba(255, 0, 0, 0.06), rgba(0, 255, 0, 0.02), rgba(0, 0, 255, 0.06)); + z-index: 2; + background-size: + 100% 2px, + 3px 100%; + pointer-events: none; } .crt { - animation: textShadow 1.6s infinite; + animation: textShadow 1.6s infinite; } diff --git a/public/css/filebrowser.css b/public/css/filebrowser.css index a36271738..db5290d30 100644 --- a/public/css/filebrowser.css +++ b/public/css/filebrowser.css @@ -1,21 +1,21 @@ form { - width: 100%; + width: 100%; } .fill-height { - height: 100%; + height: 100%; } select { - height: inherit; - width: inherit; + height: inherit; + width: inherit; } .pg-file { - color: rgb(0, 80, 0); - font-weight: bold; + color: rgb(0, 80, 0); + font-weight: bold; } .other-file { - color: rgb(126, 0, 0); -} \ No newline at end of file + color: rgb(126, 0, 0); +} diff --git a/public/css/navbar.css b/public/css/navbar.css index 68b68a715..e62979cd8 100644 --- a/public/css/navbar.css +++ b/public/css/navbar.css @@ -1,40 +1,42 @@ -* {box-sizing: border-box;} +* { + box-sizing: border-box; +} body * { - margin: 0; - font-family: 'Montserrat', sans-serif; - font-weight: 200; + margin: 0; + font-family: 'Montserrat', sans-serif; + font-weight: 200; } .topnav { - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 50px; - display: flex; - justify-content: space-between; - align-items: center; - background-color: #012C4E; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 50px; + display: flex; + justify-content: space-between; + align-items: center; + background-color: #012c4e; } .topnav a { - display: block; - color: white; - text-align: center; - padding: 14px 16px; - text-decoration: none; - font-size: 17px; + display: block; + color: white; + text-align: center; + padding: 14px 16px; + text-decoration: none; + font-size: 17px; } .topnav a:hover .dropdown:hover .dropbtn { - background-color: #00BCD4; - color: black; + background-color: #00bcd4; + color: black; } .topnav a.active { - background-color: #012C4E; - color: white; + background-color: #012c4e; + color: white; } .dropdown { @@ -42,41 +44,41 @@ body * { } .dropdown .dropbtn { - font-size: 16px; - border: none; - outline: none; - color: white; - padding: 14px 16px; - background-color: inherit; - font-family: inherit; - margin: 0; + font-size: 16px; + border: none; + outline: none; + color: white; + padding: 14px 16px; + background-color: inherit; + font-family: inherit; + margin: 0; } .dropdown-content { - display: none; - position: fixed; - background-color: #f9f9f9; - min-width: 160px; - box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); - z-index: 5; + display: none; + position: fixed; + background-color: #f9f9f9; + min-width: 160px; + box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2); + z-index: 5; } .dropdown-content a { - color: white; - background-color: #012C4E; - padding: 12px 16px; - text-decoration: none; - display: block; - text-align: left; + color: white; + background-color: #012c4e; + padding: 12px 16px; + text-decoration: none; + display: block; + text-align: left; } .dropdown-content a:hover { - background-color: #607B90; - color: black; + background-color: #607b90; + color: black; } .dropdown:hover .dropdown-content { - display: block; + display: block; } .search-container { @@ -84,68 +86,70 @@ body * { } .topnav .search-container { - display: flex; - justify-content: flex-start; - align-items: center; - column-gap: 10px; - padding: 10px; + display: flex; + justify-content: flex-start; + align-items: center; + column-gap: 10px; + padding: 10px; } -.topnav input[type=text] { - padding: 6px; - border: none; +.topnav input[type='text'] { + padding: 6px; + border: none; } .topnav .search-container button { - padding: 6px 10px; - background: #C0CAD3; - font-size: 17px; - border: none; - cursor: pointer; + padding: 6px 10px; + background: #c0cad3; + font-size: 17px; + border: none; + cursor: pointer; } .topnav .search-container button:hover { - background: #A0B0BD; + background: #a0b0bd; } @media screen and (max-width: 600px) { - .topnav a, .topnav input[type=text], .topnav .search-container button { - display: block; - text-align: left; - width: 100%; - margin: 0; - padding: 14px; - } - .topnav input[type=text] { - border: 1px solid #ccc; - } + .topnav a, + .topnav input[type='text'], + .topnav .search-container button { + display: block; + text-align: left; + width: 100%; + margin: 0; + padding: 14px; + } + .topnav input[type='text'] { + border: 1px solid #ccc; + } } .dropdown-item .fa { - display: none; + display: none; } .dropdown-item.selected .fa { - display: inline-block; + display: inline-block; } #problemSeed { - background-color: #DFE5E9; - color: #2B193D; + background-color: #dfe5e9; + color: #2b193d; } -#sourceFilePath{ - border:none; - background-color: #DFE5E9; - color:#2B193D; - min-width:130px; +#sourceFilePath { + border: none; + background-color: #dfe5e9; + color: #2b193d; + min-width: 130px; } -#hiddenSourceFilePath{ - display:none; - white-space:pre; - padding: 6px; - margin-top: 7px; - margin-right: 16px; - font-size: 17px; +#hiddenSourceFilePath { + display: none; + white-space: pre; + padding: 6px; + margin-top: 7px; + margin-right: 16px; + font-size: 17px; } diff --git a/public/css/opl-flex.css b/public/css/opl-flex.css index 2edbcfac0..71c89c121 100644 --- a/public/css/opl-flex.css +++ b/public/css/opl-flex.css @@ -1,54 +1,54 @@ * { - box-sizing: border-box; + box-sizing: border-box; } body { - margin: 0px; + margin: 0px; } .container { - display: flex; - flex-direction: row; - align-content: stretch; - height: 100%; - width: 100%; + display: flex; + flex-direction: row; + align-content: stretch; + height: 100%; + width: 100%; } .left { - display: flex; - flex-direction: column; - width: 25%; - height: inherit; - padding: 10px; - background-color: #838d9f; + display: flex; + flex-direction: column; + width: 25%; + height: inherit; + padding: 10px; + background-color: #838d9f; } .middle { - display: flex; - flex-direction: column; - flex-grow: 1; - max-width: 50%; - height: inherit; - padding: 10px; - background-color: #525a6a; + display: flex; + flex-direction: column; + flex-grow: 1; + max-width: 50%; + height: inherit; + padding: 10px; + background-color: #525a6a; } .right { - display: flex; - flex-direction: column; - width: 25%; - height: inherit; - padding: 10px; - background-color: #919aaa; + display: flex; + flex-direction: column; + width: 25%; + height: inherit; + padding: 10px; + background-color: #919aaa; } .header { - width: 100%; - margin-bottom: 10px; + width: 100%; + margin-bottom: 10px; } .content { - display: flex; - flex-grow: 1; - width: 100%; + display: flex; + flex-grow: 1; + width: 100%; } diff --git a/public/css/rtl.css b/public/css/rtl.css index 8d532de3b..b1ad16241 100644 --- a/public/css/rtl.css +++ b/public/css/rtl.css @@ -3,4 +3,3 @@ /* The changes which were needed here in WeBWorK 2.16 are no * longer needed in WeBWorK 2.17. The file is being retained * for potential future use. */ - diff --git a/public/css/tags.css b/public/css/tags.css index a3a345415..c78a40b1b 100644 --- a/public/css/tags.css +++ b/public/css/tags.css @@ -1,38 +1,38 @@ - .wrapper { - background-color: whitesmoke; - list-style-type: none; - padding: 0; - } +.wrapper { + background-color: whitesmoke; + list-style-type: none; + padding: 0; +} - .form-row { - display: flex; - justify-content: flex-end; - padding: .5em; - } +.form-row { + display: flex; + justify-content: flex-end; + padding: 0.5em; +} - .form-row > label { - padding: .5em 1em .5em 0; - } +.form-row > label { + padding: 0.5em 1em 0.5em 0; +} - .form-row > input, - .form-row > textarea, - .form-row > select { - width: 100%; - text-overflow: ellipsis; - flex: 1; - } +.form-row > input, +.form-row > textarea, +.form-row > select { + width: 100%; + text-overflow: ellipsis; + flex: 1; +} - .form-row > select > option { - overflow:hidden; - } +.form-row > select > option { + overflow: hidden; +} - .form-row > input, - .form-row > button { - padding: .5em; - } - - .form-row > button { - background: gray; - color: white; - border: 0; - } +.form-row > input, +.form-row > button { + padding: 0.5em; +} + +.form-row > button { + background: gray; + color: white; + border: 0; +} diff --git a/public/css/twocolumn.css b/public/css/twocolumn.css index de3674ab0..a973ef598 100644 --- a/public/css/twocolumn.css +++ b/public/css/twocolumn.css @@ -1,97 +1,97 @@ * { - box-sizing: border-box; + box-sizing: border-box; } /* Create two equal columns that floats next to each other */ .column { - width: 50%; - height: auto; - padding: 10px; - position: absolute; - z-index: 1; - display: block; - bottom: 0; - top: 47px; + width: 50%; + height: auto; + padding: 10px; + position: absolute; + z-index: 1; + display: block; + bottom: 0; + top: 47px; } .left { - left: 0; - background-color:#aaa; + left: 0; + background-color: #aaa; } .right { - right: 0; - background-color:#bbb; + right: 0; + background-color: #bbb; } /* Clear floats after the columns */ .row:after { - content: ""; - display: table; - clear: both; + content: ''; + display: table; + clear: both; } .content { - position: absolute; - top: 50px; - bottom: 0px; - left: 0px; - right: 0px; - padding: 10px; + position: absolute; + top: 50px; + bottom: 0px; + left: 0px; + right: 0px; + padding: 10px; } .iframe-header { - position: relative; - overflow: hidden; + position: relative; + overflow: hidden; } .iframe-responsive { - top: 0; - left: 0; - width: 100%; - max-height: 100%; - min-width: 100%; - border: 0; + top: 0; + left: 0; + width: 100%; + max-height: 100%; + min-width: 100%; + border: 0; } /* Responsive layout - makes the two columns stack on top of each other instead of next to each other */ @media screen and (max-width: 600px) { - .column { - width: 100%; - } + .column { + width: 100%; + } } #currentEditPath { - font-size: 11px; - padding: 5px; - padding-bottom: 13px; + font-size: 11px; + padding: 5px; + padding-bottom: 13px; } .iframe-header button { - float: left; - padding-top: 6px; - padding-right: 10px; - padding-bottom: 6px; - padding-left: 10px; - margin-bottom: 8px; - margin-left: 16px; - background: #ddd; - font-size: 17px; - border: none; - cursor: pointer; + float: left; + padding-top: 6px; + padding-right: 10px; + padding-bottom: 6px; + padding-left: 10px; + margin-bottom: 8px; + margin-left: 16px; + background: #ddd; + font-size: 17px; + border: none; + cursor: pointer; } .iframe-header .render-option { - padding-top: 6px; - padding-right: 10px; - padding-bottom: 6px; - padding-left: 10px; - margin-bottom: 8px; - margin-left: 16px; - display: block; - float: left; + padding-top: 6px; + padding-right: 10px; + padding-bottom: 6px; + padding-left: 10px; + margin-bottom: 8px; + margin-left: 16px; + display: block; + float: left; } .iframe-header button:hover { - background: #ccc; + background: #ccc; } diff --git a/public/css/typing-sim.css b/public/css/typing-sim.css index 3af186ffb..80ff6bd88 100644 --- a/public/css/typing-sim.css +++ b/public/css/typing-sim.css @@ -2,46 +2,56 @@ @import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@300;700&family=VT323&display=swap'); * { - margin: 0; + margin: 0; } body { - background: rgb(49, 49, 49); - color: lime; - box-shadow: inset -53px -41px 198px black, inset 95px -2px 200px black; - display:flex; - align-items:center; - height:100vh; - justify-content: center; + background: rgb(49, 49, 49); + color: lime; + box-shadow: + inset -53px -41px 198px black, + inset 95px -2px 200px black; + display: flex; + align-items: center; + height: 100vh; + justify-content: center; } .typewriter { - font-family: 'VT323', monospace; - /* font-weight: 700; */ - width: 70%; + font-family: 'VT323', monospace; + /* font-weight: 700; */ + width: 70%; } h1 { - overflow: hidden; - margin: 0 auto; - display: inline-block; - font-weight: normal; + overflow: hidden; + margin: 0 auto; + display: inline-block; + font-weight: normal; } h1:after { - content: ''; - display: inline-block; - background-color: lime; - margin-left: 2px; - height: 25px; - width: 13px; - animation: cursor 0.4s infinite; + content: ''; + display: inline-block; + background-color: lime; + margin-left: 2px; + height: 25px; + width: 13px; + animation: cursor 0.4s infinite; } /* The typewriter cursor effect */ @keyframes cursor { - 0% { opacity: 1; } - 49% { opacity: 1; } - 50% { opacity: 0; } - 100% { opacity: 0; } + 0% { + opacity: 1; + } + 49% { + opacity: 1; + } + 50% { + opacity: 0; + } + 100% { + opacity: 0; + } } diff --git a/public/generate-assets.js b/public/generate-assets.js index fa9a061ce..4d68de265 100755 --- a/public/generate-assets.js +++ b/public/generate-assets.js @@ -15,7 +15,10 @@ const rtlcss = require('rtlcss'); const cssMinify = require('cssnano'); const argv = yargs - .usage('$0 Options').version(false).alias('help', 'h').wrap(100) + .usage('$0 Options') + .version(false) + .alias('help', 'h') + .wrap(100) .option('enable-sourcemaps', { alias: 's', description: 'Generate source maps. (Not for use in production!)', @@ -30,8 +33,7 @@ const argv = yargs alias: 'd', description: 'Delete all generated files.', type: 'boolean' - }) - .argv; + }).argv; const assetFile = path.resolve(__dirname, 'static-assets.json'); const assets = {}; @@ -48,7 +50,7 @@ const cleanDir = (dir) => { } } } -} +}; // The is set to true after all files are processed for the first time. let ready = false; @@ -75,12 +77,13 @@ const processFile = async (file, _details) => { return; } - const minJS = result.code + ( - argv.enableSourcemaps && result.map - ? `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${ - Buffer.from(result.map).toString('base64')}` - : '' - ); + const minJS = + result.code + + (argv.enableSourcemaps && result.map + ? `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${Buffer.from( + result.map + ).toString('base64')}` + : ''); const contentHash = crypto.createHash('sha256'); contentHash.update(minJS); @@ -114,18 +117,19 @@ const processFile = async (file, _details) => { return; } - if (result.sourceMap) result.sourceMap.sources = [ baseName ]; + if (result.sourceMap) result.sourceMap.sources = [baseName]; // Pass the compiled css through the autoprefixer. // This is really only needed for the bootstrap.css files, but doesn't hurt for the rest. let prefixedResult = await postcss([autoprefixer, cssMinify]).process(result.css, { from: baseName }); - const minCSS = prefixedResult.css + ( - argv.enableSourcemaps && result.sourceMap - ? `/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${ - Buffer.from(JSON.stringify(result.sourceMap)).toString('base64')}*/` - : '' - ); + const minCSS = + prefixedResult.css + + (argv.enableSourcemaps && result.sourceMap + ? `/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${Buffer.from( + JSON.stringify(result.sourceMap) + ).toString('base64')}*/` + : ''); const contentHash = crypto.createHash('sha256'); contentHash.update(minCSS); @@ -149,18 +153,21 @@ const processFile = async (file, _details) => { // Pass the compiled css through rtlcss and autoprefixer to generate css for right-to-left languages. let rtlResult = await postcss([rtlcss, autoprefixer, cssMinify]).process(result.css, { from: baseName }); - const rtlCSS = rtlResult.css + ( - argv.enableSourcemaps && result.sourceMap - ? `/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${ - Buffer.from(JSON.stringify(result.sourceMap)).toString('base64')}*/` - : '' - ); + const rtlCSS = + rtlResult.css + + (argv.enableSourcemaps && result.sourceMap + ? `/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${Buffer.from( + JSON.stringify(result.sourceMap) + ).toString('base64')}*/` + : ''); const rtlContentHash = crypto.createHash('sha256'); rtlContentHash.update(rtlCSS); - const newRTLVersion = file.replace(/\.s?css$/, - `.rtl.${rtlContentHash.digest('hex').substring(0, 8)}.min.css`); + const newRTLVersion = file.replace( + /\.s?css$/, + `.rtl.${rtlContentHash.digest('hex').substring(0, 8)}.min.css` + ); fs.writeFileSync(path.resolve(__dirname, newRTLVersion), rtlCSS); const rtlAssetName = file.replace(/\.s?css$/, '.rtl.css'); @@ -180,8 +187,9 @@ const processFile = async (file, _details) => { } } else { if (argv.watchFiles) - console.log('\x1b[33mWatches established, and initial build complete.\n' - + 'Press Control-C to stop.\x1b[0m'); + console.log( + '\x1b[33mWatches established, and initial build complete.\n' + 'Press Control-C to stop.\x1b[0m' + ); ready = true; } @@ -199,15 +207,18 @@ if (argv.clean) process.exit(); // Set up the watcher. if (argv.watchFiles) console.log('\x1b[32mEstablishing watches and performing initial build.\x1b[0m'); -chokidar.watch(['js/apps', 'css'], { - ignored: /layouts|\.min\.(js|css)$/, - cwd: __dirname, // Make sure all paths are given relative to the htdocs directory. - usePolling: true, // Needed to get changes to symlinks. - interval: 500, - awaitWriteFinish: { stabilityThreshold: 500 }, - persistent: argv.watchFiles ? true : false -}) - .on('add', processFile).on('change', processFile).on('ready', processFile) +chokidar + .watch(['js/apps', 'css'], { + ignored: /layouts|\.min\.(js|css)$/, + cwd: __dirname, // Make sure all paths are given relative to the htdocs directory. + usePolling: true, // Needed to get changes to symlinks. + interval: 500, + awaitWriteFinish: { stabilityThreshold: 500 }, + persistent: argv.watchFiles ? true : false + }) + .on('add', processFile) + .on('change', processFile) + .on('ready', processFile) .on('unlink', (file) => { // If a file is deleted, then also delete the corresponding generated file. if (assets[file]) { diff --git a/public/index.html b/public/index.html index 74d30d382..e50ccb899 100644 --- a/public/index.html +++ b/public/index.html @@ -1,16 +1,16 @@ - + - -WeBWorK Placeholder Page - - + + WeBWorK Placeholder Page + + +

WeBWorK Placeholder Page

-

WeBWorK Placeholder Page

+

Exploring?

-

Exploring?

- -

This page sits at the top level of the WeBWorK 2 system htdocs directory. You should never see it, unless you're verifying that you installed WeBWorK correctly.

- - +

+ This page sits at the top level of the WeBWorK 2 system htdocs directory. You should never see it, unless + you're verifying that you installed WeBWorK correctly. +

+ diff --git a/public/js/apps/CSSMessage/css-message.js b/public/js/apps/CSSMessage/css-message.js index 8b6ff86ad..cb58771cb 100644 --- a/public/js/apps/CSSMessage/css-message.js +++ b/public/js/apps/CSSMessage/css-message.js @@ -1,9 +1,8 @@ -window.addEventListener('message', event => { +window.addEventListener('message', (event) => { let message; try { message = JSON.parse(event.data); - } - catch (e) { + } catch (e) { if (!event.data.startsWith('[iFrameSizer]')) console.warn('CSSMessage: message not JSON', event.data); return; } @@ -14,14 +13,21 @@ window.addEventListener('message', event => { if (incoming.hasOwnProperty('selector')) { elements = window.document.querySelectorAll(incoming.selector); if (incoming.hasOwnProperty('style')) { - elements.forEach(el => { el.style.cssText = incoming.style }); + elements.forEach((el) => { + el.style.cssText = incoming.style; + }); } if (incoming.hasOwnProperty('class')) { - elements.forEach(el => { el.className = incoming.class }); + elements.forEach((el) => { + el.className = incoming.class; + }); } } }); - event.source.postMessage(JSON.stringify({ type: "webwork.css.update", update: "elements updated"}), event.origin); + event.source.postMessage( + JSON.stringify({ type: 'webwork.css.update', update: 'elements updated' }), + event.origin + ); } if (message.hasOwnProperty('templates')) { @@ -30,18 +36,24 @@ window.addEventListener('message', event => { element.innerText = cssString; document.head.insertAdjacentElement('beforeend', element); }); - event.source.postMessage(JSON.stringify({ type: "webwork.css.update", update: "templates updated"}), event.origin); + event.source.postMessage( + JSON.stringify({ type: 'webwork.css.update', update: 'templates updated' }), + event.origin + ); } if (message.hasOwnProperty('showSolutions')) { const elements = Array.from(window.document.querySelectorAll('.knowl[data-type="solution"]')); - const solutions = elements.map(el => el.dataset.knowlContents); - event.source.postMessage(JSON.stringify({ type: "webwork.content.solutions", solutions: solutions }), event.origin); + const solutions = elements.map((el) => el.dataset.knowlContents); + event.source.postMessage( + JSON.stringify({ type: 'webwork.content.solutions', solutions: solutions }), + event.origin + ); } if (message.hasOwnProperty('showHints')) { const elements = Array.from(window.document.querySelectorAll('.knowl[data-type="hint"]')); - const hints = elements.map(el => el.dataset.knowlContents); - event.source.postMessage(JSON.stringify({ type: "webwork.content.hints", hints: hints }), event.origin); + const hints = elements.map((el) => el.dataset.knowlContents); + event.source.postMessage(JSON.stringify({ type: 'webwork.content.hints', hints: hints }), event.origin); } }); diff --git a/public/js/apps/MathJaxConfig/mathjax-config.js b/public/js/apps/MathJaxConfig/mathjax-config.js index 3ef132bef..6b4874179 100644 --- a/public/js/apps/MathJaxConfig/mathjax-config.js +++ b/public/js/apps/MathJaxConfig/mathjax-config.js @@ -1,37 +1,40 @@ if (!window.MathJax) { window.MathJax = { tex: { - packages: {'[+]': ['noerrors']}, - processEscapes: false, + packages: { '[+]': ['noerrors'] }, + processEscapes: false }, loader: { load: ['input/asciimath', '[tex]/noerrors'] }, startup: { - ready: function() { + ready: function () { var AM = MathJax.InputJax.AsciiMath.AM; for (var i = 0; i < AM.symbols.length; i++) { if (AM.symbols[i].input == '**') { - AM.symbols[i] = { input: "**", tag: "msup", output: "^", tex: null, ttype: AM.TOKEN.INFIX }; + AM.symbols[i] = { input: '**', tag: 'msup', output: '^', tex: null, ttype: AM.TOKEN.INFIX }; } } - return MathJax.startup.defaultReady() + return MathJax.startup.defaultReady(); } }, options: { renderActions: { - findScript: [10, function (doc) { - document.querySelectorAll('script[type^="math/tex"]').forEach(function(node) { - var display = !!node.type.match(/; *mode=display/); - var math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display); - var text = document.createTextNode(''); - node.parentNode.replaceChild(text, node); - math.start = {node: text, delim: '', n: 0}; - math.end = {node: text, delim: '', n: 0}; - doc.math.push(math); - }); - }, ''] + findScript: [ + 10, + function (doc) { + document.querySelectorAll('script[type^="math/tex"]').forEach(function (node) { + var display = !!node.type.match(/; *mode=display/); + var math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display); + var text = document.createTextNode(''); + node.parentNode.replaceChild(text, node); + math.start = { node: text, delim: '', n: 0 }; + math.end = { node: text, delim: '', n: 0 }; + doc.math.push(math); + }); + }, + '' + ] }, ignoreHtmlClass: 'tex2jax_ignore' } - }; } diff --git a/public/js/apps/Problem/problem.js b/public/js/apps/Problem/problem.js index 01cc9312d..c204f37d4 100644 --- a/public/js/apps/Problem/problem.js +++ b/public/js/apps/Problem/problem.js @@ -1,49 +1,56 @@ (() => { const frame = window.frameElement.id || window.frameElement.dataset.id || 'no-id'; // Activate the popovers in the results table. - document.querySelectorAll('.attemptResults .answer-preview[data-bs-toggle="popover"]') - .forEach((preview) => { - if (preview.dataset.bsContent) - new bootstrap.Popover(preview); - }); - + document.querySelectorAll('.attemptResults .answer-preview[data-bs-toggle="popover"]').forEach((preview) => { + if (preview.dataset.bsContent) new bootstrap.Popover(preview); + }); + // if there is a JWTanswerURLstatus element, report it to parent const status = document.getElementById('JWTanswerURLstatus')?.value; if (status) { - console.log("problem status updated:", JSON.parse(value)); + console.log('problem status updated:', JSON.parse(value)); window.parent.postMessage(value, '*'); } - + // fetch the problem-result-score and postMessage to parent const score = document.getElementById('problem-result-score')?.value; if (score) { - window.parent.postMessage(JSON.stringify({ - type: 'webwork.interaction.attempt', - status: score, - frame: frame, - }), '*'); + window.parent.postMessage( + JSON.stringify({ + type: 'webwork.interaction.attempt', + status: score, + frame: frame + }), + '*' + ); } // set up listeners on knowl hints and solutions document.querySelectorAll('.knowl[data-type="hint"]').forEach((hint) => { hint.addEventListener('click', (event) => { - window.parent.postMessage(JSON.stringify({ - type: 'webwork.interaction.hint', - status: hint.classList[1], - id: hint.dataset.bsTarget, - frame: frame, - }), '*'); + window.parent.postMessage( + JSON.stringify({ + type: 'webwork.interaction.hint', + status: hint.classList[1], + id: hint.dataset.bsTarget, + frame: frame + }), + '*' + ); }); }); document.querySelectorAll('.knowl[data-type="solution"]').forEach((solution) => { solution.addEventListener('click', (event) => { - window.parent.postMessage(JSON.stringify({ - type: 'webwork.interaction.solution', - status: solution.classList[1], - id: solution.dataset.bsTarget, - frame: frame, - }), '*'); + window.parent.postMessage( + JSON.stringify({ + type: 'webwork.interaction.solution', + status: solution.classList[1], + id: solution.dataset.bsTarget, + frame: frame + }), + '*' + ); }); }); @@ -52,13 +59,13 @@ const form = document.getElementById('problemMainForm'); let messageQueue = []; let messageTimer = null; - + function processMessageQueue() { // Process the original messages in the queue for (let message = messageQueue.pop(); message; message = messageQueue.pop()) { window.parent.postMessage(JSON.stringify(message), '*'); } - + // Clear the message queue and timer messageQueue = []; clearTimeout(messageTimer); @@ -75,47 +82,50 @@ if (messageQueue[3].id !== id) return; // toolbar interaction is focus/blur with same id, ends with answer id - if (!messageQueue[1].id.endsWith(id) - || !messageQueue[2].id.endsWith(id) - || messageQueue[1].id !== messageQueue[2].id) return; - + if ( + !messageQueue[1].id.endsWith(id) || + !messageQueue[2].id.endsWith(id) || + messageQueue[1].id !== messageQueue[2].id + ) + return; + // if we get here, we have a toolbar interaction const button = messageQueue[1].id.replace(`-${id}`, ''); messageQueue.splice(0, 4, { type: 'webwork.interaction.toolbar', - id: button, + id: button }); } - + function scheduleMessage(message) { messageQueue.unshift(message); if (messageQueue.length >= 4) { checkForButtonClick(); } - + if (messageTimer) clearTimeout(messageTimer); messageTimer = setTimeout(processMessageQueue, 350); } - + form.addEventListener('focusin', (event) => { - const id = event.composedPath().reduce((s, el) => s ? s : el.id, ''); + const id = event.composedPath().reduce((s, el) => (s ? s : el.id), ''); if (id !== 'problem_body') { scheduleMessage({ type: 'webwork.interaction.focus', id: id.replace('mq-answer-', ''), - frame: frame, + frame: frame }); } }); - + form.addEventListener('focusout', (event) => { - const id = event.composedPath().reduce((s, el) => s ? s : el.id, ''); + const id = event.composedPath().reduce((s, el) => (s ? s : el.id), ''); if (id !== 'problem_body') { scheduleMessage({ type: 'webwork.interaction.blur', id: id.replace('mq-answer-', ''), - frame: frame, + frame: frame }); } }); @@ -138,7 +148,7 @@ const url = creditForm.action; const options = { method: 'POST', - body: formData, + body: formData }; fetch(url, options) .then((response) => { diff --git a/public/js/apps/Problem/submithelper.js b/public/js/apps/Problem/submithelper.js index d1b72940b..bb9431816 100644 --- a/public/js/apps/Problem/submithelper.js +++ b/public/js/apps/Problem/submithelper.js @@ -1,13 +1,13 @@ (() => { - let problemForm = document.getElementById('problemMainForm') + let problemForm = document.getElementById('problemMainForm'); if (!problemForm) return; - problemForm.querySelectorAll('input[type="submit"]').forEach(button => { + problemForm.querySelectorAll('input[type="submit"]').forEach((button) => { button.addEventListener('click', () => { // Keep ONLY the last button clicked. - problemForm.querySelectorAll('input[type="submit"]').forEach(clean => { + problemForm.querySelectorAll('input[type="submit"]').forEach((clean) => { clean.classList.remove('btn-clicked'); }); - button.classList.add("btn-clicked"); - }) - }) + button.classList.add('btn-clicked'); + }); + }); })(); diff --git a/public/js/filebrowser.js b/public/js/filebrowser.js index 630b2cc3c..8e957baef 100644 --- a/public/js/filebrowser.js +++ b/public/js/filebrowser.js @@ -1,196 +1,203 @@ // pass the form to use for updating and a callback for updating back-navigation // examples for this callback are provided: `diveIn` and `backOut` function updateBrowser(formId, updateBackNav) { - var form = window.document.getElementById(formId); - var target = form.action; - var select = form.getElementsByTagName('select')[0]; // each form has only one element + var option = select.options[select.selectedIndex]; + var value = option.value; + var formData = new FormData(); + var processData; + + if (value.startsWith('/')) { + value = value.replace('/', ''); + } // replaces first instance only + if (value.match(/\/$/)) { + formData.set('maxDepth', 1); + formData.set('basePath', value); + processData = function (data) { + updateFileList(data); + updateBackNav(option.text); + }; + } else if (value.match(/\.pg$/)) { + target = 'render-api/'; + formData.set('sourceFilePath', value); + formData.set('problemSeed', 1234); + formData.set('outputFormat', 'static'); + formData.set('_format', 'json'); + formData.set('isInstructor', 1); formData.set('forceScaffoldsOpen', 1); formData.set('includeTags', 1); - formData.set('showComments', 1); - processData = function (data) { - updateIframe(data.renderedHTML); - updateMetadata(data); - } - } else { - // default back to the root - resetBackNav(); - return; - } - - var params = { - body: formData, - method: 'post' - }; - fetch(target, params) - .then( function(resp) { - if (resp.ok) { - return resp.json(); - } else { - throw new Error("Something went wrong: " + resp.statusText); - } - }) - .then( processData ) - .catch( function(e) { - console.log(e); - alert(e.message); - }); + formData.set('showComments', 1); + processData = function (data) { + updateIframe(data.renderedHTML); + updateMetadata(data); + }; + } else { + // default back to the root + resetBackNav(); + return; + } + + var params = { + body: formData, + method: 'post' + }; + fetch(target, params) + .then(function (resp) { + if (resp.ok) { + return resp.json(); + } else { + throw new Error('Something went wrong: ' + resp.statusText); + } + }) + .then(processData) + .catch(function (e) { + console.log(e); + alert(e.message); + }); } // use the response to update the file browser function updateFileList(data) { - var select = window.document.getElementById('file-list'); - select.innerHTML = ''; - for (var key in data) { - var opt = document.createElement('option'); - if (key.match(/\./)) { opt.className = (key.match(/\.pg$/)) ? 'pg-file' : 'other-file'; } - opt.text = key; - opt.value = data[key]; - select.add(opt); - } + var select = window.document.getElementById('file-list'); + select.innerHTML = ''; + for (var key in data) { + var opt = document.createElement('option'); + if (key.match(/\./)) { + opt.className = key.match(/\.pg$/) ? 'pg-file' : 'other-file'; + } + opt.text = key; + opt.value = data[key]; + select.add(opt); + } } // callback to extend the back-navigation function diveIn(updatePath) { - var select = window.document.getElementById('back-nav'); - var current = select.options[0]; - var newOption = document.createElement('option'); - newOption.text = `${current.text}${updatePath}/`; - newOption.value = `${current.value}${updatePath}/`; - select.add(newOption, 0); - select.selectedIndex = 0; + var select = window.document.getElementById('back-nav'); + var current = select.options[0]; + var newOption = document.createElement('option'); + newOption.text = `${current.text}${updatePath}/`; + newOption.value = `${current.value}${updatePath}/`; + select.add(newOption, 0); + select.selectedIndex = 0; } // callback to retract the back-navigation function backOut(updatePath) { - var select = window.document.getElementById('back-nav'); - while (select.selectedIndex !== 0) { - select.remove(0); - } + var select = window.document.getElementById('back-nav'); + while (select.selectedIndex !== 0) { + select.remove(0); + } } // reset the back-navigation function resetBackNav() { - var data = { - Contrib: 'Contrib/', - Library: 'Library/', - Pending: 'Pending/', - private: 'private/', - } - updateFileList(data); - - var select = window.document.getElementById('back-nav'); - select.selectedIndex = select.options.length - 1; - backOut('/'); + var data = { + Contrib: 'Contrib/', + Library: 'Library/', + Pending: 'Pending/', + private: 'private/' + }; + updateFileList(data); + + var select = window.document.getElementById('back-nav'); + select.selectedIndex = select.options.length - 1; + backOut('/'); } // in case the raw metadata text is parsed incorrectly // display it as text function updateRawMetadata(text) { - var container = window.document.getElementById('raw-metadata'); - text = text.replace(/\n/g, '
'); - text = text.replace(/#/g, ''); - container.innerHTML = text; + var container = window.document.getElementById('raw-metadata'); + text = text.replace(/\n/g, '
'); + text = text.replace(/#/g, ''); + container.innerHTML = text; } function updateIframe(html) { - var container = window.document.getElementById('rendered-problem'); - container.srcdoc = html; + var container = window.document.getElementById('rendered-problem'); + container.srcdoc = html; } function mergeArrays() { - var merged = []; - var args = Array.prototype.slice.call(arguments); - args.forEach( (arg) => merged = merged.concat(arg) ); - return merged.filter((el, ind, arr) => (el && arr.indexOf(el) === ind)); + var merged = []; + var args = Array.prototype.slice.call(arguments); + args.forEach((arg) => (merged = merged.concat(arg))); + return merged.filter((el, ind, arr) => el && arr.indexOf(el) === ind); } function updateMetadata(data) { - // obscene, but merges the two sources and eliminates duplicates, ignores undef - data.tags.resources = mergeArrays(data.tags.resources, data.resources, data.pgResources); - - if (data.tags.isplaceholder === 1) { - // reset all form-fields - var tagContainer = window.document.getElementById('tag-wrapper'); - updateEach(tagContainer, {Resources: data.tags.resources.join(', ')}); - var flagContainer = window.document.getElementById('flags-wrapper'); - updateEach(flagContainer, {}); - updateRawMetadata(''); - - alert(`${data.tags.file} is a placeholder - do not set tags!`); - console.log(data); - return; // bow out - } - - // make sure the tags form is matched to the right pg file - var pathfield = window.document.getElementById('tag-filename'); - pathfield.setAttribute('value', data.tags.file); - - if (data.raw_metadata_text) { - updateRawMetadata(data.raw_metadata_text); - } else { - updateRawMetadata(''); - } - // metadata is spread across the response object - // form data is grouped by 'location' in the response - if (data.tags) { - var tagContainer = window.document.getElementById('tag-wrapper'); - console.log("METADATA: ", data); - // description is an array of text, one entry per line - data.tags.Description = data.tags.description.join("\n"); - // keywords is an array of strings - data.tags.Keywords = data.tags.keywords.join(', '); - data.tags.Resources = data.tags.resources.join(', '); - updateEach(tagContainer, data.tags); - } - - if (data.flags) { - var flagContainer = window.document.getElementById('flags-wrapper'); - updateEach(flagContainer, data.flags); - } + // obscene, but merges the two sources and eliminates duplicates, ignores undef + data.tags.resources = mergeArrays(data.tags.resources, data.resources, data.pgResources); + + if (data.tags.isplaceholder === 1) { + // reset all form-fields + var tagContainer = window.document.getElementById('tag-wrapper'); + updateEach(tagContainer, { Resources: data.tags.resources.join(', ') }); + var flagContainer = window.document.getElementById('flags-wrapper'); + updateEach(flagContainer, {}); + updateRawMetadata(''); + + alert(`${data.tags.file} is a placeholder - do not set tags!`); + console.log(data); + return; // bow out + } + + // make sure the tags form is matched to the right pg file + var pathfield = window.document.getElementById('tag-filename'); + pathfield.setAttribute('value', data.tags.file); + + if (data.raw_metadata_text) { + updateRawMetadata(data.raw_metadata_text); + } else { + updateRawMetadata(''); + } + // metadata is spread across the response object + // form data is grouped by 'location' in the response + if (data.tags) { + var tagContainer = window.document.getElementById('tag-wrapper'); + console.log('METADATA: ', data); + // description is an array of text, one entry per line + data.tags.Description = data.tags.description.join('\n'); + // keywords is an array of strings + data.tags.Keywords = data.tags.keywords.join(', '); + data.tags.Resources = data.tags.resources.join(', '); + updateEach(tagContainer, data.tags); + } + + if (data.flags) { + var flagContainer = window.document.getElementById('flags-wrapper'); + updateEach(flagContainer, data.flags); + } } // update form fields from response data // @param container - the html parent // @param info - an object containing keys corresponding to the children of `container` function updateEach(container, info) { - for (i = 0; i < container.children.length; i++) { - var field = container.children[i].children[1]; - var fieldName = field.getAttribute('name'); - // console.log(`name: ${fieldName}; value: ${info[fieldName]}`); - if (field.getAttribute('type') === 'checkbox') { - if (info[fieldName] && info[fieldName] == 1) { // should accept either 1 or "1" - field.setAttribute('checked', 'checked'); - } else { - field.removeAttribute('checked'); - } - } else { - field.value = info[fieldName] || ''; - // when value for dropdown is not available - reset to blank and log - if (field.value !== '' && field.value !== info[fieldName]) { - console.log(`Cannot set ${fieldName} = ${info[fieldName]}`); - field.value = ''; - } - } - if (field.tagName === 'SELECT' && field.onchange) { field.onchange() }; - } + for (i = 0; i < container.children.length; i++) { + var field = container.children[i].children[1]; + var fieldName = field.getAttribute('name'); + // console.log(`name: ${fieldName}; value: ${info[fieldName]}`); + if (field.getAttribute('type') === 'checkbox') { + if (info[fieldName] && info[fieldName] == 1) { + // should accept either 1 or "1" + field.setAttribute('checked', 'checked'); + } else { + field.removeAttribute('checked'); + } + } else { + field.value = info[fieldName] || ''; + // when value for dropdown is not available - reset to blank and log + if (field.value !== '' && field.value !== info[fieldName]) { + console.log(`Cannot set ${fieldName} = ${info[fieldName]}`); + field.value = ''; + } + } + if (field.tagName === 'SELECT' && field.onchange) { + field.onchange(); + } + } } diff --git a/public/js/navbar.js b/public/js/navbar.js index 5adf305b1..05338392d 100644 --- a/public/js/navbar.js +++ b/public/js/navbar.js @@ -1,56 +1,48 @@ -window.addEventListener('message', event => { +window.addEventListener('message', (event) => { let message; try { - message = JSON.parse(event.data); - } - catch (e) { - return; + message = JSON.parse(event.data); + } catch (e) { + return; } console.log(message); }); -const templateSelect = document.getElementById("template-select"); -const templateItems = - document - .getElementById("template-select-dropdown") - ?.querySelectorAll(".dropdown-item") ?? []; +const templateSelect = document.getElementById('template-select'); +const templateItems = document.getElementById('template-select-dropdown')?.querySelectorAll('.dropdown-item') ?? []; for (const element of templateItems) { - element.addEventListener("click", (e) => { + element.addEventListener('click', (e) => { e.preventDefault(); templateItems.forEach((item) => { - item.classList.remove("selected"); + item.classList.remove('selected'); }); - element.classList.add("selected"); - templateSelect.innerHTML = - element.textContent + ' '; + element.classList.add('selected'); + templateSelect.innerHTML = element.textContent + ' '; }); } $(function () { - $("#hiddenSourceFilePath").text($("#sourceFilePath").val()); - $("#sourceFilePath").width($("#hiddenSourceFilePath").width()); -}).on("input", function () { - $("#hiddenSourceFilePath").text($("#sourceFilePath").val()); - $("#sourceFilePath").width($("#hiddenSourceFilePath").width() + 12); + $('#hiddenSourceFilePath').text($('#sourceFilePath').val()); + $('#sourceFilePath').width($('#hiddenSourceFilePath').width()); +}).on('input', function () { + $('#hiddenSourceFilePath').text($('#sourceFilePath').val()); + $('#sourceFilePath').width($('#hiddenSourceFilePath').width() + 12); const remaining = - document.querySelector(".topnav").offsetWidth - - document.querySelector("#template-select").offsetWidth - - 330; - $("#sourceFilePath").css("maxWidth", remaining); + document.querySelector('.topnav').offsetWidth - document.querySelector('#template-select').offsetWidth - 330; + $('#sourceFilePath').css('maxWidth', remaining); }); -let loadbutton = document.getElementById("load-problem"); -let savebutton = document.getElementById("save-problem"); -let renderbutton = document.getElementById("render-button"); -let problemiframe = document.getElementById("rendered-problem"); +let loadbutton = document.getElementById('load-problem'); +let savebutton = document.getElementById('save-problem'); +let renderbutton = document.getElementById('render-button'); +let problemiframe = document.getElementById('rendered-problem'); -problemiframe.addEventListener("load", () => { - console.log("loaded..."); +problemiframe.addEventListener('load', () => { + console.log('loaded...'); insertListener(); activeButton(); }); - const editorContainer = document.querySelector('.code-mirror-editor'); const cm = new PGCodeMirrorEditor.View(editorContainer, { source: '# Load a problem, then click on "render contents."', @@ -58,24 +50,18 @@ const cm = new PGCodeMirrorEditor.View(editorContainer, { theme: 'Cobalt' }); -savebutton.addEventListener("click", (_event) => { - const writeurl = "render-api/can"; +savebutton.addEventListener('click', (_event) => { + const writeurl = 'render-api/can'; let formData = new FormData(); encoder = new TextEncoder(); - formData.set( - "problemSource", - Base64.fromUint8Array(encoder.encode(cm.source)) - ); + formData.set('problemSource', Base64.fromUint8Array(encoder.encode(cm.source))); - formData.set( - "writeFilePath", - document.getElementById("sourceFilePath").value - ); + formData.set('writeFilePath', document.getElementById('sourceFilePath').value); const write_params = { body: formData, - method: "post", + method: 'post' }; fetch(writeurl, write_params) @@ -88,11 +74,10 @@ savebutton.addEventListener("click", (_event) => { }) .then(function (data) { if (data.message) { - throw new Error("Could not write to file: " + data.message); + throw new Error('Could not write to file: ' + data.message); } else { - document.getElementById("currentEditPath").innerText = - document.getElementById("sourceFilePath").value; - alert("Successfully written to file: " + data); + document.getElementById('currentEditPath').innerText = document.getElementById('sourceFilePath').value; + alert('Successfully written to file: ' + data); } }) .catch(function (e) { @@ -100,18 +85,15 @@ savebutton.addEventListener("click", (_event) => { }); }); -loadbutton.addEventListener("click", (event) => { +loadbutton.addEventListener('click', (event) => { event.preventDefault(); - const sourceurl = "render-api/tap"; + const sourceurl = 'render-api/tap'; let formData = new FormData(); - formData.set( - "sourceFilePath", - document.getElementById("sourceFilePath").value - ); + formData.set('sourceFilePath', document.getElementById('sourceFilePath').value); const source_params = { body: formData, - method: "post", + method: 'post' }; fetch(sourceurl, source_params) @@ -119,15 +101,12 @@ loadbutton.addEventListener("click", (event) => { if (response.ok) { return response.text(); } else { - throw new Error( - "Could not reach the API: " + response.statusText - ); + throw new Error('Could not reach the API: ' + response.statusText); } }) .then(function (data) { cm.source = data; - document.getElementById("currentEditPath").innerText = - document.getElementById("sourceFilePath").value; + document.getElementById('currentEditPath').innerText = document.getElementById('sourceFilePath').value; }) .catch(function (error) { cm.source = error.message; @@ -135,38 +114,32 @@ loadbutton.addEventListener("click", (event) => { }); }); -renderbutton.addEventListener("click", (event) => { +renderbutton.addEventListener('click', (event) => { event.preventDefault(); - document.getElementById("rendered-problem").srcdoc = "Loading..."; - const renderurl = "render-api"; + document.getElementById('rendered-problem').srcdoc = 'Loading...'; + const renderurl = 'render-api'; - const selectedformat = document.querySelector(".dropdown-item.selected"); + const selectedformat = document.querySelector('.dropdown-item.selected'); const outputFormat = selectedformat?.id ?? 'default'; let formData = new FormData(); - formData.set("showComments", 1); - formData.set( - "sourceFilePath", - document.getElementById("sourceFilePath").value - ); - formData.set("problemSeed", document.getElementById("problemSeed").value); - formData.set("outputFormat", outputFormat); - if (outputFormat == 'debug') formData.set("clientDebug", 1); + formData.set('showComments', 1); + formData.set('sourceFilePath', document.getElementById('sourceFilePath').value); + formData.set('problemSeed', document.getElementById('problemSeed').value); + formData.set('outputFormat', outputFormat); + if (outputFormat == 'debug') formData.set('clientDebug', 1); encoder = new TextEncoder(); - formData.set( - "problemSource", - Base64.fromUint8Array(encoder.encode(cm.source)) - ); + formData.set('problemSource', Base64.fromUint8Array(encoder.encode(cm.source))); - [...document.querySelectorAll(".checkbox-input:checked")] + [...document.querySelectorAll('.checkbox-input:checked')] .map((e) => e.name) .forEach((box) => { formData.append(box, 1); }); - formData.append("_format", "json"); + formData.append('_format', 'json'); const render_params = { body: formData, - method: "post", + method: 'post' }; fetch(renderurl, render_params) @@ -174,86 +147,70 @@ renderbutton.addEventListener("click", (event) => { if (response.ok) { return response.json(); } else { - throw new Error( - "Could not reach the API: " + response.statusText - ); + throw new Error('Could not reach the API: ' + response.statusText); } }) .then(function (data) { - console.log("render data: ", data); + console.log('render data: ', data); problemiframe.srcdoc = data.renderedHTML; - if (data.debug.perl_warn !== "") { - alert(data.debug.perl_warn.replace(//g, "")); + if (data.debug.perl_warn !== '') { + alert(data.debug.perl_warn.replace(//g, '')); } }) .catch(function (error) { - document.getElementById("rendered-problem").innerHTML = - error.message; + document.getElementById('rendered-problem').innerHTML = error.message; }); return true; }); function activeButton() { - let problemForm = - problemiframe.contentWindow.document.getElementById("problemMainForm"); + let problemForm = problemiframe.contentWindow.document.getElementById('problemMainForm'); if (!problemForm) { - console.log("could not find form! has a problem been rendered?"); + console.log('could not find form! has a problem been rendered?'); return; } - problemForm.querySelectorAll(".btn-primary").forEach((button) => { - button.addEventListener("click", () => { - button.classList.add("btn-clicked"); + problemForm.querySelectorAll('.btn-primary').forEach((button) => { + button.addEventListener('click', () => { + button.classList.add('btn-clicked'); }); }); } function insertListener() { // assuming global problemiframe - too sloppy? - let problemForm = - problemiframe.contentWindow.document.getElementById("problemMainForm"); + let problemForm = problemiframe.contentWindow.document.getElementById('problemMainForm'); // don't croak when the empty iframe is first loaded if (!problemForm) { - console.log("could not find form! has a problem been rendered?"); + console.log('could not find form! has a problem been rendered?'); return; } - problemForm.addEventListener("submit", (event) => { + problemForm.addEventListener('submit', (event) => { event.preventDefault(); let formData = new FormData(problemForm); - let clickedButton = problemForm.querySelector(".btn-clicked"); - formData.set("_format", "json"); - const selectedformat = document.querySelector( - ".dropdown-item.selected" - ); + let clickedButton = problemForm.querySelector('.btn-clicked'); + formData.set('_format', 'json'); + const selectedformat = document.querySelector('.dropdown-item.selected'); const outputFormat = selectedformat?.id ?? 'default'; - formData.set("isInstructor", 1); - formData.set("includeTags", 1); - formData.set("showComments", 1); - formData.set( - "sourceFilePath", - document.getElementById("sourceFilePath").value - ); - formData.set( - "problemSeed", - document.getElementById("problemSeed").value - ); - formData.set("outputFormat", outputFormat); + formData.set('isInstructor', 1); + formData.set('includeTags', 1); + formData.set('showComments', 1); + formData.set('sourceFilePath', document.getElementById('sourceFilePath').value); + formData.set('problemSeed', document.getElementById('problemSeed').value); + formData.set('outputFormat', outputFormat); formData.set(clickedButton.name, clickedButton.value); encoder = new TextEncoder(); - formData.set( - "problemSource", - Base64.fromUint8Array(encoder.encode(cm.source)) - ); + formData.set('problemSource', Base64.fromUint8Array(encoder.encode(cm.source))); - [...document.querySelectorAll(".checkbox-input:checked")] + [...document.querySelectorAll('.checkbox-input:checked')] .map((e) => e.name) .forEach((box) => { formData.append(box, 1); }); - const submiturl = "render-api"; + const submiturl = 'render-api'; const submit_params = { body: formData, - method: "post", + method: 'post' }; fetch(submiturl, submit_params) @@ -261,18 +218,15 @@ function insertListener() { if (response.ok) { return response.json(); } else { - throw new Error( - "Could not submit your answers: " + response.statusText - ); + throw new Error('Could not submit your answers: ' + response.statusText); } }) .then(function (data) { - console.log("render data: ", data); + console.log('render data: ', data); problemiframe.srcdoc = data.renderedHTML; }) .catch(function (error) { - document.getElementById("rendered-problem").innerHTML = - error.message; + document.getElementById('rendered-problem').innerHTML = error.message; }); }); } diff --git a/public/js/tags.js b/public/js/tags.js index 12d8b3463..040ceeca2 100644 --- a/public/js/tags.js +++ b/public/js/tags.js @@ -1,82 +1,87 @@ function updateDBsubject() { - var subjectSelect = window.document.getElementById('db-subject'); - var subjects = Object.keys(taxo) || []; - addOptions(subjectSelect, subjects); + var subjectSelect = window.document.getElementById('db-subject'); + var subjects = Object.keys(taxo) || []; + addOptions(subjectSelect, subjects); } function updateDBchapter() { - var subjectSelect = window.document.getElementById('db-subject'); - var subject = subjectSelect.options[subjectSelect.selectedIndex]?.value; - var chapterSelect = window.document.getElementById('db-chapter') - var chapters = (taxo[subject]) ? Object.keys(taxo[subject]) : []; - addOptions(chapterSelect, chapters); + var subjectSelect = window.document.getElementById('db-subject'); + var subject = subjectSelect.options[subjectSelect.selectedIndex]?.value; + var chapterSelect = window.document.getElementById('db-chapter'); + var chapters = taxo[subject] ? Object.keys(taxo[subject]) : []; + addOptions(chapterSelect, chapters); } function updateDBsection() { - var subjectSelect = window.document.getElementById('db-subject'); - var subject = subjectSelect.options[subjectSelect.selectedIndex]?.value; - var chapterSelect = window.document.getElementById('db-chapter'); - var chapter = chapterSelect.options[chapterSelect.selectedIndex]?.value; - var sectionSelect = window.document.getElementById('db-section'); - var sections = (taxo[subject] && taxo[subject][chapter]) ? taxo[subject][chapter] : []; - addOptions(sectionSelect, sections); + var subjectSelect = window.document.getElementById('db-subject'); + var subject = subjectSelect.options[subjectSelect.selectedIndex]?.value; + var chapterSelect = window.document.getElementById('db-chapter'); + var chapter = chapterSelect.options[chapterSelect.selectedIndex]?.value; + var sectionSelect = window.document.getElementById('db-section'); + var sections = taxo[subject] && taxo[subject][chapter] ? taxo[subject][chapter] : []; + addOptions(sectionSelect, sections); } function addOptions(selectElement, optionsArray) { - if (selectElement.innerHTML) { selectElement.innerHTML = '' } - optionsArray.forEach(function (opt) { - var option = document.createElement('option'); - option.value = opt; - option.text = opt; - selectElement.add(option); - }); - var emptyOption = document.createElement('option'); - emptyOption.value = ''; - emptyOption.text = 'blank'; - selectElement.add(emptyOption, 0); - selectElement.selectedIndex = 0; + if (selectElement.innerHTML) { + selectElement.innerHTML = ''; + } + optionsArray.forEach(function (opt) { + var option = document.createElement('option'); + option.value = opt; + option.text = opt; + selectElement.add(option); + }); + var emptyOption = document.createElement('option'); + emptyOption.value = ''; + emptyOption.text = 'blank'; + selectElement.add(emptyOption, 0); + selectElement.selectedIndex = 0; } function submitTags(e) { - e.preventDefault(); - var formData = new FormData(e.target); + e.preventDefault(); + var formData = new FormData(e.target); - // disassemble the Description - formData = parseStringAndAppend(formData, 'Description'); + // disassemble the Description + formData = parseStringAndAppend(formData, 'Description'); - // disassemble the list of keywords - formData = parseStringAndAppend(formData, 'Keywords'); + // disassemble the list of keywords + formData = parseStringAndAppend(formData, 'Keywords'); - // disassemble any resources - formData = parseStringAndAppend(formData, 'Resources'); + // disassemble any resources + formData = parseStringAndAppend(formData, 'Resources'); - var params = { - body: formData, - method: 'post' - }; - fetch(e.target.action, params) - .then( function (resp) { - if (resp.ok) { - return resp.json(); - } else { - throw new Error("Something went wrong: " + resp.statusText); - } - }) - .then( d => updateMetadata(d) ) - .catch( e => {console.log(e); alert(e.message);} ); + var params = { + body: formData, + method: 'post' + }; + fetch(e.target.action, params) + .then(function (resp) { + if (resp.ok) { + return resp.json(); + } else { + throw new Error('Something went wrong: ' + resp.statusText); + } + }) + .then((d) => updateMetadata(d)) + .catch((e) => { + console.log(e); + alert(e.message); + }); } // uses the convention that tags want these arrays as lowercase // UI uses the joined string in key with first-capital function parseStringAndAppend(formData, elementName) { - var string = window.document.getElementsByName(elementName)[0].value; - if (string && string !== '') { - var array = string.split(',').map(el => el.trim()); - array.forEach(item => formData.append(elementName.toLowerCase(), item)); - formData.delete(elementName); - } - return formData; + var string = window.document.getElementsByName(elementName)[0].value; + if (string && string !== '') { + var array = string.split(',').map((el) => el.trim()); + array.forEach((item) => formData.append(elementName.toLowerCase(), item)); + formData.delete(elementName); + } + return formData; } updateDBsubject(); -window.document.getElementById('problem-tags').addEventListener('submit', submitTags); \ No newline at end of file +window.document.getElementById('problem-tags').addEventListener('submit', submitTags);