View Javadoc
1   /**
2    * This file Copyright (c) 2018 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.ui.editor;
35  
36  import static java.util.stream.Collectors.toList;
37  
38  import info.magnolia.i18nsystem.SimpleTranslator;
39  import info.magnolia.icons.MagnoliaIcons;
40  import info.magnolia.ui.contentapp.Datasource;
41  import info.magnolia.ui.framework.WithImplementation;
42  import info.magnolia.ui.theme.ResurfaceTheme;
43  
44  import java.util.ArrayList;
45  import java.util.Collections;
46  import java.util.LinkedHashMap;
47  import java.util.List;
48  import java.util.Locale;
49  import java.util.Map;
50  import java.util.concurrent.CompletableFuture;
51  import java.util.stream.Stream;
52  
53  import javax.inject.Inject;
54  
55  import org.slf4j.Logger;
56  import org.slf4j.LoggerFactory;
57  
58  import com.vaadin.data.BinderValidationStatus;
59  import com.vaadin.ui.AbstractOrderedLayout;
60  import com.vaadin.ui.Alignment;
61  import com.vaadin.ui.Button;
62  import com.vaadin.ui.Component;
63  import com.vaadin.ui.HorizontalLayout;
64  import com.vaadin.ui.Notification;
65  import com.vaadin.ui.VerticalLayout;
66  
67  import lombok.EqualsAndHashCode;
68  import lombok.Getter;
69  import lombok.Setter;
70  
71  /**
72   * Editor view which hosts a number of similar child editors.
73   *
74   * @param <T>
75   *     item type.
76   */
77  public class MultiFormView<T> implements EditorView<T> {
78  
79      private static final Logger log = LoggerFactory.getLogger(MultiFormView.class);
80  
81      private final MultiFormDefinition<T> definition;
82      private final SimpleTranslator i18n;
83      private final Locale locale;
84      private final Datasource<T> datasource;
85      private final MultiFormState state = new MultiFormState();
86  
87      private VerticalLayout rootLayout = new VerticalLayout();
88  
89      @Inject
90      public MultiFormView(MultiFormDefinition<T> definition, SimpleTranslator i18n, LocaleContext localeContext, Datasource<T> datasource) {
91          this.definition = definition;
92          this.i18n = i18n;
93          this.locale = localeContext.getDefault();
94          this.datasource = datasource;
95          this.state.entryResolution = create(definition.getEntryResolution(), this.locale);
96          this.rootLayout.setSpacing(true);
97          this.rootLayout.addStyleName("multi-form-view");
98  
99          layout();
100     }
101 
102     @Override
103     public List<BinderValidationStatus<?>> validate() {
104         return getAllChildren()
105                 .flatMap(view -> view.validate().stream())
106                 .collect(toList());
107     }
108 
109     @Override
110     public void write(T item) {
111         Map<EditorView<T>, ItemProviderStrategy<T, T>> children = state.children;
112         state.removedItemAccessors.stream()
113                 .map(accessor -> accessor.read(item, locale))
114                 .forEach(itemToMaybeDelete ->
115                         itemToMaybeDelete
116                                 .ifPresent(this.datasource::remove));
117 
118         List<T> itemOrder = new ArrayList<>();
119         state.order.forEach(subForm ->
120                 children.get(subForm).read(item, locale).ifPresent(localisedItem -> {
121                     itemOrder.add(localisedItem);
122                     subForm.write(localisedItem);
123                 }));
124 
125         create(this.definition.getOrderHandler(), locale).applyOrder(itemOrder);
126     }
127 
128     @Override
129     public Component asVaadinComponent() {
130         return rootLayout;
131     }
132 
133     @Override
134     public void populate(T item) {
135         getAllChildren().forEach(subForm -> {
136            rootLayout.removeComponent(subForm.asVaadinComponent());
137            subForm.destroy();
138         });
139 
140         state.clear();
141         state.entryResolution.resolveForRoot(item).forEach(propertyDefinition -> {
142             if (propertyDefinition != null) {
143                 EditorView<T> subForm = createSubForm(propertyDefinition);
144                 addSubFormToState(subForm, propertyDefinition);
145                 populate(item, subForm);
146             }
147         });
148 
149         layout();
150     }
151 
152     private EditorView<T> createSubForm(ComplexPropertyDefinition<T> propertyDefinition) {
153         final EditorView<T> subForm = create("child", propertyDefinition.getEditorDefinition());
154         if (subForm.asVaadinComponent().getCaption() == null) {
155             subForm.asVaadinComponent().setCaption(propertyDefinition.getLabel());
156         }
157         return subForm;
158     }
159 
160     private void addSubFormToState(EditorView<T> subForm, ComplexPropertyDefinition<T> propertyDefinition) {
161         ItemProviderStrategy<T, T> itemProviderStrategy = create(propertyDefinition.getItemProvider());
162         state.children.put(subForm, itemProviderStrategy);
163         state.order.add(subForm);
164     }
165 
166     private void populate(T item, EditorView<T> subForm) {
167         state.children.get(subForm).read(item, locale).ifPresent(subForm::populate);
168     }
169 
170     public void layout() {
171         rootLayout.removeAllComponents();
172         rootLayout.setMargin(false);
173         state.children.keySet().stream()
174                 .map(this::wrapChildForm)
175                 .forEach(this.rootLayout::addComponent);
176         attachAddButton();
177     }
178 
179     protected Component wrapChildForm(EditorView<T> subForm) {
180         HorizontalLayout wrapLayout = new HorizontalLayout();
181         wrapLayout.setWidth("100%");
182         subForm.asVaadinComponent().addStyleName("multi-form-entry-content");
183 
184         HorizontalLayout buttonLayout = createButtonsLayout(subForm, wrapLayout);
185         wrapLayout.addComponents(subForm.asVaadinComponent(), buttonLayout);
186         wrapLayout.setExpandRatio(subForm.asVaadinComponent(), 1f);
187         wrapLayout.setComponentAlignment(buttonLayout, Alignment.TOP_CENTER);
188         wrapLayout.addStyleName("multi-form-entry");
189 
190         return wrapLayout;
191     }
192 
193     private HorizontalLayout createButtonsLayout(EditorView<T> subForm, HorizontalLayout wrapLayout) {
194         HorizontalLayout buttonLayout = new HorizontalLayout();
195         buttonLayout.setSpacing(false);
196 
197         if (!(definition.getOrderHandler() instanceof MultiFormDefinition.OrderHandlerDefinition.Noop)) {
198             buttonLayout.addComponents(
199                     new Button(MagnoliaIcons.ARROW2_N, e -> onMove(wrapLayout, true)),
200                     new Button(MagnoliaIcons.ARROW2_S, e -> onMove(wrapLayout, false))
201             );
202         }
203         if (definition.isCanRemoveItems()) {
204             buttonLayout.addComponent(new Button(MagnoliaIcons.TRASH, e -> onDelete(subForm)));
205         }
206 
207         buttonLayout.forEach(button -> button.addStyleName(ResurfaceTheme.BUTTON_ICON));
208         return buttonLayout;
209     }
210 
211     protected void attachAddButton() {
212         Button addButton = new Button(this.i18n.translate("buttons.add"));
213         addButton.addStyleName("add-multi-form-entry-button");
214         addButton.addClickListener(e -> {
215             state.entryResolution.pick().thenAccept(propertyDefinition -> {
216                 if (propertyDefinition != null) {
217                     EditorView<T> subForm = createSubForm(propertyDefinition);
218                     addSubFormToState(subForm, propertyDefinition);
219                     rootLayout.addComponent(wrapChildForm(subForm), rootLayout.getComponentCount() - 1);
220                 }
221             }).exceptionally(ex -> {
222                 log.warn("Failed to create a multi field entry", ex);
223                 Notification.show("Failed to create multi field entry");
224                 return null;
225             });
226         });
227 
228         rootLayout.addComponent(addButton);
229     }
230 
231     private Stream<EditorView<T>> getAllChildren() {
232         return state.children.keySet().stream();
233     }
234 
235     private void onMove(AbstractOrderedLayout movedLayout, boolean moveUp) {
236         int currentPosition = rootLayout.getComponentIndex(movedLayout);
237         int newPosition = moveUp ? currentPosition - 1 : currentPosition + 1;
238 
239         if (currentPosition == 0 && moveUp) {
240             return;
241         }
242 
243         if (newPosition >= rootLayout.getComponentCount() - 1) {
244             return;
245         }
246 
247         Collections.swap(state.order, currentPosition, newPosition);
248         rootLayout.replaceComponent(rootLayout.getComponent(currentPosition), rootLayout.getComponent(newPosition));
249     }
250 
251     private void onDelete(EditorView<T> subForm) {
252         rootLayout.removeComponent(subForm.asVaadinComponent().getParent());
253 
254         state.removedItemAccessors.add(state.children.get(subForm));
255         state.children.remove(subForm);
256         state.order.remove(subForm);
257     }
258 
259     class MultiFormState {
260         Map<EditorView<T>, ItemProviderStrategy<T, T>> children = new LinkedHashMap<>();
261         List<ItemProviderStrategy<T, T>> removedItemAccessors = new ArrayList<>();
262         List<EditorView<T>> order = new ArrayList<>();
263         EntryResolution<T> entryResolution;
264 
265         void clear() {
266             children.clear();
267             removedItemAccessors.clear();
268             order.clear();
269         }
270     }
271 
272     /**
273      * Multi-form entry resolution strategy.
274      *
275      * @param <T>
276      */
277     public interface EntryResolution<T> {
278 
279         Stream<ComplexPropertyDefinition<T>> resolveForRoot(T rootDatasource);
280 
281         CompletableFuture<ComplexPropertyDefinition<T>> pick();
282 
283         @Getter
284         @Setter
285         @EqualsAndHashCode
286         class Definition<T> implements WithImplementation<EntryResolution<T>> {
287             private Class<? extends EntryResolution<T>> implementationClass;
288         }
289     }
290 }