Example usage for com.google.gwt.user.client.ui HTMLPanel HTMLPanel

List of usage examples for com.google.gwt.user.client.ui HTMLPanel HTMLPanel

Introduction

In this page you can find the example usage for com.google.gwt.user.client.ui HTMLPanel HTMLPanel.

Prototype

private HTMLPanel(Element elem) 

Source Link

Document

Construct a new HTMLPanel with the specified element.

Usage

From source file:net.scran24.staff.client.SuspendSurvey.java

public SuspendSurvey(final SurveyParameters parameters, final SurveyControlServiceAsync surveyControl) {
    FlowPanel contents = new FlowPanel();

    HTMLPanel label = new HTMLPanel(SafeHtmlUtils.fromSafeConstant("<h3>Reason for suspension:</h3>"));
    final TextBox reason = new TextBox();
    Button suspend = WidgetFactory.createButton("Suspend", new ClickHandler() {
        @Override/*from www .  j a v a2  s .  co m*/
        public void onClick(ClickEvent event) {
            if (reason.getText().isEmpty()) {
                Window.alert("Please give a reason for suspension.");
            } else {
                surveyControl.setParameters(
                        parameters.withSuspensionReason(reason.getText()).withState(SurveyState.SUSPENDED),
                        new AsyncCallback<Void>() {
                            @Override
                            public void onSuccess(Void result) {
                                Location.reload();
                            }

                            @Override
                            public void onFailure(Throwable caught) {
                                Window.alert("Server error: " + caught.getMessage());
                            }
                        });
            }
        }
    });

    suspend.getElement().addClassName("scran24-admin-button");

    contents.add(label);
    contents.add(reason);
    contents.add(suspend);

    initWidget(contents);
}

From source file:net.scran24.user.client.CallbackRequestForm.java

private void doRequest() {
    requestCallbackButton.setEnabled(false);

    errorMessage.clear();/*w  ww  .j a  v  a  2  s. c  o  m*/

    if (nameTextBox.getText().isEmpty() || phoneNumberTextBox.getText().isEmpty()) {
        errorMessage
                .add(new HTMLPanel(SafeHtmlUtils.fromSafeConstant(messages.callbackRequestForm_fieldsEmpty())));
        errorMessage.getElement().addClassName("intake24-login-error-message");
        requestCallbackButton.setEnabled(true);
        return;
    }

    if (CurrentUser.userInfo.surveyId.equals("demo")) {
        errorMessage.add(new HTMLPanel(SafeHtmlUtils
                .fromSafeConstant(messages.callbackRequestForm_disabledForDemo("support@intake24.co.uk"))));
        errorMessage.getElement().addClassName("intake24-login-error-message");
        requestCallbackButton.setEnabled(true);
        return;
    }

    errorMessage.add(new LoadingWidget());

    helpService.requestCall(nameTextBox.getText(), phoneNumberTextBox.getText(), new AsyncCallback<Boolean>() {

        @Override
        public void onFailure(Throwable caught) {
            errorMessage.clear();
            errorMessage.add(new HTMLPanel(SafeHtmlUtils.fromSafeConstant(messages.serverError())));
            errorMessage.getElement().addClassName("intake24-login-error-message");
            requestCallbackButton.setEnabled(true);
        }

        @Override
        public void onSuccess(Boolean result) {
            if (result) {
                errorMessage.clear();
                errorMessage.getElement().addClassName("intake24-login-success-message");
                errorMessage.add(
                        new HTMLPanel(SafeHtmlUtils.fromSafeConstant(messages.callbackRequestForm_success())));

                GoogleAnalytics.trackHelpCallbackAccepted();
            } else {
                errorMessage.clear();
                errorMessage.getElement().addClassName("intake24-login-error-message");
                errorMessage.add(
                        new HTMLPanel(SafeHtmlUtils.fromSafeConstant(messages.callbackRequestForm_tooSoon())));

                GoogleAnalytics.trackHelpCallbackRejected();
            }
        }

    });
}

From source file:net.scran24.user.client.CallbackRequestForm.java

