1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.ui.editor;
35
36 import info.magnolia.ui.api.i18n.I18NAuthoringSupport;
37 import info.magnolia.ui.framework.ContextProperty;
38 import info.magnolia.ui.framework.UiComponentContext;
39 import info.magnolia.ui.framework.UiComponentContextProxy;
40
41 import java.util.Collections;
42 import java.util.List;
43 import java.util.Locale;
44 import java.util.Optional;
45 import java.util.stream.Stream;
46
47
48
49
50
51 public interface LocaleContext extends UiComponentContext {
52
53 ContextProperty<Locale> current();
54
55 ContextProperty<List<Locale>> availableLocales();
56
57 ContextProperty<Locale> defaultLocale();
58
59 default Stream<Locale> getAvailableLocales() {
60 return availableLocales().value().map(List::stream).orElse(Stream.empty());
61 }
62
63 default Locale getCurrent() {
64 return current().value().orElse(getDefault());
65 }
66
67 default Locale getDefault() {
68 return defaultLocale().nullableValue();
69 }
70
71 default boolean isPopulated() {
72 return availableLocales().value().map(locales -> locales.size() > 0).orElse(false);
73 }
74
75 default <T> void populateFromI18NAuthoringSupport(T item, I18NAuthoringSupport<T> i18NAuthoringSupport) {
76 Locale defaultLocale = i18NAuthoringSupport.getDefaultLocale(item);
77
78 if (defaultLocale == null) {
79 restrictTo(Locale.getDefault());
80 return;
81 }
82
83 List<Locale> availableLocales = Optional.ofNullable(i18NAuthoringSupport.getAvailableLocales(item)).orElse(Collections.emptyList());
84
85 defaultLocale().set(defaultLocale);
86
87 if (!availableLocales.contains(current().nullableValue())) {
88 current().set(defaultLocale);
89 }
90
91 availableLocales().set(availableLocales);
92 }
93
94 default void restrictTo(Locale locale) {
95 defaultLocale().set(locale);
96 current().set(locale);
97 availableLocales().set(Collections.singletonList(locale));
98 }
99
100
101
102
103 static LocaleContext of(Locale locale) {
104 LocaleContext localeContext = new UiComponentContextProxy().createUiComponentContext(LocaleContext.class);
105 localeContext.restrictTo(locale);
106 return localeContext;
107 }
108 }