Example usage for org.apache.wicket.extensions.ajax.markup.html.autocomplete AutoCompleteSettings setThrottleDelay

List of usage examples for org.apache.wicket.extensions.ajax.markup.html.autocomplete AutoCompleteSettings setThrottleDelay

Introduction

In this page you can find the example usage for org.apache.wicket.extensions.ajax.markup.html.autocomplete AutoCompleteSettings setThrottleDelay.

Prototype

public AutoCompleteSettings setThrottleDelay(final int throttleDelay) 

Source Link

Document

set the throttle delay how long the browser will wait before sending a request to the browser after the user released a key.

Usage

From source file:com.servoy.j2db.server.headlessclient.dataui.WebDataLookupField.java

License:Open Source License

private void init() {

    add(new HeaderContributor(new IHeaderContributor() {
        private static final long serialVersionUID = 1L;

        public void renderHead(IHeaderResponse response) {
            response.renderCSSReference(
                    new CompressedResourceReference(WebDataLookupField.class, "servoy_lookupfield.css")); //$NON-NLS-1$
        }/*  w  ww  .  j a v a 2 s.  co m*/
    }) {
        @Override
        public boolean isEnabled(Component component) {
            return !getScriptObject().isReadOnly() && getScriptObject().isEnabled();
        }
    });

    setOutputMarkupPlaceholderTag(true);

    AutoCompleteSettings behSettings = new AutoCompleteSettings();
    behSettings.setMaxHeightInPx(200);
    behSettings.setPreselect(true);
    behSettings.setShowCompleteListOnFocusGain(true);
    behSettings.setAdjustInputWidth(false);

    ClientProperties clp = (application.getApplicationType() != IApplication.HEADLESS_CLIENT
            ? ((WebClientInfo) Session.get().getClientInfo()).getProperties()
            : null); // in case of batch processors/jsp, we can't get browser info because UI is not given by web client components
    if (clp != null && (!clp.isBrowserInternetExplorer() || clp.getBrowserVersionMajor() >= 8)) {
        // smart positioning doesn't work on IE < 8 (probably because of unreliable clientWidth/clientHeight browser element js properties)
        behSettings.setUseSmartPositioning(true);
        behSettings.setUseHideShowCoveredIEFix(false); // don't know if the problem this setting is for can still be reproduced (I couldn't reproduce it)... this is true by default and makes fields in IE and Opera appear/dissapear if they would be covered by type-ahead popup
    } else {
        behSettings.setUseSmartPositioning(false);
        behSettings.setUseHideShowCoveredIEFix(true);
    }
    behSettings.setThrottleDelay(500);

    IAutoCompleteRenderer<Object> renderer = new IAutoCompleteRenderer<Object>() {
        protected String getTextValue(Object object) {
            String str = ""; //$NON-NLS-1$
            if (object instanceof DisplayString) {
                str = object.toString();
            } else if (object != null && !(object instanceof String)) {
                IConverter con = getConverter(object.getClass());
                if (con != null) {
                    str = con.convertToString(object, getLocale());
                } else {
                    str = object.toString();
                }
            } else if (object != null) {
                str = object.toString();
            }
            if (str == null || str.trim().equals("")) //$NON-NLS-1$
                str = "&nbsp;"; //$NON-NLS-1$
            return str;
        }

        protected void renderChoice(Object object, Response response, String criteria) {
            if (IValueList.SEPARATOR_DESIGN_VALUE.equals(object))
                return;
            String renderedObject = getTextValue(object);
            // escape the markup if it is not html or not just an empty none breaking space (null or empty string object)
            if (!renderedObject.equals("&nbsp;") && !HtmlUtils.hasHtmlTag(renderedObject)) //$NON-NLS-1$
                renderedObject = HtmlUtils.escapeMarkup(renderedObject, true, false).toString();
            response.write(renderedObject);
        }

        /*
         * (non-Javadoc)
         *
         * @see org.apache.wicket.extensions.ajax.markup.html.autocomplete.IAutoCompleteRenderer#render(java.lang.Object, org.apache.wicket.Response,
         * java.lang.String)
         */
        public void render(Object object, Response response, String criteria) {
            String textValue = getTextValue(object);
            if (textValue == null) {
                throw new IllegalStateException(
                        "A call to textValue(Object) returned an illegal value: null for object: "
                                + object.toString());
            }
            textValue = textValue.replaceAll("\\\"", "&quot;");

            response.write("<li textvalue=\"" + textValue + "\"");
            response.write(">");
            renderChoice(object, response, criteria);
            response.write("</li>");
        }

        /*
         * (non-Javadoc)
         *
         * @see org.apache.wicket.extensions.ajax.markup.html.autocomplete.IAutoCompleteRenderer#renderHeader(org.apache.wicket.Response)
         */
        @SuppressWarnings("nls")
        public void renderHeader(Response response) {
            StringBuffer listStyle = new StringBuffer();
            listStyle.append("style=\"");

            String fFamily = "Tahoma, Arial, Helvetica, sans-serif";
            String bgColor = "#ffffff";
            String fgColor = "#000000";
            String fSize = TemplateGenerator.DEFAULT_FONT_SIZE + "px";
            String padding = "2px";
            String margin = "0px";
            if (getFont() != null) {
                Font f = getFont();
                if (f != null) {
                    if (f.getFamily() != null) {
                        fFamily = f.getFamily();
                        if (fFamily.contains(" "))
                            fFamily = "'" + fFamily + "'";
                    }
                    if (f.getName() != null) {
                        String fName = f.getName();
                        if (fName.contains(" "))
                            fName = "'" + fName + "'";
                        fFamily = fName + "," + fFamily;
                    }
                    if (f.isBold())
                        listStyle.append("font-weight:bold; ");
                    if (f.isItalic())
                        listStyle.append("font-style:italic; ");

                    fSize = Integer.toString(f.getSize()) + "px";
                }
            }

            if (getListColor() != null && getListColor().getAlpha() == 255) {
                // background shouldn't be transparent
                bgColor = getWebColor(getListColor().getRGB());
            }
            if (getForeground() != null) {
                fgColor = getWebColor(getForeground().getRGB());
            }
            Insets _padding = getPadding();
            if (getPadding() != null)
                padding = _padding.top + "px " + _padding.right + "px " + _padding.bottom + "px "
                        + _padding.left + "px";

            listStyle.append("font-family:" + fFamily + "; ");
            listStyle.append("background-color: " + bgColor + "; ");
            listStyle.append("color: " + fgColor + "; ");
            listStyle.append("font-size:" + fSize + "; ");
            listStyle.append("min-width:" + (getSize().width - 6) + "px; "); // extract padding and border
            listStyle.append("margin: " + margin + "; ");
            listStyle.append("padding: " + padding + "; ");
            listStyle.append(
                    "text-align:" + TemplateGenerator.getHorizontalAlignValue(getHorizontalAlignment()));
            listStyle.append("\"");

            response.write("<ul " + listStyle + ">");
        }

        /*
         * (non-Javadoc)
         *
         * @see org.apache.wicket.extensions.ajax.markup.html.autocomplete.IAutoCompleteRenderer#renderFooter(org.apache.wicket.Response)
         */
        public void renderFooter(Response response) {
            response.write("</ul>"); //$NON-NLS-1$
        }

        /**
         * Returns web color representation of int rgba color by
         * removing the alpha value
         *
         * @param color int representation of rgba color
         * @return web color of form #rrggbb
         */
        private String getWebColor(int color) {
            String webColor = Integer.toHexString(color);
            int startIdx = webColor.length() - 6;
            if (startIdx < 0)
                startIdx = 0;
            webColor = webColor.substring(startIdx);

            StringBuilder sb = new StringBuilder();
            sb.append('#');
            int nrMissing0 = 6 - webColor.length();
            for (int i = 0; i < nrMissing0; i++) {
                sb.append('0');
            }
            sb.append(webColor);

            return sb.toString();
        }
    };

    AutoCompleteBehavior<Object> beh = new AutoCompleteBehavior<Object>(renderer, behSettings) {
        private static final long serialVersionUID = 1L;

        /**
         * @see org.apache.wicket.extensions.ajax.markup.html.autocomplete.AutoCompleteBehavior#getChoices(java.lang.String)
         */
        @Override
        protected Iterator<Object> getChoices(String input) {
            String filteredInput = filterInput(input);
            if (changeListener != null)
                dlm.getValueList().removeListDataListener(changeListener);
            try {
                dlm.fill(parentState, getDataProviderID(), filteredInput, false);
                return dlm.iterator();
            } catch (Exception ex) {
                Debug.error(ex);
            } finally {
                if (changeListener != null)
                    dlm.getValueList().addListDataListener(changeListener);
            }
            return Collections.emptyList().iterator();
        }

        /**
         * filters the input in case of masked input (removes the mask)
         */
        private String filterInput(String input) {
            String displayFormat = WebDataLookupField.this.parsedFormat.getDisplayFormat();
            if (displayFormat != null && displayFormat.length() > 0
                    && input.length() == displayFormat.length()) {
                int index = firstBlankSpacePosition(input, displayFormat);
                if (index == -1)
                    return input;
                return input.substring(0, index);
            }
            return input;
        }

        /**
         * Computes the index of the first space char found in the input and is not ' ' nor '*' in the format
         * Example:
         * input  '12 - 3  -  '
         * format '## - ## - #'
         * returns 6
         * @param input
         * @param displayFormat
         * @return The index of the first space char found in the input and is not ' ' nor '*' in the format
         */
        private int firstBlankSpacePosition(String input, String displayFormat) {
            for (int i = 0; i < input.length(); i++) {
                if ((input.charAt(i) == ' ') && (displayFormat.charAt(i) != ' ')
                        && (displayFormat.charAt(i) != '*'))
                    return i;
            }
            return 0;
        }

        /**
         * @see org.apache.wicket.ajax.AbstractDefaultAjaxBehavior#getFailureScript()
         */
        @Override
        protected CharSequence getFailureScript() {
            return "onAjaxError();"; //$NON-NLS-1$
        }

        /**
         * @see org.apache.wicket.ajax.AbstractDefaultAjaxBehavior#getPreconditionScript()
         */
        @Override
        protected CharSequence getPreconditionScript() {
            return "onAjaxCall();" + super.getPreconditionScript(); //$NON-NLS-1$
        }

        // need to set this behavior to true (enterHidesWithNoSelection) because otherwise the onKeyDown events
        // or other events for the component with type ahead would be null in Firefox, and would not execute as
        // expected on the other browsers...
        @Override
        public void renderHead(IHeaderResponse response) {
            settings.setShowListOnEmptyInput(Boolean.TRUE.equals(UIUtils.getUIProperty(getScriptObject(),
                    application, IApplication.TYPE_AHEAD_SHOW_POPUP_WHEN_EMPTY, Boolean.TRUE)));
            settings.setShowListOnFocusGain(Boolean.TRUE.equals(UIUtils.getUIProperty(getScriptObject(),
                    application, IApplication.TYPE_AHEAD_SHOW_POPUP_ON_FOCUS_GAIN, Boolean.TRUE)));
            if (!getScriptObject().isReadOnly() && getScriptObject().isEnabled()) {
                super.renderHead(response);
                response.renderJavascript("Wicket.AutoCompleteSettings.enterHidesWithNoSelection = true;", //$NON-NLS-1$
                        "AutocompleteSettingsID"); //$NON-NLS-1$
            }
        }

        /**
         * @see org.apache.wicket.behavior.AbstractBehavior#isEnabled(org.apache.wicket.Component)
         */
        @Override
        public boolean isEnabled(Component component) {
            IFormUIInternal<?> formui = findParent(IFormUIInternal.class);
            if (formui != null && formui.isDesignMode()) {
                return false;
            }
            return super.isEnabled(component) && WebClientSession.get().useAjax();
        }
    };
    add(beh);
}

