К основному содержанию
правило официальный · GitHub

pcf-api-reference: правило PCF API для GitHub Copilot

Правило подкладывает в контекст Copilot справочник по интерфейсам Power Apps component framework и таблицу их доступности в model-driven и canvas-приложениях.

Установить в GitHub Copilot · Вручную: положить файлы Все способы и платформы ↓
.github/instructions/pcf-api-reference.instructions.md
Открыть на GitHub

Что делает pcf-api-reference

## Что внутри

Справочник перечисляет интерфейсы PCF и отмечает, где каждый из них работает. Почти все доступны в обоих типах приложений: Client, Column, ConditionExpression, Context, DataSet, Device, Entity, Events, Factory, Filtering, Formatting, ImageObject, Linking, Mode, Navigation, NumberFormattingInfo, Paging, Popup, PopupService, PropertyHelper, Resources, SortStatus, StandardControl, UserSettings, Utility, WebApi.

Исключение одно — AttributeMetadata есть только в model-driven приложениях. Если компонент должен собираться и там, и там, метаданные колонок через этот интерфейс не достать.

## Как разложены API

Интерфейсы сгруппированы по назначению. Context — точка входа: через него приходят клиент, устройство, ресурсы, настройки пользователя, навигация и WebApi. Данные живут в DataSet, Column, Entity, Filtering, Linking, Paging, SortStatus. Диалоги — Popup и PopupService. Базовый интерфейс компонента StandardControl задаёт жизненный цикл: init(), updateView(), destroy(), getOutputs().

## Правила работы

Правило советует проверять доступность API под целевую платформу до того, как писать код. Поведение части интерфейсов различается между model-driven и canvas, поэтому компонент стоит прогнать в том окружении, где он будет жить.

Какие задачи решает

  • Проверить, доступен ли интерфейс PCF в canvas-приложении, а не только в model-driven
  • Вспомнить точный состав Context и его вложенных объектов
  • Разложить жизненный цикл компонента по методам StandardControl
  • Найти примеры вызовов WebApi, Device и Formatting

Примеры запросов агенту

  • Проверь по справочнику, сработает ли AttributeMetadata в canvas-приложении
  • Покажи, какие методы жизненного цикла есть у StandardControl
  • Напиши вызов context.webAPI.retrieveMultipleRecords для таблицы account

Как установить pcf-api-reference

Вручную: положить файлы

.github/instructions/pcf-api-reference.instructions.md

Поле applyTo задаёт, к каким файлам применять

По шагам, с командами для каждой платформы: AGENTS.md и CLAUDE.md: что это, кто читает и какой выбрать

Вопросы о pcf-api-reference

Как установить pcf-api-reference в GitHub Copilot?

Положите файл .github/instructions/pcf-api-reference.instructions.md в репозиторий. Правило подхватится для файлов по маске **/*.{ts,tsx,js}.

Что делает pcf-api-reference?

Даёт Copilot справочник по интерфейсам Power Apps component framework и таблицу их доступности в model-driven и canvas-приложениях. Агент опирается на него, когда пишет код компонента.

Какие API PCF работают только в model-driven приложениях?

AttributeMetadata — единственный интерфейс из списка, которого нет в canvas-приложениях. Остальные доступны в обоих типах.

Исходный текст

pcf-api-reference.instructions.md · MIT
---
description: 'Complete PCF API reference with all interfaces and their availability in model-driven and canvas apps'
applyTo: '**/*.{ts,tsx,js}'
---

# Power Apps Component Framework API Reference

The Power Apps component framework provides a rich set of APIs that enable you to create powerful code components. This reference lists all available interfaces and their availability across different app types.

## API Availability

The following table shows all API interfaces available in the Power Apps component framework, along with their availability in model-driven apps and canvas apps.

| API | Model-driven apps | Canvas apps |
|-----|------------------|-------------|
| AttributeMetadata | Yes | No |
| Client | Yes | Yes |
| Column | Yes | Yes |
| ConditionExpression | Yes | Yes |
| Context | Yes | Yes |
| DataSet | Yes | Yes |
| Device | Yes | Yes |
| Entity | Yes | Yes |
| Events | Yes | Yes |
| Factory | Yes | Yes |
| Filtering | Yes | Yes |
| Formatting | Yes | Yes |
| ImageObject | Yes | Yes |
| Linking | Yes | Yes |
| Mode | Yes | Yes |
| Navigation | Yes | Yes |
| NumberFormattingInfo | Yes | Yes |
| Paging | Yes | Yes |
| Popup | Yes | Yes |
| PopupService | Yes | Yes |
| PropertyHelper | Yes | Yes |
| Resources | Yes | Yes |
| SortStatus | Yes | Yes |
| StandardControl | Yes | Yes |
| UserSettings | Yes | Yes |
| Utility | Yes | Yes |
| WebApi | Yes | Yes |

## Key API Namespaces

### Context APIs

The `Context` object provides access to all framework capabilities and is passed to your component's lifecycle methods. It contains:

