define(["require", "exports", "tslib", "react", "@uifabric/react-hooks", "@uifabric/experiments/lib/UnifiedPeoplePicker", "@uifabric/example-data", "@uifabric/experiments/lib/SelectedItemsList", "@uifabric/experiments/lib/FloatingPeopleSuggestionsComposite", "@uifabric/experiments/lib/Utilities"], function (require, exports, tslib_1, React, react_hooks_1, UnifiedPeoplePicker_1, example_data_1, SelectedItemsList_1, FloatingPeopleSuggestionsComposite_1, Utilities_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var _suggestions = [
        {
            key: '1',
            id: '1',
            displayText: 'Suggestion 1',
            item: example_data_1.mru[0],
            isSelected: true,
            showRemoveButton: true,
        },
        {
            key: '2',
            id: '2',
            displayText: 'Suggestion 2',
            item: example_data_1.mru[1],
            isSelected: false,
            showRemoveButton: true,
        },
        {
            key: '3',
            id: '3',
            displayText: 'Suggestion 3',
            item: example_data_1.mru[2],
            isSelected: false,
            showRemoveButton: true,
        },
        {
            key: '4',
            id: '4',
            displayText: 'Suggestion 4',
            item: example_data_1.mru[3],
            isSelected: false,
            showRemoveButton: true,
        },
        {
            key: '5',
            id: '5',
            displayText: 'Suggestion 5',
            item: example_data_1.mru[4],
            isSelected: false,
            showRemoveButton: true,
        },
    ];
    exports.UnifiedPeoplePickerWithEditExample = function () {
        var _a = React.useState(tslib_1.__spreadArrays(_suggestions)), peopleSuggestions = _a[0], setPeopleSuggestions = _a[1];
        var _b = React.useState([]), peopleSelectedItems = _b[0], setPeopleSelectedItems = _b[1];
        var _c = React.useState(''), inputText = _c[0], setInputText = _c[1];
        var _d = React.useState(-1), editingIndex = _d[0], setEditingIndex = _d[1];
        var ref = React.useRef();
        var suggestionProps = react_hooks_1.useConst(function () {
            return {
                // uncomment below section to see any example of a selectable header item
                headerItemsProps: [
                    {
                        renderItem: function () {
                            return React.createElement(React.Fragment, null, "People Suggestions");
                        },
                        shouldShow: function () {
                            return peopleSuggestions.length > 0;
                        },
                    },
                ],
                footerItemsProps: [
                    {
                        renderItem: function () {
                            return React.createElement(React.Fragment, null,
                                "Showing ",
                                peopleSuggestions.length,
                                " results");
                        },
                        shouldShow: function () {
                            return peopleSuggestions.length > 0;
                        },
                    },
                    {
                        renderItem: function () {
                            return React.createElement(React.Fragment, null, "Select to log out to console");
                        },
                        shouldShow: function () {
                            return peopleSuggestions.length > 0;
                        },
                        onExecute: function () {
                            console.log(peopleSuggestions);
                        },
                    },
                ],
            };
        });
        var _getSuggestions = function (value) {
            var allPeople = example_data_1.people;
            var suggestions = allPeople.filter(function (item) { return _startsWith(item.text || '', value); });
            var suggestionList = suggestions.map(function (item) {
                return { item: item, isSelected: false, key: item.key };
            });
            return suggestionList;
        };
        var _isValid = React.useCallback(function (item) { return Boolean(item.secondaryText); }, []);
        var SelectedItemInternal = function (props) { return (React.createElement(SelectedItemsList_1.SelectedPersona, tslib_1.__assign({ isValid: _isValid }, props))); };
        /**
         * Build a custom selected item capable of being edited when the item is right clicked
         */
        var SelectedItem = SelectedItemsList_1.EditableItem({
            editingItemComponent: SelectedItemsList_1.DefaultEditingItem({
                getEditingItemText: function (persona) { return persona.text || ''; },
                getSuggestions: _getSuggestions,
                pickerSuggestionsProps: suggestionProps,
                onRenderFloatingPicker: function (props) { return (React.createElement(FloatingPeopleSuggestionsComposite_1.FloatingPeopleSuggestions, tslib_1.__assign({}, props, { isSuggestionsVisible: true }))); },
            }),
            itemComponent: SelectedItemsList_1.ItemWithContextMenu({
                menuItems: function (item, onTrigger) { return [
                    {
                        key: 'copy',
                        text: 'copy',
                        onClick: function () {
                            _copyToClipboardWrapper(item);
                        },
                    },
                    {
                        key: 'edit',
                        text: 'Edit',
                        onClick: function () { return onTrigger && onTrigger(); },
                    },
                ]; },
                itemComponent: SelectedItemsList_1.TriggerOnContextMenu(SelectedItemInternal),
            }),
            getIsEditing: function (item, index) { return index === editingIndex; },
            onEditingStarted: function (item, index) { return setEditingIndex(index); },
            onEditingCompleted: function () { return setEditingIndex(-1); },
        });
        var _copyToClipboardWrapper = function (item) {
            var _a;
            var selectedItems = (_a = ref.current) === null || _a === void 0 ? void 0 : _a.getSelectedItems();
            if (selectedItems && selectedItems.length > 1) {
                _copyToClipboard(_getItemsCopyText(selectedItems));
            }
            else {
                _copyToClipboard(_getItemsCopyText([item]));
            }
        };
        var _copyToClipboard = function (copyString) {
            navigator.clipboard.writeText(copyString).then(function () {
                /* clipboard successfully set */
            }, function () {
                /* clipboard write failed */
                throw new Error();
            });
        };
        var _onSuggestionSelected = function (ev, item) {
            _markSuggestionSelected(item);
            setPeopleSelectedItems(function (prevPeopleSelectedItems) { return tslib_1.__spreadArrays(prevPeopleSelectedItems, [item.item]); });
        };
        var _onSuggestionRemoved = function (ev, suggestionToRemove) {
            // Intentionally checking on complete item object to ensure it is removed. Id cannot be used as the
            // property is not populated for all the suggestions, and key does not exist on type checking.
            setPeopleSuggestions(function (suggestions) {
                var modifiedSuggestions = suggestions.filter(function (suggestion) { return suggestion.item !== suggestionToRemove.item; });
                return modifiedSuggestions;
            });
        };
        var _markSuggestionSelected = function (selectedSuggestion) {
            setPeopleSuggestions(function (suggestions) {
                var modifiedSuggestions = suggestions.map(function (suggestion) {
                    return suggestion.id === selectedSuggestion.id
                        ? tslib_1.__assign(tslib_1.__assign({}, suggestion), { isSelected: true }) : tslib_1.__assign(tslib_1.__assign({}, suggestion), { isSelected: false });
                });
                return modifiedSuggestions;
            });
        };
        var _getItemsCopyText = function (itemsToCopy) {
            var copyText = '';
            if (itemsToCopy && itemsToCopy.length > 0) {
                itemsToCopy.forEach(function (item) {
                    copyText = copyText.concat((item.text || '') + ',');
                });
            }
            return copyText;
        };
        var _onPaste = function (pastedValue, selectedItemsList) {
            // Find the suggestion corresponding to the specific text name
            // and update the selectedItemsList to re-render everything.
            var newList = [];
            if (pastedValue !== null) {
                pastedValue.split(',').forEach(function (textValue) {
                    if (textValue) {
                        example_data_1.people.forEach(function (suggestionItem) {
                            if (suggestionItem.text === textValue) {
                                selectedItemsList.push(suggestionItem);
                                newList.push(suggestionItem);
                            }
                        });
                    }
                });
            }
            setPeopleSelectedItems(function (prevPeopleSelectedItems) { return tslib_1.__spreadArrays(prevPeopleSelectedItems, newList); });
        };
        var _onItemsRemoved = function (itemsToRemove) {
            // Updating the local copy as well at the parent level.
            var currentItems = tslib_1.__spreadArrays(peopleSelectedItems);
            var updatedItems = currentItems;
            // Intentionally not using .filter here as we want to only remove a specific
            // item in case of duplicates of same item.
            itemsToRemove.forEach(function (item) {
                var index = updatedItems.indexOf(item);
                updatedItems.splice(index, 1);
            });
            setPeopleSelectedItems(updatedItems);
        };
        var _replaceItem = function (newItem, index) {
            var newItemsArray = !Array.isArray(newItem) ? [newItem] : newItem;
            if (index >= 0) {
                var newItems = tslib_1.__spreadArrays(peopleSelectedItems);
                newItems.splice.apply(newItems, tslib_1.__spreadArrays([index, 1], newItemsArray));
                setPeopleSelectedItems(newItems);
            }
        };
        var _createGenericItem = function (input) {
            return { text: input };
        };
        var _addGenericItem = function (text) {
            var _a;
            setPeopleSelectedItems(function (prevPeopleSelectedItems) { return tslib_1.__spreadArrays(prevPeopleSelectedItems, [_createGenericItem(text)]); });
            (_a = ref.current) === null || _a === void 0 ? void 0 : _a.clearInput();
            setInputText('');
        };
        var _onInputChange = function (filterText) {
            // Add a generic item to the end of the list
            // and clear the input if the user types a semicolon or comma
            var lastCharIndex = filterText.length - 1;
            var lastChar = filterText[lastCharIndex];
            if (lastChar === ';' || lastChar === ',') {
                var itemText = filterText.slice(0, filterText.length - 1);
                _addGenericItem(itemText);
            }
            else {
                // Save the input text for force resolve
                setInputText(filterText);
            }
            var allPeople = example_data_1.people;
            var suggestions = allPeople.filter(function (item) { return _startsWith(item.text || '', filterText); });
            var suggestionList = suggestions.map(function (item) {
                return { item: item, isSelected: false, key: item.key };
            });
            // We want to show top 5 results
            setPeopleSuggestions(suggestionList.splice(0, 5));
        };
        var _onKeyDown = React.useCallback(function (ev) {
            var _a;
            if (ev.ctrlKey && ev.which === Utilities_1.KeyCodes.k) {
                ev.preventDefault();
                // If the input has text, resolve that
                if (inputText !== undefined && inputText !== '' && inputText !== null) {
                    // try force resolving, then if that doesn't work, add a generic item
                    if (!((_a = ref.current) === null || _a === void 0 ? void 0 : _a.forceResolve())) {
                        _addGenericItem(inputText);
                    }
                }
                else {
                    // put invalid items into edit mode
                }
            }
        }, 
        // eslint-disable-next-line react-hooks/exhaustive-deps
        [inputText, ref]);
        function _startsWith(text, filterText) {
            return text.toLowerCase().indexOf(filterText.toLowerCase()) === 0;
        }
        var _onValidateInput = React.useCallback(function (input) {
            return true;
        }, []);
        var floatingPeoplePickerProps = {
            suggestions: tslib_1.__spreadArrays(peopleSuggestions),
            isSuggestionsVisible: false,
            targetElement: null,
            onSuggestionSelected: _onSuggestionSelected,
            onRemoveSuggestion: _onSuggestionRemoved,
            suggestionsHeaderText: 'People suggestions',
            noResultsFoundText: 'No suggestions',
            onFloatingSuggestionsDismiss: undefined,
            showSuggestionRemoveButton: true,
            pickerWidth: '300px',
        };
        var selectedPeopleListProps = {
            selectedItems: tslib_1.__spreadArrays(peopleSelectedItems),
            removeButtonAriaLabel: 'Remove',
            onItemsRemoved: _onItemsRemoved,
            getItemCopyText: _getItemsCopyText,
            onRenderItem: SelectedItem,
            replaceItem: _replaceItem,
            createGenericItem: _createGenericItem,
        };
        var inputProps = {
            'aria-label': 'Add people',
        };
        return (React.createElement(React.Fragment, null,
            React.createElement(UnifiedPeoplePicker_1.UnifiedPeoplePicker, { componentRef: ref, selectedItemsListProps: selectedPeopleListProps, floatingSuggestionProps: floatingPeoplePickerProps, inputProps: inputProps, 
                // eslint-disable-next-line react/jsx-no-bind
                onInputChange: _onInputChange, 
                // eslint-disable-next-line react/jsx-no-bind
                onPaste: _onPaste, defaultDragDropEnabled: false, onKeyDown: _onKeyDown, onValidateInput: _onValidateInput })));
    };
});
//# sourceMappingURL=UnifiedPeoplePicker.WithEdit.Example.js.map