public CallbackRequestForm(final Callback onComplete) {
    Grid g = new Grid(2, 2);

    g.setCellPadding(5);//from   ww  w . j  a  va2  s.c om
    Label nameLabel = new Label(messages.callbackRequestForm_nameLabel());
    Label phoneNumberLabel = new Label(messages.callbackRequestForm_phoneNumberLabel());

    this.nameTextBox = new TextBox();
    this.phoneNumberTextBox = new TextBox();

    g.setWidget(0, 0, nameLabel);
    g.setWidget(1, 0, phoneNumberLabel);
    g.setWidget(0, 1, nameTextBox);
    g.setWidget(1, 1, phoneNumberTextBox);

    VerticalPanel p = new VerticalPanel();
    p.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

    FlowPanel videoLinkDiv = new FlowPanel();
    videoLinkDiv.add(WidgetFactory.createTutorialVideoLink());

    p.add(new HTMLPanel(messages.callbackRequestForm_watchWalkthrough()));
    p.add(videoLinkDiv);

    HTMLPanel pp = new HTMLPanel(SafeHtmlUtils.fromSafeConstant(messages.callbackRequestForm_promptText()));
    pp.getElement().addClassName("intake24-login-prompt-text");
    p.add(pp);
    p.add(g);

    errorMessage = new FlowPanel();
    p.add(errorMessage);

    requestCallbackButton = WidgetFactory
            .createButton(messages.callbackRequestForm_requestCallbackButtonLabel(), new ClickHandler() {
                @Override
                public void onClick(ClickEvent event) {
                    doRequest();
                }
            });

    hideFormButton = WidgetFactory.createButton(messages.callbackRequestForm_hideButtonLabel(),
            new ClickHandler() {
                @Override
                public void onClick(ClickEvent event) {
                    onComplete.call();
                }
            });

    requestCallbackButton.getElement().setId("intake24-login-button");

    nameTextBox.addKeyPressHandler(new KeyPressHandler() {
        @Override
        public void onKeyPress(KeyPressEvent event) {
            if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER)
                doRequest();
        }
    });

    phoneNumberTextBox.addKeyPressHandler(new KeyPressHandler() {
        @Override
        public void onKeyPress(KeyPressEvent event) {
            if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER)
                doRequest();
        }
    });

    p.add(WidgetFactory.createButtonsPanel(requestCallbackButton, hideFormButton));
    p.addStyleName("intake24-login-form");

    initWidget(p);
}

From source file:net.scran24.user.client.Scran24.java

License:Apache License

public void initPage(final UserInfo userInfo) {
    final RootPanel links = RootPanel.get("navigation-bar");

    Anchor watchTutorial = new Anchor(surveyMessages.navBar_tutorialVideo(), TutorialVideo.url, "_blank");

    Anchor logOut = new Anchor(surveyMessages.navBar_logOut(),
            "../../common/logout" + Location.getQueryString());

    // These divs are no longer used for content, but this code is left here
    // to handle legacy survey files

    Element se = Document.get().getElementById("suspended");
    if (se != null)
        se.removeFromParent();// ww w .j a  va2s.  com
    Element ae = Document.get().getElementById("active");
    if (ae != null)
        ae.removeFromParent();
    Element fe = Document.get().getElementById("finished");
    if (fe != null)
        fe.removeFromParent();
    Element ee = Document.get().getElementById("serverError");
    if (ee != null)
        ee.removeFromParent();
    Element fpe = Document.get().getElementById("finalPage");
    if (fpe != null)
        fpe.removeFromParent();

    mainContent = Document.get().getElementById("main-content");
    mainContent.setInnerHTML("");

    HTMLPanel mainContentPanel = HTMLPanel.wrap(mainContent);

    switch (userInfo.surveyParameters.state) {
    case NOT_INITIALISED:
        mainContentPanel
                .add(new HTMLPanel(SafeHtmlUtils.fromSafeConstant(surveyMessages.survey_notInitialised())));
        links.add(new NavigationBar(watchTutorial, logOut));
        break;
    case SUSPENDED:
        mainContentPanel.add(new HTMLPanel(SafeHtmlUtils.fromSafeConstant(surveyMessages
                .survey_suspended(SafeHtmlUtils.htmlEscape(userInfo.surveyParameters.suspensionReason)))));
        links.add(new NavigationBar(watchTutorial, logOut));
        break;
    case ACTIVE:
        Date now = new Date();

        if (now.getTime() > userInfo.surveyParameters.endDate) {
            mainContentPanel
                    .add(new HTMLPanel(SafeHtmlUtils.fromSafeConstant(surveyMessages.survey_finished())));
        } else {
            SurveyInterfaceManager surveyInterfaceManager = new SurveyInterfaceManager(mainContentPanel);

            SurveyScheme scheme = SurveySchemeMap.initScheme(
                    SurveySchemes.schemeForId(userInfo.surveyParameters.schemeName),
                    LocaleInfo.getCurrentLocale().getLocaleName(), surveyInterfaceManager);

            links.add(new NavigationBar(scheme.navBarLinks(), watchTutorial, logOut));

            scheme.showNextPage();
        }
        break;
    }

    RootPanel.get("loading").getElement().removeFromParent();

    initComplete();
}

