Логотип Create Modal

Create Modal

СообществоПопулярный
marcus
create-modal

Создавайте декларативные модальные окна с помощью API библиотеки modal. Описаны типы окон (confirm, input, select, form), секции (Text, Buttons, Input, Textarea, Checkbox, Select, List, Combo, When, Custom), отображение с помощью OverlayModal и обработка клавиатуры и мыши. Используйте при добавлении модальных окон или диалогов в приложение.

Add to TypingMind

Обзор

Издательmarcus
Репозиторийsidecar
Название навыкаcreate-modal
Звёзды
1.1K
Форки
82
Файлы в комплекте
1
ЛицензияMIT
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Файлы в комплекте: 1

    Скрипты, шаблоны и справочные материалы, которые модель может читать во время работы. Файлы доступны только для чтения и никогда не выполняются.

  • Открытый исходный код

    Издатель навыка на GitHub — marcus. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Create Modal в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/marcus/sidecar/tree/main/.claude/skills/create-modal
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/marcus/sidecar.git /tmp/sidecar
mkdir -p .claude/skills
cp -r /tmp/sidecar/.claude/skills/create-modal .claude/skills/create-modal
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Create Modal в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Create Modal, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Create Modal не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Creating Declarative Modals

Use the internal/modal package. The library handles keyboard navigation, mouse hit regions, hover states, and scrolling automatically.

Quick Start

go
import "github.com/marcus/sidecar/internal/modal"

// 1. Create the modal
m := modal.New("Delete Worktree?",
    modal.WithWidth(58),
    modal.WithVariant(modal.VariantDanger),
    modal.WithPrimaryAction("delete"),
).
    AddSection(modal.Text("Name: " + wt.Name)).
    AddSection(modal.Spacer()).
    AddSection(modal.Buttons(
        modal.Btn(" Delete ", "delete", modal.BtnDanger()),
        modal.Btn(" Cancel ", "cancel"),
    ))

// 2. Render in View
func (p *Plugin) View(width, height int) string {
    background := p.renderListView(width, height)
    rendered := p.myModal.Render(width, height, p.mouseHandler)
    return ui.OverlayModal(background, rendered, width, height)
}

// 3. Handle input in Update
case tea.KeyMsg:
    action, cmd := p.myModal.HandleKey(msg)
    if action != "" {
        return p.handleAction(action) // "delete", "cancel", etc.
    }
    return p, cmd

case tea.MouseMsg:
    action := p.myModal.HandleMouse(msg, p.mouseHandler)
    if action != "" {
        return p.handleAction(action)
    }
    return p, nil

Critical: Modal Initialization Pattern

The modal must exist before input handling. Create an ensure function called in both View and Update:

go
func (p *Plugin) ensureMyModal() {
    if p.targetItem == nil {
        return // Required state missing
    }

    modalW := 50
    if modalW > p.width-4 {
        modalW = p.width - 4
    }
    if modalW < 20 {
        modalW = 20
    }

    // Only rebuild if needed
    if p.myModal != nil && p.myModalWidthCache == modalW {
        return
    }
    p.myModalWidthCache = modalW

    p.myModal = modal.New("Title", modal.WithWidth(modalW), ...).
        AddSection(...)
}

Call ensureModal() before the nil check in key handlers:

go
func (p *Plugin) handleMyModalKeys(msg tea.KeyMsg) tea.Cmd {
    p.ensureMyModal()  // CRITICAL: Before nil check
    if p.myModal == nil {
        return nil
    }
    action, cmd := p.myModal.HandleKey(msg)
    // ...
}

Without this, the first keypress after opening drops because View runs after Update in bubbletea.

Constructor and Options

go
m := modal.New(title string, opts ...Option)
OptionDescriptionDefault
WithWidth(int)Modal width in characters50
WithVariant(Variant)Visual styleVariantDefault
WithPrimaryAction(string)Action ID for Enter on inputs""
WithHints(bool)Show "Tab to switch..." hinttrue
WithCloseOnBackdropClick(bool)Backdrop click returns "cancel"true

Variants: VariantDefault, VariantDanger (red), VariantWarning (yellow), VariantInfo (blue)

Built-in Sections

Text and Spacer

go
modal.Text("Static text with auto line wrapping")
modal.Spacer()  // Single blank line

Buttons

go
modal.Buttons(
    modal.Btn(" Save ", "save"),              // Standard button
    modal.Btn(" Delete ", "delete", modal.BtnDanger()),  // Red
    modal.Btn(" Submit ", "submit", modal.BtnPrimary()), // Primary
    modal.Btn(" Cancel ", "cancel"),
)
  • Include padding in labels: " Save " not "Save"
  • Button IDs are returned as actions
  • Tab/Shift+Tab cycles focus

