UI 拡張機能から SharePoint Framework ListView コマンド セットへ

この記事の SharePoint アドインの部分は、 従来のガイダンスです。 以下の廃止によって、ここで説明する他の API やプラットフォームが廃止されるわけではありません。

重要

SharePoint アドインは、2026 年 4 月 2 日に SharePoint Online のサポートが終了しました。 SharePoint でホストされているアドインとプロバイダーでホストされているアドインはどちらも廃止され、政府機関向けクラウドを含む SharePoint Online では機能しなくなります。 アドインの開発、展開、使用に関するガイダンスは、新しい SharePoint Online ソリューション用ではなく、履歴参照と該当する SharePoint Server シナリオ用に保持されます。

オンプレミスのアプリ カタログを通じて展開された SharePoint Server アドインは、この変更によって廃止されません。 パブリック マーケットプレースからの SharePoint アドインの取得は、SharePoint Server の 2026 年 4 月 2 日に終了しました。

この廃止により、SharePoint REST API、CSOM、JSOM、または SharePoint Framework (SPFx) は廃止されません。 SharePoint Online の場合は、ユーザー インターフェイス拡張機能に SPFx を使用し、外部アプリケーションへの認証に Microsoft Entra ID を使用します。 廃止のお知らせとアドインの移行ガイダンスを参照してください。

SharePoint アドイン モデルでは、UI 拡張機能を作成して、リスト ビューとライブラリのリボン バーと ECB (コントロール ブロックの編集) メニューを拡張することに慣れています。 新しい SharePoint Framework では、いわゆる ListView コマンド セットを作成することで同じ結果を得ることができます。

この記事では、既存の UI 拡張機能を ListView コマンド セットに変換する方法に関する詳細情報を確認できます。

必要に応じて、記事全体を読む代わりに、次のビデオを視聴することもできますが、これはさらに詳細な参考資料として検討できます。

IMAGE_ALT

注:

SharePoint Framework ListView コマンドセットの作成の詳細については、ドキュメント「最初の ListView コマンドセット拡張機能を構築する」を参照してください。

UI 拡張機能の ListView コマンド セットへの変換

ドキュメント ライブラリのコマンド バーにカスタム ボタンをレンダリングしたり、同じライブラリの ECB メニューにカスタム メニュー項目を追加したりするための UI 拡張機能があるとします。 また、ドキュメント ライブラリに対してのみ、ユーザーが 1 つのドキュメントだけを選択した場合にのみ、ボタンと ECB メニュー項目を表示すると仮定します。 UI 拡張機能には、選択したファイルに関する詳細情報を含むページが表示されます。 次の画面では、SharePoint クラシック UI で現在選択されているドキュメントの ECB メニューを拡張するときに、SharePoint アドイン モデルを使用して構築された UI 拡張機能の UI を見ることができます。

ECB メニューを拡張するときの UI 拡張機能の UI。

次のスクリーンショットでは、SharePoint クラシック UI でドキュメント ライブラリのリボンを拡張するときに、SharePoint アドイン モデルで構築された UI 拡張機能の UI を見ることができます。

リボン メニューを拡張したときの UI 拡張機能の UI。

最後に、次のスクリーンショットでは、選択したドキュメントの詳細を表示しているときに、UI 拡張機能の実際の UI が動作しているのを確認できます。

ドキュメントの詳細をレンダリングするときの UI 拡張機能の UI。

次に、カスタマイズを SharePoint Framework で構築された最新の ListView コマンド セットに変換します。

移行元の SharePoint アドイン モデル ソリューション

次のコードの抜粋では、JavaScript コードを使用して構築された UI 拡張機能の実際の実装を確認できます。

var hostweburl;
var appweburl;
var clientContext;
var hostweb;
var documentsLibrary;
var libraryId;
var itemId;

// This code runs when the DOM is ready and creates a context object which is
// needed to use the SharePoint object model
$(document).ready(function () {
    hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
    libraryId = decodeURIComponent(getQueryStringParameter("SPListId"));
    itemId = decodeURIComponent(getQueryStringParameter("SPListItemId"));

    if (libraryId !== 'undefined' && itemId !== 'undefined') {
        var scriptbase = hostweburl + "/_layouts/15/";
        $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);
    }
});