- **Client**: Information about the client (form factor, network status)
- **Device**: Device capabilities (camera, location, microphone)
- **Factory**: Factory methods for creating framework objects
- **Formatting**: Number and date formatting
- **Mode**: Component mode and tracking
- **Navigation**: Navigation methods
- **Resources**: Access to resources (images, strings)
- **UserSettings**: User settings (locale, number format, security roles)
- **Utils**: Utility methods (getEntityMetadata, hasEntityPrivilege, lookupObjects)
- **WebApi**: Dataverse Web API methods

### Data APIs

- **DataSet**: Work with tabular data
- **Column**: Access column metadata and data
- **Entity**: Access record data
- **Filtering**: Define data filtering
- **Linking**: Define relationships
- **Paging**: Handle data pagination
- **SortStatus**: Manage sorting

### UI APIs

- **Popup**: Create popup dialogs
- **PopupService**: Manage popup lifecycle
- **Mode**: Get component rendering mode

### Metadata APIs

- **AttributeMetadata**: Column metadata (model-driven only)
- **PropertyHelper**: Property metadata helpers

### Standard Control

- **StandardControl**: Base interface for all code components with lifecycle methods:
  - `init()`: Initialize component
  - `updateView()`: Update component UI
  - `destroy()`: Cleanup resources
  - `getOutputs()`: Return output values

## Usage Guidelines

### Model-Driven vs Canvas Apps

Some APIs are only available in model-driven apps due to platform differences:

- **AttributeMetadata**: Model-driven only - provides detailed column metadata
- Most other APIs are available in both platforms

### API Version Compatibility

- Always check the API availability for your target platform (model-driven or canvas)
- Some APIs may have different behaviors across platforms
- Test components in the target environment to ensure compatibility

### Common Patterns

1. **Accessing Context APIs**
   ```typescript
   // In init or updateView
   const userLocale = context.userSettings.locale;
   const isOffline = context.client.isOffline();
   ```

2. **Working with DataSet**
   ```typescript
   // Access dataset records
   const records = context.parameters.dataset.records;
   
   // Get sorted columns
   const sortedColumns = context.parameters.dataset.sorting;
   ```

3. **Using WebApi**
   ```typescript
   // Retrieve records
   context.webAPI.retrieveMultipleRecords("account", "?$select=name");
   
   // Create record
   context.webAPI.createRecord("contact", data);
   ```

4. **Device Capabilities**
   ```typescript
   // Capture image
   context.device.captureImage();
   
   // Get current position
   context.device.getCurrentPosition();
   ```

5. **Formatting**
   ```typescript
   // Format date
   context.formatting.formatDateLong(date);
   
   // Format number
   context.formatting.formatDecimal(value);
   ```

## Best Practices

1. **Type Safety**: Use TypeScript for type checking and IntelliSense
2. **Null Checks**: Always check for null/undefined before accessing API objects
3. **Error Handling**: Wrap API calls in try-catch blocks
4. **Platform Detection**: Check `context.client.getFormFactor()` to adapt behavior
5. **API Availability**: Verify API availability for your target platform before use
6. **Performance**: Cache API results when appropriate to avoid repeated calls

## Additional Resources

- For detailed documentation on each API, refer to the [Power Apps component framework API reference](https://learn.microsoft.com/power-apps/developer/component-framework/reference/)
- Sample code for each API is available in the [PowerApps-Samples repository](https://github.com/microsoft/PowerApps-Samples/tree/master/component-framework)

© github · MIT · github/awesome-copilot

Похожие правила IDE

Все правила IDE по теме «Фронтенд и UI» →

Из того же набора928

Весь набор →
pcf-community-resources Правило собирает ориентиры по PCF: галерею компонентов, обучающие видео, блоги и инструменты. Пригодится, когда вы ищете пример, способ отладки или быстрый старт. ★ 40 418звёзд репо pcf-code-components Правило объясняет Copilot, как устроены code components в Power Apps component framework: манифест, реализация, ресурсы. Пригодится, когда правите ControlManifest.Input.xml или index.ts. ★ 40 418звёзд репо pcf-canvas-apps Задаёт контекст GitHub Copilot при создании PCF-компонентов для canvas apps. Помогает учесть безопасность токенов, версионирование манифестов и требования к среде. ★ 40 418звёзд репо pcf-best-practices Правило подсказывает, как разрабатывать PCF-компоненты с учётом загрузки данных, очистки ресурсов и ограничений разных типов приложений. Пригодится, когда Copilot помогает писать или менять такой код. ★ 40 418звёзд репо pcf-alm Инструкция по управлению жизненным циклом кодовых компонентов PCF в Microsoft Dataverse. Помогает настроить сборку, версионирование и поставку решений. ★ 40 418звёзд репо oqtane Правило задаёт Copilot паттерны для Oqtane-модулей на Blazor и C#. Оно пригодится при создании клиентской и серверной частей модуля. ★ 40 418звёзд репо oop-design-patterns Правило для GitHub Copilot, которое подталкивает его к паттернам GoF и принципам SOLID при генерации и рефакторинге ООП-кода. ★ 40 418звёзд репо object-calisthenics Правило заставляет GitHub Copilot писать доменный код на C#, TypeScript и Java по принципам Object Calisthenics без вложенных условий и лишних полей. ★ 40 418звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой