<commit_before># -*- coding: utf-8 -*-
"""
    Custom widgets to extend Web2Py

    @author: <NAME> (<EMAIL>)
    @date-created: 2010-03-17

"""

import copy

from lxml import etree
from gluon.sqlhtml import *
from gluon.html import P, URL
from gluon.validators import *
from s3gis import GIS
from s3utils import *
from validators import *

repr_select = lambda l: len(l.name) > 48 and "%s..." % l.name[:44] or l.name

# -----------------------------------------------------------------------------
class S3DateWidget:
    """
        @author: <NAME> (<EMAIL>)

        Standard Date widget, but with a modified yearRange to support Birth dates
    """

    def __init__(self,
                 before=10,  # How many years to show before the current one
                 after=10    # How many years to show after the current one
                ):
        self.min = before
        self.max = after
    
    def __call__(self ,field, value, **attributes):
        default = dict(
            _type = "text",
            value = (value!=None and str(value)) or "",
            )
        attr = StringWidget._attributes(field, default, **attributes)

        selector = str(field).replace(".", "_")
        
        date_options = """
    $(function() {
        $( '#%s' ).datepicker( 'option', 'yearRange', 'c-%s:c+%s' );
    });
    """ % (selector, self.min, self.max)
        
        return TAG[""](
                        INPUT(**attr),
                        SCRIPT(date_options)
                      )
                      
# -----------------------------------------------------------------------------
class S3AutocompleteWidget:
    """
        @author: <NAME> (<EMAIL>)

        Renders a SELECT as an INPUT field with AJAX Autocomplete
    """
    def __init__(self,
                 request,
                 prefix,
                 resourcename,
                 fieldname="name",
                 post_process = "",
                 min_length=2):

        self.request = request
        self.prefix = prefix
        self.resourcename = resourcename
        self.fieldname = fieldname
        self.post_process = post_process
        self.min_length = min_length

    def __call__(self ,field, value, **attributes):
        default = dict(
            _type = "text",
            value = (value != None and str(value)) or "",
            )
        attr = StringWidget._attributes(field, default, **attributes)

        # Hide the real field
        attr["_class"] = attr["_class"] + " hidden"
        
        real_input = str(field).replace(".", "_")
        dummy_input = "dummy_%s" % real_input
        fieldname = self.fieldname
        url = URL(r=self.request, c=self.prefix, f=self.resourcename, args="search.json", vars={"filter":"~", "field":fieldname})
        
        js_autocomplete = """
        (function()
        {
            var data = { val : $('#%s').val(), accept : false };

            $('#%s').autocomplete({
                source: '%s',
                minLength: %d,
                focus: function( event, ui ) {
                    $( '#%s' ).val( ui.item.%s );
                    return false;
                },
                select: function( event, ui ) {
                    $( '#%s' ).val( ui.item.%s );
                    $( '#%s' ).val( ui.item.id );
                    """ % (dummy_input, dummy_input, url, self.min_length, dummy_input, fieldname, dummy_input, fieldname, real_input) + self.post_process + """
                    return false;
                }
            })
            .data( 'autocomplete' )._renderItem = function( ul, item ) {
                return $( '<li></li>' )
                    .data( 'item.autocomplete', item )
                    .append( '<a>' + item.%s + '</a>' )
                    .click(function()
                    {
                        data.accept = true;
                    })
                    .appendTo( ul );
            };

            $('#%s').blur(function()
            {
                if(!data.accept) $('#%s').val(data.val);
                else data.val = $('#%s').val();

                data.accept = false;
            });
        })();
        """ % (fieldname, dummy_input, dummy_input, dummy_input)
        
        if value:
            text = str(field.represent(default["value"]))
            if "<" in text:
                # Strip Markup
                try:
                    markup = etree.XML(text)
                    text = markup.xpath(".//text()")
                    if text:
                        text = " ".join(text)
                    else:
                        text = ""
                except etree.XMLSyntaxError:
                    pass
            represent = text
        else:
            represent = ""
        
        return TAG[""](
                        INPUT(_id=dummy_input, _value=represent),
                        INPUT(**attr),
                        SCRIPT(js_autocomplete)
                      )

# -----------------------------------------------------------------------------
class S3PersonAutocompleteWidget:
    """
        @author: <NAME> (<EMAIL>)

        Renders a pr_person SELECT as an INPUT field with AJAX Autocomplete<commit_msg>Work on #521 From Tony Young <rofflwaffls at gmail dot com> Still issues if the autocomplete option is selected by using arrow keys.<commit_after># -*- coding: utf-8 -*-
"""
    Custom widgets to extend Web2Py

    @author: <NAME> (<EMAIL>)
    @date-created: 2010-03-17