From source file:de.jetwick.ese.ui.SearchBox.java

License:Apache License

public SearchBox(String id, final String loggedInUser, String searchTypeAsStr) {
    super(id);//ww  w .j  av  a  2  s  . c  om

    form = new StatelessForm("searchform") {

        @Override
        public void onSubmit() {
            setResponsePage(getApplication().getHomePage(), getParams(query));
        }
    };
    form.setMarkupId("queryform");
    add(form);

    AutoCompleteSettings config = new AutoCompleteSettings().setUseHideShowCoveredIEFix(false);
    config.setThrottleDelay(200);

    // connect the form's textfield with the java property        
    queryTF = new org.apache.wicket.markup.html.form.TextField<Object>("textField",
            new PropertyModel(this, "query"));
    //queryTF.add(new DefaultFocusBehaviour());        
    form.add(queryTF);
    form.add(new BookmarkablePageLink("homelink", HomePage.class));
}

From source file:de.jetwick.ui.GrabTweetsDialog.java

License:Apache License

public GrabTweetsDialog(String id, String user) {
    super(id);/* ww w. j  a v a  2 s  . c o m*/

    this.userName = user;
    final Form form = new Form("grabForm");
    final ProgressBar bar = new ProgressBar("bar", new ProgressionModel() {

        @Override
        protected Progression getProgression() {
            if (pkg == null)
                return new Progression(0);

            return new Progression(pkg.getProgress());
        }
    }) {

        @Override
        protected void onFinished(AjaxRequestTarget target) {
            logger.info("finished: " + pkg.getProgress() + " canceled:" + pkg.isCanceled());

            if (pkg.getException() != null) {
                logger.error("Error while storing archive", pkg.getException());
                String msg = TwitterSearch.getMessage(pkg.getException());
                if (msg.length() > 0)
                    error(msg);
                else
                    error("Couldn't process your request. Please contact admin "
                            + "or twitter.com/jetwick if problem remains!");
            } else
                info(grabber.getTweetCount() + " tweets were stored for " + grabber.getUserName()
                        + ". In approx. 5min they will be searchable.");

            GrabTweetsDialog.this.updateAfterAjax(target);
            GrabTweetsDialog.this.onClose(target);
            started = false;
        }
    };
    form.add(bar);
    form.add(new AjaxSubmitLink("ajaxSubmit") {

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            if (!started) {
                started = true;
                bar.start(target);
                final String userName = getUsername();
                if (getMaxTweets() > 0) {
                    grabber.setUserName(userName);
                    grabber.setTweetsCount(getMaxTweets());
                    grabber.setTwitterSearch(getTwitterSearch());
                    pkg = grabber.queueArchiving();
                    new Thread(pkg).start();
                }
            } else {
                info("You've already queued a job.");
                GrabTweetsDialog.this.updateAfterAjax(target);
            }
        }
    });
    add(form);
    AutoCompleteSettings config = new AutoCompleteSettings().setUseHideShowCoveredIEFix(false);
    config.setThrottleDelay(200);
    form.add(field = new MyAutoCompleteTextField("userName", new PropertyModel(this, "userName"), config) {

        @Override
        protected Iterator getChoices(String input) {
            return GrabTweetsDialog.this.getUserChoices(input).iterator();
        }

        @Override
        protected void onSelectionChange(AjaxRequestTarget target, String newValue) {
            // skip
        }
    });
    choices = new DropDownChoice<SelectOption<Integer, String>>("tweetMenu", new ListModel(),
            Arrays.asList(new SelectOption<Integer, String>(200, "200"),
                    new SelectOption<Integer, String>(1000, "1000"),
                    new SelectOption<Integer, String>(3200, "MAX")));
    choices.getModel().setObject(choices.getChoices().get(0));
    choices.setNullValid(false);
    form.add(choices);
}