From source file:net.scran24.user.client.Scran24.java

License:Apache License

public void onModuleLoad() {

    GWT.setUncaughtExceptionHandler(new Intake24UncaughtExceptionHandler());

    // These divs are no longer used for content, but this code is left here
    // to handle legacy survey files

    final Element serverError = Document.get().getElementById("serverError");

    if (serverError != null)
        serverError.removeFromParent();/*w  w  w  .  j  a v  a 2 s  .c o m*/

    log.info("Fetching user information");

    // This page should not be accessed unless the user is authenticated
    // as a respondent (see net.scran24.common.server.auth.ScranAuthFilter)

    loginService.getUserInfo(new AsyncCallback<Option<UserInfo>>() {
        @Override
        public void onSuccess(Option<UserInfo> result) {
            result.accept(new Option.SideEffectVisitor<UserInfo>() {
                @Override
                public void visitSome(final UserInfo userInfo) {
                    CurrentUser.setUserInfo(userInfo);

                    // Singleton portion size method for weight type-in
                    // Inserted dynamically by client runtime but depends on
                    // server-side configuration parameters (base image url)
                    // so still has to be loaded once

                    FoodLookupPrompt.preloadWeightPortionSizeMethod(new Callback() {
                        @Override
                        public void call() {
                            initPage(userInfo);
                        }
                    }, new Callback() {

                        @Override
                        public void call() {
                            HTMLPanel mainContentPanel = HTMLPanel.wrap(mainContent);
                            mainContentPanel
                                    .add(new HTMLPanel(SafeHtmlUtils.fromString(commonMessages.serverError())));
                        }
                    });

                }

                @Override
                public void visitNone() {
                    // this should never happen as any unauthenticated user
                    // should be
                    // redirected to the log in page, but still may happen
                    // in some weird
                    // case where the authentication token is lost between
                    // the
                    // authentication and opening this page
                    LoginForm.showPopup(new Callback1<UserInfo>() {
                        @Override
                        public void call(final UserInfo userInfo) {
                            initPage(userInfo);
                        }
                    });
                }
            });
        }

        @Override
        public void onFailure(Throwable caught) {
            HTMLPanel mainContentPanel = HTMLPanel.wrap(mainContent);
            mainContentPanel.add(new HTMLPanel(SafeHtmlUtils.fromString(commonMessages.serverError())));

        }
    });
}

From source file:net.scran24.user.client.survey.flat.FlatFinalPage.java

License:Apache License

