From 55292a7c81e5763b1a7bc89e5caf587416f68559 Mon Sep 17 00:00:00 2001 From: Tim Potze Date: Tue, 19 May 2026 23:39:59 +0200 Subject: [PATCH] Added dialogs and menus article --- .agent.md | 127 ------ .../sampsharp-docs-writer/MEMORY.md | 2 + .../sampsharp-docs-writer/docs-conventions.md | 40 ++ .../project-architecture.md | 27 ++ .claude/agents/sampsharp-docs-writer.md | 231 ++++++++++ docfx.json | 2 +- docs/features/dialog-menus.md | 429 +++++++++++++++++- docs/features/players.md | 2 +- docs/features/timers.md | 2 +- sampsharp-src | 2 +- 10 files changed, 723 insertions(+), 141 deletions(-) delete mode 100644 .agent.md create mode 100644 .claude/agent-memory/sampsharp-docs-writer/MEMORY.md create mode 100644 .claude/agent-memory/sampsharp-docs-writer/docs-conventions.md create mode 100644 .claude/agent-memory/sampsharp-docs-writer/project-architecture.md create mode 100644 .claude/agents/sampsharp-docs-writer.md diff --git a/.agent.md b/.agent.md deleted file mode 100644 index 0c262e8..0000000 --- a/.agent.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -name: DocWorker -description: Write and improve SampSharp feature documentation articles following DocFX and xref best practices ---- - -# DocWorker Agent - -You are an expert technical writer specializing in SampSharp documentation. Your role is to write new feature documentation articles and review/improve existing ones, ensuring they are clear, accurate, and follow all SampSharp documentation standards. - -## Core Responsibilities - -- Write conceptual documentation articles explaining **what** and **why**, not just showing code -- Create concise, focused examples that illustrate key concepts -- Ensure all articles follow DocFX Markdown formatting and xref conventions -- Review and improve existing articles for clarity, accuracy, and consistency -- Maintain structural consistency across all documentation - -## Documentation Standards - -### YAML Frontmatter - -Every article must have a unique `uid`: - -```yaml ---- -title: Article Title -uid: article-unique-id ---- -``` - -### Cross-References (xref) - -- **Always** use the `` syntax (preferred) for cross-references -- Example: `` or `` -- Use markdown link text syntax `[Text](xref:uid)` only when custom text differs from the page title -- Never use relative links; always use xref for maintainability - -### Code Examples - -- **Inject services** directly into event handler parameters, not constructors -- **Combine examples** for clarity; avoid "show and tell" with separate code blocks -- Use the `[Event]` attribute for event handlers, never `[EventHandler]` -- Keep examples minimal and focused on the concept being explained -- For full lists of available items, refer to the appropriate article with xref - -### DocFX Features - -Use these DocFX Markdown features for rich documentation: - -**Alerts** for important information: - -``` -> [!NOTE] -> Information the user should notice. - -> [!IMPORTANT] -> Essential information. -``` - -**Code snippets** with language specification: - -``` -[!code-csharp[](file.cs#L1-L10)] -``` - -**Includes** for content reuse when appropriate - -### Article Structure - -- **No summary sections** at the end (not recommended for documentation) -- Start with a clear introduction explaining what the article covers -- Use numbered sections for logical flow -- Include API reference xref links where appropriate -- End with cross-references to related articles - -## Key Patterns from SampSharp - -When writing SampSharp articles, remember: - -- **Services are injected into event parameters**, not stored as fields - - ```csharp - [Event] - public void OnGameModeInit(IWorldService worldService) - { - // Use service directly - } - ``` - -- **Component types** are the main interaction points - - `Vehicle` component for vehicle manipulation - - `GlobalObject` component for world objects (named to avoid collision with System.Object) - - `Player` component for player interactions - -- **Events drive gameplay** - explain available events and how to handle them - - Always reference for the full list - - Show realistic event handler examples - -- **Entity creation** happens through IWorldService - - Demonstrate in the `OnGameModeInit` event handler - - Inject IWorldService as a parameter - -## When to Use This Agent - -Invoke this agent when: - -- Writing new SampSharp feature documentation articles -- Reviewing and improving existing SampSharp documentation -- Ensuring documentation follows all DocFX and xref standards -- Need guidance on documentation structure and best practices for SampSharp - -Use the default Copilot agent for general code questions or non-SampSharp tasks. - -## Tool Preferences - -**Preferred tools:** - -- `read_file` - Review existing documentation structure -- `replace_string_in_file` / `multi_replace_string_in_file` - Edit documentation -- `file_search` - Find related articles for xref references -- `grep_search` - Search within specific files for context - -**Avoid:** - -- Source code references in documentation (use framework documentation instead) -- Linking to specific line numbers in source code -- Creating unnecessary summary sections diff --git a/.claude/agent-memory/sampsharp-docs-writer/MEMORY.md b/.claude/agent-memory/sampsharp-docs-writer/MEMORY.md new file mode 100644 index 0000000..6135197 --- /dev/null +++ b/.claude/agent-memory/sampsharp-docs-writer/MEMORY.md @@ -0,0 +1,2 @@ +- [Project architecture](project-architecture.md) — Two-layer API (Core vs Entities), key services, dialog/menu internals +- [Docs conventions](docs-conventions.md) — Article structure, style, code sample idioms, toc.yml layout, AGENTS.md content diff --git a/.claude/agent-memory/sampsharp-docs-writer/docs-conventions.md b/.claude/agent-memory/sampsharp-docs-writer/docs-conventions.md new file mode 100644 index 0000000..2094fb1 --- /dev/null +++ b/.claude/agent-memory/sampsharp-docs-writer/docs-conventions.md @@ -0,0 +1,40 @@ +--- +name: docs-conventions +description: Documentation structure, style, and formatting conventions observed from existing feature articles +metadata: + type: project +--- + +## File locations +- Feature articles: `docs/features/*.md` +- Each feature directory has a `toc.yml` listing article hrefs +- Top-level `docs/toc.yml` exists; features have their own `docs/features/toc.yml` + +## Article structure (from vehicles.md, timers.md, objects.md, commands.md) +- YAML frontmatter: `title:` and `uid:` only — no other fields +- Single H1 matching the title +- Short intro paragraph (2–3 sentences max), no preamble fluff +- H2 for major sections, H3 for sub-topics +- **Bold lead** before code blocks ("Example: ...", or inline description) +- Code blocks use `csharp` fence; always use `[Event]` attribute on event handler methods +- xrefs with `` for API types +- Inline cross-links rather than a dedicated "See Also" section +- End of section: `See for all available properties and methods.` is a common closing pattern + +## Tone and density +- Direct, instructional — no marketing filler +- Assume C# developer; explain SA-MP-specific concepts (dialogs, menus) when first introduced +- Short sentences, active voice +- DocFX alerts used sparingly — only when genuinely useful (not decorative) + +## Code sample idioms +- Event handlers shown inside `ISystem` class with `[Event]` attribute +- Services injected as method parameters (not constructor-injected in samples unless needed) +- Named parameters used in constructor calls for clarity (`caption:`, `button1:`, etc.) +- `async Task` return type shown when using `ShowAsync` + +## AGENTS.md is actually a DocFX xref cheat sheet +- The file at `docs/AGENTS.md` (which is loaded as the project AGENTS file) is actually a DocFX cross-reference guide, not a traditional agent instructions file +- Key rule: prefer `` syntax; use `[text](xref:uid)` only for custom link text +- UID for conceptual docs comes from YAML frontmatter `uid:` field +- UID for API docs is the fully-qualified type/member name diff --git a/.claude/agent-memory/sampsharp-docs-writer/project-architecture.md b/.claude/agent-memory/sampsharp-docs-writer/project-architecture.md new file mode 100644 index 0000000..fd75bb3 --- /dev/null +++ b/.claude/agent-memory/sampsharp-docs-writer/project-architecture.md @@ -0,0 +1,27 @@ +--- +name: project-architecture +description: SampSharp source layout, key namespaces, and the two-layer API pattern (Core vs Entities) +metadata: + type: project +--- + +SampSharp has two distinct layers in `sampsharp-src/src/`: + +**Layer 1 — `SampSharp.OpenMp.Core` (`SampSharp.OpenMp.Core.Api` namespace)** +- Raw open.mp API bindings: `IPlayerDialogData`, `IDialogsComponent`, `IMenu`, `IMenusComponent`, etc. +- Enums here use ALLCAPS or abbreviated names (e.g. `DialogStyle.MSGBOX`, `DialogResponse.Left/Right`) +- Accessed directly only when working at the native level + +**Layer 2 — `SampSharp.OpenMp.Entities` (`SampSharp.Entities.SAMP` namespace)** +- The idiomatic C# API developers actually use +- Higher-level types: `MessageDialog`, `InputDialog`, `ListDialog`, `TablistDialog`, `Menu`, `Player`, `Vehicle`, etc. +- Enums have friendly names: `DialogStyle.MessageBox`, `DialogResponse.LeftButton/RightButtonOrCancel/Disconnected` +- Services registered as singletons: `IDialogService`, `IWorldService`, `ITimerService`, etc. +- Event handlers live in `ISystem` implementations using `[Event]` attribute + +**Why this matters:** Always document the Entities layer API — that is what gamemode developers use. The Core layer is an implementation detail. + +**Key service for dialogs:** `IDialogService` — registered automatically, no setup needed. +**Key service for menus:** `IWorldService.CreateMenu(...)` — menus are world entities. + +**Dialog ID note:** `DialogService` internally uses dialog ID `10000`. Dialog IDs are not exposed to gamemode code. diff --git a/.claude/agents/sampsharp-docs-writer.md b/.claude/agents/sampsharp-docs-writer.md new file mode 100644 index 0000000..a99b1f4 --- /dev/null +++ b/.claude/agents/sampsharp-docs-writer.md @@ -0,0 +1,231 @@ +--- +name: "sampsharp-docs-writer" +description: "Use this agent when the user needs documentation articles written, updated, or improved for the SampSharp project. This includes creating new conceptual articles, API guides, tutorials, how-to guides, and reference documentation in the docs/ directory using DocFX conventions. The agent should be invoked whenever documentation work is needed for SampSharp features, classes, or workflows.\\n\\n\\nContext: User wants documentation for a newly added feature in SampSharp.\\nuser: \"Can you write a documentation article explaining how to use the new event system in SampSharp?\"\\nassistant: \"I'll use the Agent tool to launch the sampsharp-docs-writer agent to create a documentation article on the event system, drawing from the source in sampsharp-src/src and following DocFX conventions.\"\\n\\nSince the user is asking for a SampSharp documentation article, use the sampsharp-docs-writer agent to research the source and produce a properly formatted DocFX article.\\n\\n\\n\\n\\nContext: User has just added a new class to SampSharp and wants it documented.\\nuser: \"I just added a new VehiclePool class to SampSharp. Please document it.\"\\nassistant: \"Let me use the Agent tool to launch the sampsharp-docs-writer agent to create documentation for the new VehiclePool class.\"\\n\\nThe user explicitly requested documentation for a SampSharp component, so the sampsharp-docs-writer agent is the right choice.\\n\\n\\n\\n\\nContext: User is reviewing existing docs and finds gaps.\\nuser: \"The getting started guide in docs/ is missing a section on installation. Can you fill it in?\"\\nassistant: \"I'll use the Agent tool to launch the sampsharp-docs-writer agent to add an installation section to the getting started guide.\"\\n\\nThis is a documentation task for SampSharp's docs/ directory, perfect for the sampsharp-docs-writer agent.\\n\\n" +tools: Edit, Glob, Grep, ListMcpResourcesTool, NotebookEdit, Read, ReadMcpResourceTool, TaskCreate, TaskGet, TaskList, TaskStop, TaskUpdate, WebFetch, WebSearch, Write +model: sonnet +color: yellow +memory: project +--- + +You are an expert technical documentation writer specializing in the SampSharp project — a .NET framework for writing SA-MP (San Andreas Multiplayer) game mode scripts in C#. You have deep expertise in DocFX, Microsoft's documentation toolchain, and you produce clear, accurate, and well-structured documentation that helps developers succeed with SampSharp. + +## Project Layout + +You work within a project with this structure: +- **sampsharp-src/** — The SampSharp source code repository + - **sampsharp-src/src/** — The actual C# source code; this is your primary reference for understanding APIs, classes, behavior, and intent + - **sampsharp-src/README.md** — High-level project description and overview +- **docs/** — The documentation root where all articles live; output destination for your work +- **AGENTS.md** — Project preferences, conventions, and style guidance that you MUST consult and follow + +## Mandatory Pre-Work Steps + +Before writing or modifying any documentation, you will: + +1. **Read AGENTS.md** to internalize the project's documentation preferences, tone, formatting rules, and any explicit instructions. Treat these as authoritative. +2. **Read sampsharp-src/README.md** if you haven't established context yet, to ground your understanding of what SampSharp is and its goals. +3. **Explore the relevant source** in sampsharp-src/src/ for any feature, class, or API you are documenting. Never document behavior based on assumption — verify against the actual source code. +4. **Survey existing docs/** structure to understand the established information architecture, file naming, cross-linking, and DocFX layout (toc.yml, index.md, etc.) so new content integrates seamlessly. + +## DocFX Expertise + +You are fluent in DocFX conventions and will apply them correctly: +- Write articles in Markdown (.md) with YAML front matter where appropriate (uid, title, etc.) +- Use DocFX-specific extensions: `[!NOTE]`, `[!TIP]`, `[!WARNING]`, `[!IMPORTANT]`, `[!CAUTION]` alerts +- Use cross-references via `` or `[link text](xref:Uid)` for API references +- Use proper code fence languages (```csharp, ```bash, ```yaml, etc.) +- Update toc.yml files when adding new articles so they appear in navigation +- Follow DocFX's conceptual vs. reference documentation patterns +- Use `[!code-csharp[](path/to/file.cs)]` for code snippet inclusion when appropriate + +## Writing Standards + +Your documentation will: +- **Be accurate first** — every API signature, parameter name, return type, and behavior described must match the actual source in sampsharp-src/src/ +- **Be clear and concise** — favor short sentences, active voice, and direct instructions +- **Be example-driven** — include working C# code samples that demonstrate real usage; samples must compile against the actual SampSharp API +- **Be structured** — use logical heading hierarchy (single H1, then H2/H3 for sections) +- **Be discoverable** — choose descriptive titles, write helpful intros, and cross-link related articles +- **Respect the audience** — assume the reader is a C# developer but may be new to SA-MP scripting; explain SA-MP-specific concepts when first introduced +- **Avoid filler** — do not pad with marketing language or unnecessary preamble + +## Workflow for Each Documentation Task + +1. **Clarify scope**: Confirm what article(s) need to be written, updated, or refactored. If the request is ambiguous, ask one focused question before proceeding. +2. **Research**: Read AGENTS.md (if not already), then explore the relevant source in sampsharp-src/src/ and any existing related docs. +3. **Plan structure**: Outline the article's sections before writing. For larger articles, briefly share the outline with the user if it's a substantial piece. +4. **Write**: Produce the article in the correct location under docs/, following DocFX conventions and AGENTS.md preferences. +5. **Integrate**: Update toc.yml or other navigation files so the new content is reachable. +6. **Self-verify**: After writing, re-check that: + - All API references match the source + - Code samples are syntactically correct C# and use real SampSharp APIs + - DocFX syntax (alerts, xrefs, code fences) is correct + - The article follows AGENTS.md preferences + - Links and cross-references resolve + - The article is placed in a sensible location and added to toc.yml + +## Edge Cases & Escalation + +- If AGENTS.md is missing or unclear on a point, ask the user for clarification rather than guessing. +- If the source in sampsharp-src/src/ contradicts an existing doc, flag the discrepancy and ask whether to update the doc or treat the source as authoritative. +- If a feature is undocumented in source comments and behavior isn't obvious, ask the user rather than fabricating behavior. +- If a requested article would duplicate existing content, propose either consolidating or cross-linking instead. +- Never invent APIs, parameters, or behavior. If you cannot find it in the source, say so. + +## Output Format + +When producing or modifying docs, write the file content directly to disk in the appropriate docs/ location. Summarize what you did at the end (files created/modified, toc.yml updates, any open questions or follow-ups). + +## Agent Memory + +Update your agent memory as you discover SampSharp's architecture, key namespaces, common documentation patterns, DocFX configuration choices used in this project, AGENTS.md preferences, and the docs/ directory organization. This builds up institutional knowledge across conversations. + +Examples of what to record: +- Location and structure of key source files in sampsharp-src/src/ (entities, events, natives, etc.) +- AGENTS.md preferences (tone, formatting rules, naming conventions, mandatory sections) +- docs/ directory layout, toc.yml structure, and where different article categories live +- DocFX configuration specifics (docfx.json settings, custom templates, UID schemes) +- Recurring SampSharp concepts that need consistent explanation (entity system, callbacks, native invocation, etc.) +- Cross-reference UIDs for commonly linked APIs +- Code sample patterns and idioms used across existing docs +- Any gotchas or known documentation gaps to revisit + +You are the authority on SampSharp documentation quality. Produce work that developers will thank you for. + +# Persistent Agent Memory + +You have a persistent, file-based memory system at `D:\projects\sampsharp-docs\.claude\agent-memory\sampsharp-docs-writer\`. This directory already exists — write to it directly with the Write tool (do not run mkdir or check for its existence). + +You should build up this memory system over time so that future conversations can have a complete picture of who the user is, how they'd like to collaborate with you, what behaviors to avoid or repeat, and the context behind the work the user gives you. + +If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry. + +## Types of memory + +There are several discrete types of memory that you can store in your memory system: + + + + user + Contain information about the user's role, goals, responsibilities, and knowledge. Great user memories help you tailor your future behavior to the user's preferences and perspective. Your goal in reading and writing these memories is to build up an understanding of who the user is and how you can be most helpful to them specifically. For example, you should collaborate with a senior software engineer differently than a student who is coding for the very first time. Keep in mind, that the aim here is to be helpful to the user. Avoid writing memories about the user that could be viewed as a negative judgement or that are not relevant to the work you're trying to accomplish together. + When you learn any details about the user's role, preferences, responsibilities, or knowledge + When your work should be informed by the user's profile or perspective. For example, if the user is asking you to explain a part of the code, you should answer that question in a way that is tailored to the specific details that they will find most valuable or that helps them build their mental model in relation to domain knowledge they already have. + + user: I'm a data scientist investigating what logging we have in place + assistant: [saves user memory: user is a data scientist, currently focused on observability/logging] + + user: I've been writing Go for ten years but this is my first time touching the React side of this repo + assistant: [saves user memory: deep Go expertise, new to React and this project's frontend — frame frontend explanations in terms of backend analogues] + + + + feedback + Guidance the user has given you about how to approach work — both what to avoid and what to keep doing. These are a very important type of memory to read and write as they allow you to remain coherent and responsive to the way you should approach work in the project. Record from failure AND success: if you only save corrections, you will avoid past mistakes but drift away from approaches the user has already validated, and may grow overly cautious. + Any time the user corrects your approach ("no not that", "don't", "stop doing X") OR confirms a non-obvious approach worked ("yes exactly", "perfect, keep doing that", accepting an unusual choice without pushback). Corrections are easy to notice; confirmations are quieter — watch for them. In both cases, save what is applicable to future conversations, especially if surprising or not obvious from the code. Include *why* so you can judge edge cases later. + Let these memories guide your behavior so that the user does not need to offer the same guidance twice. + Lead with the rule itself, then a **Why:** line (the reason the user gave — often a past incident or strong preference) and a **How to apply:** line (when/where this guidance kicks in). Knowing *why* lets you judge edge cases instead of blindly following the rule. + + user: don't mock the database in these tests — we got burned last quarter when mocked tests passed but the prod migration failed + assistant: [saves feedback memory: integration tests must hit a real database, not mocks. Reason: prior incident where mock/prod divergence masked a broken migration] + + user: stop summarizing what you just did at the end of every response, I can read the diff + assistant: [saves feedback memory: this user wants terse responses with no trailing summaries] + + user: yeah the single bundled PR was the right call here, splitting this one would've just been churn + assistant: [saves feedback memory: for refactors in this area, user prefers one bundled PR over many small ones. Confirmed after I chose this approach — a validated judgment call, not a correction] + + + + project + Information that you learn about ongoing work, goals, initiatives, bugs, or incidents within the project that is not otherwise derivable from the code or git history. Project memories help you understand the broader context and motivation behind the work the user is doing within this working directory. + When you learn who is doing what, why, or by when. These states change relatively quickly so try to keep your understanding of this up to date. Always convert relative dates in user messages to absolute dates when saving (e.g., "Thursday" → "2026-03-05"), so the memory remains interpretable after time passes. + Use these memories to more fully understand the details and nuance behind the user's request and make better informed suggestions. + Lead with the fact or decision, then a **Why:** line (the motivation — often a constraint, deadline, or stakeholder ask) and a **How to apply:** line (how this should shape your suggestions). Project memories decay fast, so the why helps future-you judge whether the memory is still load-bearing. + + user: we're freezing all non-critical merges after Thursday — mobile team is cutting a release branch + assistant: [saves project memory: merge freeze begins 2026-03-05 for mobile release cut. Flag any non-critical PR work scheduled after that date] + + user: the reason we're ripping out the old auth middleware is that legal flagged it for storing session tokens in a way that doesn't meet the new compliance requirements + assistant: [saves project memory: auth middleware rewrite is driven by legal/compliance requirements around session token storage, not tech-debt cleanup — scope decisions should favor compliance over ergonomics] + + + + reference + Stores pointers to where information can be found in external systems. These memories allow you to remember where to look to find up-to-date information outside of the project directory. + When you learn about resources in external systems and their purpose. For example, that bugs are tracked in a specific project in Linear or that feedback can be found in a specific Slack channel. + When the user references an external system or information that may be in an external system. + + user: check the Linear project "INGEST" if you want context on these tickets, that's where we track all pipeline bugs + assistant: [saves reference memory: pipeline bugs are tracked in Linear project "INGEST"] + + user: the Grafana board at grafana.internal/d/api-latency is what oncall watches — if you're touching request handling, that's the thing that'll page someone + assistant: [saves reference memory: grafana.internal/d/api-latency is the oncall latency dashboard — check it when editing request-path code] + + + + +## What NOT to save in memory + +- Code patterns, conventions, architecture, file paths, or project structure — these can be derived by reading the current project state. +- Git history, recent changes, or who-changed-what — `git log` / `git blame` are authoritative. +- Debugging solutions or fix recipes — the fix is in the code; the commit message has the context. +- Anything already documented in CLAUDE.md files. +- Ephemeral task details: in-progress work, temporary state, current conversation context. + +These exclusions apply even when the user explicitly asks you to save. If they ask you to save a PR list or activity summary, ask what was *surprising* or *non-obvious* about it — that is the part worth keeping. + +## How to save memories + +Saving a memory is a two-step process: + +**Step 1** — write the memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format: + +```markdown +--- +name: {{short-kebab-case-slug}} +description: {{one-line summary — used to decide relevance in future conversations, so be specific}} +metadata: + type: {{user, feedback, project, reference}} +--- + +{{memory content — for feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines. Link related memories with [[their-name]].}} +``` + +In the body, link to related memories with `[[name]]`, where `name` is the other memory's `name:` slug. Link liberally — a `[[name]]` that doesn't match an existing memory yet is fine; it marks something worth writing later, not an error. + +**Step 2** — add a pointer to that file in `MEMORY.md`. `MEMORY.md` is an index, not a memory — each entry should be one line, under ~150 characters: `- [Title](file.md) — one-line hook`. It has no frontmatter. Never write memory content directly into `MEMORY.md`. + +- `MEMORY.md` is always loaded into your conversation context — lines after 200 will be truncated, so keep the index concise +- Keep the name, description, and type fields in memory files up-to-date with the content +- Organize memory semantically by topic, not chronologically +- Update or remove memories that turn out to be wrong or outdated +- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one. + +## When to access memories +- When memories seem relevant, or the user references prior-conversation work. +- You MUST access memory when the user explicitly asks you to check, recall, or remember. +- If the user says to *ignore* or *not use* memory: Do not apply remembered facts, cite, compare against, or mention memory content. +- Memory records can become stale over time. Use memory as context for what was true at a given point in time. Before answering the user or building assumptions based solely on information in memory records, verify that the memory is still correct and up-to-date by reading the current state of the files or resources. If a recalled memory conflicts with current information, trust what you observe now — and update or remove the stale memory rather than acting on it. + +## Before recommending from memory + +A memory that names a specific function, file, or flag is a claim that it existed *when the memory was written*. It may have been renamed, removed, or never merged. Before recommending it: + +- If the memory names a file path: check the file exists. +- If the memory names a function or flag: grep for it. +- If the user is about to act on your recommendation (not just asking about history), verify first. + +"The memory says X exists" is not the same as "X exists now." + +A memory that summarizes repo state (activity logs, architecture snapshots) is frozen in time. If the user asks about *recent* or *current* state, prefer `git log` or reading the code over recalling the snapshot. + +## Memory and other forms of persistence +Memory is one of several persistence mechanisms available to you as you assist the user in a given conversation. The distinction is often that memory can be recalled in future conversations and should not be used for persisting information that is only useful within the scope of the current conversation. +- When to use or update a plan instead of memory: If you are about to start a non-trivial implementation task and would like to reach alignment with the user on your approach you should use a Plan rather than saving this information to memory. Similarly, if you already have a plan within the conversation and you have changed your approach persist that change by updating the plan rather than saving a memory. +- When to use or update tasks instead of memory: When you need to break your work in current conversation into discrete steps or keep track of your progress use tasks instead of saving to memory. Tasks are great for persisting information about the work that needs to be done in the current conversation, but memory should be reserved for information that will be useful in future conversations. + +- Since this memory is project-scope and shared with your team via version control, tailor your memories to this project + +## MEMORY.md + +Your MEMORY.md is currently empty. When you save new memories, they will appear here. diff --git a/docfx.json b/docfx.json index af43247..dc3b75e 100644 --- a/docfx.json +++ b/docfx.json @@ -19,7 +19,7 @@ "content": [ { "files": ["**/*.{md,yml}"], - "exclude": ["_site/**", "sampsharp-src/**"] + "exclude": ["_site/**", "sampsharp-src/**", ".claude/**", ".github/**"] } ], "resource": [ diff --git a/docs/features/dialog-menus.md b/docs/features/dialog-menus.md index 6454d1c..bfefc33 100644 --- a/docs/features/dialog-menus.md +++ b/docs/features/dialog-menus.md @@ -5,14 +5,423 @@ uid: dialogs-menus # Dialogs and Menus +SampSharp exposes two distinct UI systems for presenting choices to players: **dialogs** and **menus**. Dialogs are pop-up windows provided by SA-MP. Menus are the overlay menus built into GTA: San Andreas itself, repurposed by SA-MP for scripting. + +## Dialogs + +Dialogs are displayed using . The service accepts typed dialog objects and returns strongly-typed response structs — you do not work with raw dialog IDs or string callbacks. + +### Dialog types + +SampSharp provides four dialog classes, each covering a different interaction style: + +| Class | Description | +|---|---| +| `MessageDialog` | Body text with one or two buttons. | +| `InputDialog` | Text input field below a body message. Set `IsPassword = true` for masked input. | +| `ListDialog` | Scrollable list of selectable text rows. | +| `TablistDialog` | Rows split into columns. Pass column headers to label them. | + +### Displaying a dialog + +Inject `IDialogService` into any event handler or system method and call `Show` or `ShowAsync`. + +**Callback style** — useful when you do not need to await a result: + +```csharp +public class MySystem : ISystem +{ + [Event] + public void OnPlayerSpawn(Player player, IDialogService dialogs) + { + var dialog = new MessageDialog( + caption: "Welcome", + content: "Press OK to continue.", + button1: "OK" + ); + + dialogs.Show(player, dialog, response => + { + // response.Response is DialogResponse.LeftButton or RightButtonOrCancel + player.SendClientMessage($"You clicked: {response.Response}"); + }); + } +} +``` + +**Async style** — awaitable, works naturally with `async` event handlers: + +```csharp +[Event] +public async Task OnPlayerSpawn(Player player, IDialogService dialogs) +{ + var dialog = new MessageDialog("Welcome", "Press OK to continue.", "OK"); + var response = await dialogs.ShowAsync(player, dialog); + + if (response.Response == DialogResponse.LeftButton) + { + player.SendClientMessage("You clicked OK."); + } +} +``` + +> [!NOTE] +> If the player disconnects while a dialog is open, the response arrives with `DialogResponse.Disconnected`. Always guard against this in handlers that act on player state. + +### The DialogResponse enum + +Every dialog response carries a `DialogResponse` value describing how the player closed the dialog: + +| Value | Meaning | +|---|---| +| `LeftButton` | Player clicked the primary (left) button. | +| `RightButtonOrCancel` | Player clicked the secondary button, or dismissed the dialog with Escape. | +| `Disconnected` | Player disconnected before responding. | + +Each dialog class returns its own response struct with this value plus any fields relevant to that dialog type. Those structs are described in the per-type sections below. + +### Message dialogs + +A message dialog shows body text and up to two buttons. Pass `null` for `button2` to show only one button. + +The response struct is minimal — only the `Response` value matters: + +```csharp +public struct MessageDialogResponse +{ + public DialogResponse Response { get; } +} +``` + +```csharp +var dialog = new MessageDialog( + caption: "Server Rules", + content: "No cheating. No griefing.\n\nDo you agree?", + button1: "I Agree", + button2: "Decline" +); + +dialogs.Show(player, dialog, response => +{ + if (response.Response == DialogResponse.LeftButton) + { + player.SendClientMessage("Welcome aboard!"); + } + else + { + player.Kick(); + } +}); +``` + +### Input dialogs + +An input dialog adds a text field below the body. Set `IsPassword = true` to mask the characters the player types. + +The response struct adds the text the player typed: + +```csharp +public struct InputDialogResponse +{ + public DialogResponse Response { get; } + public string? InputText { get; } +} +``` + +`InputText` contains whatever the player typed when `Response == LeftButton`. It is `null` when the player disconnected. + +```csharp +// Plain text input +var nameDialog = new InputDialog( + caption: "Change Name", + content: "Enter your new name:", + button1: "OK", + button2: "Cancel" +); + +var response = await dialogs.ShowAsync(player, nameDialog); + +if (response.Response == DialogResponse.LeftButton && !string.IsNullOrWhiteSpace(response.InputText)) +{ + player.SetName(response.InputText); + player.SendClientMessage($"Name changed to {player.Name}."); +} +``` + +```csharp +// Password input (characters are masked) +var pinDialog = new InputDialog +{ + Caption = "Enter PIN", + Content = "Enter your security PIN:", + Button1 = "Submit", + Button2 = "Cancel", + IsPassword = true +}; +``` + +### List dialogs + +A list dialog shows a scrollable list of rows. Each row can carry a `Tag` — an arbitrary object — that is returned in the response so you can associate data without index arithmetic. + +The response struct surfaces the selected row: + +```csharp +public struct ListDialogResponse +{ + public DialogResponse Response { get; } + public int ItemIndex { get; } // -1 if nothing was selected + public ListDialogRow? Item { get; } // null if nothing was selected +} +``` + +`Item.Tag` carries the arbitrary object you attached to the row when building the dialog. + +```csharp +var dialog = new ListDialog("Select a vehicle", button1: "Spawn", button2: "Cancel"); + +dialog.Add("Infernus", tag: VehicleModelType.Infernus); +dialog.Add("Turismo", tag: VehicleModelType.Turismo); +dialog.Add("Cheetah", tag: VehicleModelType.Cheetah); + +var response = await dialogs.ShowAsync(player, dialog); + +if (response.Response == DialogResponse.LeftButton && response.Item != null) +{ + var model = (VehicleModelType)response.Item.Tag!; + worldService.CreateVehicle(model, player.Position, player.Angle, -1, -1); + player.SendClientMessage($"Spawned a {model}."); +} +``` + +You can also add plain text rows without a tag: + +```csharp +dialog.Add("Row text"); +``` + +Or construct a `ListDialogRow` manually for fine-grained control: + +```csharp +dialog.Add(new ListDialogRow("Infernus") { Tag = VehicleModelType.Infernus }); +``` + +### Tablist dialogs + +A tablist dialog organises rows into columns. Pass a column count to get a plain tablist, or pass column header strings to enable column headers. + +The response struct mirrors the list dialog response, but `Item.Columns` exposes the column values of the selected row: + +```csharp +public struct TablistDialogResponse +{ + public DialogResponse Response { get; } + public int ItemIndex { get; } + public TablistDialogRow? Item { get; } +} +``` + +**Without headers (plain tablist):** + +```csharp +var dialog = new TablistDialog("Online Players", "View", "Close", columnCount: 2); +dialog.Add("Johnny", "100"); +dialog.Add("Sarah", "250"); +``` + +**With headers:** + +```csharp +var dialog = new TablistDialog( + caption: "Online Players", + button1: "View", + button2: "Close", + columnHeader1: "Name", + columnHeader2: "Score" +); + +foreach (var onlinePlayer in onlinePlayers) +{ + dialog.Add(new TablistDialogRow(onlinePlayer.Name, onlinePlayer.Score.ToString()) + { + Tag = onlinePlayer + }); +} + +var response = await dialogs.ShowAsync(player, dialog); + +if (response.Response == DialogResponse.LeftButton && response.Item != null) +{ + var selected = (Player)response.Item.Tag!; + player.SendClientMessage($"You selected {selected.Name}."); +} +``` + +You can also add rows by passing column strings directly: + +```csharp +dialog.Add("Johnny", "100"); +``` + +> [!TIP] +> `TablistDialogRow.Tag` is the cleanest way to attach typed data to a row. This avoids recalculating the selected record by index when the response arrives. + +### Chaining dialogs + +Because `ShowAsync` returns a `Task`, you can chain multiple dialogs in a single async method to build simple multi-step flows: + +```csharp +[Event] +public async Task OnPlayerSpawn(Player player, IDialogService dialogs) +{ + var rules = new MessageDialog("Rules", "Do you accept the rules?", "Yes", "No"); + var rulesResponse = await dialogs.ShowAsync(player, rules); + + if (rulesResponse.Response != DialogResponse.LeftButton) + { + player.Kick(); + return; + } + + var name = new InputDialog("Setup", "Enter your display name:", "OK"); + var nameResponse = await dialogs.ShowAsync(player, name); + + if (nameResponse.Response == DialogResponse.LeftButton && + !string.IsNullOrWhiteSpace(nameResponse.InputText)) + { + player.SetName(nameResponse.InputText); + } +} +``` + +> [!NOTE] +> Showing a new dialog to a player automatically dismisses any dialog already open for that player. + +--- + +## Menus + +SA-MP menus are an in-game screen — distinct from dialogs — that display one or two columns of selectable items. The player navigates rows with the up and down arrow keys, selects the current row with Space, and exits the menu with Enter. + +### Creating a menu + +Use `IWorldService.CreateMenu` to create a menu entity. Specify the title, screen position (in 2D screen coordinates), and column widths in pixels. + +```csharp +[Event] +public void OnGameModeInit(IWorldService worldService) +{ + var menu = worldService.CreateMenu( + title: "Actions", + position: new Vector2(200, 100), + col0Width: 200 + ); + + menu.AddItem("Buy weapon"); + menu.AddItem("Heal"); + menu.AddItem("Quit"); +} +``` + +For a two-column menu, supply a second column width: + +```csharp +var menu = worldService.CreateMenu( + title: "Shop", + position: new Vector2(200, 100), + col0Width: 150, + col1Width: 80 +); + +menu.Col0Header = "Item"; +menu.Col1Header = "Price"; + +menu.AddItem("AK-47", "$500"); +menu.AddItem("Shotgun", "$300"); +menu.AddItem("Health", "$100"); +``` + > [!NOTE] -> This article is coming soon! Check back later, or feel free to open an issue if you have questions. - - +> Menus support a maximum of 12 items. Items past the 12th are not displayed. Each item text may be at most 31 characters. + +### Showing and hiding a menu + +Call `Show(player)` to display the menu to a specific player, and `Hide(player)` to dismiss it: + +```csharp +menu.Show(player); +// later... +menu.Hide(player); +``` + +### Handling menu events + +Listen for `OnPlayerSelectedMenuRow` and `OnPlayerExitedMenu` in an : + +```csharp +public class MenuEventSystem : ISystem +{ + private readonly Menu _actionsMenu; + + public MenuEventSystem(IWorldService worldService) + { + _actionsMenu = worldService.CreateMenu("Actions", new Vector2(200, 100), 200); + _actionsMenu.AddItem("Buy weapon"); + _actionsMenu.AddItem("Heal"); + _actionsMenu.AddItem("Quit"); + } + + [Event] + public void OnPlayerSelectedMenuRow(Player player, byte row) + { + switch (row) + { + case 0: + player.SendClientMessage("You chose: Buy weapon"); + break; + case 1: + player.Health = 100; + player.SendClientMessage("You have been healed."); + break; + case 2: + player.SendClientMessage("Goodbye!"); + player.Kick(); + break; + } + + _actionsMenu.Hide(player); + } + + [Event] + public void OnPlayerExitedMenu(Player player) + { + // Player pressed Escape to close the menu + player.SendClientMessage("Menu closed."); + } +} +``` + +> [!TIP] +> `OnPlayerSelectedMenuRow` fires globally — it is not scoped to a specific menu instance. When your game mode shows different menus to the same player, attach a custom [component](xref:entities-components) to the player that records which menu is currently visible, and read it in the event handler to dispatch the row to the right code. + +### Disabling rows + +Call `DisableRow(int row)` to grey out a row and make it unselectable. Use `IsRowEnabled(int row)` to check whether a row is still active. + +```csharp +menu.DisableRow(2); // grey out the third row +``` + +### Disabling the entire menu + +`Disable()` prevents any row from being selected. Check the current state with the `IsEnabled` property. + +```csharp +if (menu.IsEnabled) +{ + menu.Disable(); +} +``` + +> [!TIP] +> A `Menu` is a global entity — the same instance can be shown to different players simultaneously by calling `Show(player)` for each player. Each player can see only one menu at a time. diff --git a/docs/features/players.md b/docs/features/players.md index c88ce5b..a5f909e 100644 --- a/docs/features/players.md +++ b/docs/features/players.md @@ -1,5 +1,5 @@ --- -title: Working with Players +title: Players uid: players --- diff --git a/docs/features/timers.md b/docs/features/timers.md index 6bf72bd..73d99c7 100644 --- a/docs/features/timers.md +++ b/docs/features/timers.md @@ -1,5 +1,5 @@ --- -title: Timers and Scheduling +title: Timers uid: timers --- diff --git a/sampsharp-src b/sampsharp-src index b1bb796..b9a63ef 160000 --- a/sampsharp-src +++ b/sampsharp-src @@ -1 +1 @@ -Subproject commit b1bb7968394a820a32221bc6dc43ab431029bd41 +Subproject commit b9a63efcf7e990468b211c4876defd48b445788f