// Make the actual request for the document using the cross-domain Request Executor
function execCrossDomainRequest() {

    var itemUri = appweburl +
        "/_api/SP.AppContextSite(@target)/web/lists/GetById('" + libraryId + "')/Items(" + itemId + ")?$select=ID,Title,Created,Modified,ServerRedirectedEmbedUrl&@target='" + hostweburl + "'";

    console.log(itemUri);

    var executor = new SP.RequestExecutor(appweburl);

    // First request, to retrieve the form digest
    executor.executeAsync({
        url: itemUri,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            var jsonObject = JSON.parse(data.body);
            console.log(jsonObject);
            var document = jsonObject.d;
            showDocumentDetails(document);
        },
        error: function (data, errorCode, errorMessage) {
            var errMsg = "Error retrieving the document details: " + errorMessage;
            $("#error").text(errMsg);
            $("#error").show();
        }
    });
}

// In case of successful retrieval of the document
function showDocumentDetails(document) {
    $("#document").empty();

    if (document !== undefined) {

        var docId = document.ID;
        var docTitle = document.Title;
        var docCreated = document.Created;
        var docModified = document.Modified;
        var docUrl = document.ServerRedirectedEmbedUrl;

        $("#document").append('<ul>');
        $("#document").append('<li><a href="' + docUrl + '">[' + docId + '] ' + docTitle + '</a></li>');
        $("#document").append('<li>Created on: ' + docCreated + '</li>');
        $("#document").append('<li>Modified on: ' + docModified + '</li>');
        $("#document").append('</ul>');
    }
}

function getQueryStringParameter(paramToRetrieve) {
    var params =
        document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}

ご覧のとおり、このコードは完全にクライアント側コード (JavaScript) に基づいており、SharePoint JavaScript オブジェクト モデルに依存して、現在のアプリ サイトへの参照を取得します。RemoteExecutor は、ホスト サイトからターゲット ドキュメントのプロパティを読み取るための REST API 呼び出しをモデル化します。 ファイル プロパティが取得されると、サンプルは動的に生成される一連の HTML 要素を通じて基本的なドキュメントの詳細を表示します。

次に、ECB メニュー項目をレンダリングする UI 拡張機能は、SharePoint 機能フレームワークの CustomAction 要素に依存し、次の構文で XML 要素ファイルで定義されます。

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction Id="8d267eab-0cc9-4abf-88fd-25e320f1202f.ShowDocumentDetailsMenuItem"
                RegistrationType="List"
                RegistrationId="101"
                Location="EditControlBlock"
                Sequence="10001"
                Title="Document Details">
    <!--
    Update the Url below to the page you want the custom action to use.
    Start the URL with the token ~remoteAppUrl if the page is in the
    associated web project, use ~appWebUrl if page is in the app project.
    -->
    <UrlAction Url="~appWebUrl/Pages/Default.aspx?{StandardTokens}&amp;SPListItemId={ItemId}&amp;SPListId={ListId}" />
  </CustomAction>
</Elements>

カスタム要素では、拡張機能が RegistrationType 属性と RegistrationId 属性を介してタイプ 101 のリスト (つまり、ドキュメント ライブラリ) を対象とすることを宣言していることに注意してください。 また、カスタム アクションの 場所 がターゲット リストまたはライブラリの EditControlBlock であることを宣言します。

同様に、カスタム リボン コマンドは、SharePoint 機能フレームワークの CustomAction 要素に依存している別の XML 要素ファイルで定義され、構文は次のようになります。

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction Id="f453c11a-3ee4-4247-b520-107b80c79892.ShowDocumentDetailsCommand"
                RegistrationType="List"
                RegistrationId="101"
                Location="CommandUI.Ribbon"
                Sequence="10001"
                Title="Invoke &apos;ShowDocumentDetailsCommand&apos; action">
    <CommandUIExtension>
      <!--
      Update the UI definitions below with the controls and the command actions
      that you want to enable for the custom action.
      -->
      <CommandUIDefinitions>
        <CommandUIDefinition Location="Ribbon.Documents.Manage.Controls._children">
          <Button Id="Ribbon.Documents.Manage.ShowDocumentDetailsCommandButton"
                  Alt="Document Details"
                  Sequence="100"
                  Command="Invoke_ShowDocumentDetailsCommandButtonRequest"
                  LabelText="Document Details"
                  TemplateAlias="o1"
                  Image32by32="_layouts/15/images/placeholder32x32.png"
                  Image16by16="_layouts/15/images/placeholder16x16.png" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler Command="Invoke_ShowDocumentDetailsCommandButtonRequest"
                          CommandAction="~appWebUrl/Pages/Default.aspx?{StandardTokens}&amp;SPListItemId={SelectedItemId}&amp;SPListId={SelectedListId}"/>
      </CommandUIHandlers>
    </CommandUIExtension >
  </CustomAction>