@Override
public SimpleSurveyStageInterface getInterface(Callback1<Survey> onComplete,
        Callback2<Survey, Boolean> onIntermediateStateChange) {
    final CompletedSurvey finalData = data.finalise(log);
    final FlowPanel contents = new FlowPanel();
    contents.addStyleName("intake24-survey-content-container");

    contents.add(new LoadingPanel(messages.submitPage_loadingMessage()));

    AsyncRequestAuthHandler.execute(new AsyncRequest<Void>() {
        @Override/*from ww  w .j  a  v  a  2  s.  c om*/
        public void execute(AsyncCallback<Void> callback) {
            processingService.submit(finalData, callback);
        }
    }, new AsyncCallback<Void>() {
        @Override
        public void onFailure(final Throwable caught) {
            contents.clear();

            caught.printStackTrace();

            if (caught instanceof RequestTimeoutException) {
                final AsyncCallback<Void> outer = this;

                contents.add(new HTMLPanel(SafeHtmlUtils.fromSafeConstant(messages.submitPage_timeout())));

                contents.add(WidgetFactory.createGreenButton(messages.submitPage_tryAgainButton(),
                        new ClickHandler() {
                            @Override
                            public void onClick(ClickEvent event) {
                                processingService.submit(finalData, outer);
                            }
                        }));
            } else {
                contents.add(new HTMLPanel(SafeHtmlUtils.fromSafeConstant(messages.submitPage_error())));
            }

            contents.add(new HTMLPanel(finalPageHtml));
        }

        @Override
        public void onSuccess(Void result) {
            contents.clear();
            contents.add(new HTMLPanel(SafeHtmlUtils.fromSafeConstant(messages.submitPage_success())));

            CurrentUser.userInfo.surveyParameters.surveyMonkeyUrl
                    .accept(new Option.SideEffectVisitor<String>() {
                        @Override
                        public void visitSome(final String url) {

                            FlowPanel surveyMonkeyDiv = new FlowPanel();

                            surveyMonkeyDiv.add(WidgetFactory.createGreenButton(
                                    surveyMessages.finalPage_continueToSurveyMonkey(), new ClickHandler() {
                                        @Override
                                        public void onClick(ClickEvent clickEvent) {
                                            Window.Location.replace(url.replace("[intake24_username_value]",
                                                    CurrentUser.userInfo.userName));
                                        }
                                    }));

                            contents.add(surveyMonkeyDiv);
                        }

                        @Override
                        public void visitNone() {

                        }
                    });

            contents.add(new HTMLPanel(finalPageHtml));
            StateManagerUtil.clearLatestState(CurrentUser.userInfo.userName);
        }
    });

    return new SimpleSurveyStageInterface(contents);
}

From source file:net.scran24.user.client.survey.flat.NavigationPanel.java

License:Apache License

public void stateChanged(final Survey state) {
    mealsPanel.clear();/* w  w  w  . j  a va2s.  c  om*/

    Button addMealButton = WidgetFactory.createButton(messages.addMealLabel(), new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            addMealClickedJS();
            requestAddMeal.call();
        }
    });

    addMealButton.getElement().setId("intake24-add-meal-button");

    UnorderedList<MealPanel> mealList = new UnorderedList<MealPanel>();
    mealList.addStyleName("intake24-meal-list");

    for (WithIndex<Meal> m : state.mealsSortedByTime) {
        MealPanel p = new MealPanel(m.value, m.index, state.selectedElement, new Callback1<Selection>() {
            @Override
            public void call(Selection arg1) {
                requestSelection.call(arg1);
            }
        });
        mealList.addItem(p);
    }

    FlowPanel headerContainer = new FlowPanel();
    headerContainer.addStyleName("intake24-meals-panel-header-container");

    FlowPanel headerButton = new FlowPanel();
    headerButton.addStyleName("intake24-meals-panel-header-button");

    HTMLPanel header = new HTMLPanel(SafeHtmlUtils.fromSafeConstant(messages.navPanelHeader()));
    header.addStyleName("intake24-meals-panel-header");

    headerContainer.add(headerButton);
    headerContainer.add(header);

    mealsPanel.add(headerContainer);
    mealsPanel.add(mealList);
    mealsPanel.add(addMealButton);

    stateChangedJS();
}

From source file:net.scran24.user.client.survey.prompts.AssociatedFoodPrompt.java

License:Apache License

