@box/metadata-template-editor 2.5.9 → 2.5.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/metadata-field-list.js +1 -1
- package/dist/chunks/metadata-template-editor.js +1 -1
- package/dist/chunks/types.js +1 -1
- package/dist/esm/lib/components/field-type-tiles/field-type-tiles.js +1 -1
- package/dist/esm/lib/components/metadata-field-configurator/components/field-edit-content/field-edit-content.js +1 -1
- package/dist/esm/lib/components/metadata-field-configurator/components/type-specific-configuration/index.js +1 -1
- package/dist/esm/lib/components/metadata-field-configurator/components/type-specific-configuration/user/user-field-configuration.js +1 -0
- package/dist/esm/lib/components/metadata-field-configurator/context/editor-config-context.js +1 -1
- package/dist/esm/lib/components/metadata-field-configurator/hooks/useFieldValidation.js +1 -1
- package/dist/esm/lib/components/metadata-field-configurator/messages/user-messages.js +1 -0
- package/dist/esm/lib/components/metadata-field-configurator/utils.js +1 -1
- package/dist/esm/lib/utils/field-options/field-type-icon.js +1 -1
- package/dist/esm/lib/utils/field-options/messages.js +1 -1
- package/dist/esm/lib/utils/field-options/useFieldOptions.js +1 -1
- package/dist/esm/lib/utils/template-type-conversion/convertLocalConfiguratorToTemplateField.js +1 -1
- package/dist/esm/lib/utils/template-type-conversion/convertTemplateFieldToLocalConfigurator.js +1 -1
- package/dist/esm/lib/utils/template-type-conversion/generateJSONPatchTemplateOperations.js +1 -1
- package/dist/types/lib/components/metadata-field-configurator/components/type-specific-configuration/index.d.ts +1 -0
- package/dist/types/lib/components/metadata-field-configurator/components/type-specific-configuration/user/user-field-configuration.d.ts +4 -0
- package/dist/types/lib/components/metadata-field-configurator/context/editor-config-context.d.ts +5 -0
- package/dist/types/lib/components/metadata-field-configurator/messages/user-messages.d.ts +13 -0
- package/dist/types/lib/components/metadata-field-list/metadata-field-list.d.ts +6 -0
- package/dist/types/lib/index.d.ts +1 -1
- package/dist/types/lib/metadata-template-editor.d.ts +9 -1
- package/dist/types/lib/types.d.ts +33 -10
- package/dist/types/lib/utils/field-options/messages.d.ts +10 -0
- package/dist/types/lib/utils/field-options/useFieldOptions.d.ts +3 -3
- package/dist/types/lib/utils/template-type-conversion/convertTemplateFieldToLocalConfigurator.d.ts +13 -4
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as isUnsupportedField,o as FieldType}from"./types.js";import{FieldTypeIcon}from"../esm/lib/utils/field-options/field-type-icon.js";import{EditorConfigContext,useEditorConfig}from"../esm/lib/components/metadata-field-configurator/context/editor-config-context.js";import{general}from"../esm/lib/components/metadata-field-configurator/messages/configurator-messages.js";import{useTemplateFieldSchema}from"../esm/lib/components/metadata-field-configurator/hooks/useTemplateFieldSchema.js";import{TaxonomyOptionsContext}from"../esm/lib/components/metadata-field-configurator/context/taxonomy-options-context.js";import{FieldExtensionsContext}from"../esm/lib/components/metadata-field-configurator/context/field-extensions-context.js";import{useTaxonomyFetch}from"../esm/lib/components/metadata-field-configurator/hooks/useTaxonomyFetch.js";import{MetadataFieldConfigurator}from"../esm/lib/components/metadata-field-configurator/metadata-field-configurator.js";import{Accordion,InlineNotice}from"@box/blueprint-web";import{useIntl}from"react-intl";import{jsx,jsxs}from"react/jsx-runtime";import{forwardRef,useCallback,useEffect,useImperativeHandle,useMemo,useRef,useState}from"react";import*as Yup from"yup";import clsx from"clsx";import cloneDeep from"lodash/cloneDeep";import uniqueId from"lodash/uniqueId";import{DndContext,DragOverlay,KeyboardSensor,PointerSensor,TouchSensor,closestCenter,useSensor,useSensors}from"@dnd-kit/core";import{SortableContext,arrayMove,sortableKeyboardCoordinates,useSortable,verticalListSortingStrategy}from"@dnd-kit/sortable";import{CSS}from"@dnd-kit/utilities";import '../styles/metadata-field-list.css';var metadata_field_list_module_default={fieldList:`_fieldList_18x5c_1`,fieldItem:`_fieldItem_18x5c_11`,dragging:`_dragging_18x5c_11`,accordionRootContainer:`_accordionRootContainer_18x5c_15`},FIELDS_AGGREGATE_VALIDATION_DEBOUNCE_MS=150;function getFieldId(field){return field.id}var ACCORDION_ANIMATION_MS=150,FieldListKeyboardSensor=class extends KeyboardSensor{static activators=[{eventName:`onKeyDown`,handler:(event,options,context)=>{let target=event.nativeEvent?.target??event.target??null;return target instanceof HTMLElement&&[`BUTTON`,`INPUT`,`SELECT`,`TEXTAREA`,`A`].includes(target.tagName)?!1:KeyboardSensor.activators[0].handler(event,options,context)}}]};function SortableFieldItem({field,index,maxIndex,isExpanded,onChangeField,onDeleteAtIndex,onDuplicateAtIndex,onReorderFields,onRequestExpand,fetchTaxonomyByKey,submitAttemptCount}){let id=getFieldId(field),{attributes,listeners,setNodeRef,transform,transition,isDragging}=useSortable({id,disabled:isUnsupportedField(field)});return jsx(`li`,{ref:setNodeRef,style:{transform:CSS.Translate.toString(transform),transition},"data-field-id":id,className:clsx(metadata_field_list_module_default.fieldItem,{[metadata_field_list_module_default.dragging]:isDragging}),children:jsx(MetadataFieldConfigurator,{values:field,onValuesChange:onChangeField,index,maxIndex,onDelete:()=>onDeleteAtIndex(index),onDuplicate:()=>onDuplicateAtIndex(index),onReorderFields,dndDragHandleProps:{listeners,attributes},isExpanded,onExpandedChange:expanded=>{expanded&&onRequestExpand()},submitAttemptCount,fetchTaxonomyByKey})})}var MetadataFieldList=forwardRef(function({fields,onChangeFields,onDeleteFieldAtIndex,onDuplicateField,taxonomyOptions,fetchTaxonomies,fetchTaxonomyByKey,disabledFieldTypes,taxonomyInitialStateLabels,firstInvalidFieldIndex,submitAttemptCount,fieldExtensions,onValidationChange,readOnly=!1},ref){let{formatMessage}=useIntl(),parentEditorConfig=useEditorConfig(),taxonomyContextValue=useTaxonomyFetch({fetchTaxonomies,staticOptions:taxonomyOptions,fetchTaxonomyByKey}),fieldListRef=useRef(null),pendingScrollFieldIdRef=useRef(null),seenFieldIdsRef=useRef(new Set(fields.map(field=>getFieldId(field)))),fieldSchema=useTemplateFieldSchema(),lastEmittedAggregateValidRef=useRef(null);useEffect(()=>{lastEmittedAggregateValidRef.current=null},[onValidationChange]),useEffect(()=>{if(!onValidationChange)return;let cancelled=!1,timeoutId=setTimeout(()=>{Yup.array().of(fieldSchema).validate(fields,{abortEarly:!0}).then(()=>{cancelled||lastEmittedAggregateValidRef.current===!0||(lastEmittedAggregateValidRef.current=!0,onValidationChange(!0))}).catch(()=>{cancelled||lastEmittedAggregateValidRef.current===!1||(lastEmittedAggregateValidRef.current=!1,onValidationChange(!1))})},FIELDS_AGGREGATE_VALIDATION_DEBOUNCE_MS);return()=>{cancelled=!0,clearTimeout(timeoutId)}},[fields,fieldSchema,onValidationChange]);let[expandedFieldKey,setExpandedFieldKey]=useState(()=>{let firstNewField=fields.find(f=>f.isFieldNew);return firstNewField?getFieldId(firstNewField):null});useImperativeHandle(ref,()=>({scrollToAndExpand(fieldId){pendingScrollFieldIdRef.current=fieldId,expandedFieldKey===fieldId?(pendingScrollFieldIdRef.current=null,setTimeout(()=>{(fieldListRef.current?.querySelector(`[data-field-id="${fieldId}"]`))?.scrollIntoView({behavior:`smooth`,block:`nearest`})},0)):setExpandedFieldKey(fieldId)}}),[expandedFieldKey]),useEffect(()=>{fields.forEach(field=>{let id=getFieldId(field);seenFieldIdsRef.current.has(id)||(seenFieldIdsRef.current.add(id),pendingScrollFieldIdRef.current=id,setExpandedFieldKey(id))})},[fields]),useEffect(()=>{if(firstInvalidFieldIndex==null||!submitAttemptCount)return;let field=fields[firstInvalidFieldIndex];if(!field)return;let fieldId=getFieldId(field);setExpandedFieldKey(fieldId),requestAnimationFrame(()=>{(fieldListRef.current?.querySelector(`[data-field-id="${fieldId}"]`))?.scrollIntoView({behavior:`smooth`,block:`nearest`})})},[submitAttemptCount]),useEffect(()=>{let fieldId=pendingScrollFieldIdRef.current;if(!fieldId||fieldId!==expandedFieldKey)return;pendingScrollFieldIdRef.current=null;let timer=setTimeout(()=>{(fieldListRef.current?.querySelector(`[data-field-id="${fieldId}"]`))?.scrollIntoView({behavior:`smooth`,block:`nearest`})},ACCORDION_ANIMATION_MS);return()=>clearTimeout(timer)},[expandedFieldKey]);let[activeFieldId,setActiveFieldId]=useState(null),sensors=useSensors(useSensor(PointerSensor,{activationConstraint:{distance:8}}),useSensor(TouchSensor,{activationConstraint:{delay:250,tolerance:5}}),useSensor(FieldListKeyboardSensor,{coordinateGetter:sortableKeyboardCoordinates})),handleDragStart=useCallback(event=>{setActiveFieldId(String(event.active.id))},[]),handleDragEnd=useCallback(event=>{setActiveFieldId(null);let{active,over}=event;if(over&&active.id!==over.id){let oldIndex=fields.findIndex(f=>getFieldId(f)===active.id),newIndex=fields.findIndex(f=>getFieldId(f)===over.id);oldIndex!==-1&&newIndex!==-1&&!isUnsupportedField(fields[oldIndex])&&onChangeFields?.(arrayMove(fields,oldIndex,newIndex))}},[fields,onChangeFields]),handleDragCancel=useCallback(()=>{setActiveFieldId(null)},[]),handleFieldChange=useCallback((index,field)=>{onChangeFields?.(fields.map((f,i)=>i===index?field:f))},[fields,onChangeFields]),handleDeleteAtIndex=useCallback(index=>{let fieldToDelete=fields[index],fieldId=getFieldId(fieldToDelete);setExpandedFieldKey(prev=>prev===fieldId?null:prev),onChangeFields?.(fields.filter((_,i)=>i!==index)),onDeleteFieldAtIndex?.(index,fieldToDelete)},[fields,onChangeFields,onDeleteFieldAtIndex]),handleDuplicateAtIndex=useCallback(index=>{let fieldToDuplicate=fields[index];if(isUnsupportedField(fieldToDuplicate))return;let duplicated=cloneDeep(fieldToDuplicate);duplicated.id=uniqueId(`field-`),duplicated.key=``,duplicated.isFieldNew=!0,duplicated.type===FieldType.Dropdown&&(duplicated.dropdown.options=duplicated.dropdown.options.map(opt=>({...opt,id:uniqueId()})));let newFields=[...fields];newFields.splice(index+1,0,duplicated),onChangeFields?.(newFields),onDuplicateField?.(duplicated)},[fields,onChangeFields,onDuplicateField]),handleReorderFields=useCallback((fromIndex,toIndex)=>{toIndex<0||toIndex>=fields.length||isUnsupportedField(fields[fromIndex])||onChangeFields?.(arrayMove(fields,fromIndex,toIndex))},[fields,onChangeFields]),handleAccordionValueChange=useCallback(value=>{let newKey=value||null;setExpandedFieldKey(newKey),newKey&&setTimeout(()=>{(fieldListRef.current?.querySelector(`[data-field-id="${newKey}"]`))?.scrollIntoView({behavior:`smooth`,block:`nearest`})},ACCORDION_ANIMATION_MS)},[]),items=fields.map(f=>getFieldId(f)),activeField=activeFieldId?fields.find(f=>getFieldId(f)===activeFieldId):null,OverlayTitleIcon=activeField?FieldTypeIcon(activeField.type):null,overlayTitle=activeField?(field=>{let name=field.name||formatMessage(general.fieldNameInputPlaceholder);return field.type===FieldType.Dropdown?`${name} (${field.dropdown?.options?.length??0})`:name})(activeField):``,editorConfigValue=useMemo(()=>({disabledFieldTypes:disabledFieldTypes??parentEditorConfig.disabledFieldTypes,taxonomyInitialStateLabels:taxonomyInitialStateLabels??parentEditorConfig.taxonomyInitialStateLabels}),[disabledFieldTypes,taxonomyInitialStateLabels,parentEditorConfig]),listItems=readOnly?jsx(`ul`,{ref:fieldListRef,className:metadata_field_list_module_default.fieldList,children:fields.map((field,index)=>{let fieldId=getFieldId(field);return jsx(`li`,{"data-field-id":fieldId,className:metadata_field_list_module_default.fieldItem,children:jsx(MetadataFieldConfigurator,{values:field,onValuesChange:()=>void 0,index,maxIndex:fields.length-1,onDuplicate:()=>void 0,onReorderFields:()=>void 0,onDragStart:()=>void 0,onDragEnd:()=>void 0,onTouchStart:()=>void 0,isExpanded:expandedFieldKey===fieldId,onExpandedChange:expanded=>{expanded&&setExpandedFieldKey(fieldId)},fetchTaxonomyByKey,readOnly:!0})},fieldId)})}):jsx(SortableContext,{items,strategy:verticalListSortingStrategy,children:jsx(`ul`,{ref:fieldListRef,className:metadata_field_list_module_default.fieldList,children:fields.map((field,index)=>{let fieldId=getFieldId(field);return jsx(SortableFieldItem,{field,index,maxIndex:fields.length-1,isExpanded:expandedFieldKey===fieldId,onChangeField:updatedField=>handleFieldChange(index,updatedField),onDeleteAtIndex:handleDeleteAtIndex,onDuplicateAtIndex:handleDuplicateAtIndex,onReorderFields:handleReorderFields,onRequestExpand:()=>setExpandedFieldKey(fieldId),submitAttemptCount,fetchTaxonomyByKey},fieldId)})})}),accordionContainer=jsx(`div`,{className:metadata_field_list_module_default.accordionRootContainer,children:jsx(Accordion,{type:`single`,collapsible:!0,value:expandedFieldKey??``,onValueChange:handleAccordionValueChange,children:listItems})}),coreContent=readOnly?accordionContainer:jsxs(DndContext,{sensors,collisionDetection:closestCenter,onDragStart:handleDragStart,onDragEnd:handleDragEnd,onDragCancel:handleDragCancel,children:[accordionContainer,jsx(DragOverlay,{dropAnimation:null,children:activeField&&OverlayTitleIcon?jsx(Accordion,{type:`single`,children:jsx(Accordion.Item,{value:`ghost`,title:overlayTitle,startElement:jsx(OverlayTitleIcon,{fontSize:`20px`,role:`presentation`}),children:null})}):null})]}),hasUnsupportedFields=useMemo(()=>fields.some(field=>isUnsupportedField(field)),[fields]),listContent=jsx(EditorConfigContext.Provider,{value:editorConfigValue,children:jsxs(TaxonomyOptionsContext.Provider,{value:taxonomyContextValue,children:[hasUnsupportedFields&&jsx(InlineNotice,{variant:`warning`,variantIconAriaLabel:formatMessage(general.unsupportedFieldsBanner),children:formatMessage(general.unsupportedFieldsBanner)}),coreContent]})});return fieldExtensions===void 0?listContent:jsx(FieldExtensionsContext.Provider,{value:fieldExtensions,children:listContent})});export{MetadataFieldList as t};
|
|
1
|
+
import{d as isUnsupportedField,o as FieldType}from"./types.js";import{FieldTypeIcon}from"../esm/lib/utils/field-options/field-type-icon.js";import{EditorConfigContext,useEditorConfig}from"../esm/lib/components/metadata-field-configurator/context/editor-config-context.js";import{general}from"../esm/lib/components/metadata-field-configurator/messages/configurator-messages.js";import{useTemplateFieldSchema}from"../esm/lib/components/metadata-field-configurator/hooks/useTemplateFieldSchema.js";import{TaxonomyOptionsContext}from"../esm/lib/components/metadata-field-configurator/context/taxonomy-options-context.js";import{FieldExtensionsContext}from"../esm/lib/components/metadata-field-configurator/context/field-extensions-context.js";import{useTaxonomyFetch}from"../esm/lib/components/metadata-field-configurator/hooks/useTaxonomyFetch.js";import{MetadataFieldConfigurator}from"../esm/lib/components/metadata-field-configurator/metadata-field-configurator.js";import{Accordion,InlineNotice}from"@box/blueprint-web";import{useIntl}from"react-intl";import{jsx,jsxs}from"react/jsx-runtime";import{forwardRef,useCallback,useEffect,useImperativeHandle,useMemo,useRef,useState}from"react";import*as Yup from"yup";import clsx from"clsx";import cloneDeep from"lodash/cloneDeep";import uniqueId from"lodash/uniqueId";import{DndContext,DragOverlay,KeyboardSensor,PointerSensor,TouchSensor,closestCenter,useSensor,useSensors}from"@dnd-kit/core";import{SortableContext,arrayMove,sortableKeyboardCoordinates,useSortable,verticalListSortingStrategy}from"@dnd-kit/sortable";import{CSS}from"@dnd-kit/utilities";import '../styles/metadata-field-list.css';var metadata_field_list_module_default={fieldList:`_fieldList_18x5c_1`,fieldItem:`_fieldItem_18x5c_11`,dragging:`_dragging_18x5c_11`,accordionRootContainer:`_accordionRootContainer_18x5c_15`},FIELDS_AGGREGATE_VALIDATION_DEBOUNCE_MS=150;function getFieldId(field){return field.id}var ACCORDION_ANIMATION_MS=150,FieldListKeyboardSensor=class extends KeyboardSensor{static activators=[{eventName:`onKeyDown`,handler:(event,options,context)=>{let target=event.nativeEvent?.target??event.target??null;return target instanceof HTMLElement&&[`BUTTON`,`INPUT`,`SELECT`,`TEXTAREA`,`A`].includes(target.tagName)?!1:KeyboardSensor.activators[0].handler(event,options,context)}}]};function SortableFieldItem({field,index,maxIndex,isExpanded,onChangeField,onDeleteAtIndex,onDuplicateAtIndex,onReorderFields,onRequestExpand,fetchTaxonomyByKey,submitAttemptCount}){let id=getFieldId(field),{attributes,listeners,setNodeRef,transform,transition,isDragging}=useSortable({id,disabled:isUnsupportedField(field)});return jsx(`li`,{ref:setNodeRef,style:{transform:CSS.Translate.toString(transform),transition},"data-field-id":id,className:clsx(metadata_field_list_module_default.fieldItem,{[metadata_field_list_module_default.dragging]:isDragging}),children:jsx(MetadataFieldConfigurator,{values:field,onValuesChange:onChangeField,index,maxIndex,onDelete:()=>onDeleteAtIndex(index),onDuplicate:()=>onDuplicateAtIndex(index),onReorderFields,dndDragHandleProps:{listeners,attributes},isExpanded,onExpandedChange:expanded=>{expanded&&onRequestExpand()},submitAttemptCount,fetchTaxonomyByKey})})}var MetadataFieldList=forwardRef(function({fields,onChangeFields,onDeleteFieldAtIndex,onDuplicateField,taxonomyOptions,fetchTaxonomies,fetchTaxonomyByKey,isUserFieldEnabled,disabledFieldTypes,taxonomyInitialStateLabels,firstInvalidFieldIndex,submitAttemptCount,fieldExtensions,onValidationChange,readOnly=!1},ref){let{formatMessage}=useIntl(),parentEditorConfig=useEditorConfig(),taxonomyContextValue=useTaxonomyFetch({fetchTaxonomies,staticOptions:taxonomyOptions,fetchTaxonomyByKey}),fieldListRef=useRef(null),pendingScrollFieldIdRef=useRef(null),seenFieldIdsRef=useRef(new Set(fields.map(field=>getFieldId(field)))),fieldSchema=useTemplateFieldSchema(),lastEmittedAggregateValidRef=useRef(null);useEffect(()=>{lastEmittedAggregateValidRef.current=null},[onValidationChange]),useEffect(()=>{if(!onValidationChange)return;let cancelled=!1,timeoutId=setTimeout(()=>{Yup.array().of(fieldSchema).validate(fields,{abortEarly:!0}).then(()=>{cancelled||lastEmittedAggregateValidRef.current===!0||(lastEmittedAggregateValidRef.current=!0,onValidationChange(!0))}).catch(()=>{cancelled||lastEmittedAggregateValidRef.current===!1||(lastEmittedAggregateValidRef.current=!1,onValidationChange(!1))})},FIELDS_AGGREGATE_VALIDATION_DEBOUNCE_MS);return()=>{cancelled=!0,clearTimeout(timeoutId)}},[fields,fieldSchema,onValidationChange]);let[expandedFieldKey,setExpandedFieldKey]=useState(()=>{let firstNewField=fields.find(f=>f.isFieldNew);return firstNewField?getFieldId(firstNewField):null});useImperativeHandle(ref,()=>({scrollToAndExpand(fieldId){pendingScrollFieldIdRef.current=fieldId,expandedFieldKey===fieldId?(pendingScrollFieldIdRef.current=null,setTimeout(()=>{(fieldListRef.current?.querySelector(`[data-field-id="${fieldId}"]`))?.scrollIntoView({behavior:`smooth`,block:`nearest`})},0)):setExpandedFieldKey(fieldId)}}),[expandedFieldKey]),useEffect(()=>{fields.forEach(field=>{let id=getFieldId(field);seenFieldIdsRef.current.has(id)||(seenFieldIdsRef.current.add(id),pendingScrollFieldIdRef.current=id,setExpandedFieldKey(id))})},[fields]),useEffect(()=>{if(firstInvalidFieldIndex==null||!submitAttemptCount)return;let field=fields[firstInvalidFieldIndex];if(!field)return;let fieldId=getFieldId(field);setExpandedFieldKey(fieldId),requestAnimationFrame(()=>{(fieldListRef.current?.querySelector(`[data-field-id="${fieldId}"]`))?.scrollIntoView({behavior:`smooth`,block:`nearest`})})},[submitAttemptCount]),useEffect(()=>{let fieldId=pendingScrollFieldIdRef.current;if(!fieldId||fieldId!==expandedFieldKey)return;pendingScrollFieldIdRef.current=null;let timer=setTimeout(()=>{(fieldListRef.current?.querySelector(`[data-field-id="${fieldId}"]`))?.scrollIntoView({behavior:`smooth`,block:`nearest`})},ACCORDION_ANIMATION_MS);return()=>clearTimeout(timer)},[expandedFieldKey]);let[activeFieldId,setActiveFieldId]=useState(null),sensors=useSensors(useSensor(PointerSensor,{activationConstraint:{distance:8}}),useSensor(TouchSensor,{activationConstraint:{delay:250,tolerance:5}}),useSensor(FieldListKeyboardSensor,{coordinateGetter:sortableKeyboardCoordinates})),handleDragStart=useCallback(event=>{setActiveFieldId(String(event.active.id))},[]),handleDragEnd=useCallback(event=>{setActiveFieldId(null);let{active,over}=event;if(over&&active.id!==over.id){let oldIndex=fields.findIndex(f=>getFieldId(f)===active.id),newIndex=fields.findIndex(f=>getFieldId(f)===over.id);oldIndex!==-1&&newIndex!==-1&&!isUnsupportedField(fields[oldIndex])&&onChangeFields?.(arrayMove(fields,oldIndex,newIndex))}},[fields,onChangeFields]),handleDragCancel=useCallback(()=>{setActiveFieldId(null)},[]),handleFieldChange=useCallback((index,field)=>{onChangeFields?.(fields.map((f,i)=>i===index?field:f))},[fields,onChangeFields]),handleDeleteAtIndex=useCallback(index=>{let fieldToDelete=fields[index],fieldId=getFieldId(fieldToDelete);setExpandedFieldKey(prev=>prev===fieldId?null:prev),onChangeFields?.(fields.filter((_,i)=>i!==index)),onDeleteFieldAtIndex?.(index,fieldToDelete)},[fields,onChangeFields,onDeleteFieldAtIndex]),handleDuplicateAtIndex=useCallback(index=>{let fieldToDuplicate=fields[index];if(isUnsupportedField(fieldToDuplicate))return;let duplicated=cloneDeep(fieldToDuplicate);duplicated.id=uniqueId(`field-`),duplicated.key=``,duplicated.isFieldNew=!0,duplicated.type===FieldType.Dropdown&&(duplicated.dropdown.options=duplicated.dropdown.options.map(opt=>({...opt,id:uniqueId()})));let newFields=[...fields];newFields.splice(index+1,0,duplicated),onChangeFields?.(newFields),onDuplicateField?.(duplicated)},[fields,onChangeFields,onDuplicateField]),handleReorderFields=useCallback((fromIndex,toIndex)=>{toIndex<0||toIndex>=fields.length||isUnsupportedField(fields[fromIndex])||onChangeFields?.(arrayMove(fields,fromIndex,toIndex))},[fields,onChangeFields]),handleAccordionValueChange=useCallback(value=>{let newKey=value||null;setExpandedFieldKey(newKey),newKey&&setTimeout(()=>{(fieldListRef.current?.querySelector(`[data-field-id="${newKey}"]`))?.scrollIntoView({behavior:`smooth`,block:`nearest`})},ACCORDION_ANIMATION_MS)},[]),items=fields.map(f=>getFieldId(f)),activeField=activeFieldId?fields.find(f=>getFieldId(f)===activeFieldId):null,OverlayTitleIcon=activeField?FieldTypeIcon(activeField.type):null,overlayTitle=activeField?(field=>{let name=field.name||formatMessage(general.fieldNameInputPlaceholder);return field.type===FieldType.Dropdown?`${name} (${field.dropdown?.options?.length??0})`:name})(activeField):``,editorConfigValue=useMemo(()=>({disabledFieldTypes:disabledFieldTypes??parentEditorConfig.disabledFieldTypes,taxonomyInitialStateLabels:taxonomyInitialStateLabels??parentEditorConfig.taxonomyInitialStateLabels,isUserFieldEnabled:isUserFieldEnabled??parentEditorConfig.isUserFieldEnabled}),[disabledFieldTypes,taxonomyInitialStateLabels,isUserFieldEnabled,parentEditorConfig]),listItems=readOnly?jsx(`ul`,{ref:fieldListRef,className:metadata_field_list_module_default.fieldList,children:fields.map((field,index)=>{let fieldId=getFieldId(field);return jsx(`li`,{"data-field-id":fieldId,className:metadata_field_list_module_default.fieldItem,children:jsx(MetadataFieldConfigurator,{values:field,onValuesChange:()=>void 0,index,maxIndex:fields.length-1,onDuplicate:()=>void 0,onReorderFields:()=>void 0,onDragStart:()=>void 0,onDragEnd:()=>void 0,onTouchStart:()=>void 0,isExpanded:expandedFieldKey===fieldId,onExpandedChange:expanded=>{expanded&&setExpandedFieldKey(fieldId)},fetchTaxonomyByKey,readOnly:!0})},fieldId)})}):jsx(SortableContext,{items,strategy:verticalListSortingStrategy,children:jsx(`ul`,{ref:fieldListRef,className:metadata_field_list_module_default.fieldList,children:fields.map((field,index)=>{let fieldId=getFieldId(field);return jsx(SortableFieldItem,{field,index,maxIndex:fields.length-1,isExpanded:expandedFieldKey===fieldId,onChangeField:updatedField=>handleFieldChange(index,updatedField),onDeleteAtIndex:handleDeleteAtIndex,onDuplicateAtIndex:handleDuplicateAtIndex,onReorderFields:handleReorderFields,onRequestExpand:()=>setExpandedFieldKey(fieldId),submitAttemptCount,fetchTaxonomyByKey},fieldId)})})}),accordionContainer=jsx(`div`,{className:metadata_field_list_module_default.accordionRootContainer,children:jsx(Accordion,{type:`single`,collapsible:!0,value:expandedFieldKey??``,onValueChange:handleAccordionValueChange,children:listItems})}),coreContent=readOnly?accordionContainer:jsxs(DndContext,{sensors,collisionDetection:closestCenter,onDragStart:handleDragStart,onDragEnd:handleDragEnd,onDragCancel:handleDragCancel,children:[accordionContainer,jsx(DragOverlay,{dropAnimation:null,children:activeField&&OverlayTitleIcon?jsx(Accordion,{type:`single`,children:jsx(Accordion.Item,{value:`ghost`,title:overlayTitle,startElement:jsx(OverlayTitleIcon,{fontSize:`20px`,role:`presentation`}),children:null})}):null})]}),hasUnsupportedFields=useMemo(()=>fields.some(field=>isUnsupportedField(field)),[fields]),listContent=jsx(EditorConfigContext.Provider,{value:editorConfigValue,children:jsxs(TaxonomyOptionsContext.Provider,{value:taxonomyContextValue,children:[hasUnsupportedFields&&jsx(InlineNotice,{variant:`warning`,variantIconAriaLabel:formatMessage(general.unsupportedFieldsBanner),children:formatMessage(general.unsupportedFieldsBanner)}),coreContent]})});return fieldExtensions===void 0?listContent:jsx(FieldExtensionsContext.Provider,{value:fieldExtensions,children:listContent})});export{MetadataFieldList as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{s as MetadataTemplateEditorMode}from"./types.js";import{EditorConfigContext}from"../esm/lib/components/metadata-field-configurator/context/editor-config-context.js";import"../esm/lib/utils/constants.js";import messages_default from"../esm/lib/messages.js";import{t as MetadataTemplateEditorForm}from"./metadata-template-editor-form.js";import{UnsavedChangesModal}from"../esm/lib/components/unsaved-changes-modal/unsaved-changes-modal.js";import{useMetadataTemplateFormSchema}from"../esm/lib/hooks/useMetadataTemplateFormSchema.js";import{convertApiMetadataTemplateFieldToLocalConfiguratorField}from"../esm/lib/utils/template-type-conversion/convertTemplateFieldToLocalConfigurator.js";import{generateJSONPatchTemplateOperations}from"../esm/lib/utils/template-type-conversion/generateJSONPatchTemplateOperations.js";import{mapFieldsWithUniqueKeys}from"../esm/lib/utils/template-type-conversion/mapFieldsWithUniqueKeys.js";import{EmptyState,LoadingIndicator,Text,useNotification}from"@box/blueprint-web";import{useIntl}from"react-intl";import{jsx,jsxs}from"react/jsx-runtime";import{useCallback,useEffect,useMemo,useState}from"react";import{ArrowsRotating}from"@box/blueprint-web-assets/icons/Line";import{ErrorState404}from"@box/blueprint-web-assets/illustrations/Medium";import{Formik}from"formik";import '../styles/metadata-template-editor.css';var metadata_template_editor_module_default={loading:`_loading_fd3t9_1`,error:`_error_fd3t9_8`},DEFAULT_VALUES={displayName:``,templateKey:``,fields:[],hidden:!1};function MetadataTemplateEditor({onCancel,onDirtyStateChange,onValidationChange,onSubmitError,onTemplateLoad,taxonomyOptions,fetchTaxonomies,fetchTaxonomyByKey,disabledFieldTypes,taxonomyInitialStateLabels,formId,hideActions=!1,isVisibilityToggleAllowed=!1,fieldExtensions,...modeProps}){let schema=useMetadataTemplateFormSchema(),{formatMessage}=useIntl(),{addNotification}=useNotification(),isEditMode=modeProps.mode===MetadataTemplateEditorMode.Edit,isReadOnlyMode=modeProps.mode===MetadataTemplateEditorMode.ReadOnly,[isDirty,setIsDirty]=useState(!1),[isUnsavedChangesModalOpen,setIsUnsavedChangesModalOpen]=useState(!1),handleCancel=useCallback(()=>{isDirty?setIsUnsavedChangesModalOpen(!0):onCancel?.()},[isDirty,onCancel]),handleDirtyStateChange=useCallback(dirty=>{setIsDirty(dirty),onDirtyStateChange?.(dirty)},[onDirtyStateChange]),[isLoading,setIsLoading]=useState(isEditMode||isReadOnlyMode),[hasFetchError,setHasFetchError]=useState(!1),[retryCount,setRetryCount]=useState(0),[fetchedValues,setFetchedValues]=useState(void 0),fetchTemplate=isEditMode||isReadOnlyMode?modeProps.fetchTemplate:void 0,handleRetry=()=>{setRetryCount(c=>c+1)};useEffect(()=>{if(!fetchTemplate)return;let cancelled=!1;return setIsLoading(!0),setHasFetchError(!1),setFetchedValues(void 0),(async()=>{try{let response=await fetchTemplate();cancelled||setFetchedValues(response)}catch{cancelled||setHasFetchError(!0)}finally{cancelled||setIsLoading(!1)}})(),()=>{cancelled=!0}},[fetchTemplate,retryCount]),useEffect(()=>{fetchedValues!==void 0&&onTemplateLoad?.(fetchedValues)},[fetchedValues,onTemplateLoad]);let createNamespace=isEditMode||isReadOnlyMode?void 0:modeProps.namespace,mergedInitialValues=useMemo(()=>fetchedValues?{displayName:fetchedValues.displayName,templateKey:fetchedValues.templateKey,namespace:fetchedValues.namespace,hidden:fetchedValues.hidden,fields:fetchedValues.fields.map(field=>convertApiMetadataTemplateFieldToLocalConfiguratorField(field))}:{...DEFAULT_VALUES,namespace:createNamespace??``},[fetchedValues,createNamespace]),editorConfigValue=useMemo(()=>({disabledFieldTypes,taxonomyInitialStateLabels}),[disabledFieldTypes,taxonomyInitialStateLabels]);return isLoading?jsx(`div`,{className:metadata_template_editor_module_default.loading,children:jsx(LoadingIndicator,{size:`large`,"aria-label":formatMessage(messages_default.loading)})}):hasFetchError?jsx(`div`,{className:metadata_template_editor_module_default.error,children:jsx(EmptyState,{body:jsx(Text,{as:`p`,children:formatMessage(messages_default.fetchError)}),illustration:ErrorState404,size:`large`,children:jsx(EmptyState.PrimaryAction,{startIcon:ArrowsRotating,onClick:handleRetry,children:formatMessage(messages_default.reload)})})}):jsxs(EditorConfigContext.Provider,{value:editorConfigValue,children:[jsx(Formik,{initialValues:mergedInitialValues,validationSchema:isReadOnlyMode?void 0:schema,onSubmit:async values=>{if(!isReadOnlyMode)try{if(isEditMode){let patchItems=generateJSONPatchTemplateOperations(mergedInitialValues,values);await modeProps.onEditTemplate(patchItems,{namespaceFQN:mergedInitialValues.namespace,templateKey:mergedInitialValues.templateKey})}else{let convertedFields=mapFieldsWithUniqueKeys(values.fields),createBody={namespace:values.namespace,templateKey:values.templateKey,displayName:values.displayName,hidden:values.hidden,fields:convertedFields};await modeProps.onCreateTemplate(createBody)}addNotification({sensitivity:`foreground`,variant:`success`,styledText:formatMessage(messages_default.saveSuccessNotification),typeIconAriaLabel:formatMessage(messages_default.notificationSuccessIconAriaLabel),closeButtonAriaLabel:formatMessage(messages_default.notificationCloseButtonAriaLabel)})}catch(error){let errorMessage;if(error instanceof Error&&`status`in error){let{status}=error;errorMessage=formatMessage(status===409?messages_default.displayNameUsedBefore:messages_default.saveErrorNotification)}else errorMessage=formatMessage(messages_default.saveErrorNotification);addNotification({sensitivity:`foreground`,variant:`error`,styledText:errorMessage,typeIconAriaLabel:formatMessage(messages_default.notificationErrorIconAriaLabel),closeButtonAriaLabel:formatMessage(messages_default.notificationCloseButtonAriaLabel)});try{onSubmitError?.(error)}catch{}throw error}},children:jsx(MetadataTemplateEditorForm,{formId,onCancel:handleCancel,taxonomyOptions,fetchTaxonomies,fetchTaxonomyByKey,hideActions,isEditMode,isVisibilityToggleAllowed,readOnly:isReadOnlyMode,onDirtyStateChange:handleDirtyStateChange,onValidationChange,fieldExtensions})}),isUnsavedChangesModalOpen&&jsx(UnsavedChangesModal,{onKeepEditing:()=>setIsUnsavedChangesModalOpen(!1),onDiscard:()=>{setIsUnsavedChangesModalOpen(!1),onCancel?.()}})]})}export{MetadataTemplateEditor as t};
|
|
1
|
+
import{s as MetadataTemplateEditorMode}from"./types.js";import{EditorConfigContext}from"../esm/lib/components/metadata-field-configurator/context/editor-config-context.js";import"../esm/lib/utils/constants.js";import messages_default from"../esm/lib/messages.js";import{t as MetadataTemplateEditorForm}from"./metadata-template-editor-form.js";import{UnsavedChangesModal}from"../esm/lib/components/unsaved-changes-modal/unsaved-changes-modal.js";import{useMetadataTemplateFormSchema}from"../esm/lib/hooks/useMetadataTemplateFormSchema.js";import{convertApiMetadataTemplateFieldToLocalConfiguratorField}from"../esm/lib/utils/template-type-conversion/convertTemplateFieldToLocalConfigurator.js";import{generateJSONPatchTemplateOperations}from"../esm/lib/utils/template-type-conversion/generateJSONPatchTemplateOperations.js";import{mapFieldsWithUniqueKeys}from"../esm/lib/utils/template-type-conversion/mapFieldsWithUniqueKeys.js";import{EmptyState,LoadingIndicator,Text,useNotification}from"@box/blueprint-web";import{useIntl}from"react-intl";import{jsx,jsxs}from"react/jsx-runtime";import{useCallback,useEffect,useMemo,useState}from"react";import{ArrowsRotating}from"@box/blueprint-web-assets/icons/Line";import{ErrorState404}from"@box/blueprint-web-assets/illustrations/Medium";import{Formik}from"formik";import '../styles/metadata-template-editor.css';var metadata_template_editor_module_default={loading:`_loading_fd3t9_1`,error:`_error_fd3t9_8`},DEFAULT_VALUES={displayName:``,templateKey:``,fields:[],hidden:!1};function MetadataTemplateEditor({onCancel,onDirtyStateChange,onValidationChange,onSubmitError,onTemplateLoad,taxonomyOptions,fetchTaxonomies,fetchTaxonomyByKey,disabledFieldTypes,taxonomyInitialStateLabels,formId,hideActions=!1,isVisibilityToggleAllowed=!1,isUserFieldEnabled=!1,fieldExtensions,...modeProps}){let schema=useMetadataTemplateFormSchema(),{formatMessage}=useIntl(),{addNotification}=useNotification(),isEditMode=modeProps.mode===MetadataTemplateEditorMode.Edit,isReadOnlyMode=modeProps.mode===MetadataTemplateEditorMode.ReadOnly,[isDirty,setIsDirty]=useState(!1),[isUnsavedChangesModalOpen,setIsUnsavedChangesModalOpen]=useState(!1),handleCancel=useCallback(()=>{isDirty?setIsUnsavedChangesModalOpen(!0):onCancel?.()},[isDirty,onCancel]),handleDirtyStateChange=useCallback(dirty=>{setIsDirty(dirty),onDirtyStateChange?.(dirty)},[onDirtyStateChange]),[isLoading,setIsLoading]=useState(isEditMode||isReadOnlyMode),[hasFetchError,setHasFetchError]=useState(!1),[retryCount,setRetryCount]=useState(0),[fetchedValues,setFetchedValues]=useState(void 0),fetchTemplate=isEditMode||isReadOnlyMode?modeProps.fetchTemplate:void 0,handleRetry=()=>{setRetryCount(c=>c+1)};useEffect(()=>{if(!fetchTemplate)return;let cancelled=!1;return setIsLoading(!0),setHasFetchError(!1),setFetchedValues(void 0),(async()=>{try{let response=await fetchTemplate();cancelled||setFetchedValues(response)}catch{cancelled||setHasFetchError(!0)}finally{cancelled||setIsLoading(!1)}})(),()=>{cancelled=!0}},[fetchTemplate,retryCount]),useEffect(()=>{fetchedValues!==void 0&&onTemplateLoad?.(fetchedValues)},[fetchedValues,onTemplateLoad]);let createNamespace=isEditMode||isReadOnlyMode?void 0:modeProps.namespace,mergedInitialValues=useMemo(()=>fetchedValues?{displayName:fetchedValues.displayName,templateKey:fetchedValues.templateKey,namespace:fetchedValues.namespace,hidden:fetchedValues.hidden,fields:fetchedValues.fields.map(field=>convertApiMetadataTemplateFieldToLocalConfiguratorField(field,{isUserFieldEnabled}))}:{...DEFAULT_VALUES,namespace:createNamespace??``},[fetchedValues,createNamespace,isUserFieldEnabled]),editorConfigValue=useMemo(()=>({disabledFieldTypes,taxonomyInitialStateLabels,isUserFieldEnabled}),[disabledFieldTypes,taxonomyInitialStateLabels,isUserFieldEnabled]);return isLoading?jsx(`div`,{className:metadata_template_editor_module_default.loading,children:jsx(LoadingIndicator,{size:`large`,"aria-label":formatMessage(messages_default.loading)})}):hasFetchError?jsx(`div`,{className:metadata_template_editor_module_default.error,children:jsx(EmptyState,{body:jsx(Text,{as:`p`,children:formatMessage(messages_default.fetchError)}),illustration:ErrorState404,size:`large`,children:jsx(EmptyState.PrimaryAction,{startIcon:ArrowsRotating,onClick:handleRetry,children:formatMessage(messages_default.reload)})})}):jsxs(EditorConfigContext.Provider,{value:editorConfigValue,children:[jsx(Formik,{initialValues:mergedInitialValues,validationSchema:isReadOnlyMode?void 0:schema,onSubmit:async values=>{if(!isReadOnlyMode)try{if(isEditMode){let patchItems=generateJSONPatchTemplateOperations(mergedInitialValues,values);await modeProps.onEditTemplate(patchItems,{namespaceFQN:mergedInitialValues.namespace,templateKey:mergedInitialValues.templateKey})}else{let convertedFields=mapFieldsWithUniqueKeys(values.fields),createBody={namespace:values.namespace,templateKey:values.templateKey,displayName:values.displayName,hidden:values.hidden,fields:convertedFields};await modeProps.onCreateTemplate(createBody)}addNotification({sensitivity:`foreground`,variant:`success`,styledText:formatMessage(messages_default.saveSuccessNotification),typeIconAriaLabel:formatMessage(messages_default.notificationSuccessIconAriaLabel),closeButtonAriaLabel:formatMessage(messages_default.notificationCloseButtonAriaLabel)})}catch(error){let errorMessage;if(error instanceof Error&&`status`in error){let{status}=error;errorMessage=formatMessage(status===409?messages_default.displayNameUsedBefore:messages_default.saveErrorNotification)}else errorMessage=formatMessage(messages_default.saveErrorNotification);addNotification({sensitivity:`foreground`,variant:`error`,styledText:errorMessage,typeIconAriaLabel:formatMessage(messages_default.notificationErrorIconAriaLabel),closeButtonAriaLabel:formatMessage(messages_default.notificationCloseButtonAriaLabel)});try{onSubmitError?.(error)}catch{}throw error}},children:jsx(MetadataTemplateEditorForm,{formId,onCancel:handleCancel,taxonomyOptions,fetchTaxonomies,fetchTaxonomyByKey,hideActions,isEditMode,isVisibilityToggleAllowed,readOnly:isReadOnlyMode,onDirtyStateChange:handleDirtyStateChange,onValidationChange,fieldExtensions})}),isUnsavedChangesModalOpen&&jsx(UnsavedChangesModal,{onKeepEditing:()=>setIsUnsavedChangesModalOpen(!1),onDiscard:()=>{setIsUnsavedChangesModalOpen(!1),onCancel?.()}})]})}export{MetadataTemplateEditor as t};
|
package/dist/chunks/types.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var MetadataTemplateEditorMode=function(MetadataTemplateEditorMode){return MetadataTemplateEditorMode.Create=`create`,MetadataTemplateEditorMode.Edit=`edit`,MetadataTemplateEditorMode.ReadOnly=`readOnly`,MetadataTemplateEditorMode}({}),FieldType=function(FieldType){return FieldType.Text=`text`,FieldType.Number=`number`,FieldType.Date=`date`,FieldType.Dropdown=`dropdown`,FieldType.Taxonomy=`taxonomy`,FieldType.Unsupported=`unsupported`,FieldType}({}),CREATABLE_FIELD_TYPES=[`text`,`number`,`date`,`dropdown`,`taxonomy`],isUnsupportedField=field=>field.type===`unsupported`,TaxonomySelection=function(TaxonomySelection){return TaxonomySelection.RequireSpecific=`requireSpecific`,TaxonomySelection.AllowAny=`allowAny`,TaxonomySelection}({}),ApiMetadataTemplateFieldType=function(ApiMetadataTemplateFieldType){return ApiMetadataTemplateFieldType.Float=`float`,ApiMetadataTemplateFieldType.Taxonomy=`taxonomy`,ApiMetadataTemplateFieldType.MultiSelect=`multiSelect`,ApiMetadataTemplateFieldType.Date=`date`,ApiMetadataTemplateFieldType.String=`string`,ApiMetadataTemplateFieldType.Enum=`enum`,ApiMetadataTemplateFieldType}({}),TemplateOperations=function(TemplateOperations){return TemplateOperations.EditTemplate=`editTemplate`,TemplateOperations}({}),FieldOperations=function(FieldOperations){return FieldOperations.AddField=`addField`,FieldOperations.ReorderFields=`reorderFields`,FieldOperations.EditField=`editField`,FieldOperations.RemoveField=`removeField`,FieldOperations}({}),EnumOperations=function(EnumOperations){return EnumOperations.AddEnumOption=`addEnumOption`,EnumOperations.ReorderEnumOptions=`reorderEnumOptions`,EnumOperations.EditEnumOption=`editEnumOption`,EnumOperations.RemoveEnumOption=`removeEnumOption`,EnumOperations}({}),MultiSelectOperations=function(MultiSelectOperations){return MultiSelectOperations.AddMultiSelectOption=`addMultiSelectOption`,MultiSelectOperations.ReorderMultiSelectOptions=`reorderMultiSelectOptions`,MultiSelectOperations.EditMultiSelectOption=`editMultiSelectOption`,MultiSelectOperations.RemoveMultiSelectOption=`removeMultiSelectOption`,MultiSelectOperations}({}),AllOps={...TemplateOperations,...FieldOperations,...EnumOperations,...MultiSelectOperations};export{FieldOperations as a,MultiSelectOperations as c,isUnsupportedField as d,EnumOperations as i,TaxonomySelection as l,ApiMetadataTemplateFieldType as n,FieldType as o,CREATABLE_FIELD_TYPES as r,MetadataTemplateEditorMode as s,AllOps as t,TemplateOperations as u};
|
|
1
|
+
var MetadataTemplateEditorMode=function(MetadataTemplateEditorMode){return MetadataTemplateEditorMode.Create=`create`,MetadataTemplateEditorMode.Edit=`edit`,MetadataTemplateEditorMode.ReadOnly=`readOnly`,MetadataTemplateEditorMode}({}),FieldType=function(FieldType){return FieldType.Text=`text`,FieldType.Number=`number`,FieldType.Date=`date`,FieldType.Dropdown=`dropdown`,FieldType.Taxonomy=`taxonomy`,FieldType.User=`user`,FieldType.Unsupported=`unsupported`,FieldType}({}),CREATABLE_FIELD_TYPES=[`text`,`number`,`date`,`dropdown`,`taxonomy`,`user`],isUnsupportedField=field=>field.type===`unsupported`,TaxonomySelection=function(TaxonomySelection){return TaxonomySelection.RequireSpecific=`requireSpecific`,TaxonomySelection.AllowAny=`allowAny`,TaxonomySelection}({}),ApiMetadataTemplateFieldType=function(ApiMetadataTemplateFieldType){return ApiMetadataTemplateFieldType.Float=`float`,ApiMetadataTemplateFieldType.Taxonomy=`taxonomy`,ApiMetadataTemplateFieldType.MultiSelect=`multiSelect`,ApiMetadataTemplateFieldType.Date=`date`,ApiMetadataTemplateFieldType.String=`string`,ApiMetadataTemplateFieldType.Enum=`enum`,ApiMetadataTemplateFieldType.User=`user`,ApiMetadataTemplateFieldType}({}),TemplateOperations=function(TemplateOperations){return TemplateOperations.EditTemplate=`editTemplate`,TemplateOperations}({}),FieldOperations=function(FieldOperations){return FieldOperations.AddField=`addField`,FieldOperations.ReorderFields=`reorderFields`,FieldOperations.EditField=`editField`,FieldOperations.RemoveField=`removeField`,FieldOperations}({}),EnumOperations=function(EnumOperations){return EnumOperations.AddEnumOption=`addEnumOption`,EnumOperations.ReorderEnumOptions=`reorderEnumOptions`,EnumOperations.EditEnumOption=`editEnumOption`,EnumOperations.RemoveEnumOption=`removeEnumOption`,EnumOperations}({}),MultiSelectOperations=function(MultiSelectOperations){return MultiSelectOperations.AddMultiSelectOption=`addMultiSelectOption`,MultiSelectOperations.ReorderMultiSelectOptions=`reorderMultiSelectOptions`,MultiSelectOperations.EditMultiSelectOption=`editMultiSelectOption`,MultiSelectOperations.RemoveMultiSelectOption=`removeMultiSelectOption`,MultiSelectOperations}({}),AllOps={...TemplateOperations,...FieldOperations,...EnumOperations,...MultiSelectOperations};export{FieldOperations as a,MultiSelectOperations as c,isUnsupportedField as d,EnumOperations as i,TaxonomySelection as l,ApiMetadataTemplateFieldType as n,FieldType as o,CREATABLE_FIELD_TYPES as r,MetadataTemplateEditorMode as s,AllOps as t,TemplateOperations as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useFieldOptions}from"../../utils/field-options/useFieldOptions.js";import{emptyStateMessages}from"./messages.js";import{RadioTiles}from"@box/blueprint-web";import{useIntl}from"react-intl";import{jsx}from"react/jsx-runtime";import{bpSize080,bpSurfaceSurfaceBrand}from"@box/blueprint-web-assets/tokens/tokens";function FieldTypeTiles({onFieldAdd}){let{formatMessage}=useIntl(),fieldTypes=useFieldOptions();return jsx(`div`,{"data-testid":`md-template-type-picker-tiles`,children:jsx(RadioTiles,{name:`field-type-picker`,value:void 0,columns:5,"aria-label":formatMessage(emptyStateMessages.selectFieldTypeAriaLabel),onChange:event=>{let fieldType=fieldTypes.availableFieldTypes.find(ft=>ft.type===event.target.value);fieldType&&onFieldAdd(fieldType)},children:fieldTypes.availableFieldTypes.map(fieldType=>jsx(RadioTiles.Option,{value:fieldType.type,label:fieldType.label,icon:jsx(fieldType.Icon,{"aria-hidden":!0,color:bpSurfaceSurfaceBrand,height:bpSize080,width:bpSize080})},fieldType.type))})})}export{FieldTypeTiles,FieldTypeTiles as default};
|
|
1
|
+
import{useFieldOptions}from"../../utils/field-options/useFieldOptions.js";import{emptyStateMessages}from"./messages.js";import{RadioTiles}from"@box/blueprint-web";import{useIntl}from"react-intl";import{jsx}from"react/jsx-runtime";import{bpSize080,bpSurfaceSurfaceBrand}from"@box/blueprint-web-assets/tokens/tokens";function FieldTypeTiles({onFieldAdd}){let{formatMessage}=useIntl(),fieldTypes=useFieldOptions();return jsx(`div`,{"data-testid":`md-template-type-picker-tiles`,children:jsx(RadioTiles,{name:`field-type-picker`,value:void 0,columns:5,"aria-label":formatMessage(emptyStateMessages.selectFieldTypeAriaLabel),onChange:event=>{let fieldType=fieldTypes.availableFieldTypes.find(ft=>ft.type===event.target.value);fieldType&&onFieldAdd(fieldType)},variant:`compact`,children:fieldTypes.availableFieldTypes.map(fieldType=>jsx(RadioTiles.Option,{value:fieldType.type,label:fieldType.label,icon:jsx(fieldType.Icon,{"aria-hidden":!0,color:bpSurfaceSurfaceBrand,height:bpSize080,width:bpSize080})},fieldType.type))})})}export{FieldTypeTiles,FieldTypeTiles as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as isUnsupportedField
|
|
1
|
+
import{d as isUnsupportedField}from"../../../../../../chunks/types.js";import{useFieldOptions}from"../../../../utils/field-options/useFieldOptions.js";import{general}from"../../messages/configurator-messages.js";import{t as metadata_field_configurator_module_default}from"../../../../../../chunks/metadata-field-configurator.module.js";import{useFieldConfigurator}from"../../context/field-configurator-context.js";import{getConfigurationByType}from"../../utils.js";import{InlineNotice,Select,Text,TextInput,TextWithInfoBadge,TooltipProvider}from"@box/blueprint-web";import{useIntl}from"react-intl";import{jsx,jsxs}from"react/jsx-runtime";import{useMemo}from"react";var FieldEditContent=({nameInputId,descriptionInputId,isTypeEditable,externalErrors,externalTouched,handleTypeChange,hideDescription=!1,readOnly=!1})=>{let{formatMessage}=useIntl(),fieldTypes=useFieldOptions(),{values,errors,touched,handleChange,handleBlur}=useFieldConfigurator(),getFieldError=fieldName=>{if(externalErrors&&externalTouched?.[fieldName])return externalErrors[fieldName];let error=errors[fieldName];if(touched[fieldName]&&error!=null&&typeof error==`string`)return error},descriptionLabel=useMemo(()=>jsx(TooltipProvider,{children:jsx(TextWithInfoBadge,{infoBadgeAriaLabel:formatMessage(general.descriptionLearnMoreBadgeAriaLabel),infoText:formatMessage(general.descriptionInfoTooltip),children:jsx(Text,{as:`label`,className:metadata_field_configurator_module_default.labelWithTooltip,htmlFor:descriptionInputId,variant:`bodyDefaultBold`,children:formatMessage(general.fieldDescriptionLabel)})})}),[descriptionInputId,formatMessage]),isUnsupported=isUnsupportedField(values),unsupportedTypeLabel=values.originalApiType||values.type,isReadOnly=readOnly||values.isFieldReadOnly||isUnsupported,typeSpecificConfiguration=getConfigurationByType(values.type);return jsx(`fieldset`,{className:metadata_field_configurator_module_default.fieldset,children:jsxs(`div`,{className:metadata_field_configurator_module_default.expandedContent,children:[isUnsupported&&jsx(InlineNotice,{variant:`warning`,variantIconAriaLabel:formatMessage(general.unsupportedFieldNotice,{fieldType:unsupportedTypeLabel}),children:formatMessage(general.unsupportedFieldNotice,{fieldType:unsupportedTypeLabel})}),jsxs(`div`,{className:metadata_field_configurator_module_default.basic,children:[jsx(TextInput,{name:`name`,id:nameInputId,label:formatMessage(general.fieldNameLabel),placeholder:formatMessage(general.fieldNameInputPlaceholder),value:values.name,error:isReadOnly?void 0:getFieldError(`name`),onChange:handleChange,onBlur:handleBlur,readOnly:isReadOnly,required:!isReadOnly}),isUnsupported?jsx(TextInput,{name:`type`,label:formatMessage(general.fieldTypeLabel),value:unsupportedTypeLabel,readOnly:!0}):jsx(Select,{name:`type`,label:formatMessage(general.fieldTypeLabel),placeholder:formatMessage(general.fieldTypePlaceholder),value:values.type,"aria-readonly":isReadOnly||!isTypeEditable,readonly:isReadOnly||!isTypeEditable,onValueChange:handleTypeChange,className:metadata_field_configurator_module_default.fieldTypeSelect,required:!isReadOnly,children:jsx(Select.Content,{children:fieldTypes.availableFieldTypes.map(fieldType=>jsx(Select.Option,{text:typeof fieldType.label==`string`?fieldType.label:String(fieldType.label),value:fieldType.type},fieldType.type))})})]}),!isUnsupported&&typeSpecificConfiguration&&jsx(`div`,{className:metadata_field_configurator_module_default.typeSpecific,children:typeSpecificConfiguration}),!hideDescription&&jsx(`div`,{className:metadata_field_configurator_module_default.description,children:jsx(TextInput,{name:`description`,id:descriptionInputId,label:descriptionLabel,placeholder:formatMessage(general.fieldDescriptionInputPlaceholder),value:values.description??``,error:isReadOnly?void 0:getFieldError(`description`),hideLabel:!0,readOnly:isReadOnly,onChange:handleChange,onBlur:handleBlur})})]})})};export{FieldEditContent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as DropdownFieldConfiguration}from"../../../../../../chunks/dropdown-field-configuration.js";import{t as TaxonomyFieldConfiguration}from"../../../../../../chunks/taxonomy-field-configuration.js";export{DropdownFieldConfiguration,TaxonomyFieldConfiguration};
|
|
1
|
+
import{t as DropdownFieldConfiguration}from"../../../../../../chunks/dropdown-field-configuration.js";import{t as TaxonomyFieldConfiguration}from"../../../../../../chunks/taxonomy-field-configuration.js";import{UserFieldConfiguration}from"./user/user-field-configuration.js";export{DropdownFieldConfiguration,TaxonomyFieldConfiguration,UserFieldConfiguration};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{useFieldConfigurator}from"../../../context/field-configurator-context.js";import user_messages_default from"../../../messages/user-messages.js";import{Switch}from"@box/blueprint-web";import{useIntl}from"react-intl";import{Fragment,jsx,jsxs}from"react/jsx-runtime";function UserFieldConfiguration(){let{formatMessage}=useIntl(),{values,setFieldValue}=useFieldConfigurator();return jsxs(Fragment,{children:[jsx(Switch.Item,{name:`user.allowMultipleSelections`,checked:values.user.allowMultipleSelections,disabled:!values.isFieldNew||values.isFieldReadOnly,label:formatMessage(user_messages_default.allowMultipleSelection),onCheckedChange:allowMultipleSelections=>setFieldValue(`user`,{...values.user,allowMultipleSelections}),value:`true`}),jsx(Switch.Item,{name:`user.notifyWhenUsersAreAdded`,checked:values.user.notifyWhenUsersAreAdded,disabled:values.isFieldReadOnly,label:formatMessage(user_messages_default.notifyWhenUsersAreAdded),onCheckedChange:notifyWhenUsersAreAdded=>setFieldValue(`user`,{...values.user,notifyWhenUsersAreAdded}),value:`true`})]})}export{UserFieldConfiguration};
|
package/dist/esm/lib/components/metadata-field-configurator/context/editor-config-context.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createContext,useContext}from"react";var EditorConfigContext=createContext({disabledFieldTypes:[]}),useEditorConfig=()=>useContext(EditorConfigContext);export{EditorConfigContext,useEditorConfig};
|
|
1
|
+
import{createContext,useContext}from"react";var EditorConfigContext=createContext({disabledFieldTypes:[],isUserFieldEnabled:!1}),useEditorConfig=()=>useContext(EditorConfigContext);export{EditorConfigContext,useEditorConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useTemplateFieldSchema}from"./useTemplateFieldSchema.js";import{markAllTouched}from"../utils.js";import{useCallback,useEffect,useRef,useState}from"react";import*as Yup from"yup";import cloneDeep from"lodash/cloneDeep";import set from"lodash/set";function yupErrorsToRecord(err){let map={};return(err.inner.length>0?err.inner:[err]).forEach(e=>{e.path&&set(map,e.path,e.message)}),map}function useFieldValidation(values){let schema=useTemplateFieldSchema(),[errors,setErrors]=useState({}),[isValid,setIsValid]=useState(!1),[touched,setTouchedState]=useState({}),validate=useCallback(async(v,run)=>{try{if(await schema.validate(v,{abortEarly:!1}),run?.cancelled)return;setErrors({}),setIsValid(!0)}catch(err){if(run?.cancelled)return;err instanceof Yup.ValidationError&&(setErrors(yupErrorsToRecord(err)),setIsValid(!1))}},[schema]);useEffect(()=>{let run={cancelled:!1};return validate(values,run),()=>{run.cancelled=!0}},[values,validate]);let prevTypeRef=useRef(values.type);return useEffect(()=>{prevTypeRef.current!==values.type&&(prevTypeRef.current=values.type,setTouchedState(({dropdown:_d,taxonomy:_t,...shared})=>shared))},[values.type]),{errors,touched,isValid,validateForm:useCallback(()=>validate(values),[validate,values]),touchAll:useCallback(()=>setTouchedState(markAllTouched(values)),[values]),setFieldTouched:useCallback((field,isTouched=!0)=>{setTouchedState(prev=>{let next=cloneDeep(prev);return set(next,field,isTouched),next})},[]),setTouched:useCallback(newTouched=>setTouchedState(newTouched),[]),handleBlur:useCallback(e=>{let target=e.target;target.name&&setTouchedState(prev=>{let next=cloneDeep(prev);return set(next,target.name,!0),next})},[])}}export{useFieldValidation};
|
|
1
|
+
import{useTemplateFieldSchema}from"./useTemplateFieldSchema.js";import{markAllTouched}from"../utils.js";import{useCallback,useEffect,useRef,useState}from"react";import*as Yup from"yup";import cloneDeep from"lodash/cloneDeep";import set from"lodash/set";function yupErrorsToRecord(err){let map={};return(err.inner.length>0?err.inner:[err]).forEach(e=>{e.path&&set(map,e.path,e.message)}),map}function useFieldValidation(values){let schema=useTemplateFieldSchema(),[errors,setErrors]=useState({}),[isValid,setIsValid]=useState(!1),[touched,setTouchedState]=useState({}),validate=useCallback(async(v,run)=>{try{if(await schema.validate(v,{abortEarly:!1}),run?.cancelled)return;setErrors({}),setIsValid(!0)}catch(err){if(run?.cancelled)return;err instanceof Yup.ValidationError&&(setErrors(yupErrorsToRecord(err)),setIsValid(!1))}},[schema]);useEffect(()=>{let run={cancelled:!1};return validate(values,run),()=>{run.cancelled=!0}},[values,validate]);let prevTypeRef=useRef(values.type);return useEffect(()=>{prevTypeRef.current!==values.type&&(prevTypeRef.current=values.type,setTouchedState(({dropdown:_d,taxonomy:_t,user:_u,...shared})=>shared))},[values.type]),{errors,touched,isValid,validateForm:useCallback(()=>validate(values),[validate,values]),touchAll:useCallback(()=>setTouchedState(markAllTouched(values)),[values]),setFieldTouched:useCallback((field,isTouched=!0)=>{setTouchedState(prev=>{let next=cloneDeep(prev);return set(next,field,isTouched),next})},[]),setTouched:useCallback(newTouched=>setTouchedState(newTouched),[]),handleBlur:useCallback(e=>{let target=e.target;target.name&&setTouchedState(prev=>{let next=cloneDeep(prev);return set(next,target.name,!0),next})},[])}}export{useFieldValidation};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{defineMessages}from"react-intl";var user_messages_default=defineMessages({allowMultipleSelection:{id:`groupSharedFeatures.metadataTemplateEditor.configurator.user.allowMultipleSelection`,defaultMessage:`Allow Multiple Selections`},notifyWhenUsersAreAdded:{id:`groupSharedFeatures.metadataTemplateEditor.configurator.user.notifyWhenUsersAreAdded`,defaultMessage:`Notify when users are added`}});export{user_messages_default as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{o as FieldType}from"../../../../chunks/types.js";import{t as DropdownFieldConfiguration}from"../../../../chunks/dropdown-field-configuration.js";import{taxonomyDefaultValues}from"./components/type-specific-configuration/taxonomy/taxonomy-default-values.js";import{t as TaxonomyFieldConfiguration}from"../../../../chunks/taxonomy-field-configuration.js";import{jsx}from"react/jsx-runtime";import"react";import uniqueId from"lodash/uniqueId";function createDefaultFieldValues(type){return{id:uniqueId(`field-`),key:``,hidden:!1,name:``,type:type??void 0,description:``,isFieldNew:!0,isFieldReadOnly:!1,...taxonomyDefaultValues,dropdown:{options:type===FieldType.Dropdown?[{id:uniqueId(),key:``,isNew:!0}]:[],allowMultipleSelections:!1,isAllowMultipleSelectionsEnabled:!0}}}var getConfigurationByType=type=>{switch(type){case FieldType.Dropdown:return jsx(DropdownFieldConfiguration,{});case FieldType.Taxonomy:return jsx(TaxonomyFieldConfiguration,{});default:return null}};function hasVisibleErrors(errors,touched){return errors?touched===!0?!0:typeof errors!=`object`||typeof touched!=`object`||!touched?!1:Object.keys(errors).some(key=>hasVisibleErrors(errors[key],touched[key])):!1}function markAllTouched(obj){return Object.keys(obj).reduce((acc,key)=>{let val=obj[key];return Array.isArray(val)?acc[key]=val.map(item=>typeof item==`object`&&item?markAllTouched(item):!0):typeof val==`object`&&val?acc[key]=markAllTouched(val):acc[key]=!0,acc},{})}export{createDefaultFieldValues,getConfigurationByType,hasVisibleErrors,markAllTouched};
|
|
1
|
+
import{o as FieldType}from"../../../../chunks/types.js";import{t as DropdownFieldConfiguration}from"../../../../chunks/dropdown-field-configuration.js";import{taxonomyDefaultValues}from"./components/type-specific-configuration/taxonomy/taxonomy-default-values.js";import{t as TaxonomyFieldConfiguration}from"../../../../chunks/taxonomy-field-configuration.js";import{UserFieldConfiguration}from"./components/type-specific-configuration/user/user-field-configuration.js";import{jsx}from"react/jsx-runtime";import"react";import uniqueId from"lodash/uniqueId";function createDefaultFieldValues(type){return{id:uniqueId(`field-`),key:``,hidden:!1,name:``,type:type??void 0,description:``,isFieldNew:!0,isFieldReadOnly:!1,...taxonomyDefaultValues,dropdown:{options:type===FieldType.Dropdown?[{id:uniqueId(),key:``,isNew:!0}]:[],allowMultipleSelections:!1,isAllowMultipleSelectionsEnabled:!0},user:{allowMultipleSelections:!1,notifyWhenUsersAreAdded:!1}}}var getConfigurationByType=type=>{switch(type){case FieldType.Dropdown:return jsx(DropdownFieldConfiguration,{});case FieldType.Taxonomy:return jsx(TaxonomyFieldConfiguration,{});case FieldType.User:return jsx(UserFieldConfiguration,{});default:return null}};function hasVisibleErrors(errors,touched){return errors?touched===!0?!0:typeof errors!=`object`||typeof touched!=`object`||!touched?!1:Object.keys(errors).some(key=>hasVisibleErrors(errors[key],touched[key])):!1}function markAllTouched(obj){return Object.keys(obj).reduce((acc,key)=>{let val=obj[key];return Array.isArray(val)?acc[key]=val.map(item=>typeof item==`object`&&item?markAllTouched(item):!0):typeof val==`object`&&val?acc[key]=markAllTouched(val):acc[key]=!0,acc},{})}export{createDefaultFieldValues,getConfigurationByType,hasVisibleErrors,markAllTouched};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{o as FieldType}from"../../../../chunks/types.js";import{Calendar,Numbers,Section,Taxonomy,TextInput}from"@box/blueprint-web-assets/icons/Medium";import{jsx}from"react/jsx-runtime";import"react";var FieldTypeIcon=type=>props=>{switch(type){case FieldType.Text:return jsx(TextInput,{...props});case FieldType.Number:return jsx(Numbers,{...props});case FieldType.Date:return jsx(Calendar,{...props});case FieldType.Dropdown:return jsx(Section,{...props});case FieldType.Taxonomy:return jsx(Taxonomy,{...props});default:return jsx(TextInput,{...props})}};export{FieldTypeIcon};
|
|
1
|
+
import{o as FieldType}from"../../../../chunks/types.js";import{Avatar,Calendar,Numbers,Section,Taxonomy,TextInput}from"@box/blueprint-web-assets/icons/Medium";import{jsx}from"react/jsx-runtime";import"react";var FieldTypeIcon=type=>props=>{switch(type){case FieldType.Text:return jsx(TextInput,{...props});case FieldType.Number:return jsx(Numbers,{...props});case FieldType.Date:return jsx(Calendar,{...props});case FieldType.Dropdown:return jsx(Section,{...props});case FieldType.Taxonomy:return jsx(Taxonomy,{...props});case FieldType.User:return jsx(Avatar,{...props});default:return jsx(TextInput,{...props})}};export{FieldTypeIcon};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineMessages}from"react-intl";var fieldTypesTitleMessages=defineMessages({text:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypes.text`,defaultMessage:`Text`},number:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypes.number`,defaultMessage:`Number`},date:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypes.date`,defaultMessage:`Date`},dropdown:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypes.dropdown`,defaultMessage:`Dropdown`},taxonomy:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypes.taxonomy`,defaultMessage:`Taxonomy`}}),fieldTypeDescriptionMessages=defineMessages({text:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypeDescriptions.text`,defaultMessage:`Free text input up to 10,000 characters`},number:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypeDescriptions.number`,defaultMessage:`Supports all numeric values`},date:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypeDescriptions.date`,defaultMessage:`Date field with calendar picker`},dropdown:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypeDescriptions.dropdown`,defaultMessage:`Supports single and multiple selections`},taxonomy:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypeDescriptions.taxonomy`,defaultMessage:`Hierarchical list of selectable options`}});export{fieldTypeDescriptionMessages,fieldTypesTitleMessages};
|
|
1
|
+
import{defineMessages}from"react-intl";var fieldTypesTitleMessages=defineMessages({text:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypes.text`,defaultMessage:`Text`},number:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypes.number`,defaultMessage:`Number`},date:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypes.date`,defaultMessage:`Date`},dropdown:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypes.dropdown`,defaultMessage:`Dropdown`},taxonomy:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypes.taxonomy`,defaultMessage:`Taxonomy`},user:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypes.user`,defaultMessage:`User`}}),fieldTypeDescriptionMessages=defineMessages({text:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypeDescriptions.text`,defaultMessage:`Free text input up to 10,000 characters`},number:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypeDescriptions.number`,defaultMessage:`Supports all numeric values`},date:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypeDescriptions.date`,defaultMessage:`Date field with calendar picker`},dropdown:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypeDescriptions.dropdown`,defaultMessage:`Supports single and multiple selections`},taxonomy:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypeDescriptions.taxonomy`,defaultMessage:`Hierarchical list of selectable options`},user:{id:`groupSharedFeatures.metadataTemplateEditor.fieldTypeDescriptions.user`,defaultMessage:`Supports selecting users and groups`}});export{fieldTypeDescriptionMessages,fieldTypesTitleMessages};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as CREATABLE_FIELD_TYPES}from"../../../../chunks/types.js";import{FieldTypeIcon}from"./field-type-icon.js";import{fieldTypeDescriptionMessages,fieldTypesTitleMessages}from"./messages.js";import{useEditorConfig}from"../../components/metadata-field-configurator/context/editor-config-context.js";import{useIntl}from"react-intl";import{useMemo}from"react";function useFieldOptions(){let intl=useIntl(),{disabledFieldTypes}=useEditorConfig();return{availableFieldTypes:useMemo(()=>CREATABLE_FIELD_TYPES.filter(type
|
|
1
|
+
import{o as FieldType,r as CREATABLE_FIELD_TYPES}from"../../../../chunks/types.js";import{FieldTypeIcon}from"./field-type-icon.js";import{fieldTypeDescriptionMessages,fieldTypesTitleMessages}from"./messages.js";import{useEditorConfig}from"../../components/metadata-field-configurator/context/editor-config-context.js";import{useIntl}from"react-intl";import{useMemo}from"react";function useFieldOptions(){let intl=useIntl(),{disabledFieldTypes,isUserFieldEnabled}=useEditorConfig();return{availableFieldTypes:useMemo(()=>CREATABLE_FIELD_TYPES.filter(type=>type===FieldType.User&&!isUserFieldEnabled?!1:!disabledFieldTypes?.includes(type)).map(type=>({type,label:intl.formatMessage(fieldTypesTitleMessages[type]),description:intl.formatMessage(fieldTypeDescriptionMessages[type]),Icon:FieldTypeIcon(type)})),[intl,disabledFieldTypes,isUserFieldEnabled])}}export{useFieldOptions};
|
package/dist/esm/lib/utils/template-type-conversion/convertLocalConfiguratorToTemplateField.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{l as TaxonomySelection,n as ApiMetadataTemplateFieldType,o as FieldType}from"../../../../chunks/types.js";import"../constants.js";import{findTaxonomyOption}from"../taxonomy-identity.js";import{generateKey}from"../key-generation.js";var resolveSelectableLevels=field=>{let{taxonomy}=field,levels=findTaxonomyOption(taxonomy.availableTaxonomies,taxonomy)?.levels.map(level=>level.level)||[];return taxonomy.selection===TaxonomySelection.AllowAny&&levels.length>0?levels:taxonomy.selectedLevels||[]},convertLocalConfiguratorToTemplateField=(field,existingKeys=[])=>{let{name:displayName,description,hidden,type}=field,key=generateKey({displayName,existingKeys,defaultKey:`field`,maxKeyLength:256}),baseFieldData={key,displayName,description,hidden},result;switch(type){case FieldType.Text:result={...baseFieldData,type:ApiMetadataTemplateFieldType.String};break;case FieldType.Number:result={...baseFieldData,type:ApiMetadataTemplateFieldType.Float};break;case FieldType.Date:result={...baseFieldData,type:ApiMetadataTemplateFieldType.Date};break;case FieldType.Dropdown:result={...baseFieldData,type:field.dropdown.allowMultipleSelections?ApiMetadataTemplateFieldType.MultiSelect:ApiMetadataTemplateFieldType.Enum,options:field.dropdown.options.map(option=>({key:option.key}))};break;case FieldType.Taxonomy:result={...baseFieldData,type:ApiMetadataTemplateFieldType.Taxonomy,taxonomyKey:field.taxonomy.taxonomyKey,optionsRules:{selectableLevels:resolveSelectableLevels(field),multiSelect:field.taxonomy.allowMultipleSelections},namespace:field.taxonomy.namespace};break;case FieldType.Unsupported:default:throw Error(`Cannot create field with unsupported type: ${field.originalApiType||type}`)}return{field:result,updatedKeys:[...existingKeys,key]}};export{convertLocalConfiguratorToTemplateField,resolveSelectableLevels};
|
|
1
|
+
import{l as TaxonomySelection,n as ApiMetadataTemplateFieldType,o as FieldType}from"../../../../chunks/types.js";import"../constants.js";import{findTaxonomyOption}from"../taxonomy-identity.js";import{generateKey}from"../key-generation.js";var resolveSelectableLevels=field=>{let{taxonomy}=field,levels=findTaxonomyOption(taxonomy.availableTaxonomies,taxonomy)?.levels.map(level=>level.level)||[];return taxonomy.selection===TaxonomySelection.AllowAny&&levels.length>0?levels:taxonomy.selectedLevels||[]},convertLocalConfiguratorToTemplateField=(field,existingKeys=[])=>{let{name:displayName,description,hidden,type}=field,key=generateKey({displayName,existingKeys,defaultKey:`field`,maxKeyLength:256}),baseFieldData={key,displayName,description,hidden},result;switch(type){case FieldType.Text:result={...baseFieldData,type:ApiMetadataTemplateFieldType.String};break;case FieldType.Number:result={...baseFieldData,type:ApiMetadataTemplateFieldType.Float};break;case FieldType.Date:result={...baseFieldData,type:ApiMetadataTemplateFieldType.Date};break;case FieldType.Dropdown:result={...baseFieldData,type:field.dropdown.allowMultipleSelections?ApiMetadataTemplateFieldType.MultiSelect:ApiMetadataTemplateFieldType.Enum,options:field.dropdown.options.map(option=>({key:option.key}))};break;case FieldType.Taxonomy:result={...baseFieldData,type:ApiMetadataTemplateFieldType.Taxonomy,taxonomyKey:field.taxonomy.taxonomyKey,optionsRules:{selectableLevels:resolveSelectableLevels(field),multiSelect:field.taxonomy.allowMultipleSelections},namespace:field.taxonomy.namespace};break;case FieldType.User:result={...baseFieldData,type:ApiMetadataTemplateFieldType.User,optionsRules:{allowMultipleSelections:field.user.allowMultipleSelections,notifyWhenUsersAreAdded:field.user.notifyWhenUsersAreAdded}};break;case FieldType.Unsupported:default:throw Error(`Cannot create field with unsupported type: ${field.originalApiType||type}`)}return{field:result,updatedKeys:[...existingKeys,key]}};export{convertLocalConfiguratorToTemplateField,resolveSelectableLevels};
|
package/dist/esm/lib/utils/template-type-conversion/convertTemplateFieldToLocalConfigurator.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{l as TaxonomySelection,n as ApiMetadataTemplateFieldType,o as FieldType}from"../../../../chunks/types.js";import uniqueId from"lodash/uniqueId";var convertApiMetadataTemplateFieldToLocalConfiguratorField=(field,isReadOnly=!1)=>{let{key,displayName:name,description,type,hidden}=field,baseField={key,name,id:uniqueId(),description:description||``,hidden,dropdown:{allowMultipleSelections:!1,options:[],isAllowMultipleSelectionsEnabled:!1},taxonomy:{availableTaxonomies:[],allowMultipleSelections:!1,selection:TaxonomySelection.RequireSpecific,selectedLevels:[],taxonomySearchValue:``,taxonomyKey:``,namespace:``},isFieldNew:!1,isFieldReadOnly:isReadOnly};switch(type){case ApiMetadataTemplateFieldType.String:return{...baseField,type:FieldType.Text};case ApiMetadataTemplateFieldType.Float:return{...baseField,type:FieldType.Number};case ApiMetadataTemplateFieldType.Date:return{...baseField,type:FieldType.Date};case ApiMetadataTemplateFieldType.Enum:case ApiMetadataTemplateFieldType.MultiSelect:return{...baseField,type:FieldType.Dropdown,dropdown:{options:field.options
|
|
1
|
+
import{l as TaxonomySelection,n as ApiMetadataTemplateFieldType,o as FieldType}from"../../../../chunks/types.js";import uniqueId from"lodash/uniqueId";function isTaxonomyOptionRules(value){return typeof value==`object`&&!!value&&!Array.isArray(value)&&`selectableLevels`in value}function isUserFieldOptionRules(value){return typeof value==`object`&&!!value&&!Array.isArray(value)&&`allowMultipleSelections`in value}var convertApiMetadataTemplateFieldToLocalConfiguratorField=(field,{isReadOnly=!1,isUserFieldEnabled=!1}={})=>{let{key,displayName:name,description,type,hidden}=field,baseField={key,name,id:uniqueId(),description:description||``,hidden,dropdown:{allowMultipleSelections:!1,options:[],isAllowMultipleSelectionsEnabled:!1},taxonomy:{availableTaxonomies:[],allowMultipleSelections:!1,selection:TaxonomySelection.RequireSpecific,selectedLevels:[],taxonomySearchValue:``,taxonomyKey:``,namespace:``},user:{allowMultipleSelections:!0,notifyWhenUsersAreAdded:!1},isFieldNew:!1,isFieldReadOnly:isReadOnly};switch(type){case ApiMetadataTemplateFieldType.String:return{...baseField,type:FieldType.Text};case ApiMetadataTemplateFieldType.Float:return{...baseField,type:FieldType.Number};case ApiMetadataTemplateFieldType.Date:return{...baseField,type:FieldType.Date};case ApiMetadataTemplateFieldType.Enum:case ApiMetadataTemplateFieldType.MultiSelect:return{...baseField,type:FieldType.Dropdown,dropdown:{options:Array.isArray(field.options)?field.options.map(option=>({id:uniqueId(),key:option.key,isNew:!1})):[],allowMultipleSelections:type===ApiMetadataTemplateFieldType.MultiSelect,isAllowMultipleSelectionsEnabled:type===ApiMetadataTemplateFieldType.MultiSelect}};case ApiMetadataTemplateFieldType.Taxonomy:{let taxonomyRules=isTaxonomyOptionRules(field.optionsRules)?field.optionsRules:void 0;return{...baseField,type:FieldType.Taxonomy,taxonomy:{availableTaxonomies:[],allowMultipleSelections:taxonomyRules?.multiSelect||!1,selection:taxonomyRules?.selectableLevels.length===1?TaxonomySelection.RequireSpecific:TaxonomySelection.AllowAny,selectedLevels:taxonomyRules?.selectableLevels||[],taxonomySearchValue:``,taxonomyKey:field.taxonomyKey||``,namespace:field.namespace||``}}}case ApiMetadataTemplateFieldType.User:{if(!isUserFieldEnabled)return{...baseField,type:FieldType.Unsupported,originalApiType:type};let userRules=isUserFieldOptionRules(field.optionsRules)?field.optionsRules:void 0;return{...baseField,type:FieldType.User,user:{allowMultipleSelections:userRules?.allowMultipleSelections??!1,notifyWhenUsersAreAdded:userRules?.notifyWhenUsersAreAdded??!1}}}default:return{...baseField,type:FieldType.Unsupported,originalApiType:type}}};export{convertApiMetadataTemplateFieldToLocalConfiguratorField};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as isUnsupportedField,n as ApiMetadataTemplateFieldType,o as FieldType,t as AllOps,u as TemplateOperations}from"../../../../chunks/types.js";import"../constants.js";import{generateKey}from"../key-generation.js";import{resolveSelectableLevels}from"./convertLocalConfiguratorToTemplateField.js";import isEqual from"lodash/isEqual";var configuratorFieldTypeToMetadataFieldTypeMap={[FieldType.Text]:ApiMetadataTemplateFieldType.String,[FieldType.Date]:ApiMetadataTemplateFieldType.Date,[FieldType.Number]:ApiMetadataTemplateFieldType.Float};function handleTemplateLevelChanges(initialTemplate,updatedTemplate){let patchItems=[],data={};return initialTemplate.displayName!==updatedTemplate.displayName&&(data.displayName=updatedTemplate.displayName),initialTemplate.hidden!==updatedTemplate.hidden&&(data.hidden=updatedTemplate.hidden),Object.keys(data).length>0&&patchItems.push({op:AllOps.EditTemplate,data}),patchItems}function handleFieldEdits(field,initialField,patchItems){if(!(isUnsupportedField(field)||isUnsupportedField(initialField))&&(field.description!==initialField.description||field.name!==initialField.name||field.hidden!==initialField.hidden)){let data={};field.name!==initialField.name&&(data.displayName=field.name),field.description!==initialField.description&&(data.description=field.description),field.hidden!==initialField.hidden&&(data.hidden=field.hidden),patchItems.push({op:AllOps.EditField,fieldKey:field.key,data})}}function handleDropdownOptionChanges(field,initialField,patchItems){if(field.type!==FieldType.Dropdown||initialField?.type!==FieldType.Dropdown)return;let isMultiSelect=field.dropdown.allowMultipleSelections,initialOptions=initialField.dropdown.options,updatedOptions=field.dropdown.options,initialOptionKeysMap=new Map(initialOptions.map(option=>[option.id,option])),updatedOptionKeysMap=new Map(updatedOptions.map(option=>[option.id,option]));initialOptions.forEach(option=>{if(!updatedOptionKeysMap.has(option.id)&&field.key){if(!option.key)throw Error(`optionKey is required`);patchItems.push({fieldKey:field.key,...isMultiSelect?{op:AllOps.RemoveMultiSelectOption,multiSelectOptionKey:option.key}:{op:AllOps.RemoveEnumOption,enumOptionKey:option.key}})}}),updatedOptions.forEach(option=>{let initialOption=initialOptionKeysMap.get(option.id);if(!initialOption)patchItems.push({op:isMultiSelect?AllOps.AddMultiSelectOption:AllOps.AddEnumOption,fieldKey:field.key,data:{key:option.key}});else if(initialOption.key!==option.key){if(!option.key)throw Error(`optionKey is required`);patchItems.push({fieldKey:field.key,...isMultiSelect?{op:AllOps.EditMultiSelectOption,multiSelectOptionKey:initialOption.key}:{op:AllOps.EditEnumOption,enumOptionKey:initialOption.key},data:{key:option.key}})}});let initialOptionOrder=initialOptions.map(option=>option.key),updatedOptionOrder=updatedOptions.map(option=>option.key);isEqual(initialOptionOrder,updatedOptionOrder)||patchItems.push({fieldKey:field.key,...isMultiSelect?{op:AllOps.ReorderMultiSelectOptions,multiSelectOptionKeys:updatedOptionOrder}:{op:AllOps.ReorderEnumOptions,enumOptionKeys:updatedOptionOrder}})}function buildApiFieldData(field,key){if(isUnsupportedField(field))throw Error(`Cannot create field with unsupported type: ${field.originalApiType||field.type}`);let baseData={displayName:field.name,hidden:field.hidden,key,description:field.description};return field.type===FieldType.Taxonomy?{...baseData,type:ApiMetadataTemplateFieldType.Taxonomy,taxonomyKey:field.taxonomy.taxonomyKey,optionsRules:{selectableLevels:resolveSelectableLevels(field),multiSelect:field.taxonomy.allowMultipleSelections},namespace:field.taxonomy.namespace}:field.type===FieldType.Dropdown?{...baseData,type:field.dropdown.allowMultipleSelections?ApiMetadataTemplateFieldType.MultiSelect:ApiMetadataTemplateFieldType.Enum,options:field.dropdown.options.map(option=>({key:option.key}))}:{...baseData,type:configuratorFieldTypeToMetadataFieldTypeMap[field.type]}}function handleNewField(field,knownKeys,patchItems){let uniqueKey=generateKey({displayName:field.name,existingKeys:Array.from(knownKeys),defaultKey:`field`,maxKeyLength:256});return knownKeys.add(uniqueKey),patchItems.push({op:AllOps.AddField,fieldKey:uniqueKey,data:buildApiFieldData(field,uniqueKey)}),{...field,key:uniqueKey}}function handleFieldChanges(initialFields,updatedFields){let initialFieldMap=new Map(initialFields.map(field=>[field.key,field])),knownKeys=new Set([...initialFields.map(f=>f.key),...updatedFields.map(f=>f.key)].filter(Boolean)),removePatchItems=[],updatedFieldKeySet=new Set(updatedFields.filter(f=>f.key).map(f=>f.key));initialFields.forEach(field=>{updatedFieldKeySet.has(field.key)||removePatchItems.push({op:AllOps.RemoveField,fieldKey:field.key})});let addEditPatchItems=[],resolvedFields=[];return updatedFields.forEach(field=>{let initialField=initialFieldMap.get(field.key);if(!initialField){resolvedFields.push(handleNewField(field,knownKeys,addEditPatchItems));return}resolvedFields.push(field),handleFieldEdits(field,initialField,addEditPatchItems),handleDropdownOptionChanges(field,initialField,addEditPatchItems)}),{patchItems:[...removePatchItems,...addEditPatchItems],resolvedFields}}function handleFieldReordering(initialFields,updatedFields){let initialFieldOrder=initialFields.map(field=>field.key).filter(Boolean),updatedFieldOrder=updatedFields.map(field=>field.key).filter(Boolean);return initialFieldOrder.length!==updatedFieldOrder.length||initialFieldOrder.some((key,i)=>key!==updatedFieldOrder[i])?[{op:AllOps.ReorderFields,fieldKeys:updatedFieldOrder}]:[]}function generateJSONPatchTemplateOperations(initialTemplate,updatedTemplate){let patchItems=[];patchItems.push(...handleTemplateLevelChanges(initialTemplate,updatedTemplate));let{patchItems:fieldPatchItems,resolvedFields}=handleFieldChanges(initialTemplate.fields||[],updatedTemplate.fields||[]);return patchItems.push(...fieldPatchItems),patchItems.push(...handleFieldReordering(initialTemplate.fields||[],resolvedFields)),patchItems}function generateJSONPatchTemplateOperationToUpdateTemplateName(displayName){return[{op:TemplateOperations.EditTemplate,data:{displayName}}]}export{configuratorFieldTypeToMetadataFieldTypeMap,generateJSONPatchTemplateOperationToUpdateTemplateName,generateJSONPatchTemplateOperations};
|
|
1
|
+
import{d as isUnsupportedField,n as ApiMetadataTemplateFieldType,o as FieldType,t as AllOps,u as TemplateOperations}from"../../../../chunks/types.js";import"../constants.js";import{generateKey}from"../key-generation.js";import{resolveSelectableLevels}from"./convertLocalConfiguratorToTemplateField.js";import isEqual from"lodash/isEqual";var configuratorFieldTypeToMetadataFieldTypeMap={[FieldType.Text]:ApiMetadataTemplateFieldType.String,[FieldType.Date]:ApiMetadataTemplateFieldType.Date,[FieldType.Number]:ApiMetadataTemplateFieldType.Float};function handleTemplateLevelChanges(initialTemplate,updatedTemplate){let patchItems=[],data={};return initialTemplate.displayName!==updatedTemplate.displayName&&(data.displayName=updatedTemplate.displayName),initialTemplate.hidden!==updatedTemplate.hidden&&(data.hidden=updatedTemplate.hidden),Object.keys(data).length>0&&patchItems.push({op:AllOps.EditTemplate,data}),patchItems}function handleFieldEdits(field,initialField,patchItems){if(!(isUnsupportedField(field)||isUnsupportedField(initialField))&&(field.description!==initialField.description||field.name!==initialField.name||field.hidden!==initialField.hidden)){let data={};field.name!==initialField.name&&(data.displayName=field.name),field.description!==initialField.description&&(data.description=field.description),field.hidden!==initialField.hidden&&(data.hidden=field.hidden),patchItems.push({op:AllOps.EditField,fieldKey:field.key,data})}}function handleUserFieldChanges(field,initialField,patchItems){field.type!==FieldType.User||initialField?.type!==FieldType.User||field.user.notifyWhenUsersAreAdded!==initialField.user.notifyWhenUsersAreAdded&&patchItems.push({op:AllOps.EditField,fieldKey:field.key,data:{optionsRules:{allowMultipleSelections:initialField.user.allowMultipleSelections,notifyWhenUsersAreAdded:field.user.notifyWhenUsersAreAdded}}})}function handleDropdownOptionChanges(field,initialField,patchItems){if(field.type!==FieldType.Dropdown||initialField?.type!==FieldType.Dropdown)return;let isMultiSelect=field.dropdown.allowMultipleSelections,initialOptions=initialField.dropdown.options,updatedOptions=field.dropdown.options,initialOptionKeysMap=new Map(initialOptions.map(option=>[option.id,option])),updatedOptionKeysMap=new Map(updatedOptions.map(option=>[option.id,option]));initialOptions.forEach(option=>{if(!updatedOptionKeysMap.has(option.id)&&field.key){if(!option.key)throw Error(`optionKey is required`);patchItems.push({fieldKey:field.key,...isMultiSelect?{op:AllOps.RemoveMultiSelectOption,multiSelectOptionKey:option.key}:{op:AllOps.RemoveEnumOption,enumOptionKey:option.key}})}}),updatedOptions.forEach(option=>{let initialOption=initialOptionKeysMap.get(option.id);if(!initialOption)patchItems.push({op:isMultiSelect?AllOps.AddMultiSelectOption:AllOps.AddEnumOption,fieldKey:field.key,data:{key:option.key}});else if(initialOption.key!==option.key){if(!option.key)throw Error(`optionKey is required`);patchItems.push({fieldKey:field.key,...isMultiSelect?{op:AllOps.EditMultiSelectOption,multiSelectOptionKey:initialOption.key}:{op:AllOps.EditEnumOption,enumOptionKey:initialOption.key},data:{key:option.key}})}});let initialOptionOrder=initialOptions.map(option=>option.key),updatedOptionOrder=updatedOptions.map(option=>option.key);isEqual(initialOptionOrder,updatedOptionOrder)||patchItems.push({fieldKey:field.key,...isMultiSelect?{op:AllOps.ReorderMultiSelectOptions,multiSelectOptionKeys:updatedOptionOrder}:{op:AllOps.ReorderEnumOptions,enumOptionKeys:updatedOptionOrder}})}function buildApiFieldData(field,key){if(isUnsupportedField(field))throw Error(`Cannot create field with unsupported type: ${field.originalApiType||field.type}`);let baseData={displayName:field.name,hidden:field.hidden,key,description:field.description};return field.type===FieldType.Taxonomy?{...baseData,type:ApiMetadataTemplateFieldType.Taxonomy,taxonomyKey:field.taxonomy.taxonomyKey,optionsRules:{selectableLevels:resolveSelectableLevels(field),multiSelect:field.taxonomy.allowMultipleSelections},namespace:field.taxonomy.namespace}:field.type===FieldType.Dropdown?{...baseData,type:field.dropdown.allowMultipleSelections?ApiMetadataTemplateFieldType.MultiSelect:ApiMetadataTemplateFieldType.Enum,options:field.dropdown.options.map(option=>({key:option.key}))}:field.type===FieldType.User?{...baseData,type:ApiMetadataTemplateFieldType.User,optionsRules:{allowMultipleSelections:field.user.allowMultipleSelections,notifyWhenUsersAreAdded:field.user.notifyWhenUsersAreAdded}}:{...baseData,type:configuratorFieldTypeToMetadataFieldTypeMap[field.type]}}function handleNewField(field,knownKeys,patchItems){let uniqueKey=generateKey({displayName:field.name,existingKeys:Array.from(knownKeys),defaultKey:`field`,maxKeyLength:256});return knownKeys.add(uniqueKey),patchItems.push({op:AllOps.AddField,fieldKey:uniqueKey,data:buildApiFieldData(field,uniqueKey)}),{...field,key:uniqueKey}}function handleFieldChanges(initialFields,updatedFields){let initialFieldMap=new Map(initialFields.map(field=>[field.key,field])),knownKeys=new Set([...initialFields.map(f=>f.key),...updatedFields.map(f=>f.key)].filter(Boolean)),removePatchItems=[],updatedFieldKeySet=new Set(updatedFields.filter(f=>f.key).map(f=>f.key));initialFields.forEach(field=>{updatedFieldKeySet.has(field.key)||removePatchItems.push({op:AllOps.RemoveField,fieldKey:field.key})});let addEditPatchItems=[],resolvedFields=[];return updatedFields.forEach(field=>{let initialField=initialFieldMap.get(field.key);if(!initialField){resolvedFields.push(handleNewField(field,knownKeys,addEditPatchItems));return}resolvedFields.push(field),handleFieldEdits(field,initialField,addEditPatchItems),handleUserFieldChanges(field,initialField,addEditPatchItems),handleDropdownOptionChanges(field,initialField,addEditPatchItems)}),{patchItems:[...removePatchItems,...addEditPatchItems],resolvedFields}}function handleFieldReordering(initialFields,updatedFields){let initialFieldOrder=initialFields.map(field=>field.key).filter(Boolean),updatedFieldOrder=updatedFields.map(field=>field.key).filter(Boolean);return initialFieldOrder.length!==updatedFieldOrder.length||initialFieldOrder.some((key,i)=>key!==updatedFieldOrder[i])?[{op:AllOps.ReorderFields,fieldKeys:updatedFieldOrder}]:[]}function generateJSONPatchTemplateOperations(initialTemplate,updatedTemplate){let patchItems=[];patchItems.push(...handleTemplateLevelChanges(initialTemplate,updatedTemplate));let{patchItems:fieldPatchItems,resolvedFields}=handleFieldChanges(initialTemplate.fields||[],updatedTemplate.fields||[]);return patchItems.push(...fieldPatchItems),patchItems.push(...handleFieldReordering(initialTemplate.fields||[],resolvedFields)),patchItems}function generateJSONPatchTemplateOperationToUpdateTemplateName(displayName){return[{op:TemplateOperations.EditTemplate,data:{displayName}}]}export{configuratorFieldTypeToMetadataFieldTypeMap,generateJSONPatchTemplateOperationToUpdateTemplateName,generateJSONPatchTemplateOperations};
|
package/dist/types/lib/components/metadata-field-configurator/context/editor-config-context.d.ts
CHANGED
|
@@ -12,6 +12,11 @@ export interface TaxonomyInitialStateLabels {
|
|
|
12
12
|
export interface EditorConfig {
|
|
13
13
|
disabledFieldTypes?: FieldType[];
|
|
14
14
|
taxonomyInitialStateLabels?: TaxonomyInitialStateLabels;
|
|
15
|
+
/**
|
|
16
|
+
* When true, User is offered in the field-type picker and API `user` fields load as a
|
|
17
|
+
* normal field. Defaults to false so existing hosts keep current behavior.
|
|
18
|
+
*/
|
|
19
|
+
isUserFieldEnabled?: boolean;
|
|
15
20
|
}
|
|
16
21
|
export declare const EditorConfigContext: import('react').Context<EditorConfig>;
|
|
17
22
|
export declare const useEditorConfig: () => EditorConfig;
|
|
@@ -40,6 +40,12 @@ export type MetadataFieldListProps = {
|
|
|
40
40
|
* Lookups are cached across fields for the lifetime of the list. Independent of `fetchTaxonomies`.
|
|
41
41
|
*/
|
|
42
42
|
readonly fetchTaxonomyByKey: FetchTaxonomyByKey;
|
|
43
|
+
/**
|
|
44
|
+
* When true, User is offered in the field-type picker. Defaults to the parent
|
|
45
|
+
* `EditorConfig` value (false when unset) so a surrounding editor can opt in
|
|
46
|
+
* without the list repeating the prop.
|
|
47
|
+
*/
|
|
48
|
+
readonly isUserFieldEnabled?: boolean;
|
|
43
49
|
/**
|
|
44
50
|
* Field types that are disabled/hidden from the field type picker (defaults to none).
|
|
45
51
|
*/
|
|
@@ -4,6 +4,6 @@ export { EditorConfigContext, useEditorConfig, } from './components/metadata-fie
|
|
|
4
4
|
export type { EditorConfig, TaxonomyInitialStateLabels, } from './components/metadata-field-configurator/context/editor-config-context';
|
|
5
5
|
export { useMetadataTemplateFormSchema } from './hooks/useMetadataTemplateFormSchema';
|
|
6
6
|
export { useTemplateNameSchema } from './hooks/useTemplateNameSchema';
|
|
7
|
-
export { convertApiMetadataTemplateFieldToLocalConfiguratorField } from './utils/template-type-conversion/convertTemplateFieldToLocalConfigurator';
|
|
7
|
+
export { convertApiMetadataTemplateFieldToLocalConfiguratorField, type ConvertApiMetadataTemplateFieldToLocalConfiguratorFieldOptions, } from './utils/template-type-conversion/convertTemplateFieldToLocalConfigurator';
|
|
8
8
|
export { mapFieldsWithUniqueKeys } from './utils/template-type-conversion/mapFieldsWithUniqueKeys';
|
|
9
9
|
export { generateJSONPatchTemplateOperations } from './utils/template-type-conversion/generateJSONPatchTemplateOperations';
|
|
@@ -134,6 +134,14 @@ type MetadataTemplateEditorCommonProps = {
|
|
|
134
134
|
* ```
|
|
135
135
|
*/
|
|
136
136
|
fetchTaxonomyByKey: FetchTaxonomyByKey;
|
|
137
|
+
/**
|
|
138
|
+
* When true, User is offered in the field-type picker and existing API `user` fields
|
|
139
|
+
* load as a normal field. Defaults to false: User is hidden and `user` fields stay
|
|
140
|
+
* Unsupported (delete-only), matching current host behavior.
|
|
141
|
+
*
|
|
142
|
+
* Do not hide User via `disabledFieldTypes` — that list is opt-out and defaults empty.
|
|
143
|
+
*/
|
|
144
|
+
isUserFieldEnabled?: boolean;
|
|
137
145
|
/**
|
|
138
146
|
* Field types that are disabled/hidden from the field type picker (defaults to none).
|
|
139
147
|
*/
|
|
@@ -322,5 +330,5 @@ export type MetadataTemplateEditorProps = MetadataTemplateEditorCommonProps & (C
|
|
|
322
330
|
* </button>
|
|
323
331
|
* ```
|
|
324
332
|
*/
|
|
325
|
-
export declare function MetadataTemplateEditor({ onCancel, onDirtyStateChange, onValidationChange, onSubmitError, onTemplateLoad, taxonomyOptions, fetchTaxonomies, fetchTaxonomyByKey, disabledFieldTypes, taxonomyInitialStateLabels, formId, hideActions, isVisibilityToggleAllowed, fieldExtensions, ...modeProps }: MetadataTemplateEditorProps): import("react/jsx-runtime").JSX.Element;
|
|
333
|
+
export declare function MetadataTemplateEditor({ onCancel, onDirtyStateChange, onValidationChange, onSubmitError, onTemplateLoad, taxonomyOptions, fetchTaxonomies, fetchTaxonomyByKey, disabledFieldTypes, taxonomyInitialStateLabels, formId, hideActions, isVisibilityToggleAllowed, isUserFieldEnabled, fieldExtensions, ...modeProps }: MetadataTemplateEditorProps): import("react/jsx-runtime").JSX.Element;
|
|
326
334
|
export default MetadataTemplateEditor;
|
|
@@ -14,6 +14,7 @@ export declare enum MetadataTemplateEditorMode {
|
|
|
14
14
|
* - Date - date field
|
|
15
15
|
* - Dropdown - field with a dropdown list
|
|
16
16
|
* - Taxonomy - taxonomy field (e.g. key-value pairs)
|
|
17
|
+
* - User - user field (select users and groups)
|
|
17
18
|
* - Unsupported - deprecated/unknown API type (read-only; delete only; cannot be created)
|
|
18
19
|
*/
|
|
19
20
|
export declare enum FieldType {
|
|
@@ -22,6 +23,7 @@ export declare enum FieldType {
|
|
|
22
23
|
Date = "date",
|
|
23
24
|
Dropdown = "dropdown",
|
|
24
25
|
Taxonomy = "taxonomy",
|
|
26
|
+
User = "user",
|
|
25
27
|
Unsupported = "unsupported"
|
|
26
28
|
}
|
|
27
29
|
/** Field types that can be created via the type picker (excludes Unsupported). */
|
|
@@ -45,6 +47,7 @@ export interface BasicField {
|
|
|
45
47
|
hidden: boolean;
|
|
46
48
|
dropdown: DropdownField['dropdown'];
|
|
47
49
|
taxonomy: TaxonomyField['taxonomy'];
|
|
50
|
+
user: UserField['user'];
|
|
48
51
|
isFieldNew: boolean;
|
|
49
52
|
isFieldReadOnly: boolean;
|
|
50
53
|
/**
|
|
@@ -65,6 +68,8 @@ export type FieldData = (BasicField & {
|
|
|
65
68
|
type: FieldType.Dropdown;
|
|
66
69
|
}) | (BasicField & TaxonomyField & {
|
|
67
70
|
type: FieldType.Taxonomy;
|
|
71
|
+
}) | (BasicField & UserField & {
|
|
72
|
+
type: FieldType.User;
|
|
68
73
|
});
|
|
69
74
|
export declare const isUnsupportedField: (field: Pick<BasicField, "type">) => field is Pick<BasicField, "type"> & {
|
|
70
75
|
type: FieldType.Unsupported;
|
|
@@ -112,6 +117,15 @@ export interface TaxonomyOption {
|
|
|
112
117
|
taxonomyKey: string;
|
|
113
118
|
namespace: string;
|
|
114
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* Represents a user field.
|
|
122
|
+
*/
|
|
123
|
+
export interface UserField {
|
|
124
|
+
user: {
|
|
125
|
+
allowMultipleSelections: boolean;
|
|
126
|
+
notifyWhenUsersAreAdded: boolean;
|
|
127
|
+
};
|
|
128
|
+
}
|
|
115
129
|
/**
|
|
116
130
|
* Looks up a single taxonomy by namespace and key.
|
|
117
131
|
*
|
|
@@ -164,7 +178,8 @@ export declare enum ApiMetadataTemplateFieldType {
|
|
|
164
178
|
MultiSelect = "multiSelect",
|
|
165
179
|
Date = "date",
|
|
166
180
|
String = "string",
|
|
167
|
-
Enum = "enum"
|
|
181
|
+
Enum = "enum",
|
|
182
|
+
User = "user"
|
|
168
183
|
}
|
|
169
184
|
export type ApiDropdownFieldOption = {
|
|
170
185
|
key: string;
|
|
@@ -175,6 +190,15 @@ export type ApiMetadataTemplateFieldBase = {
|
|
|
175
190
|
description?: string;
|
|
176
191
|
hidden: boolean;
|
|
177
192
|
};
|
|
193
|
+
export type TaxonomyOptionRules = {
|
|
194
|
+
selectableLevels: number[];
|
|
195
|
+
multiSelect: boolean;
|
|
196
|
+
};
|
|
197
|
+
export type UserFieldOptionRules = {
|
|
198
|
+
allowMultipleSelections: boolean;
|
|
199
|
+
notifyWhenUsersAreAdded: boolean;
|
|
200
|
+
};
|
|
201
|
+
type OptionRules = TaxonomyOptionRules | UserFieldOptionRules;
|
|
178
202
|
export type ApiMetadataTemplateTextField = {
|
|
179
203
|
type: ApiMetadataTemplateFieldType.String;
|
|
180
204
|
};
|
|
@@ -187,17 +211,18 @@ export type ApiMetadataTemplateDateField = {
|
|
|
187
211
|
export type ApiMetadataTemplateTaxonomyField = {
|
|
188
212
|
type: ApiMetadataTemplateFieldType.Taxonomy;
|
|
189
213
|
taxonomyKey: string;
|
|
190
|
-
optionsRules:
|
|
191
|
-
selectableLevels: number[];
|
|
192
|
-
multiSelect: boolean;
|
|
193
|
-
};
|
|
214
|
+
optionsRules: TaxonomyOptionRules;
|
|
194
215
|
namespace: string;
|
|
195
216
|
};
|
|
196
217
|
export type ApiMetadataTemplateDropdownField = {
|
|
197
218
|
type: ApiMetadataTemplateFieldType.Enum | ApiMetadataTemplateFieldType.MultiSelect;
|
|
198
219
|
options: ApiDropdownFieldOption[];
|
|
199
220
|
};
|
|
200
|
-
export type
|
|
221
|
+
export type ProposedUserFieldPayload = {
|
|
222
|
+
type: ApiMetadataTemplateFieldType.User;
|
|
223
|
+
optionsRules: UserFieldOptionRules;
|
|
224
|
+
};
|
|
225
|
+
export type ApiMetadataTemplateKnownField = ApiMetadataTemplateFieldBase & (ApiMetadataTemplateTextField | ApiMetadataTemplateNumberField | ApiMetadataTemplateDateField | ApiMetadataTemplateTaxonomyField | ApiMetadataTemplateDropdownField | ProposedUserFieldPayload);
|
|
201
226
|
/**
|
|
202
227
|
* Field shape from the API when loading a template for edit.
|
|
203
228
|
* `type` is a string so deprecated/unknown types (e.g. timeline, integer) are accepted.
|
|
@@ -205,10 +230,7 @@ export type ApiMetadataTemplateKnownField = ApiMetadataTemplateFieldBase & (ApiM
|
|
|
205
230
|
export type ApiMetadataTemplateFieldFromApi = ApiMetadataTemplateFieldBase & {
|
|
206
231
|
type: string;
|
|
207
232
|
options?: ApiDropdownFieldOption[];
|
|
208
|
-
optionsRules?:
|
|
209
|
-
selectableLevels: number[];
|
|
210
|
-
multiSelect: boolean;
|
|
211
|
-
};
|
|
233
|
+
optionsRules?: OptionRules;
|
|
212
234
|
taxonomyKey?: string;
|
|
213
235
|
namespace?: string;
|
|
214
236
|
};
|
|
@@ -311,6 +333,7 @@ export interface EditFieldOperation extends BaseOperation {
|
|
|
311
333
|
displayName?: string;
|
|
312
334
|
description?: string;
|
|
313
335
|
hidden?: boolean;
|
|
336
|
+
optionsRules?: UserFieldOptionRules;
|
|
314
337
|
};
|
|
315
338
|
}
|
|
316
339
|
interface RemoveFieldOperation extends BaseOperation {
|
|
@@ -27,6 +27,11 @@ export declare const fieldTypesTitleMessages: {
|
|
|
27
27
|
description: string;
|
|
28
28
|
id: string;
|
|
29
29
|
};
|
|
30
|
+
user: {
|
|
31
|
+
defaultMessage: string;
|
|
32
|
+
description: string;
|
|
33
|
+
id: string;
|
|
34
|
+
};
|
|
30
35
|
};
|
|
31
36
|
/**
|
|
32
37
|
* Detailed descriptions for each metadata field type.
|
|
@@ -57,4 +62,9 @@ export declare const fieldTypeDescriptionMessages: {
|
|
|
57
62
|
description: string;
|
|
58
63
|
id: string;
|
|
59
64
|
};
|
|
65
|
+
user: {
|
|
66
|
+
defaultMessage: string;
|
|
67
|
+
description: string;
|
|
68
|
+
id: string;
|
|
69
|
+
};
|
|
60
70
|
};
|
|
@@ -27,8 +27,8 @@ export type FieldOptionTypes = {
|
|
|
27
27
|
* descriptions, and icons. Both FieldTypeTiles and FieldTypeDropdown
|
|
28
28
|
* use this hook as their single field-type source.
|
|
29
29
|
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
30
|
+
* Taxonomy availability is not checked here — hosts hide Taxonomy via `disabledFieldTypes`.
|
|
31
|
+
* User is opt-in via `isUserFieldEnabled` (default false) so it stays out of the picker
|
|
32
|
+
* until a host turns the flag on.
|
|
33
33
|
*/
|
|
34
34
|
export declare function useFieldOptions(): FieldOptionTypes;
|
package/dist/types/lib/utils/template-type-conversion/convertTemplateFieldToLocalConfigurator.d.ts
CHANGED
|
@@ -1,8 +1,17 @@
|
|
|
1
1
|
import { ApiMetadataTemplateField, FieldData } from '../../types';
|
|
2
|
+
export interface ConvertApiMetadataTemplateFieldToLocalConfiguratorFieldOptions {
|
|
3
|
+
/** Marks the converted field as read-only in the configurator. Defaults to false. */
|
|
4
|
+
isReadOnly?: boolean;
|
|
5
|
+
/**
|
|
6
|
+
* When true, API `user` fields load as a normal User field.
|
|
7
|
+
* When false, they stay Unsupported so hosts that have not opted in keep delete-only behavior.
|
|
8
|
+
*/
|
|
9
|
+
isUserFieldEnabled?: boolean;
|
|
10
|
+
}
|
|
2
11
|
/**
|
|
3
|
-
* Converts
|
|
12
|
+
* Converts an API template field into the configurator's `FieldData` shape.
|
|
4
13
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
14
|
+
* API `user` fields load as a normal User field only when `isUserFieldEnabled` is true.
|
|
15
|
+
* Otherwise they stay Unsupported so hosts that have not opted in keep delete-only behavior.
|
|
7
16
|
*/
|
|
8
|
-
export declare const convertApiMetadataTemplateFieldToLocalConfiguratorField: (field: ApiMetadataTemplateField, isReadOnly?:
|
|
17
|
+
export declare const convertApiMetadataTemplateFieldToLocalConfiguratorField: (field: ApiMetadataTemplateField, { isReadOnly, isUserFieldEnabled, }?: ConvertApiMetadataTemplateFieldToLocalConfiguratorFieldOptions) => FieldData;
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@box/metadata-template-editor",
|
|
3
|
-
"version": "2.5.
|
|
3
|
+
"version": "2.5.11",
|
|
4
4
|
"license": "SEE LICENSE IN LICENSE",
|
|
5
5
|
"peerDependencies": {
|
|
6
|
-
"@box/blueprint-web": "^17.
|
|
7
|
-
"@box/blueprint-web-assets": "^5.10.
|
|
6
|
+
"@box/blueprint-web": "^17.12.1",
|
|
7
|
+
"@box/blueprint-web-assets": "^5.10.14",
|
|
8
8
|
"@dnd-kit/core": "^6.1.0",
|
|
9
9
|
"@dnd-kit/sortable": "^8.0.0",
|
|
10
10
|
"@dnd-kit/utilities": "^3.2.2",
|
|
@@ -17,10 +17,10 @@
|
|
|
17
17
|
"yup": "^1.6.1"
|
|
18
18
|
},
|
|
19
19
|
"devDependencies": {
|
|
20
|
-
"@box/blueprint-web": "^17.
|
|
21
|
-
"@box/blueprint-web-assets": "^5.10.
|
|
22
|
-
"@box/eslint-plugin-blueprint": "2.2.
|
|
23
|
-
"@box/storybook-utils": "1.2.
|
|
20
|
+
"@box/blueprint-web": "^17.12.1",
|
|
21
|
+
"@box/blueprint-web-assets": "^5.10.14",
|
|
22
|
+
"@box/eslint-plugin-blueprint": "2.2.20",
|
|
23
|
+
"@box/storybook-utils": "1.2.58",
|
|
24
24
|
"@dnd-kit/core": "^6.1.0",
|
|
25
25
|
"@dnd-kit/sortable": "^8.0.0",
|
|
26
26
|
"@dnd-kit/utilities": "^3.2.2",
|