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))
84 .filter(locales -> !locales.isEmpty())
85 .orElse(Collections.singletonList(defaultLocale));
86
87 defaultLocale().set(defaultLocale);
88
89 if (!availableLocales.contains(current().nullableValue())) {
90 current().set(defaultLocale);
91 }
92
93 availableLocales().set(availableLocales);
94 }
95
96 default void restrictTo(Locale locale) {
97 defaultLocale().set(locale);
98 current().set(locale);
99 availableLocales().set(Collections.singletonList(locale));
100 }
101
102
103
104
105 static LocaleContext of(Locale locale) {
106 LocaleContext localeContext = new UiComponentContextProxy().createUiComponentContext(LocaleContext.class);
107 localeContext.restrictTo(locale);
108 return localeContext;
109 }
110 }