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

pcf-code-components — правило для GitHub Copilot: структура

Правило объясняет Copilot, как устроены code components в Power Apps component framework: манифест, реализация, ресурсы. Пригодится, когда правите ControlManifest.Input.xml или index.ts.

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

Что делает pcf-code-components

Правило подключается к файлам по маске **/*.{ts,tsx,js,json,xml,pcfproj,csproj} и описывает три части code component: манифест, реализацию и ресурсы. Манифест — это ControlManifest.Input.xml, где заданы имя компонента, тип данных (field или dataset), настраиваемые свойства и список нужных файлов. Именно по манифесту платформа фильтрует, какие компоненты вообще можно поставить в конкретном месте.

Реализация пишется на TypeScript. Обязательные методы жизненного цикла — init, updateView и destroy, а getOutputs вызывается, когда пользователь меняет данные. Каркас index.ts с заглушками создаёт команда pac pcf init из Power Platform CLI, так что вручную прописывать сигнатуры не нужно. При загрузке страницы платформа создаёт объект по данным манифеста и вызывает init(context, notifyOutputChanged, state, container).

Ресурсы перечисляются в узле resources манифеста, и хотя бы один code-ресурс обязателен. Дополнительно можно добавить CSS, картинки и .resx для локализации. Если не реализовать destroy, обработчики событий останутся в памяти после ухода со страницы — это повод проверить компонент перед публикацией. Для хранения данных между загрузками в рамках одной сессии есть setControlState.

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

  • разобраться, какие поля обязательны в ControlManifest.Input.xml
  • понять порядок вызовов init, updateView и getOutputs
  • создать каркас компонента через pac pcf init
  • подключить CSS и .resx к компоненту
  • убрать утечку памяти через destroy

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

  • Объясни, какие свойства нужно объявить в ControlManifest.Input.xml для компонента типа field.
  • Почему updateView вызывается, а getOutputs — нет? Разбери жизненный цикл моего компонента.
  • Добавь в манифест ресурс с CSS и .resx для локализации.

Как установить pcf-code-components

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

.github/instructions/pcf-code-components.instructions.md

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

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

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

Весь набор →
php-symfony Правило задаёт Copilot стиль разработки на Symfony: структура проекта, DI, Doctrine, Twig и тесты. Пригодится, если не хочется объяснять агенту конвенции в каждом чате. ★ 40 418звёзд репо pcf-tooling Правило подсказывает Copilot, что для сборки, отладки и деплоя код-компонентов нужен Microsoft Power Platform CLI. ★ 40 418звёзд репо pcf-manifest-schema Правило подсказывает Copilot структуру ControlManifest.Input.xml: какие элементы и атрибуты бывают и что они делают. Пригодится, когда правишь манифест PCF-компонента. ★ 40 418звёзд репо pcf-events Правило подсказывает Copilot, как объявлять и обрабатывать кастомные события в компонентах Power Apps Component Framework. ★ 40 418звёзд репо oop-design-patterns Правило для GitHub Copilot, которое подталкивает его к паттернам GoF и принципам SOLID при генерации и рефакторинге ООП-кода. ★ 40 418звёзд репо no-heredoc Правило запрещает агенту писать файлы через heredoc и перенаправления в терминале, потому что в VS Code такие команды портят содержимое. ★ 40 418звёзд репо nestjs Правило подключает к GitHub Copilot набор стандартов NestJS: модули, DI, DTO и валидация. Пригодится, когда агент пишет серверный код на TypeScript. ★ 40 418звёзд репо moodle Правило задаёт Copilot стандарты Moodle: Frankenstyle-неймспейсы, Mustache-шаблоны, обязательные функции безопасности. Пригодится, если пишете плагины и темы. ★ 40 418звёзд репо

Похожие

building-components vercel Помогает проектировать доступные UI-компоненты, их API, темы и документацию. CX Codex +1 14 700установок mantine-custom-components mantinedev Скилл учит ИИ-агента создавать компоненты для Mantine 9.x по официальным паттернам библиотеки. Пригодится при настройке Styles API, CSS-переменных и фабрик компонентов. CX Codex +1 3 600установок next-cache-components официальный Vercel Labs Скилл помогает внедрять Cache Components и частичный пререндеринг в Next.js 16. Он подсказывает синтаксис директивы use cache, настройку профилей и сброс тегов. CX Codex GP ChatGPT 4установок pwa-development alinaqi Скилл для сборки Progressive Web App: манифест, service worker, стратегии кэширования и офлайн-режим. Пригодится, когда приложение должно ставиться на телефон и открываться без сети. CX Codex +1 4 100установок pwa-expert curiositech Помогает сделать веб-приложение устанавливаемым и работающим офлайн: манифест, Service Worker, стратегии кеширования, свой экран установки. CX Codex +1 544установок stitch::react-components официальный google-labs-code Превращает дизайны Stitch в компоненты React с Vite. Также синхронизирует существующие компоненты с обновлёнными макетами. CX Codex +1 50 400установок

Рядом в теме «Фронтенд и UI»

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

Вопросы о pcf-code-components

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

Скопируйте файл правила в .github/instructions/pcf-code-components.instructions.md в репозитории. Copilot подхватит его для файлов, подходящих под маску applyTo.

Что делает pcf-code-components?

Объясняет Copilot структуру code components в Power Apps component framework: манифест, реализацию на TypeScript и ресурсы. Так подсказки по ControlManifest.Input.xml и index.ts будут опираться на реальные правила фреймворка.

Чем отличаются компоненты для model-driven и canvas apps?

Определение и реализация через Power Apps component framework одинаковые. Различается только часть с конфигурацией.

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

pcf-code-components.instructions.md · MIT
---
description: 'Understanding code components structure and implementation'
applyTo: '**/*.{ts,tsx,js,json,xml,pcfproj,csproj}'
---

