Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 | 27x 27x 27x 27x 27x 27x 27x 27x 27x | import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useState } from 'react';
import PropTypes from 'prop-types';
import get from 'lodash/get';
import cloneDeep from 'lodash/cloneDeep';
import { Field, useForm, useFormState } from 'react-final-form';
import { Button, Headline, IconButton, MultiColumnList, TextField, Tooltip } from '@folio/stripes/components';
import { useKintIntl } from '../hooks';
import css from '../../../styles/ActionListFieldArray.css';
const EDITING_ACTIONS_WIDTH = 25;
const NON_EDITING_ACTIONS_WIDTH = 20;
const TOTAL_WIDTH = 100;
const propTypes = {
actionAssigner: PropTypes.func,
columnMapping: PropTypes.object,
creatableFields: PropTypes.object,
createCallback: PropTypes.func,
defaultNewObject: PropTypes.object,
editableFields: PropTypes.object,
fields: PropTypes.object,
fieldComponents: PropTypes.object,
formatter: PropTypes.object,
hideActionsColumn: PropTypes.bool,
hideCreateButton: PropTypes.bool,
intlKey: PropTypes.string,
intlNS: PropTypes.string,
label: PropTypes.oneOfType([
PropTypes.string,
PropTypes.node
]),
labelOverrides: PropTypes.object,
onRowClick: PropTypes.func,
triggerFormSubmit: PropTypes.func.isRequired,
validateFields: PropTypes.object,
visibleFields: PropTypes.arrayOf(PropTypes.string)
};
// This needs to be outside of the main component for forwardRef to work properly it seems.
const ActionTrigger = forwardRef(({ action, ...actionTriggerProps }, ref) => {
if (action.icon) {
return (
<IconButton
ref={ref}
icon={action.icon}
{...actionTriggerProps}
/>
);
}
return (
<Button
ref={ref}
marginBottom0
{...actionTriggerProps}
>
{action.label ?? action.name}
</Button>
);
});
ActionTrigger.propTypes = {
action: PropTypes.shape({
icon: PropTypes.string,
label: PropTypes.string,
name: PropTypes.string
})
};
const NEW_ROW = 'NEW_ROW';
const ActionListFieldArray = forwardRef(({
actionAssigner,
columnMapping,
creatableFields,
createCallback,
defaultNewObject,
editableFields,
fields,
fieldComponents,
hideActionsColumn = false,
hideCreateButton = false,
intlKey: passedIntlKey,
intlNS: passedIntlNS,
label,
labelOverrides = {},
onRowClick,
validateFields,
visibleFields,
triggerFormSubmit,
...mclProps // Assume anything left over is to directly apply to the MCL
}, ref) => {
// Grab finalForm functions/values from form hooks
const { change } = useForm();
const { hasValidationErrors, initialValues, pristine, submitting, values } = useFormState();
const kintIntl = useKintIntl(passedIntlKey, passedIntlNS);
/*
Keep track of which field we are editing.
null for no field, string id if we are editing an existing field and
'NEW_ROW' for a new row
*/
const [editing, setEditing] = useState((fields?.value?.filter(f => f._isNewActionListRow)?.length ?? 0) > 0 ? NEW_ROW : undefined);
const toggleEditing = useCallback((id) => {
if (editing) {
setEditing();
} else {
setEditing(id);
}
}, [editing]);
// Ensure editing doesn't get stuck in "NEW_ROW" state;
useEffect(() => {
if (editing === NEW_ROW && (fields?.value?.filter(f => f._isNewActionListRow)?.length ?? 0) === 0) {
setEditing();
}
}, [editing, fields?.value]);
const handleSave = (index) => {
const {
actionListActions: _a,
fieldName: _fn,
fieldIndex: _fi,
_isNewActionListRow: _inalr,
...rowData
} = fields.value[index];
// Find "edit" entry in actionAssigner
const editCallback = actionAssigner(rowData)?.find(act => act.name === 'edit')?.callback;
if (editCallback) {
editCallback(rowData);
}
};
const handleCreate = (index) => {
const {
actionListActions: _a,
fieldName: _fn,
fieldIndex: _fi,
_isNewActionListRow: _inalr,
...rowData
} = fields.value[index];
if (createCallback) {
createCallback(rowData);
}
};
const handleClickCreate = useCallback(() => {
toggleEditing(NEW_ROW);
fields.unshift({
...defaultNewObject,
_isNewActionListRow: true
});
}, [defaultNewObject, fields, toggleEditing]);
// Way to go into create mode from external component, and way to tell internal editing state
useImperativeHandle(ref, () => ({
create: handleClickCreate,
editing
}), [editing, handleClickCreate]);
const getColumnWidths = () => {
const widthNotInUseByActions = editing ?
TOTAL_WIDTH - EDITING_ACTIONS_WIDTH :
TOTAL_WIDTH - NON_EDITING_ACTIONS_WIDTH;
const staticWidth = (widthNotInUseByActions / (visibleFields.length));
const widthsObject = {};
visibleFields.forEach((f) => {
if (f !== 'actionListActions') {
widthsObject[f] = `${staticWidth}%`;
}
});
widthsObject.actionListActions = editing ?
`${EDITING_ACTIONS_WIDTH}%` :
`${NON_EDITING_ACTIONS_WIDTH}%`;
return widthsObject;
};
const renderActionButtons = (data) => {
const fieldName = `contentData[${data.rowIndex}]`;
const { actionListActions: actions, ...rest } = data;
if (data.id === editing || (!data.id && editing === NEW_ROW)) {
// Render the save/cancel buttons
return (
<div id={`action-button-parent-${data.rowIndex + 1}`}>
<Button
key={`save[${data.rowIndex}]`}
buttonStyle="primary"
disabled={hasValidationErrors || submitting || pristine}
marginBottom0
onClick={() => {
triggerFormSubmit(); // This is set up as () => null in ActionList, so essentially only acts here to force validation
if (!hasValidationErrors) {
if (!data.id && editing === NEW_ROW) {
handleCreate(data.rowIndex);
} else {
handleSave(data.rowIndex);
}
toggleEditing();
}
}}
type="submit"
>
{kintIntl.formatKintMessage({
id: 'save',
overrideValue: labelOverrides?.save
})}
</Button>
<Button
key={`cancel[${data.rowIndex}]`}
data-type-button="cancel"
marginBottom0
onClick={() => {
if (!data.id && editing === NEW_ROW) {
fields.remove(data.rowIndex);
toggleEditing(NEW_ROW);
} else {
change(fieldName, get(initialValues, fieldName));
toggleEditing(data.id);
}
}}
>
{kintIntl.formatKintMessage({
id: 'cancel',
overrideValue: labelOverrides?.cancel
})}
</Button>
</div>
);
}
return (
<div id={`action-button-parent-${data.rowIndex + 1}`}>
{actions?.map(action => {
let actionFunction;
if (action.callback) {
actionFunction = () => action.callback(rest);
}
// Edit has special action functionality, revealing fields etc.
if (action.name === 'edit') {
actionFunction = () => toggleEditing(data.id);
}
let ariaLabel = `action-${action.name}[${data.rowIndex}]`;
if (action?.ariaLabel) {
if (typeof action.ariaLabel === 'function') {
ariaLabel = action.ariaLabel(data);
} else if (typeof action.ariaLabel === 'string') {
ariaLabel = action.ariaLabel;
} else {
throw new Error(`Provided ariaLabel for action "${action.name}" must be a function or a string.`);
}
}
let tooltip;
let tooltipSub;
if (action?.tooltip) {
if (typeof action.tooltip === 'function') {
tooltip = action.tooltip(data);
} else {
tooltip = action.tooltip;
}
if (action?.tooltipSub) {
if (typeof action.tooltipSub === 'function') {
tooltipSub = action.tooltipSub(data);
} else {
tooltipSub = action.tooltipSub;
}
}
}
// If a tooltip is declared, render that around the actionButton
if (tooltip) {
return (
<Tooltip
id={`action-${action.name}[${data.rowIndex}]-tooltip`}
sub={tooltipSub}
text={tooltip}
>
{({ ref: actionTriggerRef, ariaIds }) => (
<ActionTrigger
key={`action-${action.name}[${data.rowIndex}]`}
ref={actionTriggerRef}
action={action}
aria-describedby={ariaIds.sub}
aria-labelledby={ariaIds.text}
disabled={!!editing}
onClick={e => {
e.stopPropagation();
if (actionFunction) {
return actionFunction();
}
return null;
}}
to={action.to}
/>
)}
</Tooltip>
);
}
// Finally, render the action button itself
return (
<ActionTrigger
key={`action-${action.name}[${data.rowIndex}]`}
action={action}
ariaLabel={ariaLabel}
disabled={!!editing}
onClick={e => {
e.stopPropagation();
if (actionFunction) {
return actionFunction();
}
return null;
}}
to={action.to}
/>
);
})}
</div>
);
};
const assignActions = () => {
return (
fields.map((fieldName, fieldIndex) => {
// Fetch the content from the field Values
const cd = cloneDeep(get(values, fieldName));
cd.actionListActions = actionAssigner(cd);
return { ...cd, fieldName, fieldIndex };
})
);
};
const { formatter, ...restOfMclProps } = mclProps; // Destructure formatter part of mclProps
const fieldAwareFormatter = () => {
const returnObj = {};
// For each visible field, if it's being edited then ignore passed formatters, else use them
visibleFields.forEach((key, index) => {
// Work out now whether or not to autofocus, so that gets cemented into the returnObj function
const shouldAutoFocus = index === 0;
returnObj[key] = cd => {
// Row is being edited if it has no id, or its id is in the editing string
const editingRow = cd.id === editing || !cd.id;
// Default to the passed formatter values
let returnValue = formatter?.[key] ? formatter[key](cd) : cd[key];
// If editing, replace values with fields
if (editingRow) {
/*
Check if the property is a visible field.
If it is not then we don't allow editing in this component.
*/
const editFunction = editableFields[key] ?? (() => true);
const createFunction = creatableFields[key] ?? (() => true);
/*
Next check if this is a new row, if so we should run the createableField function with the data.
If it is not a new row, then we run the editableField function with the data,
and it should return true/false
For both checks
true => Field, false => display value
*/
if (
(!cd.id && createFunction(cd)) ||
(!!cd.id && editFunction(cd))
) {
const passedObject = {
allValues: values,
index: cd?.fieldIndex,
key,
name: `${cd.fieldName}.${key}`,
rowFieldName: cd.fieldName
};
const validateFunction = validateFields?.[key] ? validateFields?.[key](passedObject) : null;
returnValue =
fieldComponents[key] ?
fieldComponents[key](passedObject) :
<Field
ariaLabel={key} // TODO at the moment the only way to override this is passing in an entire fieldComponent.
autoFocus={shouldAutoFocus} // TODO at the moment this will always be the first field, even if it's not editable
component={TextField}
marginBottom0
name={`${cd.fieldName}.${key}`}
parse={v => v}
validate={validateFunction}
/>;
}
}
return returnValue;
};
});
return returnObj;
};
return (
<>
<div className={css.header}>
<Headline
className={css.headerText}
>
{label}
</Headline>
{!hideCreateButton &&
<Button
buttonStyle="primary"
disabled={!!editing || !createCallback}
marginBottom0
onClick={handleClickCreate}
>
{kintIntl.formatKintMessage({
id: 'new',
overrideValue: labelOverrides?.new
})}
</Button>
}
</div>
<MultiColumnList
columnMapping={{
...columnMapping,
actionListActions: kintIntl.formatKintMessage({
id: 'actions',
overrideValue: labelOverrides?.actions
})
}}
columnWidths={getColumnWidths()}
contentData={assignActions()}
formatter={{
actionListActions: renderActionButtons,
...fieldAwareFormatter()
}}
interactive={!!onRowClick}
onRowClick={onRowClick ? (e, row) => {
// Make sure we ONLY fire row click from row, and not from action buttons.
const targetIsAction = e.target.closest('[id^=action-button-parent]') !== null;
if (!targetIsAction) {
const { actionListActions: _ala, ...rowWithoutActions } = row;
onRowClick(e, rowWithoutActions);
}
} : null}
visibleColumns={(
!hideActionsColumn ||
!!editing
) ?
[...visibleFields, 'actionListActions'] :
visibleFields
}
{...restOfMclProps}
/>
</>
);
});
ActionListFieldArray.propTypes = propTypes;
export default ActionListFieldArray;
|