</Elements>

この最後の要素ファイルでは、ドキュメント ライブラリ (RegistrationType = 'List' および RegistrationId = 101) を対象とする別のカスタム アクションが宣言されていますが、Location の値はCommandUI.Ribbon で、 CommandUIExtension 要素を介したリボン コマンドの定義を使用します。

SharePoint アドイン モデル ソリューションが機能するためには、 AppManifest.xml ファイルで定義されているライブラリの読み取りアクセス許可 (BaseTemplate=101) が必要です。 次の画面では、AppManifest.xml ファイルの構成を確認できます。

SharePoint アドイン モデル ソリューション用に構成されたアクセス許可要求。スコープ

SharePoint Framework ソリューションの作成

次に、以前の SharePoint Framework モデル ソリューションを変換するために使用する新しい SharePoint Framework ソリューションを作成しましょう。

まず、SharePoint Frameworkソリューションを足場に配置する必要があるため、コマンドプロンプトまたはターミナルウィンドウを起動し、フォルダを作成し、新しく作成したフォルダ内から次のコマンドを実行します。

重要

図示の手順を実行するには、開発環境に SharePoint Framework がインストールされている必要があります。 環境を設定する方法の詳細については、ドキュメント「SharePoint Framework 開発環境のセットアップ」を参照してください。

yo @microsoft/sharepoint

SharePoint Framework ListView コマンドセットの新しいプロジェクトを作成しているときの、PowerShell ウィンドウのスキャフォールディング ツールの UI。

プロンプトに従って、最新の ListView コマンド セットのソリューションを作成します。 具体的には、ツールからの指示に応じて、次の選択を行います。

  • ソリューション名を教えてください。 spo-sp-fx-list-view-command-set
  • どの種類のクライアント側コンポーネントを作成しますか? Extension
  • どの種類のクライアント側拡張機能を作成しますか? リスト ビュー コマンド セット
  • コマンド セット名は何ですか? DocumentDetails

上記の回答を使用して、 spo-sp-fx-list-view-command-set という名前のソリューションを作成することにしました。このソリューションには、 DocumentDetails という名前の ListView Command Set 型のカスタム拡張機能があります。

スキャフォールディング ツールによって、新しい SharePoint Framework ソリューションが生成されます。 完了したら、お気に入りのコード エディターを使用して現在のフォルダーを開くだけです。 ただし、ソリューションを開く前に、拡張機能の UI をわかりやすく見栄えよくレンダリングするためのパッケージを追加する必要があります。 実際、次のコマンドを実行して、コンポーネントの MGT (Microsoft Graph ツールキット) ライブラリと React フレームワークを参照します。

npm install @microsoft/mgt-spfx @microsoft/mgt-react react@17.0.1 react-dom@17.0.1 --save
npm install @types/react@17.0.45 @types/react-dom@17.0.17 --save-dev

実際、既定では、SharePoint Framework ListView コマンド セットのスキャフォールディング ソリューションには React パッケージが含まれていないため、ソリューションに追加するかどうかはユーザー次第です。

注:

Microsoft Graph ツールキット は、SharePoint Framework ソリューションを含むクライアント側ソリューションの UI のレンダリングを高速化するためのコンポーネント セットです。 このサンプル ソリューションでこれを使用することは必須ではありませんが、学習と開発のプロセスをスピードアップする簡単な方法です。 MGT に関する詳細情報は、ドキュメント「Microsoft Graph ツールキット の概要」を参照してください。また、ドキュメント「SharePoint Framework for Microsoft Graph ツールキット」を読んで、SharePoint Framework と統合する方法を学習できます。

