gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

field-array.jsx (1882B)


      1 /*
      2 	GoToSocial
      3 	Copyright (C) GoToSocial Authors admin@gotosocial.org
      4 	SPDX-License-Identifier: AGPL-3.0-or-later
      5 
      6 	This program is free software: you can redistribute it and/or modify
      7 	it under the terms of the GNU Affero General Public License as published by
      8 	the Free Software Foundation, either version 3 of the License, or
      9 	(at your option) any later version.
     10 
     11 	This program is distributed in the hope that it will be useful,
     12 	but WITHOUT ANY WARRANTY; without even the implied warranty of
     13 	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     14 	GNU Affero General Public License for more details.
     15 
     16 	You should have received a copy of the GNU Affero General Public License
     17 	along with this program.  If not, see <http://www.gnu.org/licenses/>.
     18 */
     19 
     20 "use strict";
     21 
     22 const React = require("react");
     23 
     24 const getFormMutations = require("./get-form-mutations");
     25 
     26 function parseFields(entries, length) {
     27 	const fields = [];
     28 
     29 	for (let i = 0; i < length; i++) {
     30 		if (entries[i] != undefined) {
     31 			fields[i] = Object.assign({}, entries[i]);
     32 		} else {
     33 			fields[i] = {};
     34 		}
     35 	}
     36 
     37 	return fields;
     38 }
     39 
     40 module.exports = function useArrayInput({ name, _Name }, { initialValue, length = 0 }) {
     41 	const fields = React.useRef({});
     42 
     43 	const value = React.useMemo(() => parseFields(initialValue, length), [initialValue, length]);
     44 
     45 	return {
     46 		name,
     47 		value,
     48 		ctx: fields.current,
     49 		maxLength: length,
     50 		selectedValues() {
     51 			// if any form field changed, we need to re-send everything
     52 			const hasUpdate = Object.values(fields.current).some((fieldSet) => {
     53 				const { updatedFields } = getFormMutations(fieldSet, { changedOnly: true });
     54 				return updatedFields.length > 0;
     55 			});
     56 			if (hasUpdate) {
     57 				return Object.values(fields.current).map((fieldSet) => {
     58 					return getFormMutations(fieldSet, { changedOnly: false }).mutationData;
     59 				});
     60 			} else {
     61 				return [];
     62 			}
     63 		}
     64 	};
     65 };