Форматирование вкладок с многозадачностью

В Microsoft Fabric можно использовать многозадачность для одновременного открытия нескольких элементов. При открытии элемента вкладка закреплена на левой панели. По умолчанию Fabric поддерживает открытие одного элемента одновременно. Набор событий жизненного цикла активируется при инициализации, деактивации и уничтожении вкладки элемента без работы, необходимой для любой рабочей нагрузки.

Изменение свойств по умолчанию для многозадачности

Определите editorTab раздел внутри манифеста элемента для редактирования свойств вкладки:

    "editorTab": {

    }

Включение одновременного открытия нескольких элементов

Определите maxInstanceCount свойство и назначьте количество элементов, которые нужно открыть одновременно (до 20 элементов):

    "editorTab": {
      "maxInstanceCount": "20"
    }

Настройка действий и обработчиков

Когда вы решаете реализовать действия и обработчики вкладок (или их часть), необходимо задать свойство во фронтенд-манифесте элемента в разделе editorTab. Это свойство прослушивает эти действия в собственном коде, обрабатывает действия соответствующим образом и возвращает результаты. Если вы не задаете какие-либо действия (или часть из них), действия по умолчанию обрабатываются автоматически.

Определите свойства для действий вкладки в editorTab разделе.

    "editorTab": {
      "onInit": "item.tab.onInit",
      "onDeactivate": "item.tab.onDeactivate",
      "canDeactivate": "item.tab.canDeactivate",
      "canDestroy": "item.tab.canDestroy",
      "onDestroy": "item.tab.onDestroy",
      "onDelete": "item.tab.onDelete"
    }

При регистрации действия нагрузки Fabric ожидает, что действие возвращает данные в определенном формате, чтобы Fabric мог прочитать или отобразить эту информацию.

   /*An OnInit event is triggered when the item is opened for the first
   time. This event contains the ID of the tab being initialized. Based on
   this tab ID, the handler needs to be able to return the display name
   or metadata.*/

   onInit: Action<never>;

   /*A CanDeactivate event is triggered when the user moves away from the tab.
   This event contains the ID of the tab being deactivated. The
   CanDeactivate handler should return a Boolean value that indicates whether
   the item tab can be deactivated. For an ideal multitasking experience,
   the handler should always return True.*/

   canDeactivate: Action<never>;

   /*An OnDeactivate event is triggered immediately after CanDeactivate
   returns True. This event contains the ID of the tab being deactivated.
   The OnDeactivate handler should cache unsaved item changes and
   the UI state.
   The next time the user goes back to the item, the item needs
   to be able to recover its data and UI state. The actual deactivation begins
   only when this handler returns.*/

   onDeactivate: Action<never>;

   /*A CanDestroy event is triggered after the close button is selected,
    before the item tab is closed. The event contains the ID of the tab
    being destroyed and also an allowInteraction parameter.
    The CanDeactivate handler should return a Boolean value that indicates
    whether the given item tab can be destroyed.
    If allowInteraction equals False, the implementation returns True
    if there are no dirty changes, and False otherwise.
    If allowInteraction equals True, a pop-up window can be used to ask
    for the user's opinion. It returns True if the user saves or discards
    dirty changes, and False if the user cancels the pop-up window.
    The OnDestroy handler gives the item the opportunity to do some
    cleanup work.*/

   canDestroy: Action<never>;

   /*An OnDestroy event is triggered when the tab is closed. The event
   contains the ID of the tab being destroyed. The OnDestroy handler gives
   the item the opportunity to do some cleanup work.*/

   onDestroy: Action<never>;

   /*An OnDelete event is triggered when the opened item is deleted.
   The event contains the ID of the item being deleted, just to tell
   the extension that the current item is deleted.*/

   onDelete: Action<never>;

Пример обработки действий вкладки

Этот пример отслеживает все действия, связанные с item.tab, и обрабатывает их соответствующим образом.

workloadClient.action.onAction(async function ({ action, data }) {
    switch (action) {
        case 'item.tab.onInit':
            const { id } = data as ItemTabActionContext;
            try{
                const getItemResult = await callItemGet(
                    id,
                    workloadClient
                );
                const item = convertGetItemResultToWorkloadItem<ItemPayload(getItemResult);
                return {title: item.displayName};
            } catch (error) {
                console.error(
                    `Error loading the Item (object ID:${id})`,
                    error
                );
                return {};
            }
        case 'item.tab.canDeactivate':
            return { canDeactivate: true };
        case 'item.tab.onDeactivate':
            return {};
        case 'item.tab.canDestroy':
            return { canDestroy: true };
        case 'item.tab.onDestroy':
            return {};
        case 'item.tab.onDelete':
            return {};
        default:
            throw new Error('Unknown action received');
    }
});
  • item.tab.onInit: извлекает данные элемента с помощью идентификатора и возвращает заголовок элемента.
  • item.tab.canDeactivate: возвращает { canDeactivate: true }, позволяющее легко переключаться между вкладками.
  • item.tab.onDeactivate, , item.tab.onDestroyitem.tab.onDelete: возвращает пустой объект для этих действий.
  • item.tab.canDestroy: возвращает { canDestroy: true }.

Для полного примера обработки действий с вкладками см. index.ui.ts в репозитории примеров. Выполните поиск действий, начинающихся с item.tab.