これで、お気に入りのコード エディターでソリューションを開くことができます。 お気に入りのコード エディターが Microsoft Visual Studio Code の場合は、次のコマンドを実行するだけです。

code .

次の図では、生成された SharePoint Framework ソリューションの概要を確認できます。

SharePoint Framework によって生成されたソリューションの概要。

開始するメイン ファイルは、src\extensions\documentDetails フォルダーの下にあるDocumentDetailsCommandSet.tsです。 このファイルは、SharePoint Framework で使用される TypeScript 構文に基づいています。

import { Log } from '@microsoft/sp-core-library';
import {
  BaseListViewCommandSet,
  Command,
  IListViewCommandSetExecuteEventParameters,
  ListViewStateChangedEventArgs
} from '@microsoft/sp-listview-extensibility';
import { Dialog } from '@microsoft/sp-dialog';

/**
 * If your command set uses the ClientSideComponentProperties JSON input,
 * it will be deserialized into the BaseExtension.properties object.
 * You can define an interface to describe it.
 */
export interface IDocumentDetailsCommandSetProperties {
  // This is an example; replace with your own properties
  sampleTextOne: string;
  sampleTextTwo: string;
}

const LOG_SOURCE: string = 'DocumentDetailsCommandSet';

export default class DocumentDetailsCommandSet extends BaseListViewCommandSet<IDocumentDetailsCommandSetProperties> {

  public onInit(): Promise<void> {
    Log.info(LOG_SOURCE, 'Initialized DocumentDetailsCommandSet');

    // initial state of the command's visibility
    const compareOneCommand: Command = this.tryGetCommand('COMMAND_1');
    compareOneCommand.visible = false;

    this.context.listView.listViewStateChangedEvent.add(this, this._onListViewStateChanged);

    return Promise.resolve();
  }

  public onExecute(event: IListViewCommandSetExecuteEventParameters): void {
    switch (event.itemId) {
      case 'COMMAND_1':
        Dialog.alert(`${this.properties.sampleTextOne}`).catch(() => {
          /* handle error */
        });
        break;
      case 'COMMAND_2':
        Dialog.alert(`${this.properties.sampleTextTwo}`).catch(() => {
          /* handle error */
        });
        break;
      default:
        throw new Error('Unknown command');
    }
  }

  private _onListViewStateChanged = (args: ListViewStateChangedEventArgs): void => {
    Log.info(LOG_SOURCE, 'List view state changed');

    const compareOneCommand: Command = this.tryGetCommand('COMMAND_1');
    if (compareOneCommand) {
      // This command should be hidden unless exactly one row is selected.
      compareOneCommand.visible = this.context.listView.selectedRows?.length === 1;
    }

    // TODO: Add your logic here

    // You should call this.raiseOnChage() to update the command bar
    this.raiseOnChange();
  }
}

上記のコードの抜粋は、 DocumentDetailsCommandSet.ts ファイルの主要なコードの抜粋を示しています。 まず、拡張機能が DocumentDetailsCommandSet という名前の TypeScript クラスとして宣言されており、基本型 BaseListViewCommandSet<IDocumentDetailsCommandSetProperties> から継承されていることがわかります。

BaseListViewCommandSet 型は SharePoint Framework の基本ライブラリによって提供されますが、インターフェイス IDocumentDetailsCommandSetProperties は Web パーツ クラス宣言の直前に定義され、カスタム拡張機能 (存在する場合) の構成プロパティを定義します。

拡張機能の OnInit メソッドでは、コードは COMMAND_1 という一意の名前を持つカスタム コマンド拡張機能への参照を取得しようとします。 コマンドが存在する場合、コードはそのコマンドを初期状態として非表示にします。

// initial state of the command's visibility
const compareOneCommand: Command = this.tryGetCommand('COMMAND_1');
compareOneCommand.visible = false;

その直後に、ターゲット リストまたはライブラリ ビューのビュー ステートの変更を処理するイベント ハンドラーが登録されます。

