Skip to content
text.py 37 KiB
Newer Older
from __future__ import annotations


__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"

__license__ = """
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.
"""

Andreas Klöckner's avatar
Andreas Klöckner committed
import re
import sys
Andreas Klöckner's avatar
Andreas Klöckner committed

import django.forms as forms
Andreas Klöckner's avatar
Andreas Klöckner committed
from django.utils.translation import gettext, gettext_lazy as _

from course.page.base import (
    AnswerFeedback,
    PageBaseWithCorrectAnswer,
    PageBaseWithHumanTextFeedback,
    PageBaseWithoutHumanGrading,
    PageBaseWithTitle,
    PageBaseWithValue,
    PageBehavior,
    PageContext,
    get_editor_interaction_mode,
Andreas Klöckner's avatar
Andreas Klöckner committed
    markup_to_html,
)
from course.validation import AttrSpec, ValidationError, validate_struct
Andreas Klöckner's avatar
Andreas Klöckner committed
from relate.utils import Struct, StyledForm, string_concat
CORRECT_ANSWER_PATTERN = string_concat(_("A correct answer is"), ": '%s'.")
Dong Zhuang's avatar
Dong Zhuang committed


class TextAnswerForm(StyledForm):
    # prevents form submission with codemirror's empty textarea
    use_required_attribute = False

    def get_text_widget(widget_type, read_only=False, check_only=False,
            interaction_mode=None, initial_text=None):
        """Returns None if no widget found."""

        if widget_type in [None, "text_input"]:
            if check_only:
                return True

            widget = forms.TextInput()

        elif widget_type == "textarea":
            if check_only:
                return True

            widget = forms.Textarea()

        elif widget_type.startswith("editor:"):
            if check_only:
                return True

            from course.utils import get_codemirror_widget
            widget, help_text = get_codemirror_widget(
                    language_mode=widget_type[widget_type.find(":")+1:],
                    interaction_mode=interaction_mode)
        widget.attrs["autofocus"] = None
        if read_only:
            widget.attrs["readonly"] = None
        return widget, help_text

    def __init__(self, read_only, interaction_mode, validators, *args, **kwargs):
        widget_type = kwargs.pop("widget_type", "text_input")
        initial_text = kwargs.pop("initial_text", None)
        super().__init__(*args, **kwargs)
        widget, help_text = self.get_text_widget(
                    widget_type, read_only,
        self.validators = validators
        self.fields["answer"] = forms.CharField(
                required=True,
                initial=initial_text,
ifaint's avatar
ifaint committed
                help_text=help_text,
                label=_("Answer"))

        answer = cleaned_data.get("answer", "")
        for i, validator in enumerate(self.validators):
            try:
                validator.validate(answer)
            except forms.ValidationError:
                if i + 1 == len(self.validators):
                    # last one, and we flunked -> not valid
                    raise
            else:
                # Found one that will take the input. Good enough.
                break
# {{{ validators

    type = "relate_page"

    def __init__(self, vctx, location, validator_desc):
        self.validator_desc = validator_desc

        validate_struct(
                vctx,
                location,
                validator_desc,
                required_attrs=(
                    ("type", str),
                    ),
                allowed_attrs=(
                    ("page_type", str),
                    ),
                )

    def validate(self, new_page_source):
        import yaml

Andreas Klöckner's avatar
Andreas Klöckner committed
        from relate.utils import dict_to_struct

Andreas Klöckner's avatar
Andreas Klöckner committed
            page_desc = dict_to_struct(yaml.safe_load(new_page_source))
Andreas Klöckner's avatar
Andreas Klöckner committed
            from course.validation import ValidationContext, validate_flow_page
            vctx = ValidationContext(
                    # FIXME
                    repo=None,
                    commit_sha=None)

            validate_flow_page(vctx, "submitted page", page_desc)

            if page_desc.type != self.validator_desc.page_type:
                raise ValidationError(gettext("page must be of type '%s'")
                        % self.validator_desc.page_type)

Andreas Klöckner's avatar
Andreas Klöckner committed
        except Exception:
            tp, e, _ = sys.exc_info()

            raise forms.ValidationError(f"{tp.__name__}: {e!s}")


TEXT_ANSWER_VALIDATOR_CLASSES = [
        RELATEPageValidator,
        ]


def get_validator_class(location, validator_type):
    for validator_class in TEXT_ANSWER_VALIDATOR_CLASSES:
        if validator_class.type == validator_type:
            return validator_class

    raise ValidationError(
            string_concat(
                "%(location)s: ",
                _("unknown validator type"),
                "'%(type)s'")
            % {"location": location, "type": validator_type})


def parse_validator(vctx, location, validator_desc):
    if not isinstance(validator_desc, Struct):
        raise ValidationError(
                string_concat(
                    "%s: ",
                    _("must be struct"))
                % location)

    if not hasattr(validator_desc, "type"):
        raise ValidationError(
                string_concat(
                    "%s: ",
Loading
Loading full blame...