К основному содержанию
скилл CX Codex

add-pen-input — скилл для Claude Code: ввод пера и установка

Скилл add-pen-input помогает создать или проверить обёртку для рукописного ввода и подписи в мобильном приложении. Его вызывает /add-native для сценариев рисования, чернил и рукописного текста.

MIT ★ 1 167 обновлён 2026-10-29

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add microsoft/power-platform-skills
/plugin install mobile-app@power-platform-skills
Открыть на GitHub

Что делает add-pen-input

Скилл работает с @microsoft/power-apps-native-pen-input: проверяет или создаёт src/native/penInput.ts и показывает, как вызвать обёртку из React Native. Результат успешного захвата — PNG data URI; отмена пользователем возвращается как USER_CANCELLED, а не как ошибка. Обёртка также обрабатывает отсутствие нативного модуля и сбой захвата.

Перед изменениями скилл проверяет, что приложение и пакет уже подготовлены, а затем сверяет совместимость запрошенных файлов и сервисов. Пакет должен уже быть в package.json и нативной сборке: скилл не устанавливает его и не меняет app.config.js. Это ограничение важно: наличие пакета только в JavaScript не гарантирует работу нативного модуля.

Вызовите /add-native pen-input, /add-native signature или /add-native @microsoft/power-apps-native-pen-input. Скилл даёт рекомендации по отображению PNG и может учитывать сохранение подписи в колонку Dataverse Image/File через сгенерированные сервисы; экран и загрузку владелец приложения реализует сам.

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

  • добавить обёртку для захвата подписи от руки
  • проверить обработку отмены пользователем
  • вернуть PNG data URI из нативного ввода
  • обработать отсутствие модуля в нативной сборке

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

  • Добавь ввод подписи от руки через /add-native pen-input.
  • Проверь захват рукописного ввода через /add-native signature.
  • Подключи @microsoft/power-apps-native-pen-input через /add-native @microsoft/power-apps-native-pen-input.

Как установить add-pen-input

1Через маркетплейс плагинов

/plugin marketplace add microsoft/power-platform-skills
/plugin install mobile-app@power-platform-skills

Команда ставит плагин mobile-app целиком, со всеми его скиллами

2Через Skills CLI (Vercel)

npx skills add microsoft/power-platform-skills --skill add-pen-input -a claude-code

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

~/.claude/skills/add-pen-input/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/add-pen-input/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы об add-pen-input

Как установить add-pen-input в Claude Code?

Добавьте маркетплейс командой /plugin marketplace add microsoft/power-platform-skills, затем установите плагин командой /plugin install mobile-app@power-platform-skills.

Что делает add-pen-input?

Скилл создаёт или проверяет src/native/penInput.ts для захвата подписи, рисунка или рукописного ввода. Он возвращает PNG data URI и отдельно обрабатывает отмену и ошибки.

Нужно ли устанавливать пакет для работы скилла?

Нет. @microsoft/power-apps-native-pen-input должен уже присутствовать в package.json и нативной сборке приложения; скилл не устанавливает пакет и не меняет нативную конфигурацию.

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

SKILL.md · MIT
---
name: add-pen-input
description: Internal implementation skill invoked by /add-native for pen, signature, ink, drawing, and handwriting capture workflows using @microsoft/power-apps-native-pen-input.
user-invocable: false
disable-model-invocation: true
allowed-tools: Read, Edit, Write, Grep, Glob, Bash, AskUserQuestion
model: sonnet
---

**📋 Shared instructions: [shared-instructions.md](${PLUGIN_ROOT}/shared/shared-instructions.md)** — read first.