this.context.listView.listViewStateChangedEvent.add(this, this._onListViewStateChanged);

現在のビューに変更がある場合、イベント ハンドラーは、選択されているアイテムまたはドキュメントが 1 つだけあるかどうかを確認します。 その場合、コードは UI にコマンドを表示します。

private _onListViewStateChanged = (args: ListViewStateChangedEventArgs): void => {
  Log.info(LOG_SOURCE, 'List view state changed');

  const compareOneCommand: Command = this.tryGetCommand('COMMAND_1');
  if (compareOneCommand) {
    // This command should be hidden unless exactly one row is selected.
    compareOneCommand.visible = this.context.listView.selectedRows?.length === 1;
  }

  // TODO: Add your logic here

  // You should call this.raiseOnChage() to update the command bar
  this.raiseOnChange();
}

最後に、ソース コードでは、拡張機能の実際の実装を提供する onExecute メソッドを定義します。

  public onExecute(event: IListViewCommandSetExecuteEventParameters): void {
    switch (event.itemId) {
      case 'COMMAND_1':
        Dialog.alert(`${this.properties.sampleTextOne}`).catch(() => {
          /* handle error */
        });
        break;
      case 'COMMAND_2':
        Dialog.alert(`${this.properties.sampleTextTwo}`).catch(() => {
          /* handle error */
        });
        break;
      default:
        throw new Error('Unknown command');
    }
  }

onExecuteメソッドが呼び出されると、event.itemIdプロパティは、ユーザーによって呼び出されたコマンドの一意の名前を定義し、それに応じて拡張ビジネスロジックを実装できます。 自動生成されたコードは、ブラウザーにダイアログ警告を表示するだけです。

拡張機能コードのどこで COMMAND_1 が宣言されているのか疑問に思うかもしれません。 これは実際には、拡張機能と同じフォルダーにある DocumentDetailsCommandSet.manifest.json というマニフェスト ファイルで定義されています。 次のコードの抜粋では、スキャフォールドされたマニフェストを確認できます。

{
  "$schema": "https://developer.microsoft.com/json-schemas/spfx/command-set-extension-manifest.schema.json",

  "id": "1602bb8e-cc1d-4417-ba7a-cc1b1d7d7022",
  "alias": "DocumentDetailsCommandSet",
  "componentType": "Extension",
  "extensionType": "ListViewCommandSet",

  // The "*" signifies that the version should be taken from the package.json
  "version": "*",
  "manifestVersion": 2,

  // If true, the component can only be installed on sites where Custom Script is allowed.
  // Components that allow authors to embed arbitrary script code should set this to true.
  // https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
  "requiresCustomScript": false,

  "items": {
    "COMMAND_1": {
      "title": { "default": "Command One" },
      "iconImageUrl": "icons/request.png",
      "type": "command"
    },
    "COMMAND_2": {
      "title": { "default": "Command Two" },
      "iconImageUrl": "icons/cancel.png",
      "type": "command"
    }
  }
}

ご覧のように、マニフェストの最初の部分では、ListViewCommandSet の拡張型を持つ、Extension 型のコンポーネントを定義することを宣言しています。 さらに、マニフェストは GUID を使用してコンポーネントの一意の ID も宣言します。 最も重要なのは、実際のコマンドが定義されている 項目 と呼ばれるセクションがあることです。 スキャフォールドされたマニフェストには、タイトルの定義、アイコン、画像の URL、および常にコマンドである型を持つ 2 つのコマンド (COMMAND_1 と COMMAND_2) があることがわかります。

ソリューションの最後の重要なファイルは、ソリューションの sharepoint\assets フォルダーで定義されている elements.xml ファイルです。 自動生成ファイルの内容を次に示します。

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <CustomAction
        Title="DocumentDetails"
        RegistrationId="100"
        RegistrationType="List"
        Location="ClientSideExtension.ListViewCommandSet.CommandBar"
        ClientSideComponentId="1602bb8e-cc1d-4417-ba7a-cc1b1d7d7022"
        ClientSideComponentProperties="{&quot;sampleTextOne&quot;:&quot;One item is selected in the list.&quot;, &quot;sampleTextTwo&quot;:&quot;This command is always visible.&quot;}">
    </CustomAction>
