From c309e71d170f6c36517fa8679bef62240c1b9404 Mon Sep 17 00:00:00 2001 From: Carlos de la Guardia Date: Fri, 11 Sep 2020 21:17:56 -0500 Subject: [PATCH] initial work --- .editorconfig | 21 ++ .github/ISSUE_TEMPLATE.md | 15 + .gitignore | 105 +++++++ .travis.yml | 29 ++ AUTHORS.rst | 13 + CONTRIBUTING.rst | 128 +++++++++ HISTORY.rst | 8 + LICENSE | 22 ++ MANIFEST.in | 11 + Makefile | 88 ++++++ README.rst | 37 +++ docs/Makefile | 20 ++ docs/authors.rst | 1 + docs/conf.py | 162 +++++++++++ docs/contributing.rst | 1 + docs/history.rst | 1 + docs/index.rst | 20 ++ docs/installation.rst | 51 ++++ docs/make.bat | 36 +++ docs/readme.rst | 1 + docs/usage.rst | 7 + questions/__init__.py | 51 ++++ questions/cli.py | 15 + questions/form.py | 164 +++++++++++ questions/questions.py | 564 ++++++++++++++++++++++++++++++++++++ questions/settings.py | 582 ++++++++++++++++++++++++++++++++++++++ questions/templates.py | 200 +++++++++++++ requirements.txt | 2 + requirements_dev.txt | 13 + setup.cfg | 26 ++ setup.py | 53 ++++ tests/__init__.py | 1 + tests/test_questions.py | 37 +++ tox.ini | 27 ++ 34 files changed, 2512 insertions(+) create mode 100644 .editorconfig create mode 100644 .github/ISSUE_TEMPLATE.md create mode 100644 .gitignore create mode 100644 .travis.yml create mode 100644 AUTHORS.rst create mode 100644 CONTRIBUTING.rst create mode 100644 HISTORY.rst create mode 100644 LICENSE create mode 100644 MANIFEST.in create mode 100644 Makefile create mode 100644 README.rst create mode 100644 docs/Makefile create mode 100644 docs/authors.rst create mode 100755 docs/conf.py create mode 100644 docs/contributing.rst create mode 100644 docs/history.rst create mode 100644 docs/index.rst create mode 100644 docs/installation.rst create mode 100644 docs/make.bat create mode 100644 docs/readme.rst create mode 100644 docs/usage.rst create mode 100644 questions/__init__.py create mode 100644 questions/cli.py create mode 100644 questions/form.py create mode 100644 questions/questions.py create mode 100644 questions/settings.py create mode 100644 questions/templates.py create mode 100644 requirements.txt create mode 100644 requirements_dev.txt create mode 100644 setup.cfg create mode 100644 setup.py create mode 100644 tests/__init__.py create mode 100644 tests/test_questions.py create mode 100644 tox.ini diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..d4a2c44 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,21 @@ +# http://editorconfig.org + +root = true + +[*] +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true +insert_final_newline = true +charset = utf-8 +end_of_line = lf + +[*.bat] +indent_style = tab +end_of_line = crlf + +[LICENSE] +insert_final_newline = false + +[Makefile] +indent_style = tab diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..9fdbae5 --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,15 @@ +* Questions version: +* Python version: +* Operating System: + +### Description + +Describe what you were trying to get done. +Tell us what happened, what went wrong, and what you expected to happen. + +### What I Did + +``` +Paste the command(s) you ran and the output. +If there was a crash, please include the traceback here. +``` diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..43091aa --- /dev/null +++ b/.gitignore @@ -0,0 +1,105 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +# IDE settings +.vscode/ \ No newline at end of file diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..e4bf0e6 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,29 @@ +# Config file for automatic testing at travis-ci.com + +language: python +python: + - 3.8 + - 3.7 + - 3.6 + - 3.5 + +# Command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors +install: pip install -U tox-travis + +# Command to run tests, e.g. python setup.py test +script: tox + +# Assuming you have installed the travis-ci CLI tool, after you +# create the Github repo and add it to Travis, run the +# following command to finish PyPI deployment setup: +# $ travis encrypt --add deploy.password +deploy: + provider: pypi + distributions: sdist bdist_wheel + user: cguardia + password: + secure: PLEASE_REPLACE_ME + on: + tags: true + repo: cguardia/questions + python: 3.8 diff --git a/AUTHORS.rst b/AUTHORS.rst new file mode 100644 index 0000000..9a49045 --- /dev/null +++ b/AUTHORS.rst @@ -0,0 +1,13 @@ +======= +Credits +======= + +Development Lead +---------------- + +* Carlos de la Guardia + +Contributors +------------ + +None yet. Why not be the first? diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst new file mode 100644 index 0000000..899191d --- /dev/null +++ b/CONTRIBUTING.rst @@ -0,0 +1,128 @@ +.. highlight:: shell + +============ +Contributing +============ + +Contributions are welcome, and they are greatly appreciated! Every little bit +helps, and credit will always be given. + +You can contribute in many ways: + +Types of Contributions +---------------------- + +Report Bugs +~~~~~~~~~~~ + +Report bugs at https://github.com/cguardia/questions/issues. + +If you are reporting a bug, please include: + +* Your operating system name and version. +* Any details about your local setup that might be helpful in troubleshooting. +* Detailed steps to reproduce the bug. + +Fix Bugs +~~~~~~~~ + +Look through the GitHub issues for bugs. Anything tagged with "bug" and "help +wanted" is open to whoever wants to implement it. + +Implement Features +~~~~~~~~~~~~~~~~~~ + +Look through the GitHub issues for features. Anything tagged with "enhancement" +and "help wanted" is open to whoever wants to implement it. + +Write Documentation +~~~~~~~~~~~~~~~~~~~ + +Questions could always use more documentation, whether as part of the +official Questions docs, in docstrings, or even on the web in blog posts, +articles, and such. + +Submit Feedback +~~~~~~~~~~~~~~~ + +The best way to send feedback is to file an issue at https://github.com/cguardia/questions/issues. + +If you are proposing a feature: + +* Explain in detail how it would work. +* Keep the scope as narrow as possible, to make it easier to implement. +* Remember that this is a volunteer-driven project, and that contributions + are welcome :) + +Get Started! +------------ + +Ready to contribute? Here's how to set up `questions` for local development. + +1. Fork the `questions` repo on GitHub. +2. Clone your fork locally:: + + $ git clone git@github.com:cguardia/questions.git + +3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: + + $ mkvirtualenv questions + $ cd questions/ + $ python setup.py develop + +4. Create a branch for local development:: + + $ git checkout -b name-of-your-bugfix-or-feature + + Now you can make your changes locally. + +5. When you're done making changes, check that your changes pass flake8 and the + tests, including testing other Python versions with tox:: + + $ flake8 questions tests + $ python setup.py test or pytest + $ tox + + To get flake8 and tox, just pip install them into your virtualenv. + +6. Commit your changes and push your branch to GitHub:: + + $ git add . + $ git commit -m "Your detailed description of your changes." + $ git push origin name-of-your-bugfix-or-feature + +7. Submit a pull request through the GitHub website. + +Pull Request Guidelines +----------------------- + +Before you submit a pull request, check that it meets these guidelines: + +1. The pull request should include tests. +2. If the pull request adds functionality, the docs should be updated. Put + your new functionality into a function with a docstring, and add the + feature to the list in README.rst. +3. The pull request should work for Python 3.5, 3.6, 3.7 and 3.8, and for PyPy. Check + https://travis-ci.com/cguardia/questions/pull_requests + and make sure that the tests pass for all supported Python versions. + +Tips +---- + +To run a subset of tests:: + +$ pytest tests.test_questions + + +Deploying +--------- + +A reminder for the maintainers on how to deploy. +Make sure all your changes are committed (including an entry in HISTORY.rst). +Then run:: + +$ bump2version patch # possible: major / minor / patch +$ git push +$ git push --tags + +Travis will then deploy to PyPI if tests pass. diff --git a/HISTORY.rst b/HISTORY.rst new file mode 100644 index 0000000..daca7cd --- /dev/null +++ b/HISTORY.rst @@ -0,0 +1,8 @@ +======= +History +======= + +0.1.0 (2020-08-15) +------------------ + +* First release on PyPI. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..70e2597 --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2020, Carlos de la Guardia + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..965b2dd --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,11 @@ +include AUTHORS.rst +include CONTRIBUTING.rst +include HISTORY.rst +include LICENSE +include README.rst + +recursive-include tests * +recursive-exclude * __pycache__ +recursive-exclude * *.py[co] + +recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..0fb87e4 --- /dev/null +++ b/Makefile @@ -0,0 +1,88 @@ +.PHONY: clean clean-test clean-pyc clean-build docs help +.DEFAULT_GOAL := help + +define BROWSER_PYSCRIPT +import os, webbrowser, sys + +from urllib.request import pathname2url + +webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) +endef +export BROWSER_PYSCRIPT + +define PRINT_HELP_PYSCRIPT +import re, sys + +for line in sys.stdin: + match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) + if match: + target, help = match.groups() + print("%-20s %s" % (target, help)) +endef +export PRINT_HELP_PYSCRIPT + +BROWSER := python -c "$$BROWSER_PYSCRIPT" + +help: + @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) + +clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts + +clean-build: ## remove build artifacts + rm -fr build/ + rm -fr dist/ + rm -fr .eggs/ + find . -name '*.egg-info' -exec rm -fr {} + + find . -name '*.egg' -exec rm -f {} + + +clean-pyc: ## remove Python file artifacts + find . -name '*.pyc' -exec rm -f {} + + find . -name '*.pyo' -exec rm -f {} + + find . -name '*~' -exec rm -f {} + + find . -name '__pycache__' -exec rm -fr {} + + +clean-test: ## remove test and coverage artifacts + rm -fr .tox/ + rm -f .coverage + rm -fr htmlcov/ + rm -fr .pytest_cache + +lint: ## check style with flake8 + flake8 questions tests + +black: ## format code with black + black --check questions tests + +test: ## run tests quickly with the default Python + pytest + +test-all: ## run tests on every Python version with tox + tox + +coverage: ## check code coverage quickly with the default Python + coverage run --source questions -m pytest + coverage report -m + coverage html + $(BROWSER) htmlcov/index.html + +docs: ## generate Sphinx HTML documentation, including API docs + rm -f docs/questions.rst + rm -f docs/modules.rst + sphinx-apidoc -o docs/ questions + $(MAKE) -C docs clean + $(MAKE) -C docs html + $(BROWSER) docs/_build/html/index.html + +servedocs: docs ## compile the docs watching for changes + watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . + +release: dist ## package and upload a release + twine upload dist/* + +dist: clean ## builds source and wheel package + python setup.py sdist + python setup.py bdist_wheel + ls -l dist + +install: clean ## install the package to the active Python's site-packages + python setup.py install diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..b3513bf --- /dev/null +++ b/README.rst @@ -0,0 +1,37 @@ +========= +Questions +========= + + +.. image:: https://img.shields.io/pypi/v/questions.svg + :target: https://pypi.python.org/pypi/questions + +.. image:: https://img.shields.io/travis/cguardia/questions.svg + :target: https://travis-ci.com/cguardia/questions + +.. image:: https://readthedocs.org/projects/questions/badge/?version=latest + :target: https://questions.readthedocs.io/en/latest/?badge=latest + :alt: Documentation Status + + + + +Questions is a form library that uses the power of SurveyJS for the UI. + + +* Free software: MIT license +* Documentation: https://questions.readthedocs.io. + + +Features +-------- + +* TODO + +Credits +------- + +This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template. + +.. _Cookiecutter: https://github.com/audreyr/cookiecutter +.. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..045c93a --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = python -msphinx +SPHINXPROJ = questions +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/authors.rst b/docs/authors.rst new file mode 100644 index 0000000..e122f91 --- /dev/null +++ b/docs/authors.rst @@ -0,0 +1 @@ +.. include:: ../AUTHORS.rst diff --git a/docs/conf.py b/docs/conf.py new file mode 100755 index 0000000..0c2afb5 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python +# +# questions documentation build configuration file, created by +# sphinx-quickstart on Fri Jun 9 13:47:02 2017. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another +# directory, add these directories to sys.path here. If the directory is +# relative to the documentation root, use os.path.abspath to make it +# absolute, like shown here. +# +import os +import sys +sys.path.insert(0, os.path.abspath('..')) + +import questions + +# -- General configuration --------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'Questions' +copyright = "2020, Carlos de la Guardia" +author = "Carlos de la Guardia" + +# The version info for the project you're documenting, acts as replacement +# for |version| and |release|, also used in various other places throughout +# the built documents. +# +# The short X.Y version. +version = questions.__version__ +# The full version, including alpha/beta/rc tags. +release = questions.__version__ + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'alabaster' + +# Theme options are theme-specific and customize the look and feel of a +# theme further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + + +# -- Options for HTMLHelp output --------------------------------------- + +# Output file base name for HTML help builder. +htmlhelp_basename = 'questionsdoc' + + +# -- Options for LaTeX output ------------------------------------------ + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass +# [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'questions.tex', + 'Questions Documentation', + 'Carlos de la Guardia', 'manual'), +] + + +# -- Options for manual page output ------------------------------------ + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'questions', + 'Questions Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ---------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'questions', + 'Questions Documentation', + author, + 'questions', + 'One line description of project.', + 'Miscellaneous'), +] + + + diff --git a/docs/contributing.rst b/docs/contributing.rst new file mode 100644 index 0000000..e582053 --- /dev/null +++ b/docs/contributing.rst @@ -0,0 +1 @@ +.. include:: ../CONTRIBUTING.rst diff --git a/docs/history.rst b/docs/history.rst new file mode 100644 index 0000000..2506499 --- /dev/null +++ b/docs/history.rst @@ -0,0 +1 @@ +.. include:: ../HISTORY.rst diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..d5315aa --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,20 @@ +Welcome to Questions's documentation! +====================================== + +.. toctree:: + :maxdepth: 2 + :caption: Contents: + + readme + installation + usage + modules + contributing + authors + history + +Indices and tables +================== +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/docs/installation.rst b/docs/installation.rst new file mode 100644 index 0000000..fb5a4d7 --- /dev/null +++ b/docs/installation.rst @@ -0,0 +1,51 @@ +.. highlight:: shell + +============ +Installation +============ + + +Stable release +-------------- + +To install Questions, run this command in your terminal: + +.. code-block:: console + + $ pip install questions + +This is the preferred method to install Questions, as it will always install the most recent stable release. + +If you don't have `pip`_ installed, this `Python installation guide`_ can guide +you through the process. + +.. _pip: https://pip.pypa.io +.. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/ + + +From sources +------------ + +The sources for Questions can be downloaded from the `Github repo`_. + +You can either clone the public repository: + +.. code-block:: console + + $ git clone git://github.com/cguardia/questions + +Or download the `tarball`_: + +.. code-block:: console + + $ curl -OJL https://github.com/cguardia/questions/tarball/master + +Once you have a copy of the source, you can install it with: + +.. code-block:: console + + $ python setup.py install + + +.. _Github repo: https://github.com/cguardia/questions +.. _tarball: https://github.com/cguardia/questions/tarball/master diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..1065464 --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,36 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=python -msphinx +) +set SOURCEDIR=. +set BUILDDIR=_build +set SPHINXPROJ=questions + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The Sphinx module was not found. Make sure you have Sphinx installed, + echo.then set the SPHINXBUILD environment variable to point to the full + echo.path of the 'sphinx-build' executable. Alternatively you may add the + echo.Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% + +:end +popd diff --git a/docs/readme.rst b/docs/readme.rst new file mode 100644 index 0000000..72a3355 --- /dev/null +++ b/docs/readme.rst @@ -0,0 +1 @@ +.. include:: ../README.rst diff --git a/docs/usage.rst b/docs/usage.rst new file mode 100644 index 0000000..9320adf --- /dev/null +++ b/docs/usage.rst @@ -0,0 +1,7 @@ +===== +Usage +===== + +To use Questions in a project:: + + import questions diff --git a/questions/__init__.py b/questions/__init__.py new file mode 100644 index 0000000..89dd65f --- /dev/null +++ b/questions/__init__.py @@ -0,0 +1,51 @@ +"""Top-level package for Questions.""" + +__author__ = """Carlos de la Guardia""" +__email__ = "cguardia@yahoo.com" +__version__ = "0.1.0" + + +from .form import Form +from .form import FormPage +from .form import FormPanel +from .questions import TextQuestion +from .questions import RadioGroupQuestion +from .questions import DropdownQuestion +from .questions import CheckboxQuestion +from .questions import ImagePickerQuestion +from .questions import BooleanQuestion +from .questions import MultipleTextQuestion +from .questions import CommentQuestion +from .questions import RatingQuestion +from .questions import FileQuestion +from .questions import MatrixQuestion +from .questions import MatrixDropdownQuestion +from .questions import MatrixDynamicQuestion +from .questions import SignaturePadQuestion +from .questions import ExpressionBlock +from .questions import HtmlBlock +from .questions import ImageBlock + + +__all__ = [ + Form, + TextQuestion, + RadioGroupQuestion, + DropdownQuestion, + CheckboxQuestion, + ImagePickerQuestion, + BooleanQuestion, + SignaturePadQuestion, + MultipleTextQuestion, + CommentQuestion, + RatingQuestion, + FileQuestion, + MatrixQuestion, + MatrixDropdownQuestion, + MatrixDynamicQuestion, + HtmlBlock, + ExpressionBlock, + ImageBlock, + FormPage, + FormPanel, +] diff --git a/questions/cli.py b/questions/cli.py new file mode 100644 index 0000000..543d9de --- /dev/null +++ b/questions/cli.py @@ -0,0 +1,15 @@ +"""Console script for questions.""" +import sys +import click + + +@click.command() +def main(args=None): + """Console script for questions.""" + click.echo("Replace this message by putting your code into " "questions.cli.main") + click.echo("See click documentation at https://click.palletsprojects.com/") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) # pragma: no cover diff --git a/questions/form.py b/questions/form.py new file mode 100644 index 0000000..6e9a04b --- /dev/null +++ b/questions/form.py @@ -0,0 +1,164 @@ +from typing import Type + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal + +from .questions import Page +from .questions import PanelBlock +from .questions import PanelDynamicBlock +from .questions import Question +from .questions import Survey +from .settings import INCLUDE_KEYS +from .settings import SURVEY_JS_CDN +from .settings import SURVEY_JS_PLATFORMS +from .settings import SURVEY_JS_THEMES +from .templates import SURVEY_JS +from .templates import SURVEY_HTML +from .templates import get_form_page +from .templates import get_platform_js_resources +from .templates import get_survey_js +from .templates import get_theme_css_resources + + +class Form(object): + def __init__( + self, + name: str = "", + method: Literal[("GET", "POST")] = "POST", + action: str = "", + theme: Literal[SURVEY_JS_THEMES] = "default", + platform: Literal[SURVEY_JS_PLATFORMS] = "jquery", + resource_url: str = SURVEY_JS_CDN, + **params, + ): + if name == "": + name = self.__class__.__name__ + self.name = name + self.theme = theme + self.method = method + self.action = action + self.platform = platform + self.resource_url = resource_url + self.params = params + self._extra_js = [] + self._extra_css = [] + + def __call__(self): + return self.render_html() + + def _construct_survey(self): + self._extra_js = [] + self._extra_css = [] + default_page = Page(name="default") + pages = {"default": default_page} + survey = Survey(**self.params) + self._add_elements(survey, self, top_level=True) + return survey + + def _add_elements(self, survey, form, top_level=False, container_name="questions"): + extra_js = [] + extra_css = [] + for element_name, element in form.__class__.__dict__.items(): + if isinstance(element, (FormPage, FormPanel, Question)): + name = getattr(element, "name", "") + if name == "": + element.name = element_name + if isinstance(element, FormPage) and top_level: + page = Page(name=name, **element.params) + self._add_elements(page, element.form) + survey.pages.append(page) + elif isinstance(element, (FormPage, FormPanel)): + container = getattr(survey, container_name) + if element.dynamic: + panel = PanelDynamicBlock(name=name, **element.params) + container_name = "template_elements" + else: + panel = PanelBlock(name=name, **element.params) + container_name = "elements" + self._add_elements( + panel, element.form, container_name=container_name + ) + container.append(panel) + else: + if element.extra_js != []: + for js in element.extra_js: + if js not in extra_js and js not in self._extra_js and js not in self.required_js: + extra_js.append(js) + if element.extra_css != []: + for css in element.extra_css: + if css not in extra_css and css not in self._extra_css and css not in self.required_css: + extra_css.append(css) + container = getattr(survey, container_name) + container.append(element) + if extra_js != []: + survey_widgets = f"{self.resource_url}/surveyjs-widgets.js" + if survey_widgets not in self._extra_js: + extra_js.append(survey_widgets) + self._extra_js = self._extra_js + extra_js + self._extra_css = self._extra_css + extra_css + + @property + def extra_js(self): + self._construct_survey() + return self._extra_js + + @property + def extra_css(self): + self._construct_survey() + return self._extra_css + + @property + def required_js(self): + return get_platform_js_resources(self.platform, self.resource_url) + + @property + def required_css(self): + return get_theme_css_resources(self.theme, self.resource_url) + + @property + def js(self): + return self.required_js + self.extra_js + + @property + def css(self): + return self.required_css + self.extra_css + + def to_json(self): + survey = self._construct_survey() + return survey.json(by_alias=True, include=INCLUDE_KEYS) + + def render_js(self): + return get_survey_js(self.to_json(), self.action, self.theme, self.platform) + + def render_html(self, title=None): + if title is None: + title = self.params.get("title", self.name) + return get_form_page(title, self.platform, self.render_js(), self.js, self.css) + + +class FormPage(object): + def __init__(self, form: Type[Form], name: str = "", **params): + self.form = form() + if name == "": + name = self.__class__.__name__ + self.name = name + self.dynamic = False + self.params = params + + +class FormPanel(object): + def __init__( + self, + form: Type[Form], + name: str = "", + dynamic: bool = False, + **params, + ): + self.form = form() + if name == "": + name = self.__class__.__name__ + self.name = name + self.dynamic = dynamic + self.params = params diff --git a/questions/questions.py b/questions/questions.py new file mode 100644 index 0000000..701f657 --- /dev/null +++ b/questions/questions.py @@ -0,0 +1,564 @@ +from typing import Any +from typing import Dict +from typing import List +from typing import Union +from pydantic import BaseModel +from pydantic import Extra +from pydantic import HttpUrl + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal + +from . import settings + + +class Base(BaseModel): + class Config: + + fields = { + "kind": "type", + "all_rows_required": "isAllRowRequired", + "expression_format": "format", + "max_value": "max", + "min_value": "min", + } + + @classmethod + def fix_name(cls, name): + words = name.split("_") + name = "" + for index, word in enumerate(words): + if index == 0: + name += word + else: + name += word.capitalize() + return name + + extra = Extra.allow + alias_generator = fix_name + + +class Validator(Base): + kind: str + + +class Question(Base): + kind: str + name: str = "" + title: str = "" + description: str = "" + is_required: bool = False + visible: bool = True + default_value: str = "" + correct_answer: str = "" + visible_if: str = "" + enable_if: str = "" + start_with_new_line: bool = True + value_name: str = "" + required_if: str = "" + required_error_text: str = "" + hide_number: bool = True + indent: int = 0 + title_location: Literal[settings.TITLE_LOCATIONS] = "default" + description_location: Literal[settings.DESCRIPTION_LOCATIONS] = "default" + width: str = "100%" + max_width: str = "initial" + min_width: str = "300px" + use_display_values_in_title: bool = True + validators: List[Validator] = [] + extra_js: List[HttpUrl] = [] + extra_css: List[HttpUrl] = [] + + +class TextQuestion(Question): + kind: str = "text" + place_holder: str = "" + input_type: Literal[settings.TEXT_INPUT_TYPES] = "text" + max_length: int = -1 + max_value: str = "" + min_value: str = "" + size: int = 0 + step: str = "" + text_update_mode: Literal[settings.TEXT_UPDATE_MODES] = "default" + input_mask: str = "none" + input_format: str = "" + prefix: str = "" + auto_unmask: bool = True + extra_js: List[HttpUrl] = [ + "https://unpkg.com/jquery", + "https://unpkg.com/inputmask@5.0.3/dist/inputmask.js", + ] + + +class ChoicesQuestion(Question): + kind: str = "" + col_count: int = 4 + choices: List[Union[str, Dict[str, Union[str, HttpUrl]]]] + choices_by_url: Dict[Literal[settings.CHOICES_BY_URL_KEYS], str] = [] + choices_order: Literal[settings.CHOICE_ORDER_VALUES] = "none" + choices_enable_if: str = "" + choices_visible_if: str = "" + hide_if_choices_empty: bool = True + has_other: bool = False + other_text: str = "Other" + other_error_text: str = "" + other_place_holder: str = "" + none_text: str = "None" + + +class RadioGroupQuestion(ChoicesQuestion): + kind: str = "radiogroup" + show_clear_button: bool = False + + +class DropdownQuestion(ChoicesQuestion): + kind: str = "dropdown" + choices_max: int = 0 + choices_min: int = 0 + choices_step: int = 1 + options_caption: str = "" + show_options_caption: bool = True + + +class CheckboxQuestion(ChoicesQuestion): + kind: str = "checkbox" + has_none: bool = False + has_select_all: bool = False + select_all_text: str = "" + + +class ImagePickerQuestion(ChoicesQuestion): + kind: str = "imagepicker" + content_mode: Literal[settings.IMAGE_CONTENT_MODE_VALUES] = "image" + show_label: bool = False + image_height: int = 200 + image_width: int = 300 + image_fit: Literal[settings.IMAGE_FIT_VALUES] = "none" + multi_select: bool = False + has_other: bool = False + other_text: str = "Other" + other_error_text: str = "" + other_place_holder: str = "" + + +class BooleanQuestion(Question): + kind: str = "boolean" + label_true: str = "" + label_false: str = "" + show_title: bool = False + value_true: str = "true" + value_false: str = "false" + + +class SignaturePadQuestion(Question): + kind: str = "signaturepad" + height: int = 200 + width: int = 300 + allow_clear: bool = False + + +class MultipleTextQuestion(Question): + kind: str = "multipletext" + col_count: int = 2 + items: List[Dict[str, str]] = [] + item_size: int = 0 + + +class CommentQuestion(Question): + kind: str = "comment" + rows: int = 3 + cols: int = 50 + max_length: int = -1 + place_holder: str = "" + text_update_mode: Literal[settings.TEXT_UPDATE_MODES] = "default" + + +class RatingQuestion(Question): + kind: str = "rating" + min_rate_description: str = "" + max_rate_description: str = "" + rate_max: int = 5 + rate_min: int = 1 + rate_step: int = 1 + rate_values: List[Union[int, Dict[str, Union[int, str]]]] = [] + + +class FileQuestion(Question): + kind: str = "file" + show_preview: bool = True + allow_multiple: bool = False + store_data_as_text: bool = True + image_height: int = 100 + image_width: int = 150 + max_size: int = 0 + accepted_types: str = "" + allow_images_preview: bool = True + need_confirm_remove_file: bool = False + wait_for_upload: bool = True + + +class MatrixQuestion(Question): + kind: str = "matrix" + columns: List[Dict[Union[int, str], str]] + rows: List[Dict[Union[int, str], str]] + all_rows_required: bool = False + cells: Dict[str, Dict[str, str]] + columns_visible_if: str = "" + rows_order: Literal[settings.ROW_ORDER_VALUES] + rows_visible_if: str = "" + show_header: bool = True + + +class MatrixDropdownQuestion(Question): + kind: str = "matrixdropdown" + columns: List[Dict[Union[int, str], Any]] + rows: List[Dict[Union[int, str], str]] + all_rows_required: bool = False + cells: Dict[str, Dict[str, Any]] + columns_visible_if: str = "" + rows_order: Literal[settings.ROW_ORDER_VALUES] + rows_visible_if: str = "" + show_header: bool = True + cell_type: Literal[settings.MATRIX_CELL_TYPES] = "dropdown" + choices: List[Any] = [] + column_col_count: int = 1 + column_layout: Literal[settings.MATRIX_COLUMN_LAYOUTS] = "horizontal" + column_min_width: str = "" + horizontal_scroll: bool = False + options_caption: str = "" + row_title_width: str = "" + total_text: str = "" + + +class MatrixDynamicQuestion(Question): + kind: str = "matrixdynamic" + columns: List[Dict[Union[int, str], Any]] + rows: List[Dict[Union[int, str], str]] + all_rows_required: bool = False + cells: Dict[str, Dict[str, Any]] + columns_visible_if: str = "" + rows_order: Literal[settings.ROW_ORDER_VALUES] + rows_visible_if: str = "" + show_header: bool = True + cell_type: Literal[settings.MATRIX_CELL_TYPES] = "dropdown" + choices: List[Any] = [] + column_col_count: int = 1 + column_layout: Literal[settings.MATRIX_COLUMN_LAYOUTS] = "horizontal" + column_min_width: str = "" + horizontal_scroll: bool = False + options_caption: str = "" + add_row_location: Literal[settings.MATRIX_ROW_LOCATIONS] = "default" + add_row_text: str = "" + allow_add_rows: bool = True + allow_remove_rows: bool = True + confirm_delete: bool = False + confirm_delete_text: str = "" + default_row_value: Any = "" + default_value_from_last_row: bool = False + key_duplication_error: str = "" + key_name: str = "" + max_row_count: int = 100 + min_row_count: int = 1 + remove_row_text: str = "" + row_count: int = 1 + + +class TagBoxQuestion(DropdownQuestion): + kind: str = "tagbox" + select2_config: str = "" + extra_js: List[HttpUrl] = [ + "https://unpkg.com/jquery", + "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js", + ] + extra_css: List[HttpUrl] = [ + "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css", + ] + + +class JQueryUIDatePicker(TextQuestion): + kind: str = "datepicker" + date_format: str = "mm/dd/yy" + config: str = "" + max_date: str = "" + min_date: str = "" + extra_js: List[HttpUrl] = [ + "https://unpkg.com/jquery", + "https://code.jquery.com/ui/1.11.4/jquery-ui.min.js", + ] + extra_css: List[HttpUrl] = [ + "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/smoothness/jquery-ui.css", + ] + + +class BootstrapDatePicker(TextQuestion): + kind: str = "bootstrapdatepicker" + date_format: str = "mm/dd/yy" + start_date: str = "" + end_date: str = "" + today_highlight: bool = True + week_start: int = 0 + clear_button: bool = False + auto_close: bool = True + days_of_week_highlighted: str = "" + disable_touch_keyboard: bool = True + extra_js: List[HttpUrl] = [ + "https://unpkg.com/jquery", + "https://unpkg.com/moment@2.24.0/moment.js", + "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.js", + ] + extra_css: List[HttpUrl] = [ + "https://unpkg.com/bootstrap@3.3.7/dist/css/bootstrap.min.css", + "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css", + ] + + +class Select2Question(DropdownQuestion): + render_as: "select2" + select2_config: str = "" + extra_js: List[HttpUrl] = [ + "https://unpkg.com/jquery", + "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js", + ] + extra_css: List[HttpUrl] = [ + "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css", + ] + + +class BarRatingQuestion(DropdownQuestion): + kind: str = "barrating" + rating_theme: Literal[settings.BAR_RATING_THEMES] = "fontawesome-stars" + show_values: bool = False + extra_js: List[HttpUrl] = [ + "https://unpkg.com/jquery", + "https://unpkg.com/jquery-bar-rating", + ] + extra_css: List[HttpUrl] = [ + "https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css", + "https://unpkg.com/jquery-bar-rating@1.2.2/dist/themes/bars-1to10.css", + "https://unpkg.com/jquery-bar-rating@1.2.2/dist/themes/bars-movie.css", + "https://unpkg.com/jquery-bar-rating@1.2.2/dist/themes/bars-pill.css", + "https://unpkg.com/jquery-bar-rating@1.2.2/dist/themes/bars-reversed.css", + "https://unpkg.com/jquery-bar-rating@1.2.2/dist/themes/bars-horizontal.css", + "https://unpkg.com/jquery-bar-rating@1.2.2/dist/themes/fontawesome-stars.css", + "https://unpkg.com/jquery-bar-rating@1.2.2/dist/themes/css-stars.css", + "https://unpkg.com/jquery-bar-rating@1.2.2/dist/themes/fontawesome-stars-o.css", + ] + + +class SortableJSQuestion(CheckboxQuestion): + kind: str = "sortablelist" + empty_text: str = "" + max_answers_count: int = -1 + extra_js: List[HttpUrl] = [ + "https://unpkg.com/jquery", + "https://unpkg.com/sortablejs@1.7.0/Sortable.js", + ] + + +class NoUISliderQuestion(Question): + kind: str = "nouislider" + step: int = 1 + range_min: int = 0 + range_max: int = 100 + pips_mode: str = "positions" + pips_values: List[int] = [0, 25, 50, 75, 100] + pips_text: List[Union[int, str]] = [0, 25, 50, 75, 100] + pips_density: int = 5 + orientation: str = "horizontal" + direction: str = "ltr" + tooltips: bool = True + extra_js: List[HttpUrl] = [ + "https://unpkg.com/jquery", + "https://unpkg.com/nouislider@9.2.0/distribute/nouislider.js", + "https://unpkg.com/wnumb@1.1.0", + ] + extra_css: List[HttpUrl] = [ + "https://unpkg.com/nouislider@9.2.0/distribute/nouislider.min.css", + ] + + +class CKEditorQuestion(Question): + kind: str = "editor" + height: str = "300px" + extra_js: List[HttpUrl] = [ + "https://unpkg.com/jquery", + "https://cdn.ckeditor.com/4.14.1/standard/ckeditor.js", + ] + + +class BootstrapSliderQuestion(Question): + kind: str = "bootstrpslider" + step: int = 1 + range_min: int = 0 + range_max: int = 100 + extra_js: List[HttpUrl] = [ + "https://unpkg.com/jquery", + "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/10.0.0/bootstrap-slider.js", + ] + extra_css: List[HttpUrl] = [ + "https://unpkg.com/bootstrap@3.3.7/dist/css/bootstrap.min.css", + "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/10.0.0/css/bootstrap-slider.css", + ] + + +class EmotionsRatingQuestion(DropdownQuestion): + kind: str = "emotionsratings" + emotions: List[str] = ["angry", "disappointed", "meh", "happy", "inLove"] + emotion_size: int = 30 + emotions_count: int = 5 + bg_emotion: str = "happy" + emotion_color: str = "FF0066" + extra_js: List[HttpUrl] = [ + "https://unpkg.com/jquery", + "https://unpkg.com/emotion-ratings@2.0.1/dist/emotion-ratings.js", + ] + + +class MicrophoneQuestion(Question): + kind: str = "microphone" + extra_js: List[HttpUrl] = [ + "https://www.WebRTC-Experiment.com/RecordRTC.js", + ] + +class HtmlBlock(Question): + kind: str = "html" + html: str = "" + + +class ImageBlock(Question): + kind: str = "image" + image_height: int = 200 + image_width: int = 300 + image_fit: Literal[settings.IMAGE_FIT_VALUES] = "none" + image_link: HttpUrl + content_mode: Literal[settings.IMAGE_CONTENT_MODE_VALUES] = "image" + + +class ExpressionBlock(Question): + kind: str = "expression" + expression: str + currency: str = "USD" + display_style: Literal[settings.EXPRESSION_DISPLAY_STYLES] = "none" + expression_format: str = "" + maximum_fraction_digits: int = -1 + minimum_fraction_digits: int = -1 + use_grouping: bool = True + + +class PanelBlock(Question): + kind: str = "panel" + inner_indent: int = 1 + elements: List[Question] = [] + question_start_index: str = "" + question_title_location: Literal[settings.TITLE_LOCATIONS] = "default" + show_number: bool = False + show_question_numbers: Literal[settings.SHOW_QUESTION_NUMBERS_VALUES] = "default" + state: Literal[settings.PANEL_STATES] = "default" + + +class PanelDynamicBlock(Question): + kind: str = "paneldynamic" + inner_indent: int = 1 + render_mode: Literal[settings.PANEL_RENDER_MODES] = "list" + panel_count: int = 1 + panel_add_text: str = "" + panel_remove_text: str = "" + template_title: str = "" + template_elements: List[Question] = [] + allow_add_panel: bool = True + allow_remove_panel: bool = True + confirm_delete: bool = False + confirm_delete_text: str = "" + default_value_from_last_panel: bool = False + key_duplication_error: str = "" + key_name: str = "" + max_panel_count: int = 100 + min_panel_count: int = 1 + panel_add_text: str = "" + panel_next_text: str = "" + panel_prev_text: str = "" + panel_remove_text: str = "" + panels_state: Literal[settings.PANEL_STATES] = "default" + show_question_numbers: Literal[settings.SHOW_QUESTION_NUMBERS_VALUES] = "default" + show_range_in_progress: bool = True + template_description: str = "" + template_title_location: Literal[settings.TITLE_LOCATIONS] = "default" + + +class Page(Base): + name: str = "" + title: str = "" + questions: List[Question] = [] + description: str = "" + max_time_to_finish: int = 0 + navigation_buttons_visibility: Literal[settings.NAV_BUTTONS_VISIBILITY] = "inherit" + question_title_location: Literal[settings.TITLE_LOCATIONS] = "default" + questions_order: Literal[settings.QUESTION_ORDER_VALUES] = "default" + + +class Survey(Base): + title: str + pages: List[Page] = [] + calculated_values: List[Any] = [] + check_errors_mode: Literal[settings.CHECK_ERRORS_MODES] = "onNextPage" + clear_invisible_values: Literal[settings.CLEAR_INVISIBLE_VALUES] = "onComplete" + completed_before_html: str = "" + completed_html: str = "" + completed_html_on_condition: List[Dict[str, str]] = [] + complete_text: str = "" + cookie_name: str = "" + description: str = "" + edit_text: str = "" + first_page_is_started: bool = False + focus_first_question_automatic: bool = True + focus_on_first_error: bool = True + go_next_page_automatic: bool = True + loading_html: str = "" + locale: Literal[settings.LOCALES] = "" + logo: HttpUrl = "" + logo_fit: Literal[settings.IMAGE_FIT_VALUES] = "contain" + logo_height: int = 200 + logo_position: Literal[settings.LOGO_POSITIONS] = "left" + logo_width: int = 300 + max_others_length: int = 0 + max_text_length: int = 0 + max_time_to_finish: int = 0 + mode: Literal[settings.SURVEY_MODES] = "edit" + navigate_to_url: HttpUrl = "" + navigate_to_url_on_condition: List[Dict[str, HttpUrl]] = [] + page_next_text: str = "" + page_prev_text: str = "" + preview_text: str = "" + progress_bar_type: Literal[settings.PROGRESS_BAR_TYPES] = "pages" + question_description_location: Literal[ + settings.QUESTION_DESCRIPTION_LOCATIONS + ] = "underTitle" + question_error_location: Literal[settings.QUESTION_ERROR_LOCATIONS] = "top" + questions_on_page_mode: Literal[settings.QUESTION_PAGE_MODES] = "standard" + questions_order: Literal[settings.QUESTION_ORDER_VALUES] = "initial" + question_start_index: str = "" + question_title_location: Literal[settings.TITLE_LOCATIONS] = "top" + question_title_pattern: str = "numTitleRequire" + question_title_template: str = "" + required_text: str = "*" + send_result_on_page_next: bool = False + show_completed_page: bool = False + show_navigation_buttons: Literal[settings.NAV_BUTTONS_POSITIONS] = "bottom" + show_page_numbers: bool = True + show_page_titles: bool = True + show_prev_button: bool = True + show_preview_before_complete: Literal[settings.SHOW_PREVIEW_VALUES] = "noPreview" + show_progress_bar: Literal[settings.SHOW_PROGRESS_BAR_OPTIONS] = "off" + show_question_numbers: Literal[settings.PAGE_SHOW_QUESTION_NUMBERS_VALUES] = "on" + show_timer_panel: Literal[settings.SHOW_TIMER_VALUES] = "none" + show_timer_panel_mode: Literal[settings.SHOW_TIMER_MODES] = "all" + show_title: bool = True + start_survey_text: str = "" + store_others_as_comment: bool = True + survey_id: str = "" + survey_post_id: str = "" + survey_show_data_saving: bool = True + text_update_mode: Literal[settings.TEXT_UPDATE_MODES] = "onBlur" + triggers: List[Any] = [] diff --git a/questions/settings.py b/questions/settings.py new file mode 100644 index 0000000..eed16e8 --- /dev/null +++ b/questions/settings.py @@ -0,0 +1,582 @@ +SURVEY_JS_VERSION = "1.8.2" + +SURVEY_JS_CDN = f"https://surveyjs.azureedge.net/{SURVEY_JS_VERSION}" + +SURVEY_JS_WIDGETS = "surveyjs-widgets.js" + +SURVEY_JS_PLATFORMS = ( + "angular", + "jquery", + "ko", + "react", + "vue", +) + +SUGGESTED_JS_BY_PLATFORM = { + "angular": [ + "https://npmcdn.com/zone.js", + "https://npmcdn.com/core-js@2.6.5/client/shim.min.js", + "https://npmcdn.com/rxjs@5.0.0-beta.6/bundles/Rx.umd.js", + "https://npmcdn.com/@angular/core@2.0.0-rc.5/bundles/core.umd.js", + "https://npmcdn.com/@angular/common@2.0.0-rc.5/bundles/common.umd.js", + "https://npmcdn.com/@angular/compiler@2.0.0-rc.5/bundles/compiler.umd.js", + "https://npmcdn.com/@angular/platform-browser@2.0.0-rc.5/bundles/platform-browser.umd.js", + "https://npmcdn.com/@angular/platform-browser-dynamic@2.0.0-rc.5/bundles/platform-browser-dynamic.umd.js", + ], + "jquery": [ + "https://unpkg.com/jquery", + ], + "ko": [ + "https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js", + ], + "react": [ + "https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/7.6.0/polyfill.js", + "https://unpkg.com/react@15/dist/react.js", + "https://unpkg.com/react-dom@15/dist/react-dom.js", + "https://unpkg.com/@babel/standalone@7.2.5/babel.min.js", + ], + "vue": [ + "https://unpkg.com/vue/dist/vue.js", + ], +} + +BOOTSTRAP_URL = "https://unpkg.com/bootstrap@3.3.7/dist/css/bootstrap.min.css" + +INCLUDE_KEYS = { + "pages": { + "__all__": { + "name": ..., + "questions": { + "__all__": { + "accepted_types": ..., + "add_row_location": ..., + "add_row_text": ..., + "allow_add_panel": ..., + "allow_add_rows": ..., + "allow_remove_panel": ..., + "allow_remove_rows": ..., + "allow_clear": ..., + "allow_images_preview": ..., + "allow_multiple": ..., + "all_rows_required": ..., + "auto_close": ..., + "auto_unmask": ..., + "bg_emotion": ..., + "cells": ..., + "cell_type": ..., + "choices": ..., + "choices_by_url": ..., + "choices_enable_if": ..., + "choices_max": ..., + "choices_min": ..., + "choices_order": ..., + "choices_step": ..., + "choices_visible_if": ..., + "clear_button": ..., + "columns": ..., + "columns_visible_if": ..., + "column_col_count": ..., + "column_layout": ..., + "column_min_width": ..., + "cols": ..., + "col_count": ..., + "config": ..., + "confirm_delete": ..., + "confirm_delete_text": ..., + "content_mode": ..., + "correct_answer": ..., + "currency": ..., + "date_format": ..., + "days_of_week_highlighted": ..., + "default_row_value": ..., + "default_value": ..., + "default_value_from_last_panel": ..., + "default_value_from_last_row": ..., + "description": ..., + "description_location": ..., + "direction": ..., + "disable_touch_keyboard": ..., + "display_style": ..., + "elements": ..., + "emotion_color": ..., + "emotion_size": ..., + "emotions": ..., + "emotions_count": ..., + "empty_text": ..., + "enable_if": ..., + "end_date": ..., + "expression": ..., + "expression_format": ..., + "has_none": ..., + "has_other": ..., + "has_select_all": ..., + "height": ..., + "hide_if_choices_empty": ..., + "hide_number": ..., + "horizontal_scroll": ..., + "html": ..., + "image_fit": ..., + "image_height": ..., + "image_width": ..., + "indent": ..., + "inner_indent": ..., + "input_format": ..., + "input_mask": ..., + "input_type": ..., + "is_required": ..., + "items": ..., + "item_size": ..., + "key_duplication_error": ..., + "key_name": ..., + "kind": ..., + "label_false": ..., + "label_true": ..., + "maximum_fraction_digits": ..., + "max_answers_count": ..., + "max_date": ..., + "max_length": ..., + "max_panel_count": ..., + "max_rate_description": ..., + "max_row_count": ..., + "max_size": ..., + "max_value": ..., + "max_width": ..., + "minimum_fraction_digits": ..., + "min_date": ..., + "min_panel_count": ..., + "min_rate_description": ..., + "min_row_count": ..., + "min_width": ..., + "min_value": ..., + "multi_select": ..., + "name": ..., + "need_confirm_remove_file": ..., + "none_text": ..., + "orientation": ..., + "options_caption": ..., + "other_text": ..., + "other_error_text": ..., + "other_place_holder": ..., + "panel_add_text": ..., + "panel_count": ..., + "panel_next_text": ..., + "panel_prev_text": ..., + "panel_remove_text": ..., + "panels_state": ..., + "pips_mode": ..., + "pips_density": ..., + "pips_text": ..., + "pips_values": ..., + "place_holder": ..., + "prefix": ..., + "question_start_index": ..., + "question_title_location": ..., + "range_max": ..., + "range_min": ..., + "rate_max": ..., + "rate_min": ..., + "rate_step": ..., + "rating_theme": ..., + "remove_row_text": ..., + "render_as": ..., + "render_mode": ..., + "required_error_text": ..., + "required_if": ..., + "rows": ..., + "rows_order": ..., + "rows_visible_if": ..., + "row_count": ..., + "row_title_width": ..., + "select_all_text": ..., + "select2_config": ..., + "show_clear_button": ..., + "show_header": ..., + "show_label": ..., + "show_number": ..., + "show_options_caption": ..., + "show_preview": ..., + "show_question_numbers": ..., + "show_range_in_progress": ..., + "show_title": ..., + "show_values": ..., + "size": ..., + "start_date": ..., + "start_with_new_line": ..., + "state": ..., + "step": ..., + "store_data_as_text": ..., + "template_elements": ..., + "template_description": ..., + "template_title": ..., + "template_title_location": ..., + "text_update_mode": ..., + "title": ..., + "title_location": ..., + "today_highlight": ..., + "tooltips": ..., + "total_text": ..., + "use_display_values_in_title": ..., + "use_grouping": ..., + "validators": ..., + "value_false": ..., + "value_name": ..., + "value_true": ..., + "visible": ..., + "visible_if": ..., + "wait_for_upload": ..., + "week_start": ..., + "width": ..., + } + }, + "title": ..., + "max_time_to_finish": ..., + "navigation_buttons_visibility": ..., + "question_title_location": ..., + "questions_order": ..., + } + }, + "title": ..., + "calculated_values": ..., + "check_errors_mode": ..., + "clear_invisible_values": ..., + "completed_before_html": ..., + "completed_html": ..., + "completed_html_on_condition": ..., + "complete_text": ..., + "cookie_name": ..., + "description": ..., + "edit_text": ..., + "first_page_is_started": ..., + "focus_first_question_automatic": ..., + "focus_on_first_error": ..., + "go_next_page_automatic": ..., + "loading_html": ..., + "locale": ..., + "logo": ..., + "logo_fit": ..., + "logo_height": ..., + "logo_position": ..., + "logo_width": ..., + "max_others_length": ..., + "max_text_length": ..., + "max_time_to_finish": ..., + "max_time_to_finish_page": ..., + "mode": ..., + "question_title_location": ..., + "questions_order": ..., + "navigate_to_url": ..., + "navigate_to_url_on_condition": ..., + "page_next_text": ..., + "page_prev_text": ..., + "preview_text": ..., + "progress_bar_type": ..., + "questions_on_page_mode": ..., + "question_description_location": ..., + "question_error_location": ..., + "question_start_index": ..., + "question_title_location": ..., + "question_title_pattern": ..., + "question_title_template": ..., + "required_text": ..., + "send_result_on_page_next": ..., + "show_completed_page": ..., + "show_navigation_buttons": ..., + "show_page_numbers": ..., + "show_page_titles": ..., + "show_prev_button": ..., + "show_preview_before_complete": ..., + "show_progress_bar": ..., + "show_question_numbers": ..., + "show_timer_panel": ..., + "show_timer_panel_mode": ..., + "show_title": ..., + "start_survey_text": ..., + "store_others_as_comment": ..., + "survey_id": ..., + "survey_post_id": ..., + "survey_show_data_saving": ..., + "text_update_mode": ..., + "triggers": ..., +} + +TEXT_INPUT_TYPES = ( + "color", + "date", + "datetime", + "datetime-local", + "email", + "month", + "number", + "password", + "range", + "tel", + "text", + "time", + "url", + "week", +) + +LOCALES = ( + "ar", + "bg", + "ca", + "cs", + "da", + "de", + "en", + "es", + "et", + "fa", + "fi", + "fr", + "gr", + "he", + "hu", + "id", + "is", + "it", + "ja", + "ka", + "ko", + "lt", + "lv", + "nl", + "no", + "pl", + "pt", + "ro", + "ru", + "sv", + "sw", + "tg", + "th", + "tr", + "ua", + "zh-cn", + "zh-tw", +) + +CHOICE_ORDER_VALUES = ( + "none", + "asc", + "desc", + "random", +) + +CHOICES_BY_URL_KEYS = ( + "path", + "titleName", + "url", + "valueName", +) + +IMAGE_FIT_VALUES = ( + "contain", + "none", + "cover", + "fill", +) + +IMAGE_CONTENT_MODE_VALUES = ( + "image", + "video", +) + +PANEL_RENDER_MODES = ( + "progressTop", + "progressBottom", +) + +DESCRIPTION_LOCATIONS = ( + "default", + "underInput", + "underTitle", +) + +TITLE_LOCATIONS = ( + "default", + "top", + "bottom", + "left", + "hidden", +) + +CHECK_ERRORS_MODES = ( + "onNextPage", + "onValueCHanged", + "onComplete", +) + +TEXT_UPDATE_MODES = ( + "default", + "onBlur", + "onTyping", +) + +EXPRESSION_DISPLAY_STYLES = ( + "none", + "decimal", + "currency", + "percent", + "date", +) + +SHOW_QUESTION_NUMBERS_VALUES = ( + "default", + "onpanel", + "off", +) + +PANEL_STATES = ( + "default", + "collapsed", + "expanded", + "firstExpanded", +) + +QUESTION_ORDER_VALUES = ( + "default", + "initial", + "random", +) + +NAV_BUTTONS_VISIBILITY = ( + "inherit", + "show", + "hide", +) + +NAV_BUTTONS_POSITIONS = ( + "none", + "top", + "bottom", + "both", +) + +CLEAR_INVISIBLE_VALUES = ( + "none", + "onHidden", + "onComplete", +) + +LOGO_POSITIONS = ( + "none", + "left", + "right", + "top", + "bottom", +) + +PROGRESS_BAR_TYPES = ( + "pages", + "questions", + "correctQuestions", +) + +SURVEY_MODES = ( + "edit", + "display", +) + +QUESTION_DESCRIPTION_LOCATIONS = ( + "underTitle", + "underInput", +) + +QUESTION_ERROR_LOCATIONS = ( + "top", + "bottom", +) + +QUESTION_PAGE_MODES = ( + "standard", + "singlePage", + "questionPerPage", +) + +PAGE_SHOW_QUESTION_NUMBERS_VALUES = ( + "on", + "onpage", + "off", +) + +SHOW_PROGRESS_BAR_OPTIONS = ( + "off", + "top", + "bottom", + "both", +) + +SHOW_PREVIEW_VALUES = ( + "noPreview", + "showAllQuestions", + "showAnsweredQuestions", +) + +SHOW_TIMER_VALUES = ( + "none", + "top", + "bottom", +) + +SHOW_TIMER_MODES = ( + "page", + "survey", + "all", +) + +SURVEY_TEXT_UPDATE_MODES = ( + "onBlur", + "onTyping", +) + +ROW_ORDER_VALUES = ( + "initial", + "random", +) + +MATRIX_CELL_TYPES = ( + "dropdown", + "checkbox", + "radiogroup", + "text", + "comment", + "boolean", + "expression", + "rating", +) + +MATRIX_COLUMN_LAYOUTS = ( + "horizontal", + "vertical", +) + +MATRIX_ROW_LOCATIONS = ( + "default", + "top", + "bottom", + "topBottom", +) + +SURVEY_JS_THEMES = ( + "default", + "bootstrap", + "orange", + "darkblue", + "darkrose", + "stone", + "winter", + "winterstone", + "modern", +) + +BAR_RATING_THEMES = ( + "fontawesome-stars", + "css-stars", + "bars-pill", + "bars-1to10", + "bars-movie", + "bars-reversed", + "bars-horizontal", + "fontawesome-stars-o", +) diff --git a/questions/templates.py b/questions/templates.py new file mode 100644 index 0000000..32a8aa1 --- /dev/null +++ b/questions/templates.py @@ -0,0 +1,200 @@ +from .settings import BOOTSTRAP_URL +from .settings import SUGGESTED_JS_BY_PLATFORM +from .settings import SURVEY_JS_CDN + + +SURVEY_JS = """ +Survey + .StylesManager + .applyTheme('{}'); + +var json = {}; + +var sendDataToServer = function(result) {{ + +fetch('{}', {{ + method: 'post', + headers: {{ + 'Accept': 'application/json, text/plain, */*', + 'Content-Type': 'application/json' + }}, + body: 'json=' + encodeURIComponent(JSON.stringify(result)) +}}) +.then(function (response) {{ + return response.json(); +}}) +.then(function (result) {{ + alert(result); +}}) +.catch (function (error) {{ + console.log('Request failed', error); +}}); + +}} + +{} +""" + +PLATFORM_JS= { + "jquery": """var survey = new Survey.Model(json); +$("#questions_form").Survey({ + model:survey, + onComplete:sendDataToServer +}); +""", + "angular": """window.survey = new Survey.Model(json); +survey + .onComplete + .add(sendDataToServer); +function onAngularComponentInit() { + Survey + .SurveyNG + .render("surveyElement", {model: survey}); +} +var QuestionsApp = ng + .core + .Component({selector: 'ng-app', template: '
'}) + .Class({ + constructor: function () {}, + ngOnInit: function () { + onAngularComponentInit(); + } + }); +document.addEventListener('DOMContentLoaded', function () { + ng + .platformBrowserDynamic + .bootstrap(QuestionsApp); +}); +""", + "ko": """var survey = new Survey.Model(json, "questions_form"); +survey.onComplete.add(sendDataToServer); +""", + "react": """window.survey = new Survey.Model(json); + ReactDOM.render(, + document.getElementById("questions_form")); +""", + "vue": """var survey = new Survey.Model(json); +survey + .onComplete + .add(sendDataToServer); +new Vue({ el: '#questions_form', data: { survey: survey } }); +""", +} + +SURVEY_HTML = { + "jquery": """ + + + {} + + {} + + + +
+ + + + + +""", + "angular": """ + + + {} + + {} + + + + + + + + + +""", + "ko": """ + + + {} + + {} + + + +
+ + + + + +""", + "react": """ + + + {} + + {} + + + +
+ + + + + +""", + "vue": """ + + + {} + + {} + + + +
+ +
+ + + + + +""", +} + + +def get_platform_js_resources(platform, resource_url): + survey_js = f"{resource_url}/survey.{platform}.min.js" + platform_js = [] + if resource_url == SURVEY_JS_CDN: + for js in SUGGESTED_JS_BY_PLATFORM[platform]: + platform_js.append(js) + platform_js.append(survey_js) + return platform_js + +def get_theme_css_resources(theme, resource_url): + if theme == "bootstrap" and resource_url == SURVEY_JS_CDN: + return [BOOTSTRAP_URL] + elif theme == "bootstrap": + return [f"{resource_url}/bootstrap.min.css"] + name = "survey" + if theme == "modern": + name = "modern" + return [f"{resource_url}/{name}.css"] + +def get_survey_js(json, action, theme, platform): + platform_js = PLATFORM_JS[platform] + return SURVEY_JS.format(theme, json, action, platform_js) + +def get_form_page(title, platform, js, js_resources, css_resources): + resources = "" + platform_html = SURVEY_HTML[platform] + for resource in js_resources: + resources += f'\n' + for resource in css_resources: + resources += f'\n' + return platform_html.format(title, resources, js) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..12cde4b --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +pydantic +typing-extensions;python_version<"3.8" diff --git a/requirements_dev.txt b/requirements_dev.txt new file mode 100644 index 0000000..9a75d9b --- /dev/null +++ b/requirements_dev.txt @@ -0,0 +1,13 @@ +pip==19.2.3 +bump2version==0.5.11 +wheel==0.33.6 +watchdog==0.9.0 +flake8==3.7.8 +tox==3.14.0 +coverage==4.5.4 +Sphinx==1.8.5 +twine==1.14.0 +Click==7.1.2 +pytest==4.6.5 +pytest-runner==5.1 +black==20.8b1 diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..20ea94e --- /dev/null +++ b/setup.cfg @@ -0,0 +1,26 @@ +[bumpversion] +current_version = 0.1.0 +commit = True +tag = True + +[bumpversion:file:setup.py] +search = version='{current_version}' +replace = version='{new_version}' + +[bumpversion:file:questions/__init__.py] +search = __version__ = '{current_version}' +replace = __version__ = '{new_version}' + +[bdist_wheel] +universal = 1 + +[flake8] +exclude = docs + +[aliases] +# Define setup.py command aliases here +test = pytest + +[tool:pytest] +collect_ignore = ['setup.py'] + diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..26b61fb --- /dev/null +++ b/setup.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python + +"""The setup script.""" + +from setuptools import setup, find_packages + +with open('README.rst') as readme_file: + readme = readme_file.read() + +with open('HISTORY.rst') as history_file: + history = history_file.read() + +requirements = ['Click>=7.0', ] + +setup_requirements = ['pytest-runner', ] + +test_requirements = ['pytest>=3', ] + +setup( + author="Carlos de la Guardia", + author_email='cguardia@yahoo.com', + python_requires='>=3.5', + classifiers=[ + 'Development Status :: 2 - Pre-Alpha', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Natural Language :: English', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + ], + description="Questions is a form library that uses the power of SurveyJS for the UI.", + entry_points={ + 'console_scripts': [ + 'questions=questions.cli:main', + ], + }, + install_requires=requirements, + license="MIT license", + long_description=readme + '\n\n' + history, + include_package_data=True, + keywords='questions', + name='questions', + packages=find_packages(include=['questions', 'questions.*']), + setup_requires=setup_requirements, + test_suite='tests', + tests_require=test_requirements, + url='https://github.com/cguardia/questions', + version='0.1.0', + zip_safe=False, +) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..26844fb --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""Unit test package for questions.""" diff --git a/tests/test_questions.py b/tests/test_questions.py new file mode 100644 index 0000000..f1d55d7 --- /dev/null +++ b/tests/test_questions.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python + +"""Tests for `questions` package.""" + +import pytest + +from click.testing import CliRunner + +from questions import questions +from questions import cli + + +@pytest.fixture +def response(): + """Sample pytest fixture. + + See more at: http://doc.pytest.org/en/latest/fixture.html + """ + # import requests + # return requests.get('https://github.com/audreyr/cookiecutter-pypackage') + + +def test_content(response): + """Sample pytest test function with the pytest fixture as an argument.""" + # from bs4 import BeautifulSoup + # assert 'GitHub' in BeautifulSoup(response.content).title.string + + +def test_command_line_interface(): + """Test the CLI.""" + runner = CliRunner() + result = runner.invoke(cli.main) + assert result.exit_code == 0 + assert "questions.cli.main" in result.output + help_result = runner.invoke(cli.main, ["--help"]) + assert help_result.exit_code == 0 + assert "--help Show this message and exit." in help_result.output diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..27498bc --- /dev/null +++ b/tox.ini @@ -0,0 +1,27 @@ +[tox] +envlist = py35, py36, py37, py38, flake8 + +[travis] +python = + 3.8: py38 + 3.7: py37 + 3.6: py36 + 3.5: py35 + +[testenv:flake8] +basepython = python +deps = flake8 +commands = flake8 questions tests + +[testenv] +setenv = + PYTHONPATH = {toxinidir} +deps = + -r{toxinidir}/requirements_dev.txt +; If you want to make tox run the tests with the same versions, create a +; requirements.txt with the pinned versions and uncomment the following line: +; -r{toxinidir}/requirements.txt +commands = + pip install -U pip + pytest --basetemp={envtmpdir} +