Input

go
var nameInput textinput.Model
modal.Input("name-input", &nameInput)
modal.InputWithLabel("name-input", "Name:", &nameInput)
modal.Input("name-input", &nameInput,
    modal.WithSubmitOnEnter(true),       // Default: true
    modal.WithSubmitAction("submit"),    // Override primary action
)

Textarea

go
var msgArea textarea.Model
modal.Textarea("message", &msgArea, 5)          // height in lines
modal.TextareaWithLabel("message", "Label:", &msgArea, 5)
  • Enter inserts newlines (never submits)

Combo (floating dropdown)

go
items := []modal.DropdownItem{
    {ID: "main", Label: "main", Value: "main"},
    {ID: "dev", Label: "dev", Value: "dev"},
}
var selectedIdx int
modal.Combo("branch", &branchInput, items, &selectedIdx)
  • Single-line input; filtered results float over later sections (modal height does not change)
  • selected is an items index (same as List)
  • Typing filters and selects the top match; up/down move the highlight
  • Enter commits the highlight and, by default, returns the modal primary action
  • Tab commits and moves focus; Esc closes the overlay without cancelling the modal
  • Click an overlay row to commit without submitting

Checkbox

go
var includeFiles bool
modal.Checkbox("include-files", "Include untracked files", &includeFiles)
  • Space toggles
  • Enter does not toggle; it submits the modal primary action (if any)

Select (one choice out of a set)

go
items := []modal.SelectItem{
    {ID: "shell", Label: "Shell", Description: "new agent/shell session"},
    {ID: "worktree", Label: "Worktree", Description: "shell in a new worktree"},
}
var selectedIdx int
modal.Select("kind", items, &selectedIdx,
    modal.WithMaxVisible(6),
    modal.WithDisabled(func(i int) string { return reasons[i] }),
    modal.WithOnSelect(func(i int) { rebuildAround(i) }),
)
  • The default control for a single choice: sort, filter, kind. modal.List is the low-level column of rows for lists that are not a single choice.
  • Two shapes, chosen by count: a segmented [ A | B | C ] under five choices, a ❯-cursor full-width list with an aligned description column at five or more (and the list whenever the segments would not fit the width). WithShape(modal.ShapeList) / WithShape(modal.ShapeSegmented) forces one.
  • The list shape is a bordered control: its rows and scroll markers sit inside a rounded border that follows focus exactly as modal.Input's does (BorderNormal idle, Primary focused, TextMuted hovered). A click on a border cell focuses the control and selects nothing. The selected row keeps its Primary fill either way — the fill says which choice is active, the border says where the keyboard is.
  • Size the modal to it. A segmented control cannot shrink: build the sections into a slice first and pass modal.WidthForSections(sections...), capped to your frame, to modal.WithWidth — otherwise a control too wide for the box truncates into a stub. See viewModalWidth in internal/pluginbrowser/overlays.go.
  • Arrows and h/j/k/l move by one and stop at the ends; home/end jump; Enter activates.
  • WithDisabled(func(i int) string) keeps a choice visible and muted with its reason in place of its description, and makes it unreachable by key or click.
  • WithMaxVisible(n) scrolls the rest, with ↑ more above / ↓ more below.
  • A click resolves to a row inside the section — hosts add no glue — and focuses the control.
  • WithOnSelect(func(i int)) reports every change; WithSelectAction(id) makes activation return a fixed action instead of the row's ID, for a selector embedded in a form.
  • See docs/reference/design-language.md ("Selectors").

List

go
items := []modal.ListItem{
    {ID: "item-1", Label: "First item", Data: someValue},
    {ID: "item-2", Label: "Second item"},
}
var selectedIdx int
modal.List("my-list", items, &selectedIdx, modal.WithMaxVisible(5))
  • j/k or up/down moves selection; Enter returns selected item's ID

When (Conditional)

go
modal.When(func() bool { return showWarning },
    modal.Text("Warning: This action is irreversible!"),
)

Custom

go
modal.Custom(
    func(contentWidth int, focusID, hoverID string) modal.RenderedSection {
        return modal.RenderedSection{
            Content: content,
            Focusables: []modal.FocusableInfo{
                {ID: "custom-btn", OffsetX: 0, OffsetY: 2, Width: 10, Height: 1},
            },
        }
    },
    func(msg tea.Msg, focusID string) (string, tea.Cmd) {
        return "", nil  // can be nil if no custom input handling
    },
)