@Override
public SurveyStageInterface getInterface(final Callback1<MealOperation> onComplete,
        Callback1<Function1<Pair<FoodEntry, Meal>, Pair<FoodEntry, Meal>>> updateIntermediateState) {
    final EncodedFood food = (EncodedFood) pair.left;
    final FoodPrompt prompt = food.enabledPrompts.get(promptIndex);

    final FlowPanel content = new FlowPanel();
    PromptUtil.addBackLink(content);//from  w  w w .  j  ava  2 s  .c o  m
    final Panel promptPanel = WidgetFactory.createPromptPanel(
            SafeHtmlUtils.fromSafeConstant("<p>" + SafeHtmlUtils.htmlEscape(prompt.text) + "</p>"),
            WidgetFactory.createHelpButton(new ClickHandler() {
                @Override
                public void onClick(ClickEvent arg0) {
                    String promptType = AssociatedFoodPrompt.class.getSimpleName();
                    GoogleAnalytics.trackHelpButtonClicked(promptType);
                    ShepherdTour.startTour(getShepherdTourSteps(), promptType);
                }
            }));
    content.add(promptPanel);
    ShepherdTour.makeShepherdTarget(promptPanel);

    final Callback1<FoodData> addNewFood = new Callback1<FoodData>() {
        @Override
        public void call(final FoodData result) {
            onComplete.call(MealOperation.update(new Function1<Meal, Meal>() {
                @Override
                public Meal apply(final Meal meal) {
                    // Special case for cereal:
                    // if a "milk on cereal" food is linked to a cereal food
                    // copy bowl type from the parent food
                    Option<String> bowl_id = getParamValue(food, "bowl");

                    FoodData foodData = bowl_id.accept(new Option.Visitor<String, FoodData>() {
                        @Override
                        public FoodData visitSome(String bowl_id) {
                            return result.withPortionSizeMethods(
                                    appendPotionSizeParameter(result.portionSizeMethods, "bowl", bowl_id));
                        }

                        @Override
                        public FoodData visitNone() {
                            return result;
                        }
                    });

                    EncodedFood assocFood = new EncodedFood(foodData, FoodLink.newUnlinked(),
                            "associated food prompt");

                    return linkAssociatedFood(meal.plusFood(assocFood), food, assocFood, prompt.linkAsMain);
                };
            }));
        }
    };

    final Callback addMissingFood = new Callback() {
        @Override
        public void call() {
            onComplete.call(MealOperation.update(new Function1<Meal, Meal>() {
                @Override
                public Meal apply(final Meal meal) {
                    FoodEntry missingFood = new MissingFood(FoodLink.newUnlinked(),
                            prompt.genericName.substring(0, 1).toUpperCase() + prompt.genericName.substring(1),
                            false, Option.<MissingFoodDescription>none())
                                    .withCustomDataField(MissingFood.KEY_ASSOC_FOOD_NAME, food.description())
                                    .withCustomDataField(MissingFood.KEY_ASSOC_FOOD_CATEGORY, prompt.code);

                    return linkAssociatedFood(meal.plusFood(missingFood), food, missingFood, prompt.linkAsMain);
                }
            }));
        }
    };

    final Callback1<FoodEntry> addExistingFood = new Callback1<FoodEntry>() {
        @Override
        public void call(final FoodEntry existing) {
            onComplete.call(MealOperation.update(new Function1<Meal, Meal>() {
                @Override
                public Meal apply(final Meal meal) {
                    return linkAssociatedFood(meal, food, existing, prompt.linkAsMain);
                };
            }));
        }
    };

    foodBrowser = new FoodBrowser(locale, new Callback1<FoodData>() {
        @Override
        public void call(FoodData result) {
            addNewFood.call(result);
        }
    }, new Callback1<String>() {
        @Override
        public void call(String code) {
            throw new RuntimeException("Special foods are not allowed as associated foods");
        }
    }, new Callback() {
        @Override
        public void call() {
            addMissingFood.call();
        }
    }, Option.<SkipFoodHandler>none(), false, Option.<Pair<String, String>>none());

    Button no = WidgetFactory.createButton(messages.assocFoods_noButtonLabel(), new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            onComplete
                    .call(MealOperation.updateEncodedFood(foodIndex, new Function1<EncodedFood, EncodedFood>() {
                        @Override
                        public EncodedFood apply(EncodedFood argument) {
                            return argument.minusPrompt(promptIndex);
                        }
                    }));
        }
    });

    Button yes = WidgetFactory.createButton(messages.assocFoods_yesButtonLabel(), new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            if (prompt.isCategoryCode) {
                content.clear();
                PromptUtil.addBackLink(content);
                content.add(promptPanel);
                content.add(new HTMLPanel(
                        SafeHtmlUtils.fromSafeConstant(messages.assocFoods_specificFoodPrompt())));
                content.add(interf);

                content.add(foodBrowser);
                isInBrowserMode = true;

                foodBrowser.browse(prompt.code, messages.assocFoods_allFoodsDataSetName());
            } else {
                content.clear();
                content.add(new LoadingPanel(messages.foodBrowser_loadingMessage()));

                AsyncRequestAuthHandler.execute(new AsyncRequest<FoodData>() {
                    @Override
                    public void execute(AsyncCallback<FoodData> callback) {
                        lookupService.getFoodData(prompt.code, locale, callback);
                    }
                }, new AsyncCallback<FoodData>() {
                    @Override
                    public void onFailure(Throwable caught) {
                        content.clear();
                        content.add(WidgetFactory.createDefaultErrorMessage());
                        content.add(WidgetFactory.createBackLink());
                    }

                    @Override
                    public void onSuccess(FoodData result) {
                        addNewFood.call(result);
                    }
                });
            }
        }
    });

    yes.getElement().setId("intake24-assoc-food-yes-button");

    final int existingIndex = CollectionUtils.indexOf(pair.right.foods, new Function1<FoodEntry, Boolean>() {
        @Override
        public Boolean apply(FoodEntry argument) {
            return argument.accept(new FoodEntry.Visitor<Boolean>() {
                @Override
                public Boolean visitRaw(RawFood food) {
                    return false;
                }

                @Override
                public Boolean visitEncoded(EncodedFood food) {
                    // don't suggest foods that are already linked to other
                    // foods
                    if (food.link.isLinked())
                        return false;
                    // don't suggest linking the food to itself
                    else if (food.link.id.equals(pair.left.link.id))
                        return false;
                    // don't suggest if the food has foods linked to it
                    else if (!Meal.linkedFoods(pair.right.foods, food).isEmpty())
                        return false;
                    else if (prompt.isCategoryCode)
                        return food.isInCategory(prompt.code);
                    else
                        return food.data.code.equals(prompt.code);
                }

                @Override
                public Boolean visitTemplate(TemplateFood food) {
                    return false;
                }

                @Override
                public Boolean visitMissing(MissingFood food) {
                    return false;
                }

                @Override
                public Boolean visitCompound(CompoundFood food) {
                    return false;
                }
            });
        }
    });

    no.getElement().setId("intake24-assoc-food-no-button");

    tour = TreePVector.<ShepherdTour.Step>empty()
            .plus(new ShepherdTour.Step("noButton", "#intake24-assoc-food-no-button",
                    helpMessages.assocFood_noButtonTitle(), helpMessages.assocFood_noButtonDescription()))
            .plus(new ShepherdTour.Step("yesButton", "#intake24-assoc-food-yes-button",
                    helpMessages.assocFood_yesButtonTitle(), helpMessages.assocFood_yesButtonDescription()));

    if (existingIndex != -1) {
        Button yesExisting = WidgetFactory.createButton(messages.assocFoods_alreadyEntered(),
                new ClickHandler() {
                    @Override
                    public void onClick(ClickEvent event) {
                        addExistingFood.call(pair.right.foods.get(existingIndex));
                    }
                });

        yesExisting.getElement().setId("intake24-assoc-food-yes-existing-button");

        tour = tour.plus(new ShepherdTour.Step("yesButton", "#intake24-assoc-food-yes-existing-button",
                helpMessages.assocFood_yesExistingButtonTitle(),
                helpMessages.assocFood_yesExistingButtonDescription(), "top right", "bottom right"));

        ShepherdTour.makeShepherdTarget(yesExisting);

        buttonsPanel = WidgetFactory.createButtonsPanel(no, yes, yesExisting);
    } else {
        buttonsPanel = WidgetFactory.createButtonsPanel(no, yes);
    }

    content.add(buttonsPanel);

    ShepherdTour.makeShepherdTarget(yes, no);

    interf = new FlowPanel();

    return new SurveyStageInterface.Aligned(content, HasHorizontalAlignment.ALIGN_LEFT,
            HasVerticalAlignment.ALIGN_TOP, SurveyStageInterface.DEFAULT_OPTIONS);
}