</Elements>

興味深いことに、SharePoint アドイン モデルで構築された UI 拡張機能を使用する場合と同様に、これは依然として SharePoint 機能フレームワークに基づくファイルです。 ただし、カスタム アクションの設定は若干異なります。 拡張機能のターゲットを定義する RegistrationId や RegistrationType などの属性はまだあります。 また、ClientSideExtension.ListViewCommandSet.CommandBar をターゲットとする新しい値を持つ Location 属性もあります。つまり、拡張機能がターゲット ビューのコマンド バーにレンダリングされます。

SharePoint Framework ListView コマンド セットでこの属性に使用できるオプションは次のとおりです。

  • ClientSideExtension.ListViewCommandSet.CommandBar: コマンド バーに拡張機能を表示します。
  • ClientSideExtension.ListViewCommandSet.ContextMenu: ECB メニューに拡張機能を表示します。
  • ClientSideExtension.ListViewCommandSet: コマンド バーと ECB メニューの両方に拡張機能を表示します。

ただし、次の 2 つの新しい属性もあります。

  • ClientSideComponentId: レンダリングする拡張機能の一意の ID を定義し、前に説明したマニフェスト ファイルで定義された id 属性にマップします。
  • ClientSideComponentProperties: 拡張機能のカスタム構成プロパティを定義します (存在する場合)。 これは、拡張機能のカスタム プロパティを宣言するインターフェイスのインスタンスを表す JSON シリアル化されたオブジェクトを含む文字列です (この例では、インターフェイスは IDocumentDetailsCommandSetProperties です)。

実際の SharePoint Framework ListView コマンド セットの構築

ソリューションの概要を把握したところで、実際の ListView コマンド セットを構築して、ドキュメントの詳細機能を提供し、古い SharePoint アドイン モデルの UI 拡張機能を変換しましょう。

まず、マニフェスト ファイルを編集し、その内容を次のファイルに置き換えます。

{
  "$schema": "https://developer.microsoft.com/json-schemas/spfx/command-set-extension-manifest.schema.json",

  "id": "1602bb8e-cc1d-4417-ba7a-cc1b1d7d7022",
  "alias": "DocumentDetailsCommandSet",
  "componentType": "Extension",
  "extensionType": "ListViewCommandSet",

  // The "*" signifies that the version should be taken from the package.json
  "version": "*",
  "manifestVersion": 2,

  // If true, the component can only be installed on sites where Custom Script is allowed.
  // Components that allow authors to embed arbitrary script code should set this to true.
  // https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
  "requiresCustomScript": false,

  "items": {
    "DOC_DETAILS": {
      "title": { "default": "Document Details" },
      "iconImageUrl": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFwAAABcCAYAAADj79JYAAAAA...AASUVORK5CYII=",
      "type": "command"
    }
  }
}

更新されたマニフェストでは、一意の名前が DOC_DETAILS、タイトルが 'Document Details'、カスタム アイコン画像 URL を持つコマンドが 1 つだけ宣言されています。 実際には、画像はURLではなく、外部ファイルに依存しないようにBase64でエンコードされた画像です。 わかりやすくするために、コードの抜粋では Base64 イメージが短縮されています。

ここで、Location 属性に ClientSideExtension.ListViewCommandSet の値を指定して、コマンド バーと ECB メニューの両方に ListView コマンド セットを表示するように要素ファイルを更新します。 さらに、サンプル拡張機能にカスタム プロパティは必要ないため、 ClientSideComponentProperties 属性の内容を削除します。 ここでは、新しい要素ファイルを表示できます。

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <CustomAction
        Title="DocumentDetails"
        RegistrationId="100"
        RegistrationType="List"
        Location="ClientSideExtension.ListViewCommandSet"
        ClientSideComponentId="1602bb8e-cc1d-4417-ba7a-cc1b1d7d7022"
        ClientSideComponentProperties="">
    </CustomAction>
</Elements>

次に、 DocumentDetailsCommandSet.ts ファイルを更新して、ListView コマンド セットの実際の実装を更新します。 まず、コマンドの一意の名前をマニフェストで定義されている新しい名前に置き換えます。 そのため、onInit、onExecute、および _onListViewStateChanged メソッドで COMMAND_1 を DOC_DETAILS に置き換え、もう存在しない COMMAND_2 拡張機能に関連するロジックを削除します。