From source file:de.jetwick.ui.SearchBox.java

License:Apache License

public SearchBox(String id, final String loggedInUser, String searchTypeAsStr, boolean showSpacer) {
    super(id);/* ww  w  . j av  a2  s .c  o  m*/

    setSearchType(searchTypeAsStr);
    add(new WebMarkupContainer("userTwitter") {

        @Override
        public boolean isVisible() {
            return !getUserName().isEmpty();
        }
    }.add(new ExternalLink("userTwitterLink", oneUserLink, oneUserLabel))
            .add(new AjaxFallbackLink("userTwitterLinkRemove") {

                @Override
                public void onClick(AjaxRequestTarget target) {
                    setSearchType(ALL);
                    setResponsePage(TweetSearchPage.class, getParams(query, selectedIndex, null, loggedInUser));
                }
            }));
    final RadioGroup rg = new RadioGroup("searchTypes", new PropertyModel(this, "selectedIndex"));
    final Button buttonRight = new Button("submitbutton") {

        @Override
        public void onSubmit() {
            setResponsePage(TweetSearchPage.class, getParams(query, selectedIndex, userName, loggedInUser));
        }
    };
    final Button bttnLeft = new Button("submitbuttonleft") {

        @Override
        public void onSubmit() {
            buttonRight.onSubmit();
        }
    };
    form = new Form("searchform") {

        @Override
        public void onSubmit() {
            buttonRight.onSubmit();
        }
    };

    form.add(new BookmarkablePageLink("homelink", TweetSearchPage.class));
    //        buttonRight.add(new EffectBehavior(new BounceEffect()));
    form.add(buttonRight);
    form.add(bttnLeft);
    form.setMarkupId("queryform");
    add(form);

    AutoCompleteSettings config = new AutoCompleteSettings().setUseHideShowCoveredIEFix(false);
    config.setThrottleDelay(200);

    // connect the form's textfield with the java property        
    queryTF = new MyAutoCompleteTextField("textField", new PropertyModel(this, "query"), config) {

        @Override
        protected Iterator getChoices(String input) {
            return SearchBox.this.getQueryChoices(input).iterator();
        }

        @Override
        protected void onSelectionChange(AjaxRequestTarget target, String newValue) {
            SearchBox.this.onSelectionChange(target, newValue);
        }
    };
    queryTF.add(new DefaultFocusBehaviour());
    // autosubmit when user selects choice -> problem: the user text will be submitted although it should be cleared before submit
    //        queryTF.add(new AjaxFormSubmitBehavior(form, "onchange") {
    //
    //            @Override
    //            protected void onSubmit(AjaxRequestTarget target) {
    //            }
    //
    //            @Override
    //            protected void onError(AjaxRequestTarget target) {
    //            }
    //        });
    queryTF.setMarkupId("querybox");
    form.add(queryTF);

    MyAutoCompleteTextField userTF = new MyAutoCompleteTextField("userTextField",
            new PropertyModel(this, "userName"), config) {

        @Override
        protected Iterator getChoices(String input) {
            return SearchBox.this.getUserChoices(input).iterator();
        }

        @Override
        protected void onSelectionChange(AjaxRequestTarget target, String newValue) {
            //"Not supported yet."
        }
    };
    userTF.setMarkupId("userbox");

    rg.add(new Radio("0", new Model(0)).setMarkupId("sbnone"));
    rg.add(new Radio("1", new Model(1)).setMarkupId("sbfriends"));
    rg.add(new Radio("2", new Model(2)).setMarkupId("sbuser"));
    rg.add(userTF);
    if (showSpacer)
        form.add(new AttributeAppender("class", new Model("not-logged-in-spacer"), " "));

    form.add(rg);

    //        Model hrefModel = new Model() {
    //
    //            @Override
    //            public Serializable getObject() {
    //                String paramStr = "";
    //                String txt = "";
    //
    //                if (userName != null && !userName.isEmpty()) {
    //                    paramStr += "user=" + userName;
    //                    txt += "@" + userName + " ";
    //                }
    //
    //                if (query != null && !query.isEmpty()) {
    //                    if (!paramStr.isEmpty()) {
    //                        paramStr += "&";
    //                        txt += "and ";
    //                    }
    //
    //                    paramStr += "q=" + query;
    //                    txt += query + " ";
    //                }
    //
    //                if (!paramStr.isEmpty())
    //                    paramStr = "?" + paramStr;
    //
    //                if (!txt.isEmpty())
    //                    txt = "about " + txt;
    //                else
    //                    txt = "about any topic at ";
    //
    //                return Helper.toTwitterStatus(Helper.twitterUrlEncode("News " + txt
    //                        + "http://jetwick.com/" + paramStr));
    //            }
    //        };

    //        form.add(new ExternalLink("tweetQuery", hrefModel));                
}

From source file:jp.xet.uncommons.wicket.gp.TimeField.java

License:Apache License

private static AutoCompleteSettings newDefaultAutoCompleteSettings() {
    AutoCompleteSettings settings = new AutoCompleteSettings();
    settings.setShowCompleteListOnFocusGain(true);
    settings.setShowListOnEmptyInput(true);
    settings.setShowListOnFocusGain(true);
    settings.setMaxHeightInPx(160); // CHECKSTYLE IGNORE THIS LINE
    settings.setThrottleDelay(0);

    return settings;
}