visibility.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. import { useState } from 'react';
  2. import Field, { getValidationRules } from './_field';
  3. import { useFormContext } from 'react-hook-form';
  4. import { NeoButton, Modal, Hidden } from 'app/design/controls'
  5. import { getVisibilityValues } from './select';
  6. import { visibilityById } from 'app/lib/util';
  7. import RbList from 'app/ui/molecules/form-controls/radio-list';
  8. import ChkList from 'app/ui/molecules/form-controls/checkbox-list';
  9. import { View, Row, Pressable } from 'app/design/view'
  10. import { Text } from 'app/design/typography'
  11. import { Icon } from 'app/ui/atoms/icon'
  12. import Profile from 'app/ui/molecules/profile/profile';
  13. import { useTranslation } from 'react-i18next'
  14. import i18n from 'i18next'
  15. import { useFormField } from 'app/lib/form/use-form-field';
  16. import { wellButtonProps } from 'app/lib/form/form-helpers';
  17. import FieldWell from './_well';
  18. const SUB_TYPES = new Set([6, 8, 9]);
  19. const needsSub = (val) => SUB_TYPES.has(Number(val));
  20. const sameId = (a, b) => String(a) === String(b);
  21. function formatOverflow(labels, max = 3) {
  22. if (labels.length <= max) return labels.join(', ');
  23. return `${labels.slice(0, max).join(', ')} ${i18n.t('+ {{count}} more', { count: labels.length - max })}`;
  24. }
  25. function OwnerAvatar({ owner, displaySize = '3xs', displayType = 'unit_wo_info', ...rest }) {
  26. if (!owner) return null;
  27. return (
  28. <Profile
  29. {...owner}
  30. displayType={displayType}
  31. displaySize={displaySize}
  32. showLinks={false}
  33. {...rest}
  34. />
  35. );
  36. }
  37. function friendOptions(values) {
  38. return (values || []).map((item) => ({
  39. value: item.key,
  40. label: item.value?.display_name,
  41. icon: (
  42. <Profile
  43. {...item.value}
  44. displayType="unit_wo_info"
  45. displaySize="sm"
  46. />
  47. ),
  48. }));
  49. }
  50. export default function FormFieldVisibility(props) {
  51. const { setValue } = useFormContext();
  52. const { name, field } = useFormField(props, {
  53. rules: getValidationRules(props),
  54. });
  55. const { t } = useTranslation();
  56. const [isModal, setIsModal] = useState(false);
  57. const [subKind, setSubKind] = useState(null);
  58. const [subValues, setSubValues] = useState(
  59. props?.subvalue ? props.subvalue.split(",").map(value => parseInt(value, 10)) : []
  60. );
  61. const handleValueChange = (val) => {
  62. field.onChange(val);
  63. if (props.onChange) {
  64. props.onChange(val)
  65. }
  66. if (val != field.value) setSubValues([]);
  67. if (needsSub(val)) setSubKind(Number(val));
  68. else setIsModal(false);
  69. }
  70. const handleSubValueChange = (val) => {
  71. setSubValues(val);
  72. setSubKind(null);
  73. }
  74. const applyVisibility = () => {
  75. setIsModal(false);
  76. setValue(name + '_items', subValues);
  77. }
  78. const openModal = () => setIsModal(true);
  79. const subOptionsMap = {
  80. 6: friendOptions(props.values_friends),
  81. 8: getVisibilityValues(props.values_relations || []),
  82. 9: getVisibilityValues(props.values_memberships || []),
  83. };
  84. const subOptions = subOptionsMap[Number(field.value)] || [];
  85. const selectedSubLabels = subOptions
  86. .filter(item => subValues.some(v => sameId(v, item.value)))
  87. .map(item => item.label);
  88. const subLabelDisplay = formatOverflow(selectedSubLabels);
  89. const filteredValues = getVisibilityValues(props.values)
  90. .filter((item) => {
  91. if (item.value === '' || item.value == null) return false;
  92. if (Number(item.value) === 6 && !props.values_friends) return false;
  93. if (Number(item.value) === 8 && !props.values_relations) return false;
  94. if (Number(item.value) === 9 && !props.values_memberships) return false;
  95. return true;
  96. })
  97. .map((item) => {
  98. const visibilityIcon = visibilityById(item.value, t);
  99. const isCurrentSub = needsSub(field.value) && sameId(item.value, field.value);
  100. return {
  101. ...item,
  102. info: isCurrentSub ? subLabelDisplay : item.info,
  103. label: visibilityIcon?.text || item.label,
  104. icon: visibilityIcon?.icon ? (
  105. <View className="h-6 w-6 overflow-hidden">
  106. <Icon icon={visibilityIcon.icon} width={24} height={24} />
  107. </View>
  108. ) : null,
  109. };
  110. });
  111. const selectedItem = filteredValues.find(item => sameId(item.value, subKind));
  112. const empty = (
  113. <Text className="text-muted-foreground text-center py-6 px-4">
  114. {t('Nothing to show')}
  115. </Text>
  116. );
  117. const modalHeader = (
  118. <Row className="w-full items-center">
  119. <View className="flex-auto absolute left-0 right-0">
  120. <Text className="text-secondary-foreground text-2xl font-bold tracking-tight text-center">{selectedItem?.label}</Text>
  121. </View>
  122. <View>
  123. <NeoButton style="glass" controlSize="regular" borderShape="circle" image="ArrowLeft" accessibilityLabel={t('Back')} onPress={() => setSubKind(null)} />
  124. </View>
  125. </Row>
  126. );
  127. const modalContent = subKind ? (
  128. subOptions.length === 0 ? empty : (
  129. <ChkList values={subOptions} setValue={handleSubValueChange} selectedValue={subValues} />
  130. )
  131. ) : filteredValues.length === 0 ? empty : (
  132. <>
  133. <RbList values={filteredValues} setValue={handleValueChange} selectedValue={field.value} />
  134. <View className="flex-row justify-end pt-3 mt-3 border-t border-border/60 ">
  135. <NeoButton
  136. style="borderedProminent"
  137. label={t('Done')}
  138. disabled={needsSub(field.value) && selectedSubLabels.length == 0}
  139. onPress={applyVisibility}
  140. />
  141. </View>
  142. </>
  143. );
  144. const modalElement = (
  145. <Modal
  146. title={subKind ? modalHeader : t('Choose audience')}
  147. onVisible={isModal}
  148. onClose={!subKind ? () => setIsModal(false) : undefined}
  149. transparent
  150. headerBorder
  151. scrollable
  152. >
  153. {modalContent}
  154. </Modal>
  155. );
  156. if (props.origtype == 'hidden') {
  157. return (
  158. <>
  159. {props.addElement}
  160. {props.renderTrigger?.({
  161. onPress: undefined,
  162. displayText: props.owner_info?.display_name || '',
  163. icon: props.owner_info ? <OwnerAvatar owner={props.owner_info} displaySize="3xs" /> : null,
  164. })}
  165. <Hidden
  166. name={name}
  167. onChangeText={field.onChange}
  168. onBlur={field.onBlur}
  169. defaultValue={props.value}
  170. />
  171. {!!props.owner_info && !props.renderTrigger && (
  172. <Row className="h-5.5 items-center text-muted-foreground web:group-hover:text-secondary-foreground web:duration-300">
  173. <View className="flex-none mb-auto">
  174. <OwnerAvatar owner={props.owner_info} displaySize="2xs" />
  175. </View>
  176. <View className="px-1 flex-auto">
  177. <OwnerAvatar
  178. owner={props.owner_info}
  179. displayType="unit_wo_image"
  180. displaySize="sm"
  181. showInfo={false}
  182. />
  183. </View>
  184. </Row>
  185. )}
  186. </>
  187. )
  188. }
  189. const visibilityData = visibilityById(field.value, t);
  190. const ownerName = props.owner_info?.display_name || '';
  191. const ownerIcon = props.owner_info ? <OwnerAvatar owner={props.owner_info} displaySize="3xs" /> : null;
  192. const icon = visibilityData ? visibilityData.icon : (ownerIcon || 'Globe');
  193. const selectedOption = filteredValues.find(item => sameId(item.value, field.value));
  194. const displayText = selectedSubLabels.length > 0
  195. ? formatOverflow(selectedSubLabels)
  196. : visibilityData?.text || selectedOption?.label || ownerName || t('Choose audience');
  197. let trigger;
  198. if (props.format == 'nofield' && props.noContainer) {
  199. trigger = props.renderTrigger
  200. ? props.renderTrigger({ onPress: openModal, displayText, icon })
  201. : (
  202. <NeoButton
  203. label={displayText}
  204. image={icon}
  205. style={props.style || 'bordered'}
  206. controlSize={props.controlSize || 'mini'}
  207. borderShape={props.borderShape || 'capsule'}
  208. onPress={openModal}
  209. />
  210. );
  211. return (
  212. <>
  213. {modalElement}
  214. {props.addElement}
  215. {trigger}
  216. </>
  217. );
  218. }
  219. if (props.format == 'nofield') {
  220. return (
  221. <>
  222. {modalElement}
  223. <Pressable onPress={openModal}>
  224. {props.addElement}
  225. <Row className="flex-none mr-auto gap-x-0.5 px-1 py-1 rounded-lg items-center text-muted-foreground web:group-hover:text-secondary-foreground h-6 web:duration-300">
  226. <Icon icon={icon} width={16} height={16} className="text-muted-foreground" />
  227. <Text className="leading-5.5 ml-1 whitespace-nowrap text-ellipsis overflow-hidden tracking-tight text-muted-foreground web:group-hover:text-secondary-foreground font-medium text-sm native:text-sm">{displayText}</Text>
  228. <Icon icon="ChevronDown" width={16} height={16} className="text-muted-foreground" />
  229. </Row>
  230. </Pressable>
  231. </>
  232. );
  233. }
  234. return (
  235. <>
  236. {modalElement}
  237. <Field {...props}>
  238. <FieldWell>
  239. <NeoButton
  240. {...wellButtonProps()}
  241. label={displayText}
  242. image={visibilityData?.icon || 'Globe'}
  243. onPress={openModal}
  244. />
  245. </FieldWell>
  246. </Field>
  247. </>
  248. );
  249. }