Handling Input

Keyboard

go
action, cmd := m.HandleKey(msg)
KeyBehavior
TabFocus next element
Shift+TabFocus previous element
EnterReturn focused element's ID (or primaryAction for inputs). Checkbox Enter submits primary without toggling. Combo Enter commits then submits.
EscOffered to the focused section first (Combo closes its overlay). Otherwise "cancel".
OtherForwarded to focused section

Mouse

go
action := m.HandleMouse(msg, p.mouseHandler)
EventBehavior
Click backdropReturn "cancel" (if enabled)
Click button/checkboxReturn element ID
Hover elementUpdate hover state
Scroll on modalScroll content

Modal Methods

go
m.FocusedID() string   // Currently focused element ID
m.HoveredID() string   // Currently hovered element ID
m.SetFocus(id string)  // Focus specific element
m.Reset()              // Reset focus, hover, scroll to initial state

Rendering Rules

Always use ui.OverlayModal for dimmed background:

go
func (p *Plugin) View(width, height int) string {
    background := p.renderNormalView(width, height)
    rendered := p.myModal.Render(width, height, p.mouseHandler)
    return ui.OverlayModal(background, rendered, width, height)
}

Do not:

  • Pre-center modal content with lipgloss.Place (OverlayModal handles centering)
  • Render footers or hint lines in plugin View (app renders unified footer)

State Management

  • Focus state persists across renders
  • Call Reset() when closing and reopening modals
  • Width caching should include state-dependent changes

Troubleshooting

IssueSolution
First keypress droppedCall ensureModal() before nil check in Update
Modal too wide/narrowUse width clamping: modalW > p.width-4
Hover not updatingPass mouseHandler to both Render and HandleMouse
Input not receiving keysCheck FocusedID()
Modal rebuilds every frameCache by width
Modal shows with wrong focusCall m.Reset() when showing modal

See references/complete-example.md for a full plugin implementation with delete confirmation modal.

Файлы в комплекте

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

Часто задаваемые вопросы

Что делает навык ИИ Create Modal?

Создавайте декларативные модальные окна с помощью API библиотеки modal. Описаны типы окон (confirm, input, select, form), секции (Text, Buttons, Input, Textarea, Checkbox, Select, List, Combo, When, Custom), отображение с помощью OverlayModal и обработка клавиатуры и мыши. Используйте при добавлении модальных окон или диалогов в приложение.

Зачем использовать Create Modal в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Create Modal — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Create Modal в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/marcus/sidecar/tree/main/.claude/skills/create-modal. TypingMind прочитает файл SKILL.md, включит сопутствующие файлы в пакет и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Create Modal?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Create Modal?

С любым количеством. В TypingMind вы можете использовать Create Modal с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Create Modal?

Да. Навык опубликован на GitHub по лицензии MIT. Издатель — marcus. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все
Логотип coreyhaines31

Ads

coreyhaines31
СообществоПопулярный

Когда пользователю нужна помощь с платными рекламными кампаниями в Google Ads, Meta (Facebook/Instagram), LinkedIn, Twitter/X или на других рекламных платформах. Используйте этот навык и при упоминании «PPC», «платной рекламы»,…

7.7K
50.7K
Файлы: 15
Открыть
Логотип coreyhaines31

Ai Seo

coreyhaines31
СообществоПопулярный

Когда пользователь хочет оптимизировать контент для поисковых систем на базе ИИ, добиться цитирования со стороны LLM или попадать в ответы, сгенерированные ИИ. Используйте этот навык и при упоминании «AI SEO», «AEO», «GEO», «LLMO», «оптимизации для…

7.7K
50.7K
Файлы: 9
Открыть
Логотип coreyhaines31

Analytics

coreyhaines31
СообществоПопулярный

Когда пользователь хочет настроить, улучшить или проверить отслеживание и измерение аналитики. Используйте этот навык и при упоминании «настроить отслеживание», «GA4», «Google Analytics», «отслеживания конверсий», «отслеживания…

7.7K
50.7K
Файлы: 4
Открыть
Логотип coreyhaines31

Aso

coreyhaines31
СообществоПопулярный

Когда пользователь хочет проверить или оптимизировать страницу приложения в App Store или Google Play. Используйте этот навык и при упоминании «ASO-аудита», «оптимизации страницы приложения», «оптимизации страницы приложения в магазине», «повышения видимости…

7.7K
50.7K
Файлы: 6
Открыть

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