# Code Components

Code components are a type of solution component that can be included in a solution file and imported into different environments. They can be added to both model-driven and canvas apps.

## Three Core Elements

Code components consist of three elements:

1. **Manifest**
2. **Component implementation**
3. **Resources**

> **Note**: The definition and implementation of code components using Power Apps component framework is the same for both model-driven and canvas apps. The only difference is the configuration part.

## Manifest

The manifest is the `ControlManifest.Input.xml` metadata file that defines a component. It is an XML document that describes:

- The name of the component
- The kind of data that can be configured, either a `field` or a `dataset`
- Any properties that can be configured in the application when the component is added
- A list of resource files that the component needs

### Manifest Purpose

When a user configures a code component, the data in the manifest file filters the available components so that only valid components for the context are available for configuration. The properties defined in the manifest file are rendered as configuration columns so that users can specify values. These property values are then available to the component at runtime.

More information: [Manifest schema reference](https://learn.microsoft.com/en-us/power-apps/developer/component-framework/manifest-schema-reference/)

## Component Implementation

Code components are implemented using TypeScript. Each code component must include an object that implements the methods described in the code component interface. The [Power Platform CLI](https://learn.microsoft.com/en-us/power-platform/developer/cli/introduction) auto-generates an `index.ts` file with stubbed implementations using the `pac pcf init` command.

### Required Methods

The component object implements these lifecycle methods:

- **init** (Required) - Called when the page loads
- **updateView** (Required) - Called when app data changes
- **getOutputs** (Optional) - Returns values when user changes data
- **destroy** (Required) - Called when the page closes

### Component Lifecycle

#### Page Load

When the page loads, the application creates an object using data from the manifest:

```typescript
var obj = new <"namespace on manifest">.<"constructor on manifest">();
```

Example:
```typescript
var controlObj = new SampleNameSpace.LinearInputComponent();
```

The page then initializes the component:

```typescript
controlObj.init(context, notifyOutputChanged, state, container);
```

**Init Parameters:**

| Parameter | Description |
|-----------|-------------|
| `context` | Contains all information about how the component is configured and all parameters. Access input properties via `context.parameters.<property name from manifest>`. Includes Power Apps component framework APIs. |
| `notifyOutputChanged` | Alerts the framework whenever the component has new outputs ready to be retrieved asynchronously. |
| `state` | Contains component data from the previous page load if explicitly stored using `setControlState` method. |
| `container` | An HTML div element to which developers can append HTML elements for the UI. |

#### User Changes Data

When a user interacts with your component to change data, call the `notifyOutputChanged` method passed in the `init` method. The platform responds by calling the `getOutputs` method, which returns values with the changes made by the user. For a `field` component, this would typically be the new value.

#### App Changes Data

If the platform changes the data, it calls the `updateView` method of the component and passes the new context object as a parameter. This method should be implemented to update the values displayed in the component.

#### Page Close

When a user navigates away from the page, the code component loses scope and all memory allocated for objects is cleared. However, some methods (like event handlers) may stay and consume memory based on browser implementation.

**Best Practices:**
- Implement the `setControlState` method to store information for the next time within the same session
- Implement the `destroy` method to remove cleanup code such as event handlers when the page closes

## Resources

The resource node in the manifest file refers to the resources that the component requires to implement its visualization. Each code component must have a resource file to construct its visualization. The `index.ts` file generated by the tooling is a `code` resource. There must be at least 1 code resource.

### Additional Resources

You can define additional resource files in the manifest:

- CSS files
- Image web resources
- Resx web resources for localization

More information: [resources element](https://learn.microsoft.com/en-us/power-apps/developer/component-framework/manifest-schema-reference/resources)

## Related Resources

- [Create and build a code component](https://learn.microsoft.com/en-us/power-apps/developer/component-framework/create-custom-controls-using-pcf)
- [Learn how to package and distribute extensions using solutions](https://learn.microsoft.com/en-us/power-platform/alm/solution-concepts-alm)

© github · MIT · github/awesome-copilot

Смотрите также

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

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