拡張機能の新しい SharePoint Framework 実装では、SharePoint Framework Dialog Framework を使用して、選択したファイルに関する詳細情報を表示する MGT コンポーネントを埋め込む見栄えの良いダイアログ ウィンドウをレンダリングします。

注:

SharePoint Framework ダイアログ フレームワークの活用の詳細については、「SharePoint Framework 拡張機能でカスタム ダイアログ ボックスを使用する」ドキュメントを参照してください。

注:

MGT の ファイル コンポーネントの詳細については、 Microsoft Graph ツールキット のドキュメント「ファイル コンポーネント」を参照してください。

次に、DocumentDetailsDialog.tsx という新しい React コンポーネント ファイルを格納するために使用する新しいフォルダー構造 src\documentDetails\components\documentDetailsDialog を作成します。 同じ新しいフォルダー内に、ダイアログ ウィンドウの構成プロパティを定義するために使用する IDocumentDetailsDialogProps.ts という名前の別のファイルも作成します。 次のコードの抜粋では、ダイアログのプロパティを定義するインターフェイスの定義を確認できます。

export interface IDocumentDetailsDialogProps {
    tenantName: string;
    siteId: string;
    webId: string;
    driveId: string;
    itemId: string;
    onClose: () => Promise<void>;
}

string 型のプロパティ セットは、tenantName、siteId、webId、driveId、itemId を使用して、Microsoft Graph 内のドキュメントへのポインターを定義します。 last プロパティは、ダイアログ ウィンドウの終了を処理するために使用されるメソッドを定義します。 これは、戻り値 (Promise<void>) のない非同期メソッドです。

次のコードの抜粋では、ダイアログ コンポーネントの実装を確認できます。

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { IDocumentDetailsDialogProps } from './IDocumentDetailsDialogProps';

import { BaseDialog, IDialogConfiguration } from '@microsoft/sp-dialog';
import {
    DefaultButton,
    DialogFooter,
    DialogContent
} from 'office-ui-fabric-react';

import { File } from '@microsoft/mgt-react/dist/es6/spfx';

class DocumentDetailsDialogContent extends
    React.Component<IDocumentDetailsDialogProps, {}> {

    public render(): JSX.Element {
        return (<div>
            <DialogContent
                title="Document Details"
                onDismiss={this.props.onClose}>

            <div>
                    <File siteId={`${this.props.tenantName},${this.props.siteId},${this.props.webId}`}
                        driveId={this.props.driveId} itemId={this.props.itemId} />
            </div>
            <DialogFooter>
                <DefaultButton text="Close"
                    title="Close" onClick={this.props.onClose} />
            </DialogFooter>
        </DialogContent>
    </div>);
    }
}

export default class DocumentDetailsDialog extends BaseDialog {

    /**
     * Constructor for the dialog window
     */
    constructor(public tenantName: string,
        public siteId: string, public webId: string,
        public driveId: string, public itemId: string) {
        super({isBlocking: true});
    }

    public render(): void {
        ReactDOM.render(<DocumentDetailsDialogContent
                tenantName={this.tenantName}
                siteId={this.siteId}
                webId={this.webId}
                driveId={this.driveId}
                itemId={this.itemId}
                onClose={this._close}
            />,
            this.domElement);
    }

    public getConfig(): IDialogConfiguration {
      return {
        isBlocking: true
      };
    }

    private _close = async (): Promise<void> => {
        ReactDOM.unmountComponentAtNode(this.domElement);
        await this.close();
    }
}

メインの種類は DocumentDetailsDialog クラスで、これはファイルの既定のエクスポートでもあります。 これは、SharePoint Framework Dialog Framework (@microsoft/sp-dialog) で定義された型である BaseDialog から継承されます。

ダイアログ クラスのパブリック コンストラクターは、Microsoft Graph を介して選択したファイルのターゲットに必要なすべてのプロパティを受け入れます。 renderメソッドは、ダイアログクラスの直前に定義されたDocumentDetailsDialogContentというReactコンポーネントのインスタンスを作成するだけです。 ダイアログ クラス内には、ダイアログを閉じ、Reactによって割り当てられたリソースのマウントを解除するために使用される _close メソッドの定義もあります。