From source file:net.scran24.user.client.survey.prompts.SameAsBeforePrompt.java

@Override
public SurveyStageInterface getInterface(final Callback1<MealOperation> onComplete,
        Callback1<Function1<Pair<FoodEntry, Meal>, Pair<FoodEntry, Meal>>> updateIntermediateState) {

    final FlowPanel content = new FlowPanel();
    PromptUtil.addBackLink(content);//from www  .j av  a2s. c  o m
    final Panel promptPanel = WidgetFactory.createPromptPanel(
            SafeHtmlUtils.fromSafeConstant(messages
                    .sameAsBefore_promptText(SafeHtmlUtils.htmlEscape(food.description().toLowerCase()))),
            ShepherdTour.createTourButton(tour, SameAsBeforePrompt.class.getSimpleName()));
    content.add(promptPanel);

    final EncodedFood mainFoodAsBefore = asBefore.mainFood;
    final PVector<FoodEntry> assocFoodsAsBefore = asBefore.linkedFoods;

    final double leftoversWeight = mainFoodAsBefore.completedPortionSize().leftoversWeight();
    final double servingWeight = mainFoodAsBefore.completedPortionSize().servingWeight();

    final int leftoversPercent = (int) (leftoversWeight * 100.0 / servingWeight);
    final int leftoversPercentRounded = (leftoversPercent + 4) / 5 * 5;

    final String portionSize = messages.sameAsBefore_servingSize(
            Integer.toString((int) servingWeight) + (mainFoodAsBefore.isDrink() ? " ml" : " g"));
    final String leftovers = (leftoversWeight < 0.01)
            ? (mainFoodAsBefore.isDrink() ? messages.sameAsBefore_noLeftoversDrink()
                    : messages.sameAsBefore_noLeftoversFood())
            : messages.sameAsBefore_leftovers(leftoversPercentRounded + "%");

    HTMLPanel portionSizePanel = new HTMLPanel(portionSize);
    portionSizePanel.getElement().setId("intake24-sab-portion-size");
    content.add(portionSizePanel);
    HTMLPanel leftoversPanel = new HTMLPanel(leftovers);
    leftoversPanel.getElement().setId("intake24-sab-leftovers");
    content.add(leftoversPanel);

    String assocFoodsHTML = messages.sameAsBefore_hadItWith();

    if (!assocFoodsAsBefore.isEmpty())
        assocFoodsHTML += "<ul>";

    for (FoodEntry f : assocFoodsAsBefore) {
        EncodedFood assocFood = f.asEncoded();

        String assocFoodDescription;

        if (assocFood.isInCategory(SpecialData.FOOD_CODE_MILK_IN_HOT_DRINK))
            assocFoodDescription = SafeHtmlUtils.htmlEscape(assocFood.description()) + " ("
                    + SafeHtmlUtils.htmlEscape(MilkInHotDrinkPortionSizeScript.amounts.get(
                            Integer.parseInt(assocFood.completedPortionSize().data.get("milkPartIndex"))).name)
                    + ")";
        else
            assocFoodDescription = SafeHtmlUtils.htmlEscape(assocFood.description()) + " ("
                    + Integer.toString((int) assocFood.completedPortionSize().servingWeight())
                    + (assocFood.isDrink() ? " ml" : " g") + ")";

        assocFoodsHTML += "<li>" + assocFoodDescription + "</li>";
    }

    HTMLPanel assocFoodsPanel;

    if (!assocFoodsAsBefore.isEmpty()) {
        assocFoodsHTML += "</ul>";
        assocFoodsPanel = new HTMLPanel(assocFoodsHTML);

    } else {
        assocFoodsPanel = new HTMLPanel(messages.sameAsBefore_noAddedFoods());
    }

    assocFoodsPanel.getElement().setId("intake24-sab-assoc-foods");
    content.add(assocFoodsPanel);

    Button yes = WidgetFactory.createButton(messages.sameAsBefore_confirmButtonLabel(), new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            onComplete.call(MealOperation.update(new Function1<Meal, Meal>() {
                @Override
                public Meal apply(final Meal meal) {

                    PVector<FoodEntry> updatedFoods = meal.foods
                            .with(foodIndex,
                                    food.withPortionSize(
                                            PortionSize.complete(mainFoodAsBefore.completedPortionSize()))
                                            .disableAllPrompts())
                            .plusAll(map(assocFoodsAsBefore, new Function1<FoodEntry, FoodEntry>() {
                                @Override
                                public FoodEntry apply(FoodEntry assocFood) {
                                    return assocFood.relink(FoodLink.newLinked(food.link.id));
                                }
                            }));

                    return meal.withFoods(updatedFoods);
                }
            }));
        }
    });

    yes.getElement().setId("intake24-sab-yes-button");

    Button no = WidgetFactory.createButton(messages.sameAsBefore_rejectButtonLabel(), new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            onComplete
                    .call(MealOperation.updateEncodedFood(foodIndex, new Function1<EncodedFood, EncodedFood>() {

                        @Override
                        public EncodedFood apply(EncodedFood argument) {
                            return argument.markNotSameAsBefore();
                        }
                    }));

        }
    });

    no.getElement().setId("intake24-sab-no-button");

    content.add(WidgetFactory.createButtonsPanel(yes, no));

    ShepherdTour.makeShepherdTarget(promptPanel, portionSizePanel, leftoversPanel, assocFoodsPanel, yes, no);

    return new SurveyStageInterface.Aligned(content, HasHorizontalAlignment.ALIGN_LEFT,
            HasVerticalAlignment.ALIGN_TOP, SurveyStageInterface.DEFAULT_OPTIONS);
}