"""

import copy

from lxml import etree
from gluon.sqlhtml import *
from gluon.html import P, URL
from gluon.validators import *
from s3gis import GIS
from s3utils import *
from validators import *

repr_select = lambda l: len(l.name) > 48 and "%s..." % l.name[:44] or l.name

# -----------------------------------------------------------------------------
class S3DateWidget:
    """
        @author: <NAME> (<EMAIL>)

        Standard Date widget, but with a modified yearRange to support Birth dates
    """

    def __init__(self,
                 before=10,  # How many years to show before the current one
                 after=10    # How many years to show after the current one
                ):
        self.min = before
        self.max = after
    
    def __call__(self ,field, value, **attributes):
        default = dict(
            _type = "text",
            value = (value!=None and str(value)) or "",
            )
        attr = StringWidget._attributes(field, default, **attributes)

        selector = str(field).replace(".", "_")
        
        date_options = """
    $(function() {
        $( '#%s' ).datepicker( 'option', 'yearRange', 'c-%s:c+%s' );
    });
    """ % (selector, self.min, self.max)
        
        return TAG[""](
                        INPUT(**attr),
                        SCRIPT(date_options)
                      )
                      
# -----------------------------------------------------------------------------
class S3AutocompleteWidget:
    """
        @author: <NAME> (<EMAIL>)

        Renders a SELECT as an INPUT field with AJAX Autocomplete
    """
    def __init__(self,
                 request,
                 prefix,
                 resourcename,
                 fieldname="name",
                 post_process = "",
                 min_length=2):

        self.request = request
        self.prefix = prefix
        self.resourcename = resourcename
        self.fieldname = fieldname
        self.post_process = post_process
        self.min_length = min_length

    def __call__(self ,field, value, **attributes):
        default = dict(
            _type = "text",
            value = (value != None and str(value)) or "",
            )
        attr = StringWidget._attributes(field, default, **attributes)

        # Hide the real field
        attr["_class"] = attr["_class"] + " hidden"
        
        real_input = str(field).replace(".", "_")
        dummy_input = "dummy_%s" % real_input
        fieldname = self.fieldname
        url = URL(r=self.request, c=self.prefix, f=self.resourcename, args="search.json", vars={"filter":"~", "field":fieldname})
        
        js_autocomplete = """
        (function()
        {
            var data = { val : $('#%s').val(), accept : false };

            $('#%s').autocomplete({
                source: '%s',
                minLength: %d,
                focus: function( event, ui ) {
                    $( '#%s' ).val( ui.item.%s );
                    return false;
                },
                select: function( event, ui ) {
                    $( '#%s' ).val( ui.item.%s );
                    $( '#%s' ).val( ui.item.id );
                    """ % (dummy_input, dummy_input, url, self.min_length, dummy_input, fieldname, dummy_input, fieldname, real_input) + self.post_process + """
                    return false;
                }
            })
            .data( 'autocomplete' )._renderItem = function( ul, item ) {
                return $( '<li></li>' )
                    .data( 'item.autocomplete', item )
                    .append( '<a>' + item.%s + '</a>' )
                    .click(function()
                    {
                        data.accept = true;
                    })
                    .appendTo( ul );
            };

            $('#%s').blur(function()
            {
                if(!$('#%s').val())
                {
                    $('#%s').val("");
                    data.accept = true;
                }

                if(!data.accept) $('#%s').val(data.val);
                else data.val = $('#%s').val();

                data.accept = false;
            });
        })();
        """ % (fieldname, dummy_input, dummy_input, real_input, dummy_input, dummy_input)
        
        if value:
            text = str(field.represent(default["value"]))
            if "<" in text:
                # Strip Markup
                try:
                    markup = etree.XML(text)
                    text = markup.xpath(".//text()")
                    if text:
                        text = " ".join(text)
                    else:
                        text = ""
                except etree.XMLSyntaxError:
                    pass
            represent = text
        else:
            represent = ""
        
        return TAG[""](
                        INPUT(_id=dummy_input, _value=represent),
                        INPUT(**attr),
                        SCRIPT(js_autocomplete)
                      )

# -----------------------------------------------------------------------------
class S3PersonAutocompleteWidget:
    """
        @author: <NAME> (<EMAIL>)

        Renders a pr_person SELECT as an INPUT field with AJAX Autocomplete
{'fraction_non_alphanumeric': 0.16829472509070612, 'fraction_numerical': 0.004744627407200669, 'mean_word_length': 1.2105696072383303, 'pattern_counts': {'":': 4, '<': 30, '<?xml version=': 0, '>': 30, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7442615', 'n_tokens_mistral': 2930, 'n_tokens_neox': 2709, 'n_words': 681}