**Working directory:** before any project read or command, execute
[native-artifact-compatibility.md Step 0](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md#0-bind-every-operation-to-the-app-root).
Inherit `/add-native`'s resolved absolute `working_dir`; bind every shell call and
file tool to it, even when this helper starts from another directory.

# Add Pen Input

**Internal helper.** Users should invoke `/add-native pen-input`, `/add-native signature`, or `/add-native @microsoft/power-apps-native-pen-input`; `/add-native` routes here after resolving the capability.

Generate or verify the native pen input wrapper and show how to call its **native React Native API**. Do not use the HostingSDK / PCF path from the package README; that is for a different use case.

## Steps

### 1. Verify app

```bash
cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
test -f app.config.js && test -f power.config.json && test -f package.json && test -d src || { echo "BLOCKED: working_dir is not an initialized app" >&2; exit 1; }
```

If this fails, tell the user to run `/create-mobile-app` first and STOP.

### 2. Verify package is already present

```bash
cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node -e "const p=require('./package.json'); const m='@microsoft/power-apps-native-pen-input'; if (!p.dependencies?.[m]) { console.error('MISSING: ' + m + ' is not in package.json. The template/app must already ship this native extension. This skill will not install it or edit native config.'); process.exit(1); } console.log('OK: pen input package present');"
```

If the check fails, STOP. Do not run `npm install`, `npx expo install`, `pod install`, or edit `app.config.js`. This package contains native iOS/Android code and must already be part of the app's native build.

### 2a. Reconcile requested artifacts

Read and execute [native-artifact-compatibility.md](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md)
Steps 1–3 for the pen input row before any writes or reuse. Inherit the current
approval/mode from `/add-native`; do not repeat a valid scoped approval.
Inspect `src/native/penInput.ts` for `captureSignature`, `stripDataUriPrefix`,
`PenInputResult`, requested options, PNG data URI output, and non-error
`USER_CANCELLED`. Check approved Image/File payload requirements as well as
capture: a missing normalizer or unknown required generated service signature
cannot be ignored. Missing required storage or an incompatible artifact outside
approval returns `NEEDS_CONTEXT` to the owner, or asks standalone.

### 3. Write or verify `src/native/penInput.ts`

Apply Step 2a's decision for `src/native/penInput.ts`: create when requested and
missing, reuse unchanged only if compatible, or make only the approved scoped
update. Preserve custom code, exports, and callers; do not overwrite from the example.

The wrapper MUST:

- Return a discriminated union and never throw.
- Return `{ ok: false, reason: 'USER_CANCELLED' }` for user cancellation; this is a non-error path.
- Return `NATIVE_MODULE_MISSING` when the extension is installed in JS but unavailable in the native build.
- Return a PNG data URI (`data:image/png;base64,...`) on success.

```ts
// src/native/penInput.ts
import {
  PenInputNative,
  PenInputStatus,
  PenInputErrorCode,
} from '@microsoft/power-apps-native-pen-input';

export type PenInputResult =
  | { ok: true; dataUri: string }
  | { ok: false; reason: 'USER_CANCELLED' | 'NATIVE_MODULE_MISSING' | 'CAPTURE_FAILED'; message?: string };

export async function captureSignature(options?: {
  backgroundColor?: string;
  strokeColor?: string;
  strokeWidth?: number;
}): Promise<PenInputResult> {
  if (!PenInputNative?.capturePenInput) {
    return { ok: false, reason: 'NATIVE_MODULE_MISSING', message: 'Pen input module is not available in this build.' };
  }

  try {
    const result = await PenInputNative.capturePenInput({
      backgroundColor: '#ffffff',
      strokeColor: '#0078d4',
      strokeWidth: 2,
      ...options,
    });

    if (result.status === PenInputStatus.Ok && result.result) {
      return { ok: true, dataUri: result.result };
    }

    if (result.error === PenInputErrorCode.UserCancelled) {
      return { ok: false, reason: 'USER_CANCELLED' };
    }

    return { ok: false, reason: 'CAPTURE_FAILED', message: result.error };
  } catch (error: any) {
    return { ok: false, reason: 'CAPTURE_FAILED', message: error?.message ?? String(error) };
  }
}

export function stripDataUriPrefix(dataUri: string): string {
  return dataUri.replace(/^data:image\/png;base64,/, '');
}
```

### 4. Use the wrapper

Integration guidance for the owner; do not edit screens in this helper.

Screens import the wrapper, not the native package directly:

```ts
import { captureSignature } from '@/native/penInput';

const result = await captureSignature({
  backgroundColor: "#ffffff",
  strokeColor: "#0078d4",
  strokeWidth: 2,
});

if (result.ok) {
  setSignatureUri(result.dataUri);
} else if (result.reason === 'USER_CANCELLED') {
  // User cancelled; do not show this as an app error.
} else {
  console.warn("Failed to capture pen input:", result.reason, result.message);
}
```

Display the captured PNG with a normal React Native image:

```tsx
{signatureUri ? (
  <Image
    source={{ uri: signatureUri }}
    style={{ width: "100%", height: 160 }}
    resizeMode="contain"
  />
) : null}
```

Notes:
- The result is a PNG data URI: `data:image/png;base64,...`.
- Color inputs support `#RGB` and `#RRGGBB`.
- Cancel is normal and returns `USER_CANCELLED`; screens should leave current state unchanged and avoid failure banners.
- Use `@microsoft/power-apps-native-pen-input` only for native freehand drawing, ink, handwriting, and signature capture. For unrelated native use cases, use the relevant Expo module or other dependency already present in `package.json`.

### 5. Optional Dataverse save

Optional means unrequested, not skippable when retention is approved. Step 2a
verifies wrapper payload support and the generated signature; the owner supplies
the screen-side save/upload below. Return missing helper-owned support or unknown
required storage as `NEEDS_CONTEXT`, not a capture-only success.

If the user wants to save the signature to a Dataverse Image/File column, use generated services only. Do not write direct Dataverse Web API calls.

Image column pattern: normalize the data URI to the generated service's expected image payload. If raw base64 is required, strip the prefix.

```ts
import { stripDataUriPrefix } from '@/native/penInput';

const signatureBase64 = stripDataUriPrefix(result.dataUri);

const update = await Cr123_evidenceService.update(id, {
  cr123_signatureimage: signatureBase64,
  cr123_signedat: new Date().toISOString(),
});

if (!update.success) {
  showError(update.error?.message ?? 'Signature was not saved.');
}
```

File column pattern: save or update the parent row first, then upload the PNG bytes/File through the generated service helper. Never put File column bytes in the create/update JSON body.

### 6. Type-check

```bash
cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
npx --no-install tsc --noEmit
```

Fix only in-scope helper errors, then execute the shared compatibility contract's
Step 4. Recheck requested capture/normalization/storage behavior, including user
cancellation, missing native module, capture failure, and Image versus File payloads.
Type-check success alone is insufficient; do not fix screen/generated files.

### 7. Native rebuild note

This skill does not install native code. If the package was just added outside the skill, the app needs a native rebuild outside this workflow. If the package was already in the build, Metro hot reload is enough for wrapper edits.

### 8. Do not use HostingSDK / PCF

Do not import or register:

```ts
import { PenInputExtension } from "@microsoft/power-apps-native-pen-input";
```

Do not wire Companion PCF or `PenInputExtension`. In Power Apps native code apps, use the native React Native API above.

### 9. Summary

Return the shared compatibility result and actual created/updated/reused paths
before this summary. Report owner-side save/integration separately; update
memory-bank only after success, and leave final updates to the owner when orchestrated.

Tell the user:

```text
Pen input added
Package present   : @microsoft/power-apps-native-pen-input
Wrapper           : src/native/penInput.ts
Output            : PNG data URI
Type-check        : PASS
Native rebuild    : not performed by this skill
Usage             : captureSignature(...)
HostingSDK / PCF  : not used
```

Update `memory-bank.md` under `Controls`:

```text
- Pen input added — @microsoft/power-apps-native-pen-input (<ISO date>)
```

© Microsoft · MIT · microsoft/power-platform-skills

Похожие скиллы

Все скиллы по теме «Мобильная разработка» →
build-zoom-meeting-sdk-app официальный Zoom Скилл build-zoom-meeting-sdk-app ведёт агента по шагам сборки приложения, которое подключается к настоящим встречам Zoom: от выбора платформы до отладки подписи SDK. CX Codex GP ChatGPT +1 ★ 8 052звёзд репо flutter-add-widget-test flutter Скилл flutter-add-widget-test для Claude Code помогает писать тесты Flutter-виджетов: проверять отображение, состояние и реакцию на действия. Включается при проверке конкретного виджета. CX Codex +1 42 900установок flutter-add-widget-preview flutter Скилл flutter-add-widget-preview для Claude Code обучает агента создавать интерактивные превью виджетов Flutter через package:flutter/widget_previews.dart. Превью позволяют верстать UI изолированно, без сборки всего приложения. CX Codex +1 40 000установок roblox-input TabooHarmony Скилл roblox-input для работы с вводом в Roblox: тач, геймпад, клавиатура, мышь, кнопки на экране и кросс-платформенные привязки. CX Codex +1 3 100установок security-pen-testing Alireza Rezvani Скилл security-pen-testing помогает искать уязвимости в коде, зависимостях, секретах и API. Он пригодится для авторизованных проверок и подготовки отчёта о тестировании. CX Codex +1 834установок design-mobile-apps designed-by-ai Скилл design-mobile-apps генерирует экраны мобильных приложений через сервис Sleek и помогает перенести готовый макет в React Native или HTML. CX Codex +1 1 500 000установок

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

Весь набор →
preview-offline-scope Скилл preview-offline-scope оценивает объём загрузки и частоту синхронизации офлайн-профиля Power Platform до отправки пользователям. Работает только в режиме чтения. CX Codex +1 ★ 1 167звёзд репо canvas-screen-builder Субагент canvas-screen-builder для Claude Code добавляет или изменяет один экран в существующем Canvas App по общему контракту и заданию. Он выполняет локальную проверку без компиляции. CX Codex ★ 1 167звёзд репо code-app-architect Субагент code-app-architect помогает проектировать Power Apps код-приложения на React и Vite, интегрировать Dataverse, выбирать коннекторы и отлаживать сборку. CX Codex ★ 1 167звёзд репо add-pdf-viewer Скилл add-pdf-viewer настраивает обёртку для встроенного просмотра PDF по ссылкам HTTPS и локальным путям file:// в мобильных приложениях Power Platform. CX Codex +1 ★ 1 167звёзд репо canvas-app-planner Субагент canvas-app-planner для Claude Code превращает одобренные изменения Canvas Apps в контракты реализации для каждого экрана, сохраняя логику и вёрстку. CX Codex ★ 1 167звёзд репо assemble-ppmplugin Скилл assemble-ppmplugin для Claude Code собирает .ppmplugin-бандл из манифеста и бинарников Android/iOS, проверяет их соответствие и упаковывает в архив. Запускается после /generate-ppmplugin-manifest и скиллов сборки. CX Codex +1 ★ 1 167звёзд репо add-geolocation Скилл add-geolocation помогает добавить в мобильное приложение фоновое GPS-отслеживание с сохранением данных и отправкой в Dataverse. Его вызывает команда /add-native geolocation. CX Codex +1 ★ 1 167звёзд репо diagnose-deployment Скилл diagnose-deployment для Claude Code ищет ошибки загрузки Power Pages и импорта решений в Dataverse. Запускается по просьбе разобраться с неудачным деплоем или исправить найденные проблемы. CX Codex +1 ★ 1 167звёзд репо

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

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