From source file:net.scran24.user.client.survey.prompts.simple.OptionalFoodPrompt.java

License:Apache License

@Override
public FlowPanel getInterface(final Callback1<Option<String>> onComplete) {
    final FlowPanel content = new FlowPanel();

    final Panel promptPanel = WidgetFactory.createPromptPanel(def.promptHtml);
    content.add(promptPanel);/* ww w  .  j a v  a2s  .  co m*/

    final FoodBrowser foodBrowser = new FoodBrowser(locale, new Callback1<FoodData>() {
        @Override
        public void call(FoodData result) {
            onComplete.call(Option.some(result.code));
        }
    }, new Callback1<String>() {
        @Override
        public void call(String code) {
            throw new RuntimeException("Special foods are not allowed as associated foods");
        }
    }, new Callback() {
        @Override
        public void call() {
            // FIXME: A quick hack to get rid of compiler errors -- this
            // prompt seems to be unused
            // fix this if this is actually used!
            onComplete.call(Option.<String>none());
        }
    }, Option.<SkipFoodHandler>none(), true, Option.<Pair<String, String>>none());

    Button no = WidgetFactory.createButton(def.noButtonText/* "No, I did not" */, new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            onComplete.call(Option.<String>none());
        }
    });

    Button yes = WidgetFactory.createButton(def.yesButtonText/* "Yes, I had some" */, new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            content.clear();
            PromptUtil.addBackLink(content);
            content.add(promptPanel);
            content.add(new HTMLPanel(def.foodChoicePromptHtml /*
                                                               * SafeHtmlUtils
                                                               * .
                                                               * fromSafeConstant
                                                               * (
                                                               * "<p>Please select the specific type of this food that you've had:</p>"
                                                               * )
                                                               */));
            content.add(interf);

            content.add(foodBrowser);

            foodBrowser.browse(def.categoryCode, "?");
        }
    });

    buttonsPanel = WidgetFactory.createButtonsPanel(no, yes);
    content.add(buttonsPanel);

    interf = new FlowPanel();

    return content;
}