DocumentDetailsDialogContent コンポーネントは、MGT の File コンポーネントをレンダリングし、ダイアログを閉じるための [閉じる] ボタンを提供する非常に簡単な React コンポーネントです。

DocumentDetailsDialog コンポーネントは、ListView コマンド セットの onExecute メソッドでインスタンス化されます。 さらに、MGT ライブラリは、@microsoft/mgt-spfx からインポートされた型に依存して、グローバル プロバイダーを登録することにより、クラスの onInit メソッドで初期化されます。 次のコードの抜粋では、更新された DocumentDetailsCommandSet.ts ファイルを確認できます。

import { Providers, SharePointProvider } from '@microsoft/mgt-spfx';
import { Log } from '@microsoft/sp-core-library';
import {
  BaseListViewCommandSet,
  Command,
  IListViewCommandSetExecuteEventParameters,
  ListViewStateChangedEventArgs
} from '@microsoft/sp-listview-extensibility';
import DocumentDetailsDialog from './components/documentDetailsDialog/DocumentDetailsDialog';

const LOG_SOURCE: string = 'DocumentDetailsCommandSet';

export default class DocumentDetailsCommandSet extends BaseListViewCommandSet<{}> {

  public onInit(): Promise<void> {
    Log.info(LOG_SOURCE, 'Initialized DocumentDetailsCommandSet');

    // Initialize MGT
    if (!Providers.globalProvider) {
      Providers.globalProvider = new SharePointProvider(this.context);
    }

    // initial state of the command's visibility
    const compareOneCommand: Command = this.tryGetCommand('DOC_DETAILS');
    compareOneCommand.visible = false;

    this.context.listView.listViewStateChangedEvent.add(this, this._onListViewStateChanged);

    return Promise.resolve();
  }

  public async onExecute(event: IListViewCommandSetExecuteEventParameters): Promise<void> {
    switch (event.itemId) {
      case 'DOC_DETAILS': {
        const tenantName: string = this.context.pageContext.site.absoluteUrl.substring(8,
          this.context.pageContext.site.absoluteUrl.indexOf('/', 8));
        const siteId: string = this.context.pageContext.site.id.toString();
        const webId: string = this.context.pageContext.web.id.toString();

        const spItemUrl: string = event.selectedRows[0].getValueByName(".spItemUrl");
        const driveId: string = spItemUrl.substring(spItemUrl.indexOf('drives/') + 7, spItemUrl.indexOf('items'));
        const itemId: string = spItemUrl.substring(spItemUrl.indexOf('items/') + 6, spItemUrl.indexOf('?'));

        await this._showDocumentDetailsDialog(
          tenantName, siteId, webId,
          driveId, itemId);
        break;
      }
      default:
        throw new Error('Unknown command');
    }
  }

  private _onListViewStateChanged = (args: ListViewStateChangedEventArgs): void => {
    Log.info(LOG_SOURCE, 'List view state changed');

    const compareOneCommand: Command = this.tryGetCommand('DOC_DETAILS');
    if (compareOneCommand) {
      // This command should be hidden unless exactly one row is selected.
      compareOneCommand.visible = this.context.listView.selectedRows?.length === 1;
    }

    // You should call this.raiseOnChage() to update the command bar
    this.raiseOnChange();
  }

  private _showDocumentDetailsDialog = async (tenantName: string,
      siteId: string, webId: string,
      driveId: string, itemId: string): Promise<void> => {
    const documentsDetailsDialog = new DocumentDetailsDialog(tenantName, siteId, webId, driveId, itemId);
    await documentsDetailsDialog.show();
  }
}

また、この改訂された実装では、 onExecuteメソッド が非同期メソッドとして定義されていることにも注意してください。 次のスクリーンショットでは、サンプルの SharePoint ドキュメント ライブラリに ListView コマンド セットの出力が表示されます。

SharePoint Framework ListView コマンドセットの出力。

このトピックの詳細については、次のドキュメントを参照してください。