diff --git a/.claude/agent-notes.md b/.claude/agent-notes.md new file mode 100644 index 0000000..364d1b5 --- /dev/null +++ b/.claude/agent-notes.md @@ -0,0 +1,17 @@ +# Agent Notes — Corrections & Standing Directives + +This file is the running log of the maintainer's corrections and standing **always/never** +directives for this repo. It is the source of truth for *how* to work here. + +**Read this file at the start of every work session, before doing any work.** + +**Append one line per directive, proactively (without being asked), whenever the maintainer makes +a correction or gives an always/never instruction.** Newest lines go at the bottom. Keep each +entry to a single line; if a directive supersedes an earlier one, update or remove the stale line +rather than leaving both. + +--- + + diff --git a/.claude/skills/claude-handoff/SKILL.md b/.claude/skills/claude-handoff/SKILL.md new file mode 100644 index 0000000..88ce8be --- /dev/null +++ b/.claude/skills/claude-handoff/SKILL.md @@ -0,0 +1,18 @@ +--- +name: claude-handoff +description: Hand the current conversation off to a fresh background agent that picks up the work immediately. +argument-hint: "What will the next session be used for?" +disable-model-invocation: true +--- + +Write a handoff summary of the current conversation so a fresh agent can continue the work. Instead of saving it, launch a background agent seeded with the summary as its prompt: `claude --bg --name "" ""`. It starts in the current working directory and returns immediately; the user manages it with `claude agents`. + +Always pass `-n`/`--name` with a descriptive name (e.g. `--name "Fix login bug"`) — it sets the display name shown in the job list, session picker, and terminal title. + +Include a "suggested skills" section in the summary, which suggests skills that the agent should invoke. + +Do not duplicate content already captured in other artifacts (PRDs, plans, ADRs, issues, commits, diffs). Reference them by path or URL instead. + +Redact any sensitive information, such as API keys, passwords, or personally identifiable information — the summary becomes the agent's prompt. + +If the user passed arguments, treat them as a description of what the next session will focus on and tailor the summary accordingly. diff --git a/.claude/skills/claude-handoff/agents/openai.yaml b/.claude/skills/claude-handoff/agents/openai.yaml new file mode 100644 index 0000000..0a7aa5d --- /dev/null +++ b/.claude/skills/claude-handoff/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Claude Handoff" + short_description: "Hand off to a background agent" +policy: + allow_implicit_invocation: false diff --git a/.claude/skills/grill-me/SKILL.md b/.claude/skills/grill-me/SKILL.md new file mode 100644 index 0000000..9470cfc --- /dev/null +++ b/.claude/skills/grill-me/SKILL.md @@ -0,0 +1,7 @@ +--- +name: grill-me +description: A relentless interview to sharpen a plan or design. +disable-model-invocation: true +--- + +Run a `/grilling` session. diff --git a/.claude/skills/grill-me/agents/openai.yaml b/.claude/skills/grill-me/agents/openai.yaml new file mode 100644 index 0000000..4d6fb0c --- /dev/null +++ b/.claude/skills/grill-me/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Grill Me" + short_description: "Sharpen a plan through interview" +policy: + allow_implicit_invocation: false diff --git a/.claude/skills/grill-with-docs/SKILL.md b/.claude/skills/grill-with-docs/SKILL.md new file mode 100644 index 0000000..bed05d2 --- /dev/null +++ b/.claude/skills/grill-with-docs/SKILL.md @@ -0,0 +1,7 @@ +--- +name: grill-with-docs +description: A relentless interview to sharpen a plan or design, which also creates docs (ADR's and glossary) as we go. +disable-model-invocation: true +--- + +Run a `/grilling` session, using the `/domain-modeling` skill. diff --git a/.claude/skills/grill-with-docs/agents/openai.yaml b/.claude/skills/grill-with-docs/agents/openai.yaml new file mode 100644 index 0000000..5dbe278 --- /dev/null +++ b/.claude/skills/grill-with-docs/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Grill with Docs" + short_description: "Grill a design and write its docs" +policy: + allow_implicit_invocation: false diff --git a/.claude/skills/grilling/SKILL.md b/.claude/skills/grilling/SKILL.md new file mode 100644 index 0000000..52d8eb3 --- /dev/null +++ b/.claude/skills/grilling/SKILL.md @@ -0,0 +1,12 @@ +--- +name: grilling +description: Grill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases. +--- + +Interview me relentlessly about every aspect of this until we reach a shared understanding. Walk down each branch of the decision tree, resolving dependencies between decisions one-by-one. For each question, provide your recommended answer. + +Ask the questions one at a time, waiting for feedback on each question before continuing. Asking multiple questions at once is bewildering. + +If a *fact* can be found by exploring the environment (filesystem, tools, etc.), look it up rather than asking me. The *decisions*, though, are mine — put each one to me and wait for my answer. + +Do not act on it until I confirm we have reached a shared understanding. diff --git a/.claude/skills/grilling/agents/openai.yaml b/.claude/skills/grilling/agents/openai.yaml new file mode 100644 index 0000000..85b1260 --- /dev/null +++ b/.claude/skills/grilling/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Grilling" + short_description: "Stress-test thinking one question at a time" diff --git a/.claude/skills/handoff/SKILL.md b/.claude/skills/handoff/SKILL.md new file mode 100644 index 0000000..043d9e1 --- /dev/null +++ b/.claude/skills/handoff/SKILL.md @@ -0,0 +1,16 @@ +--- +name: handoff +description: Compact the current conversation into a handoff document for another agent to pick up. +argument-hint: "What will the next session be used for?" +disable-model-invocation: true +--- + +Write a handoff document summarising the current conversation so a fresh agent can continue the work. Save to the temporary directory of the user's OS - not the current workspace. + +Include a "suggested skills" section in the document, which suggests skills that the agent should invoke. + +Do not duplicate content already captured in other artifacts (specs, plans, ADRs, issues, commits, diffs). Reference them by path or URL instead. + +Redact any sensitive information, such as API keys, passwords, or personally identifiable information. + +If the user passed arguments, treat them as a description of what the next session will focus on and tailor the doc accordingly. diff --git a/.claude/skills/handoff/agents/openai.yaml b/.claude/skills/handoff/agents/openai.yaml new file mode 100644 index 0000000..6e1d8da --- /dev/null +++ b/.claude/skills/handoff/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Handoff" + short_description: "Compact a conversation into a handoff" +policy: + allow_implicit_invocation: false diff --git a/.claude/skills/loop-me/SKILL.md b/.claude/skills/loop-me/SKILL.md new file mode 100644 index 0000000..3a8c52c --- /dev/null +++ b/.claude/skills/loop-me/SKILL.md @@ -0,0 +1,32 @@ +--- +name: loop-me +description: Grill me about specs for the workflows I want to build, within this workspace. +disable-model-invocation: true +argument-hint: "A workflow to design, or nothing to go find one" +--- + +Run a stateful `/grilling` session whose only output is **workflow** specs. Use the grilling discipline — relentless, one question at a time, a recommended answer attached to each — aimed at the vocabulary and goal below. Create, edit, and delete specs as the grilling resolves things. + +## The loop lens + +A **loop** is a recurring pattern in the user's life: their career, their week, their morning, a single repeated activity. Picturing a life as loops within loops reveals how predictable its activities really are — which is what makes them worth **delegating**. Use the lens to find loops worth specifying, and propose ones the user hasn't noticed. + +A **workflow** is the spec of one loop, made real. You run a workflow on a loop — the loop is its running instantiation. Workflows live in `workflows/*.md` and are the source of truth. + +## Vocabulary + +A shared language, reached for only when a workflow calls for it — never a checklist. **Mandate nothing structural**: a workflow needs no AI, no checkpoint, and no schedule unless the grilling shows it does. + +- **Trigger** — what fires each run: an **event** (a new email, a new issue) or a **schedule** (every morning). Event-triggering is usually the more efficient. +- **Checkpoint** — a human-in-the-loop point where the user is asked to verify or decide. Some workflows have none and run autonomously; some use no AI at all. +- **Push right** — defer the checkpoint as far as it will go. Do maximal work before involving the human, so they are asked once, late, with everything prepared. +- **Brief** — what a checkpoint presents: a tight, decision-ready summary — what was produced, why, and a link down to the asset itself — never the raw output. The user reads a brief, not a draft. Speed of review is imperative. + +## Definition of done + +A workflow spec is done when an implementer agent could build it without asking a single question. Grill until then; nothing is done while a question remains. + +## The workspace + +- `workflows/*.md` — one spec per workflow. +- `NOTES.md` — raw notes on the user's world: the tools they use, the channels they process, and their own terminology for both. When it is empty or thin, interview them about their world before specifying anything. Sharpen fuzzy terms into canonical ones as they surface, and record them here. diff --git a/.claude/skills/loop-me/agents/openai.yaml b/.claude/skills/loop-me/agents/openai.yaml new file mode 100644 index 0000000..1a4f411 --- /dev/null +++ b/.claude/skills/loop-me/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Loop Me" + short_description: "Spec the workflows you want to build" +policy: + allow_implicit_invocation: false diff --git a/.claude/skills/research/SKILL.md b/.claude/skills/research/SKILL.md new file mode 100644 index 0000000..0ba594a --- /dev/null +++ b/.claude/skills/research/SKILL.md @@ -0,0 +1,12 @@ +--- +name: research +description: Investigate a question against high-trust primary sources and capture the findings as a Markdown file in the repo. Use when the user wants a topic researched, docs or API facts gathered, or reading legwork delegated to a background agent. +--- + +Spin up a **background agent** to do the research, so you keep working while it reads. + +Its job: + +1. Investigate the question against **primary sources** — official docs, source code, specs, first-party APIs — not a secondary write-up of them. Follow every claim back to the source that owns it. +2. Write the findings to a single Markdown file, citing each claim's source. +3. Save it where the repo already keeps such notes; match the existing convention, and if there is none, put it somewhere sensible and say where. diff --git a/.claude/skills/research/agents/openai.yaml b/.claude/skills/research/agents/openai.yaml new file mode 100644 index 0000000..e18b96c --- /dev/null +++ b/.claude/skills/research/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Research" + short_description: "Research from high-trust sources" diff --git a/.claude/skills/to-spec/SKILL.md b/.claude/skills/to-spec/SKILL.md new file mode 100644 index 0000000..f3cca8d --- /dev/null +++ b/.claude/skills/to-spec/SKILL.md @@ -0,0 +1,75 @@ +--- +name: to-spec +description: Turn the current conversation into a spec and publish it to the project issue tracker — no interview, just synthesis of what you've already discussed. +disable-model-invocation: true +--- + +This skill takes the current conversation context and codebase understanding and produces a spec (you may know this document as a PRD). Do NOT interview the user — just synthesize what you already know. + +The issue tracker and triage label vocabulary should have been provided to you — run `/setup-matt-pocock-skills` if not. + +## Process + +1. Explore the repo to understand the current state of the codebase, if you haven't already. Use the project's domain glossary vocabulary throughout the spec, and respect any ADRs in the area you're touching. + +2. Sketch out the seams at which you're going to test the feature. Existing seams should be preferred to new ones. Use the highest seam possible. If new seams are needed, propose them at the highest point you can. The fewer seams across the codebase, the better - the ideal number is one. + +Check with the user that these seams match their expectations. + +3. Write the spec using the template below, then publish it to the project issue tracker. Apply the `ready-for-agent` triage label - no need for additional triage. + + + +## Problem Statement + +The problem that the user is facing, from the user's perspective. + +## Solution + +The solution to the problem, from the user's perspective. + +## User Stories + +A LONG, numbered list of user stories. Each user story should be in the format of: + +1. As an , I want a , so that + + +1. As a mobile bank customer, I want to see balance on my accounts, so that I can make better informed decisions about my spending + + +This list of user stories should be extremely extensive and cover all aspects of the feature. + +## Implementation Decisions + +A list of implementation decisions that were made. This can include: + +- The modules that will be built/modified +- The interfaces of those modules that will be modified +- Technical clarifications from the developer +- Architectural decisions +- Schema changes +- API contracts +- Specific interactions + +Do NOT include specific file paths or code snippets. They may end up being outdated very quickly. + +Exception: if a prototype produced a snippet that encodes a decision more precisely than prose can (state machine, reducer, schema, type shape), inline it within the relevant decision and note briefly that it came from a prototype. Trim to the decision-rich parts — not a working demo, just the important bits. + +## Testing Decisions + +A list of testing decisions that were made. Include: + +- A description of what makes a good test (only test external behavior, not implementation details) +- Which modules will be tested +- Prior art for the tests (i.e. similar types of tests in the codebase) + +## Out of Scope + +A description of the things that are out of scope for this spec. + +## Further Notes + +Any further notes about the feature. + + diff --git a/.claude/skills/to-spec/agents/openai.yaml b/.claude/skills/to-spec/agents/openai.yaml new file mode 100644 index 0000000..549e6f7 --- /dev/null +++ b/.claude/skills/to-spec/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "To Spec" + short_description: "Turn a conversation into a spec" +policy: + allow_implicit_invocation: false diff --git a/.claude/skills/to-tickets/SKILL.md b/.claude/skills/to-tickets/SKILL.md new file mode 100644 index 0000000..23140c5 --- /dev/null +++ b/.claude/skills/to-tickets/SKILL.md @@ -0,0 +1,107 @@ +--- +name: to-tickets +description: Break a plan, spec, or the current conversation into a set of tracer-bullet tickets, each declaring its blocking edges, published to the configured tracker — edges as text in one file per ticket locally, or native blocking links on a real tracker. +disable-model-invocation: true +--- + +# To Tickets + +Break a plan, spec, or conversation into a set of **tickets** — tracer-bullet vertical slices, each declaring the tickets that **block** it. + +The issue tracker and triage label vocabulary should have been provided to you — run `/setup-matt-pocock-skills` if not. + +## Process + +### 1. Gather context + +Work from whatever is already in the conversation context. If the user passes a reference (a spec path, an issue number or URL) as an argument, fetch it and read its full body and comments. + +### 2. Explore the codebase (optional) + +If you have not already explored the codebase, do so to understand the current state of the code. Ticket titles and descriptions should use the project's domain glossary vocabulary, and respect ADRs in the area you're touching. + +Look for opportunities to prefactor the code to make the implementation easier. "Make the change easy, then make the easy change." + +### 3. Draft vertical slices + +Break the work into **tracer bullet** tickets. + + + +- Each slice cuts a narrow but COMPLETE path through every layer (schema, API, UI, tests) — vertical, NOT a horizontal slice of one layer +- A completed slice is demoable or verifiable on its own +- Each slice is sized to fit in a single fresh context window +- Any prefactoring should be done first + + + +Give each ticket its **blocking edges** — the other tickets that must complete before it can start. A ticket with no blockers can start immediately. + +**Wide refactors are the exception to vertical slicing.** A **wide refactor** is one mechanical change — rename a column, retype a shared symbol — whose **blast radius** fans across the whole codebase, so a single edit breaks thousands of call sites at once and no vertical slice can land green. Don't force it into a tracer bullet; sequence it as **expand–contract**. First expand: add the new form beside the old so nothing breaks. Then migrate the call sites over in batches sized by blast radius (per package, per directory), each batch its own ticket blocked by the expand, keeping CI green batch to batch because the old form still exists. Finally contract: delete the old form once no caller remains, in a ticket blocked by every migrate batch. When even the batches can't stay green alone, keep the sequence but let them share an integration branch that all block a final integrate-and-verify ticket — green is promised only there. + +### 4. Quiz the user + +Present the proposed breakdown as a numbered list. For each ticket, show: + +- **Title**: short descriptive name +- **Blocked by**: which other tickets (if any) must complete first +- **What it delivers**: the end-to-end behaviour this ticket makes work + +Ask the user: + +- Does the granularity feel right? (too coarse / too fine) +- Are the blocking edges correct — does each ticket only depend on tickets that genuinely gate it? +- Should any tickets be merged or split further? + +Iterate until the user approves the breakdown. + +### 5. Publish the tickets to the configured tracker + +Publish the approved tickets. **How** depends on the tracker `/setup-matt-pocock-skills` configured — the tickets are the same either way, only the shape of the blocking edges changes: + +- **Local files** → write one file per ticket under `.scratch//issues/-.md`, numbered from `01` in dependency order (blockers first). Each file's "Blocked by" lists the numbers/titles it depends on. Use the per-ticket file template below — one ticket per file, never a single combined file. +- **A real issue tracker (GitHub, Linear, …)** → publish one issue per ticket in dependency order (blockers first) so each ticket's blocking edges can reference real identifiers. Use the platform's native blocking / sub-issue relationship where it has one; otherwise set each ticket's "Blocked by" to the blocking issues. Apply the `ready-for-agent` triage label unless instructed otherwise — the tickets are agent-grabbable by construction. + +Work the **frontier**: any ticket whose blockers are all done. For a purely linear chain that means top to bottom. + +Do NOT close or modify any parent issue. + + + +# + +**What to build:** the end-to-end behaviour this ticket makes work, from the user's perspective — not a layer-by-layer implementation list. + +**Blocked by:** the numbers/titles of the tickets that gate this one, or "None — can start immediately". + +**Status:** ready-for-agent + +- [ ] Acceptance criterion 1 +- [ ] Acceptance criterion 2 + + + + + +## Parent + +A reference to the parent issue on the tracker (if the source was an existing issue, otherwise omit this section). + +## What to build + +The end-to-end behaviour this ticket makes work, from the user's perspective — not layer-by-layer implementation. + +## Acceptance criteria + +- [ ] Criterion 1 +- [ ] Criterion 2 + +## Blocked by + +- A reference to each blocking ticket, or "None — can start immediately". + + + +In either form, avoid specific file paths or code snippets — they go stale fast. Exception: if a prototype produced a snippet that encodes a decision more precisely than prose can (state machine, reducer, schema, type shape), inline it and note briefly that it came from a prototype. Trim to the decision-rich parts — not a working demo, just the important bits. + +Work the frontier one ticket at a time with `/implement`, clearing context between tickets. diff --git a/.claude/skills/to-tickets/agents/openai.yaml b/.claude/skills/to-tickets/agents/openai.yaml new file mode 100644 index 0000000..24605a5 --- /dev/null +++ b/.claude/skills/to-tickets/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "To Tickets" + short_description: "Split a plan into tracer-bullet tickets" +policy: + allow_implicit_invocation: false diff --git a/.claude/skills/writing-great-skills/GLOSSARY.md b/.claude/skills/writing-great-skills/GLOSSARY.md new file mode 100644 index 0000000..0269ca8 --- /dev/null +++ b/.claude/skills/writing-great-skills/GLOSSARY.md @@ -0,0 +1,201 @@ +# Glossary — Building Great Skills + +The domain model for what makes a skill great. A skill exists to wrangle determinism out of a stochastic system; the root virtue is **Predictability**, and every term below is a lever on it. This is the disclosed reference for [`writing-great-skills`](SKILL.md). + +The terms are grouped by axis: **Invocation** (how a skill is reached), **Information Hierarchy** (how its content is arranged), **Steering** (how the agent's runtime behaviour is shaped), and **Pruning** (how it is kept lean). Each **failure mode** lives beside the lever that cures it, tagged _failure mode_. + +**Bold terms** in any definition are themselves defined in this glossary; find them by their heading. + +## Predictability + +The degree to which a skill makes the agent behave the same _way_ on every run — the same process, not the same output (a brainstorming skill should _predictably_ diverge; its tokens vary, its behaviour doesn't). The root virtue every other term serves — cost and maintainability are symptoms of it, not rivals. + +_Avoid_: consistency, reliability, robustness, output-determinism + +## Invocation + +How a skill is reached — and the two loads you pay for the choice. + +### Model-Invoked + +A skill that keeps its **description** field, so the agent can see it and fire it autonomously — and the human can still type its name, so model-invocation always _includes_ user reach. There is no model-only state: a description only ever _adds_ agent discovery, never removes the human's. Pays a permanent **context load** on every turn in exchange for that discoverability. Reachable by other skills, because the description that makes it agent-discoverable makes it invocable. A model-invoked skill whose content is all **reference** is also one home for shared reference: another skill can invoke it, so reference needed by several skills lives in one place. Pick model-invocation only when the agent must reach the skill on its own; if it never fires except by hand, drop the description and pay no context load. + +_Avoid_: ability, tool, capability + +### User-Invoked + +A skill with its **description** stripped — invisible to the agent and reachable only by the human typing its name (user-_only_, where **model-invoked** is user-_and-agent_). Trades agent-discoverability for zero **context load**. Because it has no description, nothing but the human can reach it: no other skill can fire it. + +_Avoid_: procedure, workflow, command + +### Description + +The skill's machine-readable trigger, and the one **context pointer** a **model-invoked** skill is forced to keep loaded at all times. Its mere presence _is_ the invocation axis: keep it and the skill is model-invoked (and reachable by other skills); delete it and the skill is **user-invoked**, reachable only by the human. The source of a model-invoked skill's **context load**. + +_Avoid_: frontmatter, summary + +### Context Pointer + +A reference held in the agent's context that names some out-of-context material and encodes the condition for reaching it. The **description** is the top-level context pointer (context window → skill); pointers to disclosed files are the same object one level down. Its wording, not the target, decides _when_ the agent reaches — and _how reliably_. A must-have target behind a weakly worded pointer is a variance bug: fix the wording first, and inline the material only if sharpening fails. + +_Avoid_: link, reference, import + +### Context Load + +The cost a **model-invoked** skill imposes on the agent's context window — its **description**, always loaded, spending both tokens and attention. What **user-invoked** skills escape by having no description, and the brake on splitting into more model-invoked skills. + +_Avoid_: token cost, context bloat + +### Cognitive Load + +The cost a **user-invoked** skill imposes on the human — what they must hold in their head: which skills exist and when to reach for each (the human is the index). What **model-invocation** removes by being agent-discoverable, and the brake on splitting into more user-invoked skills. Not a cost to minimise: it is the price of human agency, the reason some skills stay user-invoked. Spend it where human judgement matters; remove it where it does not. + +_Avoid_: human index, burden, overhead + +### Router Skill + +A **user-invoked** skill whose job is to point at your other user-invoked skills — naming each and when to reach for it — so the human has one skill to remember instead of many. It can only hint, never fire them: user-invoked skills have no **description**, so nothing but the human can reach them. The cure for **cognitive load** when user-invoked skills multiply. + +_Avoid_: dispatcher, menu, registry, index, router procedure + +### Granularity + +How finely you divide skills. Finer division spends one of the two loads: more **model-invoked** skills spend **context load** (more descriptions crowding the window and competing for attention); more **user-invoked** skills spend **cognitive load** (more for the human to remember and reach for). Two cuts guide the division. By **invocation**, split off a model-invoked skill where you have a distinct **leading word** to trigger it — a trigger word you actually use in your prompts. By **sequence**, split a run of **steps** where a step's **post-completion steps** need hiding, since isolating it in its own context clears what follows. Beware the reverse: merging sequences exposes each step's post-completion steps to what follows, inviting premature completion. + +_Avoid_: chunking, modularity + +## Information Hierarchy + +How a skill's content is arranged, and how far down the ladder each piece sits. + +### Information Hierarchy + +A skill's content ranked by how immediately the agent needs it — a single ladder, produced by two cuts: in-file or behind a pointer, and step or reference. The rungs: + +- **Steps** — in-file, primary +- **Reference**, in-file — secondary +- **Reference**, disclosed — behind a **context pointer** + +A skill with no **steps** uses just the bottom two rungs — often a legitimately flat peer-set (e.g. every rule of a review on one rung), which is a fine arrangement, not a smell. The hierarchy is independent of invocation: a skill can be model- or user-invoked whether it is all steps, all reference, or both. When a skill has steps, in-file reference that should be disclosed buries them and turns attending to them into a coin-flip — a variance lever, not just a legibility one. Keep the top of the ladder legible; push down it whatever you can. + +_Avoid_: structure, organization, layout + +### Steps + +The ordered actions the agent performs — when a skill has them, the primary tier of its content, and the part that earns its place in SKILL.md. Not every skill has steps: a skill can be all steps (`tdd`), all **reference** (a review), or both, independent of invocation. Every step ends on a **completion criterion**, clear or vague. + +_Avoid_: workflow, instructions, choreography + +### Reference + +Material the agent refers to on demand — definitions, facts, parameters, examples, conditional instructions. When a skill has **steps** it is secondary to them; when a skill has none it is the entire content; or it lives outside any skill entirely — see **External Reference**. Reached via **context pointers**, and the prime candidate for **progressive disclosure**. + +_Avoid_: supporting material, docs, background + +### External Reference + +**Reference** that lives outside the skill system — a plain file, no **description**, no **steps**, not invocable — that any skill can point at. The home for shared reference that needn't fire on its own, and the only shared home two **user-invoked** skills can use, since neither has a description and so neither can fire the other. + +_Avoid_: doc, resource, knowledge base + +### Progressive Disclosure + +Moving **reference** down the ladder — out of SKILL.md and behind a **context pointer** — so the top stays legible. Not primarily a token optimisation; it is how the **information hierarchy** is protected. Licensed by **branching**: disclose what only some branches need, inline what every path needs, and if a pointer fires unreliably on must-have material, sharpen its wording, and pull it back inline only if that fails. + +_Avoid_: lazy loading, chunking + +### Co-location + +Keeping the material an agent needs at once in one place — a concept's definition, rules, and caveats under a single heading, not scattered across the file — so reading one part brings its neighbours with it. The within-file companion to the **Information Hierarchy**: the hierarchy ranks _how far down_ a piece sits; co-location decides _what sits beside it_ once there. There is no formula for the right format of a body of **reference**; the test is that a skill should read like documentation written for the agent, and grouped material reads that way where scattered material does not. Distinct from **Duplication**: that repeats one meaning in two places, where scattering fragments a single meaning across many. + +_Avoid_: grouping, clustering, cohesion + +### Sprawl + +_Failure mode._ A skill that is simply too long — too many lines in SKILL.md — independent of whether they are stale or repeated. Even an all-live, all-unique skill can sprawl. It costs readability (the agent wades through more before it can act, and attention thins across the excess), maintainability (every extra line is one more to keep **relevant**), and tokens. The cure is the **information hierarchy**: push **reference** down behind **context pointers**, and split by **branch** or sequence so each path carries only what it needs. Distinct from **sediment** (length from stale accumulation) and **duplication** (length from repeated meaning) — sprawl is length itself, whatever its cause. + +_Avoid_: bloat, length, size, verbosity + +## Steering + +The levers that shape the agent's runtime behaviour toward **Predictability**. + +### Branch + +A distinct way a skill can be invoked — a case the skill handles — so different runs take different paths through it. A skill with many steps may carry many branches; a linear one has none. + +_Avoid_: path, case, fork + +### Leading Word + +A compact concept — also called a _Leitwort_ — already living in the model's pretraining, that the agent thinks with while running the skill. It encodes a behavioural principle in the fewest possible tokens by invoking priors the model already holds (e.g. _lesson_, _proximal zone of development_, _fog of war_, _tracer bullets_). Repeated as a token, never as a sentence, it accumulates a distributed definition across the skill and anchors a whole region of behaviour. Coining your own works if you define it clearly, but a made-up word recruits no priors — you pay in definition tokens what a pretrained word gives free. Reach for an existing word first. + +A leading word serves **predictability** twice. In the body it anchors **execution** — the agent reaches for the same behaviour every time the concept appears, and inside flat reference it focuses attention on a class of thing to look for, recruiting the right checks each run. In the **description** it anchors **invocation** — and not only within the skill: when the same word lives in your prompts, your docs, and your codebase, the agent links that shared language to the skill and fires it more reliably. Word a description with the leading words you actually use when you want the skill. + +_Avoid_: keyword, term, motif + +### Completion Criterion + +The condition that tells the agent a unit of work is done — the target it judges against. Two properties make it a lever, not just a quality. Its **clarity** (can the agent tell done from not-done?) resists **premature completion** — a vague bound ("understanding reached") lets the agent declare done and slip to the next step; this axis needs _steps_ to bite, since premature completion is a between-steps failure. Its **demand** (how much it requires) sets **legwork** — "every modified model accounted for" forces thorough work where "produce a change list" does not — and this axis is _not_ step-bound: it can bind a body of flat reference too, which is how a skill with no steps still carries an exhaustiveness bar ("every rule applied"). The strongest criteria are both checkable and exhaustive. + +_Avoid_: done condition, exit condition, stopping rule + +### Legwork + +The work an agent does behind the scenes within a single step — reading files, exploring the codebase, making changes, digging up what it needs rather than offloading to the user. It lives below the step structure: never written as its own step, latent in the wording, controlled by the agent rather than the skill. The within-step counterpart to **post-completion steps**' across-step pull. Raised by a **leading word** (_comprehensive_, _thorough_) or a **completion criterion** that demands the work be exhaustive — including the demand axis applied to flat reference, which is what drives a skill of flat reference to cover all its rungs. Goes thin either when that demand is missing or when **premature completion** cuts the step short. + +_Avoid_: scope, effort, diligence, coverage + +### Post-Completion Steps + +The **steps** that follow the current step. Visible, they pull the agent forward into **premature completion** — the more it sees, the stronger the tug; the defence is to hide them by splitting the sequence of steps into two. + +_Avoid_: horizon, fog of war, lookahead + +### Premature Completion + +_Failure mode._ Ending the current step before it is genuinely done, because the agent's attention slips to being done rather than to the work. A between-steps failure: it needs **steps** to occur — a skill with no steps that quits early isn't premature completion but thin **legwork** under an unmet demand. A tug-of-war between two forces: visible **post-completion steps** (the pull forward) and the **completion criterion**'s clarity (the resistance — a sharp, checkable bar holds; a vague one gives way). Fuzziness is the necessary condition: a sharp bound resists the pull no matter how many later steps are visible, so a step that never rushes needs no defending. Two levers hold a step that does, but reach for them in order: **sharpen the bound first** — it is local and cheap. Only when the criterion is irreducibly fuzzy _and_ you actually observe the rush do you **hide the later steps** — and hiding only works across a real context boundary (a user-invoked hand-off or a subagent dispatch; an inline model-invoked call leaves the later steps in context and clears nothing). One cause of thin legwork, but distinct from it: legwork can be thin even when a step runs to full completion. + +_Avoid_: premature closure, the rush, rushing, shortcutting + +### Negation + +_Failure mode._ Steering by prohibition — telling the agent what _not_ to do — which drags the forbidden behaviour into context and makes it _more_ available, not less. _Don't think of an elephant_, and the elephant is all there is; _never write verbose comments_, and verbosity is the pattern the agent has just read. The negation is a weak modifier the strongly-activated concept overruns, so the ban half-reads as an instruction to do the thing. Its **leading word** is the _elephant_: whatever a prohibition names into the frame. Cure: prompt the **positive** — describe the target behaviour ("write one-line comments") so the banned one is never spoken. A prohibition earns its place only as a hard guardrail on a behaviour you cannot phrase positively; even then, pair it with the positive target so attention lands on what to do. + +_Avoid_: ironic rebound, don't-prompting, the pink elephant + +## Pruning + +Keeping a skill lean — each remedy paired with the failure it cures. + +### Single Source of Truth + +The desired state where each meaning lives in exactly one authoritative place, so a change to the skill's behaviour is a change in one place. **Duplication** is its violation. + +_Avoid_: home, canonical location + +### Duplication + +_Failure mode._ The same meaning given more than one **single source of truth**. It costs maintenance (change one place, you must change the others), costs tokens, and inflates prominence — repeating a meaning weights it on the ladder past its real rank. The accidental inverse of a **leading word**, which raises attention on purpose by repeating a token, never the meaning. + +_Avoid_: repetition, redundancy + +### Relevance + +Whether a line still bears on what the skill does — the lens for what to keep. A line loses relevance either by never bearing on the task (mere exposition, or a **branch** that should be disclosed) or by going stale: drifting out of date as the behaviour or world it describes changes. Shorter skills are easier to keep relevant, because each line is cheaper to check. Distinct from **no-op**: relevance asks whether a line bears on the task, not whether it changes behaviour. + +_Avoid_: load-bearing, staleness, freshness + +### Sediment + +_Failure mode._ Layers of old content that settle in a skill and are never cleared, because adding feels safe and removing feels risky — so stale and irrelevant lines accumulate and you must core down through them to find what is still live. The default fate of any skill without a pruning discipline; the slow erosion of **relevance**, as opposed to **duplication**'s repeated meaning. + +_Avoid_: accretion, bloat, cruft, rot + +### No-Op + +_Failure mode._ An instruction that changes nothing because the model already does it by default — you pay load to tell the agent what it would do anyway. The test: does a line change behaviour versus the default? A line can be perfectly **relevant** and still be a no-op. The same priors that make a **leading word** free make a no-op worthless. + +A leading word is a _technique_; No-Op is a _verdict_ on a line — and they cross. A leading word too weak to beat the default is a no-op (_be thorough_ when the agent is already thorough-ish), and the fix is a stronger word that passes the verdict (_relentless_), not a different technique. So the No-Op test — does it change behaviour versus the default? — is also how you grade whether a leading word is earning its repetitions. This is model-relative, not reader-relative: two people disagreeing over whether a line is a no-op disagree about the default, and settle it by running the skill, not by debate. + +_Avoid_: redundant instruction, restating the obvious, belaboring diff --git a/.claude/skills/writing-great-skills/SKILL.md b/.claude/skills/writing-great-skills/SKILL.md new file mode 100644 index 0000000..82abd0d --- /dev/null +++ b/.claude/skills/writing-great-skills/SKILL.md @@ -0,0 +1,83 @@ +--- +name: writing-great-skills +description: Reference for writing and editing skills well — the vocabulary and principles that make a skill predictable. +disable-model-invocation: true +--- + +A skill exists to wrangle determinism out of a stochastic system. **Predictability** — the agent taking the same _process_ every run, not producing the same output — is the root virtue; every lever below serves it. + +**Bold terms** are defined in [`GLOSSARY.md`](GLOSSARY.md); look them up there for the full meaning. + +## Invocation + +Two choices, trading different costs: + +- A **model-invoked** skill keeps a **description**, so the agent can fire it autonomously _and_ other skills can reach it (you can still type its name too). It contributes to **context load** — the description sits in the window every turn. Mechanics: omit `disable-model-invocation`, and write a model-facing description with rich trigger phrasing ("Use when the user wants…, mentions…"). +- A **user-invoked** skill strips the description from the agent's reach: only you, typing its name, can invoke it — and no other skill can. Zero context load, but it spends **cognitive load**: _you_ are the index that must remember it exists. Mechanics: set `disable-model-invocation: true`; the `description` becomes human-facing — a one-line summary, trigger lists stripped. + +Pick model-invocation only when the agent must reach the skill on its own, or another skill must. If it only ever fires by hand, make it user-invoked and pay no context load. + +When user-invoked skills multiply past what you can remember, that piled-up cognitive load is cured by a **router skill**: one user-invoked skill that names the others and when to reach for each. + +## Writing the description + +A model-invoked **description** does two jobs — state what the skill is, and list the **branches** that should trigger it. Every word increases **context load**, so a description earns even harder pruning than the body: + +- **Front-load the skill's leading word** — the description is where it does its invocation work. +- **One trigger per branch.** Synonyms that rename a single branch are **duplication** — "build features using TDD … asks for test-first development" is one branch written twice. Collapse them; keep only genuinely distinct branches. +- **Cut identity that's already in the body.** Keep the description to triggers, plus any "when another skill needs…" reach clause. + +## Information hierarchy + +A skill is built from two content types — **steps** and **reference** — that mix freely: a skill can be all steps, all reference, or both. The core decision is which to use and where each sits on the **information hierarchy**, a ladder ranked by how immediately the agent needs the material: + +1. **In-skill step** — an ordered action in `SKILL.md`, the primary tier: what the agent does, in order. Each step ends on a **completion criterion**, the condition that tells the agent the work is done. Make it _checkable_ (can the agent tell done from not-done?) and, where it matters, _exhaustive_ ("every modified model accounted for", not "produce a change list") — a vague criterion invites **premature completion**. +2. **In-skill reference** — a definition, rule, or fact in `SKILL.md`, consulted on demand. Often a legitimately flat peer-set (every rule of a review on one rung) — a fine arrangement, not a smell. _This skill is all reference._ +3. **External reference** — reference pushed out of `SKILL.md` into a separate file, reached by a **context pointer**, loaded only when the pointer fires. (Spans _disclosed_ reference — a sibling file like `GLOSSARY.md`, still part of the skill — through fully **external reference** that lives outside the skill system and any skill can point at.) + +A demanding completion criterion drives thorough **legwork** — the digging the agent does within the work — whether the skill has steps or not, since "every rule applied" binds flat reference just as "every step done" binds a sequence. + +Push too little down and the top bloats; push too much and you hide material the agent actually needs. That tension is the whole decision. + +**Progressive disclosure** is the move down the ladder — out of `SKILL.md` into a linked file — so the top stays legible. Mechanics: a linked `.md` file in the skill folder, named for what it holds (this skill discloses its full definitions to `GLOSSARY.md`). Some skills are used in more than one way, and each distinct way is a **branch** — different runs taking different paths through the skill. Branching is the cleanest disclosure test: inline what every branch needs, and push behind a pointer what only some branches reach. A **context pointer**'s _wording_, not its target, decides when and how reliably the agent reaches the material. + +Where the ladder decides _how far down_ a piece sits, **co-location** decides _what sits beside it_ once there: keep a concept's definition, rules, and caveats under one heading rather than scattered, so reading one part brings its neighbours with it. + +## When to split + +**Granularity** is how finely you divide skills, and each cut spends one of the two loads, so split only when the cut earns it. Two cuts: + +- **By invocation** — split off a **model-invoked** skill when you have a distinct **leading word** that should trigger it on its own, or another skill must reach it. You pay **context load** for the new always-loaded **description**, so that independent reach has to be worth it. +- **By sequence** — split a run of **steps** when the steps still ahead (a step's **post-completion steps**) tempt the agent to rush the one in front of it (**premature completion**). Keeping them out of view encourages the agent to do more **legwork** on the current task. + +## Pruning + +Keep each meaning in a **single source of truth**: one authoritative place, so changing the behaviour is a one-place edit. + +Check every line for **relevance**: does it still bear on what the skill does? + +Then hunt **no-ops** sentence by sentence, not just line by line: run the no-op test on each sentence in isolation, and when one fails, delete the whole sentence rather than trim words from it. Be aggressive — most prose that fails should go, not be rewritten. + +## Leading words + +A **leading word** is a compact concept already living in the model's pretraining that the agent thinks with while running the skill (e.g. _lesson_, _fog of war_, _tracer bullets_). Repeated throughout the text (though not necessarily - a strong leading word might only be needed once), it accumulates a distributed definition and anchors a whole region of behaviour in the fewest tokens, by recruiting priors the model already holds. + +It serves predictability twice. In the body it anchors _execution_: the agent reaches for the same behaviour every time the word appears. In the description it anchors _invocation_: when the same word lives in your prompts, docs, and code, the agent links that shared language to the skill and fires it more reliably. + +Hunt for opportunities to refactor skills to use leading words. A triad spelled out at three sites (**duplication**), a description spending a sentence to gesture at one idea — each is a passage begging to **collapse** into a single token. Examples include: + +- "fast, deterministic, low-overhead" -> _tight_ — one quality restated across a phase — into a single pretrained word (a _tight_ loop). +- "a loop you believe in" -> _red_ — converts a fuzzy gate into a binary observable state (the loop goes _red_ on the bug, or it doesn't). + +You win twice over: fewer tokens, _and_ a sharper hook for the agent to hang its thinking on. Assume every skill is carrying restatements that leading words retire — go find them. + +## Failure modes + +Use these to diagnose issues the user may be having with the skill. + +- **Premature completion** — ending a step before it's genuinely done, attention slipping to _being done_. Defence, in order: sharpen the completion criterion first (cheap, local); only if it is irreducibly fuzzy _and_ you observe the rush, hide the post-completion steps by splitting (the sequence cut). +- **Duplication** — the same meaning in more than one place. Costs maintenance and tokens, and inflates a meaning's prominence on the ladder past its real rank. +- **Sediment** — stale layers that settle because adding feels safe and removing feels risky. The default fate of any skill without a pruning discipline. +- **Sprawl** — a skill simply too long, even when every line is live and unique. Hurts readability and maintainability and wastes tokens. The cure is the ladder: disclose **reference** behind pointers, and split by **branch** or sequence so each path carries only what it needs. +- **No-op** — a line the model already obeys by default, so you pay load to say nothing. The test: does it change behaviour versus the default? A weak leading word (_be thorough_ when the agent is already thorough-ish) is a no-op; the fix is a stronger word (_relentless_), not a different technique. +- **Negation** — steering by prohibition backfires: _don't think of an elephant_ names the elephant and makes it more available, not less. Prompt the **positive** — state the target behaviour so the banned one is never spoken; keep a prohibition only as a hard guardrail you can't phrase positively, and even then pair it with what to do instead. diff --git a/.claude/skills/writing-great-skills/agents/openai.yaml b/.claude/skills/writing-great-skills/agents/openai.yaml new file mode 100644 index 0000000..d677a13 --- /dev/null +++ b/.claude/skills/writing-great-skills/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Writing Great Skills" + short_description: "Principles for predictable skills" +policy: + allow_implicit_invocation: false diff --git a/.devcontainer/devcontainer-lock.json b/.devcontainer/devcontainer-lock.json new file mode 100644 index 0000000..8fbef47 --- /dev/null +++ b/.devcontainer/devcontainer-lock.json @@ -0,0 +1,14 @@ +{ + "features": { + "ghcr.io/devcontainers/features/common-utils:2": { + "version": "2.5.9", + "resolved": "ghcr.io/devcontainers/features/common-utils@sha256:cb0c4d3c276f157eed17935747e364178d75fee17f55c4e129966f64633deb3a", + "integrity": "sha256:cb0c4d3c276f157eed17935747e364178d75fee17f55c4e129966f64633deb3a" + }, + "ghcr.io/devcontainers/features/git:1": { + "version": "1.3.5", + "resolved": "ghcr.io/devcontainers/features/git@sha256:27905dc196c01f77d6ba8709cb82eeaf330b3b108772e2f02d1cd0d826de1251", + "integrity": "sha256:27905dc196c01f77d6ba8709cb82eeaf330b3b108772e2f02d1cd0d826de1251" + } + } +} diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..7586930 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,32 @@ +{ + "name": "Swift 6.4", + "image": "swiftlang/swift:nightly-6.4.x-noble", + "features": { + "ghcr.io/devcontainers/features/common-utils:2": { + "installZsh": "false", + "username": "vscode", + "upgradePackages": "false" + }, + "ghcr.io/devcontainers/features/git:1": { + "version": "os-provided", + "ppa": "false" + } + }, + "postStartCommand": "git config --global --add safe.directory ${containerWorkspaceFolder}", + "runArgs": [ + "--cap-add=SYS_PTRACE", + "--security-opt", + "seccomp=unconfined" + ], + "customizations": { + "vscode": { + "settings": { + "lldb.library": "/usr/lib/liblldb.so" + }, + "extensions": [ + "sswg.swift-lang" + ] + } + }, + "remoteUser": "root" +} diff --git a/.github/actions/setup-tools/action.yml b/.github/actions/setup-tools/action.yml new file mode 100644 index 0000000..6e9cd53 --- /dev/null +++ b/.github/actions/setup-tools/action.yml @@ -0,0 +1,26 @@ +name: Setup mise tools +description: >- + Restore (or build and save) the mise tool cache and put the binaries on PATH. + +runs: + using: composite + steps: + - name: Cache mise tools + id: mise-cache + uses: actions/cache@v4 + with: + path: ~/.local/share/mise/installs + key: mise-v2-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('.mise.toml') }} + restore-keys: | + mise-v2-${{ runner.os }}-${{ runner.arch }}- + - name: Install mise tools (cache miss) + if: steps.mise-cache.outputs.cache-hit != 'true' + uses: jdx/mise-action@v4 + with: + cache: false + - name: Configure PATH for cached mise tools + if: steps.mise-cache.outputs.cache-hit == 'true' + uses: jdx/mise-action@v4 + with: + install: false + cache: false diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..ae22d88 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "swift" # See documentation for possible values + directory: "/" # Location of package manifests + schedule: + interval: "weekly" diff --git a/.github/workflows/DangerPR.yml b/.github/workflows/DangerPR.yml deleted file mode 100644 index 2441c1f..0000000 --- a/.github/workflows/DangerPR.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: Pull Request Check -on: [pull_request, workflow_dispatch] -jobs: - build: - runs-on: macos-12 - steps: - - uses: actions/checkout@v3 - - name: install danger - run: brew install danger/tap/danger-swift - - name: Run Danger - run: danger-swift ci - env: - GITHUB_TOKEN: ${{ secrets.PUBLIC_REPO }} \ No newline at end of file diff --git a/.github/workflows/TailwindKit.yml b/.github/workflows/TailwindKit.yml new file mode 100644 index 0000000..37dbdee --- /dev/null +++ b/.github/workflows/TailwindKit.yml @@ -0,0 +1,255 @@ +name: TailwindKit + +# Standalone CI for this BrightDigit Swift package on Swift 6.4 (the BrightDigit +# CI template). These five workflows are kept byte-identical except the name above; +# the only per-package difference is externalized to the ENABLE_WASM repo variable. +# Linux + wasm run in the nightly-6.4 container; macOS + the Apple-platform suite +# run on the GitHub-hosted xcode-27 runner with /Applications/Xcode_27.0.app (Xcode 27 / +# Swift 6.4); Windows on a swift.org nightly snapshot; Android via a swift.org SDK +# bundle. The wasm step is gated on ENABLE_WASM — set it to 'false' where a +# dependency can't build for wasm (e.g. Yams). +on: + push: + branches: [main] + tags: ['v*.*.*'] + paths-ignore: + - '**.md' + - 'LICENSE' + pull_request: + paths-ignore: + - '**.md' + - 'LICENSE' + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.ref }} + cancel-in-progress: true + +jobs: + build-ubuntu: + name: Build on Ubuntu + needs: configure + runs-on: ubuntu-latest + container: swiftlang/swift:nightly-6.4.x-noble + if: ${{ !contains(github.event.head_commit.message, 'ci skip') }} + # Ubuntu variants from a matrix (configure → ubuntu-type): standard ('') always; + # wasm + wasm-embedded when ENABLE_WASM != 'false'. Both wasm variants share the + # same nightly-6.4.x SDK bundle. OpenAPI packages guard URLSession behind + # #if !os(WASI) so the wasm/embedded legs build. + strategy: + fail-fast: true + matrix: + type: ${{ fromJSON(needs.configure.outputs.ubuntu-type) }} + steps: + - uses: actions/checkout@v6 + - uses: brightdigit/swift-build@v1 + id: build + with: + type: ${{ matrix.type }} + # wasm / wasm-embedded are build-only: WasmKit doesn't mount the Foundation + # resource bundles the tests load, and embedded hits OpenAPIRuntime keypath + # limits at runtime. The standard ('') leg runs the full suite + coverage. + build-only: ${{ matrix.type != '' }} + wasm-sdk-url: https://download.swift.org/swift-6.4.x-branch/wasm-sdk/swift-6.4.x-DEVELOPMENT-SNAPSHOT-2026-06-15-a/swift-6.4.x-DEVELOPMENT-SNAPSHOT-2026-06-15-a_wasm.artifactbundle.tar.gz + wasm-sdk-checksum: c014a0162de6eeeef4f07904ce096ccee5405c1478a12c99a3a9750bd42d7702 + wasm-swift-flags: >- + -Xcc -D_WASI_EMULATED_SIGNAL -Xcc -D_WASI_EMULATED_MMAN + -Xlinker -lwasi-emulated-signal -Xlinker -lwasi-emulated-mman + -Xlinker -lwasi-emulated-getpid + -Xlinker --initial-memory=536870912 -Xlinker --max-memory=536870912 + - name: Install curl (required by Codecov uploader) + if: steps.build.outputs.contains-code-coverage == 'true' + run: | + if ! command -v curl &> /dev/null; then + apt-get update -q + apt-get install -y --no-install-recommends curl ca-certificates + fi + - uses: sersoft-gmbh/swift-coverage-action@v5 + if: steps.build.outputs.contains-code-coverage == 'true' + id: coverage-files + with: + search-paths: .build + - name: Upload coverage to Codecov + if: steps.build.outputs.contains-code-coverage == 'true' + uses: codecov/codecov-action@v7 + with: + fail_ci_if_error: false + flags: noble,swift-6.4 + token: ${{ secrets.CODECOV_TOKEN }} + files: ${{ join(fromJSON(steps.coverage-files.outputs.files), ',') }} + + configure: + name: Configure Matrix + runs-on: ubuntu-latest + outputs: + full-matrix: ${{ steps.check.outputs.full }} + run-windows: ${{ steps.check.outputs.windows }} + ubuntu-type: ${{ steps.check.outputs.ubuntu-type }} + steps: + - uses: actions/checkout@v6 + - id: check + name: Determine matrix scope + run: | + # Three tiers: small set (build-ubuntu[+wasm]/build-macos/lint, always) < + # full-matrix (macOS-platforms/android) < +Windows. full-matrix runs on + # main / semver / dispatch / PRs into main or semver. Windows is the most + # expensive leg, so run-windows is the same MINUS PRs into semver branches. + FULL=false; WIN=false + REF="${{ github.ref }}"; EVENT="${{ github.event_name }}"; BASE_REF="${{ github.base_ref }}" + if [[ "$REF" == "refs/heads/main" ]]; then FULL=true; WIN=true + elif [[ "$REF" =~ ^refs/heads/v?[0-9]+\.[0-9]+\.[0-9]+ ]]; then FULL=true; WIN=true + elif [[ "$EVENT" == "workflow_dispatch" ]]; then FULL=true; WIN=true + elif [[ "$EVENT" == "pull_request" ]]; then + if [[ "$BASE_REF" == "main" ]]; then FULL=true; WIN=true + elif [[ "$BASE_REF" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+ ]]; then FULL=true + fi + fi + echo "full=$FULL" >> "$GITHUB_OUTPUT" + echo "windows=$WIN" >> "$GITHUB_OUTPUT" + # Ubuntu build variants: standard ('') always; wasm + wasm-embedded + # unless the package disables wasm via ENABLE_WASM (e.g. Yams). + if [[ "${{ vars.ENABLE_WASM }}" != "false" ]]; then + echo 'ubuntu-type=["","wasm","wasm-embedded"]' >> "$GITHUB_OUTPUT" + else + echo 'ubuntu-type=[""]' >> "$GITHUB_OUTPUT" + fi + + # macOS on Swift 6.4 via the GitHub-hosted xcode-27 runner. + build-macos: + name: Build on macOS + runs-on: xcode-27 + if: ${{ !contains(github.event.head_commit.message, 'ci skip') }} + steps: + - uses: actions/checkout@v6 + - uses: brightdigit/swift-build@v1 + id: build + with: + xcode: "/Applications/Xcode_27.0.app" + - name: Process coverage + if: steps.build.outputs.contains-code-coverage == 'true' + uses: sersoft-gmbh/swift-coverage-action@v5 + with: + search-paths: .build + - name: Upload coverage to Codecov + if: steps.build.outputs.contains-code-coverage == 'true' + uses: codecov/codecov-action@v7 + with: + fail_ci_if_error: false + flags: spm,macos + token: ${{ secrets.CODECOV_TOKEN }} + + # Windows nightly 6.4 via a swift.org development snapshot (compnerd/gha-setup-swift + # under swift-build), on hosted runners. Own tier (run-windows): the most + # expensive leg, so it runs on main / semver / dispatch / PRs into main, but NOT + # PRs into semver branches. Bump the snapshot id periodically (swift.org GCs them). + build-windows: + name: Build on Windows + needs: configure + if: ${{ needs.configure.outputs.run-windows == 'true' }} + runs-on: ${{ matrix.runs-on }} + strategy: + fail-fast: true + matrix: + runs-on: [windows-2022, windows-2025] + swift: + - version: swift-6.4.x-branch + build: 6.4.x-DEVELOPMENT-SNAPSHOT-2026-06-01-a + steps: + - uses: actions/checkout@v6 + - uses: brightdigit/swift-build@v1 + id: build + with: + windows-swift-version: ${{ matrix.swift.version }} + windows-swift-build: ${{ matrix.swift.build }} + + # Full Apple-platform suite (iOS/watchOS/tvOS) on Swift 6.4, on the GitHub-hosted + # xcode-27 runner with downloadable 27.0 simulator runtimes. Blocking leg; simulator runs on the nightly + # toolchain are the most fragile leg. Bump deviceName/osVersion as Xcode-beta moves. + build-macos-platforms: + name: Build on macOS (Platforms) + needs: configure + if: ${{ needs.configure.outputs.full-matrix == 'true' }} + runs-on: xcode-27 + strategy: + fail-fast: true + matrix: + include: + - { type: ios, deviceName: "iPhone 17 Pro", osVersion: "27.0" } + - { type: watchos, deviceName: "Apple Watch Ultra 3 (49mm)", osVersion: "27.0" } + - { type: tvos, deviceName: "Apple TV 4K (3rd generation)", osVersion: "27.0" } + - { type: visionos, deviceName: "Apple Vision Pro", osVersion: "27.0" } + steps: + - uses: actions/checkout@v6 + - name: Build and Test + id: build + uses: brightdigit/swift-build@v1 + with: + type: ${{ matrix.type }} + xcode: "/Applications/Xcode_27.0.app" + deviceName: ${{ matrix.deviceName }} + osVersion: ${{ matrix.osVersion }} + download-platform: true + - name: Process coverage + if: steps.build.outputs.contains-code-coverage == 'true' + uses: sersoft-gmbh/swift-coverage-action@v5 + with: + search-paths: .build + - name: Upload coverage to Codecov + if: steps.build.outputs.contains-code-coverage == 'true' + uses: codecov/codecov-action@v7 + with: + fail_ci_if_error: false + token: ${{ secrets.CODECOV_TOKEN }} + flags: ${{ format('{0}{1}', matrix.type, matrix.osVersion) }} + + # Android on nightly 6.4 via a swift.org swift-6.4.x-branch snapshot SDK bundle + # (custom-sdk-url path through swift-build → skiptools/swift-android-action). + # Blocking leg; build-only (android-run-tests: false). + # Bump the snapshot id periodically. + build-android: + name: Build on Android + needs: configure + if: ${{ needs.configure.outputs.full-matrix == 'true' }} + runs-on: ubuntu-latest + strategy: + fail-fast: true + matrix: + android-api-level: [34] + steps: + - uses: actions/checkout@v6 + - name: Free disk space + uses: jlumbroso/free-disk-space@v1.3.1 + with: + tool-cache: false + android: false + dotnet: true + haskell: true + large-packages: true + docker-images: true + swap-storage: true + - uses: brightdigit/swift-build@v1 + with: + type: android + android-swift-version: 6.4.x-DEVELOPMENT-SNAPSHOT-2026-06-15-a + android-sdk-url: https://download.swift.org/swift-6.4.x-branch/android-sdk/swift-6.4.x-DEVELOPMENT-SNAPSHOT-2026-06-15-a/swift-6.4.x-DEVELOPMENT-SNAPSHOT-2026-06-15-a_android.artifactbundle.tar.gz + android-sdk-id: swift-6.4.x-DEVELOPMENT-SNAPSHOT-2026-06-15-a_android + android-api-level: ${{ matrix.android-api-level }} + android-run-tests: false + + lint: + name: Linting + if: ${{ !cancelled() && !failure() && !contains(github.event.head_commit.message, 'ci skip') }} + needs: [build-ubuntu, build-macos, build-windows, build-macos-platforms] + runs-on: ubuntu-latest + container: swiftlang/swift:nightly-6.4.x-noble + steps: + - name: Install curl (required by setup-tools) + run: | + apt-get update -q + apt-get install -y --no-install-recommends curl ca-certificates + - uses: actions/checkout@v6 + - uses: ./.github/actions/setup-tools + - name: Lint + run: ./Scripts/lint.sh + env: + LINT_MODE: STRICT diff --git a/.github/workflows/TailwindKitTest.yml b/.github/workflows/TailwindKitTest.yml deleted file mode 100644 index 40c7496..0000000 --- a/.github/workflows/TailwindKitTest.yml +++ /dev/null @@ -1,9 +0,0 @@ -name: Test Package -on: [push, workflow_dispatch] -jobs: - build: - runs-on: macos-12 - steps: - - uses: actions/checkout@v3 - - name: Run tests - run: swift test \ No newline at end of file diff --git a/.github/workflows/check-unsafe-flags.yml b/.github/workflows/check-unsafe-flags.yml new file mode 100644 index 0000000..3af5e56 --- /dev/null +++ b/.github/workflows/check-unsafe-flags.yml @@ -0,0 +1,39 @@ +name: Check for unsafeFlags + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +jobs: + dump-package-check: + name: Dump Swift package (authoritative) and scan JSON + runs-on: ubuntu-latest + container: + image: swiftlang/swift:nightly-6.4.x-noble + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Install jq + run: | + apt-get update && apt-get install -y jq + + - name: Dump package JSON and check for unsafeFlags + shell: bash + run: | + set -euo pipefail + # Compute unsafeFlags array directly from the dump (don't store the full dump variable) + unsafe_flags=$(swift package dump-package | jq -c '[.. | objects | .unsafeFlags? // empty]') + # Check array length to decide failure + if [ "$(echo "$unsafe_flags" | jq 'length')" -gt 0 ]; then + echo "ERROR: unsafeFlags found in resolved package JSON:" + echo "$unsafe_flags" | jq '.' || true + echo "--- resolved package dump (first 200 lines) ---" + # Print a sample of the authoritative dump (re-run dump-package for the sample) + swift package dump-package | sed -n '1,200p' || true + exit 1 + else + echo "No unsafeFlags in resolved package JSON." + fi diff --git a/.github/workflows/claude-code-review.yml b/.github/workflows/claude-code-review.yml new file mode 100644 index 0000000..b5e8cfd --- /dev/null +++ b/.github/workflows/claude-code-review.yml @@ -0,0 +1,44 @@ +name: Claude Code Review + +on: + pull_request: + types: [opened, synchronize, ready_for_review, reopened] + # Optional: Only run on specific file changes + # paths: + # - "src/**/*.ts" + # - "src/**/*.tsx" + # - "src/**/*.js" + # - "src/**/*.jsx" + +jobs: + claude-review: + # Optional: Filter by PR author + # if: | + # github.event.pull_request.user.login == 'external-contributor' || + # github.event.pull_request.user.login == 'new-developer' || + # github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR' + + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + issues: read + id-token: write + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 1 + + - name: Run Claude Code Review + id: claude-review + uses: anthropics/claude-code-action@v1 + with: + claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} + plugin_marketplaces: 'https://github.com/anthropics/claude-code.git' + plugins: 'code-review@claude-code-plugins' + prompt: '/code-review:code-review ${{ github.repository }}/pull/${{ github.event.pull_request.number }}' + # See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md + # or https://code.claude.com/docs/en/cli-reference for available options + diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml new file mode 100644 index 0000000..6b15fac --- /dev/null +++ b/.github/workflows/claude.yml @@ -0,0 +1,50 @@ +name: Claude Code + +on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + issues: + types: [opened, assigned] + pull_request_review: + types: [submitted] + +jobs: + claude: + if: | + (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) || + (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) || + (github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) || + (github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude'))) + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + issues: read + id-token: write + actions: read # Required for Claude to read CI results on PRs + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 1 + + - name: Run Claude Code + id: claude + uses: anthropics/claude-code-action@v1 + with: + claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} + + # This is an optional setting that allows Claude to read CI results on PRs + additional_permissions: | + actions: read + + # Optional: Give a custom prompt to Claude. If this is not specified, Claude will perform the instructions specified in the comment that tagged it. + # prompt: 'Update the pull request description to include a summary of changes.' + + # Optional: Add claude_args to customize behavior and configuration + # See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md + # or https://code.claude.com/docs/en/cli-reference for available options + # claude_args: '--allowed-tools Bash(gh pr *)' + diff --git a/.github/workflows/cleanup-caches.yml b/.github/workflows/cleanup-caches.yml new file mode 100644 index 0000000..f0124e2 --- /dev/null +++ b/.github/workflows/cleanup-caches.yml @@ -0,0 +1,29 @@ +name: Cleanup Branch Caches +on: + delete: + +jobs: + cleanup: + runs-on: ubuntu-latest + permissions: + actions: write + steps: + - name: Cleanup caches for deleted branch + uses: actions/github-script@v9 + with: + script: | + const ref = `refs/heads/${context.payload.ref}`; + const caches = await github.rest.actions.getActionsCacheList({ + owner: context.repo.owner, + repo: context.repo.repo, + ref: ref, + }); + for (const cache of caches.data.actions_caches) { + console.log(`Deleting cache: ${cache.key}`); + await github.rest.actions.deleteActionsCacheById({ + owner: context.repo.owner, + repo: context.repo.repo, + cache_id: cache.id, + }); + } + console.log(`Deleted ${caches.data.actions_caches.length} cache(s) for ${ref}`); diff --git a/.github/workflows/swift-source-compat.yml b/.github/workflows/swift-source-compat.yml new file mode 100644 index 0000000..d4d03bb --- /dev/null +++ b/.github/workflows/swift-source-compat.yml @@ -0,0 +1,28 @@ +name: Swift Source Compatibility + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +jobs: + swift-source-compat-suite: + name: Test Swift ${{ matrix.container }} For Source Compatibility Suite + runs-on: ubuntu-latest + if: ${{ !contains(github.event.head_commit.message, 'ci skip') }} + + strategy: + fail-fast: false + matrix: + container: + - swiftlang/swift:nightly-6.4.x-noble + + container: ${{ matrix.container }} + + steps: + - name: Checkout repository + uses: actions/checkout@v6 + + - name: Test Swift 6.x For Source Compatibility + run: swift build --disable-sandbox --verbose --configuration release diff --git a/.gitignore b/.gitignore index 3b29812..8704f86 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,144 @@ +# Created by https://www.toptal.com/developers/gitignore/api/macos,swift,SwiftPackageManager,Xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=macos,swift,SwiftPackageManager,Xcode + +### macOS ### +# General .DS_Store -/.build -/Packages -/*.xcodeproj +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### Swift ### +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## User settings xcuserdata/ + +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ DerivedData/ -.swiftpm/config/registries.json -.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata -.netrc +*.moved-aside + +# Xcode +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 + +## Obj-C/Swift specific +*.hmap + +## App packaging +*.ipa +*.dSYM.zip +*.dSYM + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +# Package.pins +# Package.resolved +*.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +.swiftpm + +.build/ + +# CocoaPods +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace + +# Carthage +# Add this line if you want to avoid checking in source code from Carthage dependencies. +# Carthage/Checkouts + +Carthage/Build/ + +# Accio dependency management +Dependencies/ +.accio/ + +# fastlane +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://docs.fastlane.tools/best-practices/source-control/#source-control + +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### SwiftPackageManager ### +# Packages +xcuserdata +*.xcodeproj + + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/macos,swift,SwiftPackageManager,Xcode + +.mint diff --git a/.mise.toml b/.mise.toml new file mode 100644 index 0000000..87bc056 --- /dev/null +++ b/.mise.toml @@ -0,0 +1,16 @@ +[settings] +# Enable experimental features (required for the spm backend) +experimental = true + +[tools] +# Swift development tools (managed via mise) +# 604.x aligns swift-format (and its swift-syntax) with the Swift 6.4 toolchain. +# Only one 604 tag exists so far; bump when a newer 604 prerelease/release lands. +"spm:swiftlang/swift-format" = "604.0.0-prerelease-2025-12-17" +"aqua:realm/SwiftLint" = "0.63.2" +"spm:peripheryapp/periphery" = "3.7.4" + +[tasks] +swift-format = "swift-format" +swiftlint = "swiftlint" +periphery = "periphery" diff --git a/.periphery.yml b/.periphery.yml new file mode 100644 index 0000000..e9b018d --- /dev/null +++ b/.periphery.yml @@ -0,0 +1,3 @@ +retain_public: true +targets: +- TailwindKit diff --git a/.spi.yml b/.spi.yml new file mode 100644 index 0000000..295c692 --- /dev/null +++ b/.spi.yml @@ -0,0 +1,6 @@ +version: 1 +builder: + configs: + - documentation_targets: [TailwindKit] + swift_version: "6.4" + custom_documentation_parameters: [--include-extended-types] diff --git a/.swift-format b/.swift-format new file mode 100644 index 0000000..257f555 --- /dev/null +++ b/.swift-format @@ -0,0 +1,70 @@ +{ + "fileScopedDeclarationPrivacy" : { + "accessLevel" : "fileprivate" + }, + "indentation" : { + "spaces" : 2 + }, + "indentConditionalCompilationBlocks" : true, + "indentSwitchCaseLabels" : false, + "lineBreakAroundMultilineExpressionChainComponents" : false, + "lineBreakBeforeControlFlowKeywords" : false, + "lineBreakBeforeEachArgument" : false, + "lineBreakBeforeEachGenericRequirement" : false, + "lineLength" : 100, + "maximumBlankLines" : 1, + "multiElementCollectionTrailingCommas" : true, + "noAssignmentInExpressions" : { + "allowedFunctions" : [ + "XCTAssertNoThrow" + ] + }, + "prioritizeKeepingFunctionOutputTogether" : false, + "respectsExistingLineBreaks" : true, + "rules" : { + "AllPublicDeclarationsHaveDocumentation" : true, + "AlwaysUseLiteralForEmptyCollectionInit" : false, + "AlwaysUseLowerCamelCase" : true, + "AmbiguousTrailingClosureOverload" : true, + "BeginDocumentationCommentWithOneLineSummary" : false, + "DoNotUseSemicolons" : true, + "DontRepeatTypeInStaticProperties" : true, + "FileScopedDeclarationPrivacy" : false, + "FullyIndirectEnum" : true, + "GroupNumericLiterals" : true, + "IdentifiersMustBeASCII" : true, + "NeverForceUnwrap" : true, + "NeverUseForceTry" : true, + "NeverUseImplicitlyUnwrappedOptionals" : true, + "NoAccessLevelOnExtensionDeclaration" : true, + "NoAssignmentInExpressions" : true, + "NoBlockComments" : true, + "NoCasesWithOnlyFallthrough" : true, + "NoEmptyTrailingClosureParentheses" : true, + "NoLabelsInCasePatterns" : true, + "NoLeadingUnderscores" : true, + "NoParensAroundConditions" : true, + "NoPlaygroundLiterals" : true, + "NoVoidReturnOnFunctionSignature" : true, + "OmitExplicitReturns" : false, + "OneCasePerLine" : true, + "OneVariableDeclarationPerLine" : true, + "OnlyOneTrailingClosureArgument" : true, + "OrderedImports" : true, + "ReplaceForEachWithForLoop" : true, + "ReturnVoidInsteadOfEmptyTuple" : true, + "TypeNamesShouldBeCapitalized" : true, + "UseEarlyExits" : false, + "UseExplicitNilCheckInConditions" : true, + "UseLetInEveryBoundCaseVariable" : true, + "UseShorthandTypeNames" : true, + "UseSingleLinePropertyGetter" : true, + "UseSynthesizedInitializer" : true, + "UseTripleSlashForDocumentationComments" : true, + "UseWhereClausesInForLoops" : true, + "ValidateDocumentationComments" : true + }, + "spacesAroundRangeFormationOperators" : false, + "tabWidth" : 2, + "version" : 1 +} diff --git a/.swift-version b/.swift-version new file mode 100644 index 0000000..944c7e2 --- /dev/null +++ b/.swift-version @@ -0,0 +1 @@ +6.4.x-snapshot diff --git a/.swiftlint.yml b/.swiftlint.yml new file mode 100644 index 0000000..4ccdb85 --- /dev/null +++ b/.swiftlint.yml @@ -0,0 +1,149 @@ +opt_in_rules: + - array_init + - closure_body_length + - closure_end_indentation + - closure_spacing + - collection_alignment + - conditional_returns_on_newline + - contains_over_filter_count + - contains_over_filter_is_empty + - contains_over_first_not_nil + - contains_over_range_nil_comparison + - convenience_type + - discouraged_object_literal + - empty_collection_literal + - empty_count + - empty_string + - empty_xctest_method + - enum_case_associated_values_count + - expiring_todo + - explicit_acl + - explicit_init + - explicit_top_level_acl + # - fallthrough + - fatal_error_message + - file_name + - file_name_no_space + - file_types_order + - first_where + - flatmap_over_map_reduce + - force_unwrapping +# - function_default_parameter_at_end + - ibinspectable_in_extension + - identical_operands + - implicit_return + - implicitly_unwrapped_optional + - indentation_width + - joined_default_parameter + - last_where + - legacy_multiple + - legacy_random + - literal_expression_end_indentation + - lower_acl_than_parent + - missing_docs + - modifier_order + - multiline_arguments + - multiline_arguments_brackets + - multiline_function_chains + - multiline_literal_brackets + - multiline_parameters + - nimble_operator + - nslocalizedstring_key + - nslocalizedstring_require_bundle + - number_separator + - object_literal + - one_declaration_per_file + - operator_usage_whitespace + - optional_enum_case_matching + - overridden_super_call + - override_in_extension + - pattern_matching_keywords + - prefer_self_type_over_type_of_self + - prefer_zero_over_explicit_init + - private_action + - private_outlet + - prohibited_interface_builder + - prohibited_super_call + - quick_discouraged_call + - quick_discouraged_focused_test + - quick_discouraged_pending_test + - reduce_into + - redundant_nil_coalescing + - redundant_type_annotation + - required_enum_case + - single_test_class + - sorted_first_last + - sorted_imports + - static_operator + - strong_iboutlet + - toggle_bool +# - trailing_closure + - type_contents_order + - unavailable_function + - unneeded_parentheses_in_closure_argument + - unowned_variable_capture + - untyped_error_in_catch + - vertical_parameter_alignment_on_call + - vertical_whitespace_closing_braces + - vertical_whitespace_opening_braces + - xct_specific_matcher + - yoda_condition +analyzer_rules: + - unused_import + - unused_declaration +cyclomatic_complexity: + - 6 + - 12 +file_length: + warning: 225 + error: 300 +function_body_length: + - 50 + - 76 +function_parameter_count: 8 +line_length: + - 108 + - 200 +closure_body_length: + - 50 + - 60 +type_name: + min_length: 3 + max_length: + warning: 50 + error: 60 +identifier_name: + excluded: + - id + - no +excluded: + - DerivedData + - .build + - .swiftpm + - "*/.swiftpm" + - "*/.build" + - Mint + - Examples + - Packages + - Package.swift +indentation_width: + indentation_width: 2 +file_name: + severity: error +fatal_error_message: + severity: error +disabled_rules: + - nesting + - implicit_getter + - switch_case_alignment + - closure_parameter_position + - trailing_comma + - opening_brace + - optional_data_string_conversion + - pattern_matching_keywords +custom_rules: + no_unchecked_sendable: + name: "No Unchecked Sendable" + regex: '@unchecked\s+Sendable' + message: "Use proper Sendable conformance instead of @unchecked Sendable to maintain strict concurrency safety" + severity: error diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..4dad837 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,181 @@ +# AGENTS.md + +This is the canonical agent instruction file for this repository. `CLAUDE.md` is a symlink +to it. + +## What this is + +TailwindKit is a small, dependency-light Swift module that emits **type-safe +[Tailwind CSS v4](https://tailwindcss.com) utility class strings** for +brightdigit.com's component markup. Swift 6.4 tools version, Swift 6 language +mode; targets macOS 13+ and Linux. Tailwind **v4 only**. + +## Commands + +```bash +swift test # run the (offline, dependency-free) tests +swift build --build-tests # compile + +# Single test: filter by suite/method +swift test --filter TailwindStyleTests/canonicalChain + +# Lint/format/check (installs pinned tools via mise, formats in place locally, builds tests, runs periphery) +./Scripts/lint.sh +LINT_MODE=STRICT ./Scripts/lint.sh # CI-style strict mode (no auto-fix; lint + build only when CI is set) + +mise install # install pinned tools (swift-format, swiftlint, periphery) +``` + +Tooling (swift-format, SwiftLint, periphery) is pinned in `.mise.toml` and run +through `mise exec --`. `Scripts/lint.sh` auto-formats and rewrites file headers +only when `CI` is unset; in CI it lints and builds without mutating files. + +## Architecture — the one design decision + +`TailwindStyleBuilder` is an immutable value builder, and **this package has no +dependencies at all** — not even Foundation. Keep it that way: `rendered` is a +plain `String`, which is the whole seam an HTML library needs. + +HTML-library sugar is opt-in via `TailwindClassAttribute` +(`Integration/TailwindClassAttribute.swift`): one static requirement, +`` `class`(_:) -> Self ``, with `.tailwind(_ style:)` supplied by a protocol +extension. The requirement is deliberately named for the factory HTML libraries +already declare, so a conformance needs **no implementation** — BrightDigit's is +literally `extension Node: TailwindClassAttribute where Context: HTMLContext {}` +in `BrightDigitSite`. Keep it that way: if you ever rename this requirement to +something library-specific, every consumer has to write a forwarding body. Do +**not** add an HTML-library dependency back to this package. + +Note that a protocol cannot be retroactively conformed to another protocol, so +element types exposing `class` as an *instance* modifier (Plot's `Component`) +can't use the seam — consumers write that one-liner directly. That asymmetry is +a Swift limitation, not an oversight. + +Because there is no Foundation import, `String.replacingOccurrences` is +unavailable; arbitrary-value space escaping goes through +`String.escapingSpaces` in `Core/String+ArbitraryValue.swift`. + +(The plain name `TailwindStyle` is the **seam protocol**, see below; `TW` is the +typealias for the builder.) + +- Every fluent member returns a new `TailwindStyleBuilder`. Bare utilities are computed + properties (`.flex`, `.gap`); parameterized ones are methods (`.gap(4)`, + `.bg(.blue, .s500)`). Static mirrors let a chain start with a leading dot. + +### The capability-protocol architecture (mirrors ButtondownKit) + +The fluent surface is organized into ~13 **public capability protocols** — one +per CSS concern, noun + `Styling` suffix — each in its own file +(`ColorStyling.swift`, `SpacingStyling.swift`, `FlexGridStyling.swift`, …). This +mirrors `ButtondownKit`'s capability-protocol pattern (`EmailListing`, … witnessed +in extensions constrained on the `UnderlyingClientProtocol` seam). + +- **The seam is `TailwindStyle`** (`TailwindStyle.swift`), a + **public** protocol exposing the two composition primitives + `appending(_ class: some TailwindClass)` and + `prefixing(_ variant: some Variant, _:)`. Each capability provides its members + in `extension XStyling where Self: TailwindStyle { public func … }`, + composing through the seam; `TailwindStyleBuilder` conforms to the seam + every + capability. The seam **must** be public — Swift forbids a `public` member in an + extension constrained on a non-public protocol. +- **Why the seam takes typed values, not `String`.** A naive port of + ButtondownKit's `underlying` seam would expose `appending(_:String)`, breaking + the invariant that the public API never accepts raw strings. Instead the seam + takes `some TailwindClass` (a full class fragment; built-ins via + `DefaultTailwindClass`, **internal init**) and `some Variant`. So the seam is + public yet there is **no raw-string entry point**. The actual string + composition (`appendingToken`/`prefixingToken`) is **file-private** in + `TailwindStyleBuilder.swift`. +- **`Variant`** (`Variant.swift`) is extensible exactly like `Color` — a + `public protocol Variant: TailwindToken` with `DefaultVariant` (internal init) + exposing `.sm`/`.md`/`.hover`/`.dark`/… A downstream module can register a + custom `@custom-variant` by conforming its own type. Variants **chain by + nesting**: `.md(.hover(.bg(.blue, .s700)))` → `md:hover:bg-blue-700`. +- **Deliberate divergence from ButtondownKit:** `TailwindStyleBuilder` retains method + bodies (the seam witnesses) rather than being pure storage, because a value + type has no injected `underlying` collaborator to hide — the "seam" is an + implementation detail, not a dependency. +- To satisfy SwiftLint's `type_contents_order`, within each capability file the + witnesses and static mirrors are split into **properties-before-methods** + extensions as needed. Every public witness carries a doc comment + (`missing_docs` is opt-in and CI runs `--strict`). +- **Value tokens split by whether Tailwind v4 makes them customizable** (see + `docs/tailwind-v4-value-model.md` for the per-family rationale, cited to the v4 + docs). The families backed by an extensible `@theme` namespace are modeled as a + **protocol + `Default…` type (SwiftUI-`Style` shape)**: `Color`, `Spacing`, + `Size`, `MaxWidth` (`--container-*`), `TextSize`, `FontWeight`, `Radius`, + `Shadow`, `DropShadow`, `Tracking`, `Ease`. The fixed CSS-keyword families stay + **closed enums** (custom values are meaningless): `Shade`, `Position`, `Flex`, + `FlexDirection`, `ListStyle`, `Align`, `Justify`, `TextAlign`, `VerticalAlign`, + `ObjectFit`, `BorderSide`. The base protocol is in `TailwindToken.swift`. +- **Token types are top-level, bare-named, one per file.** Each is its own file: + a protocol in `Color.swift`/`Radius.swift`/…, its `Default…` struct (carrying + the `where Self ==` static members) in `DefaultColor.swift`/…, each closed enum + in `Shade.swift`/`Position.swift`/… (one-declaration-per-file, so no lint + suppressions). They were previously nested as `TailwindStyleBuilder.Color`; un-nesting + removed ~375 `TailwindStyleBuilder.` qualifications across the module. **Tradeoff:** + bare `Color`/`Size`/`Position`/… can collide with `SwiftUI.Color` etc. in a + downstream file importing both — such a caller must write `TailwindKit.Color`. + TailwindKit is server-side HTML with no SwiftUI consumers, so this is latent. + (The **seam** types `TailwindClass`/`Variant` — and their `Default…` structs — are + also top-level, bare-named, one per file, matching the token types.) +- **The extensible-token pattern (Approach C):** each family is a marker + `public protocol Foo: TailwindToken {}`; built-ins live on a `public struct + DefaultFoo: Foo` whose init is **internal** (so it is *not constructible by + name* — like SwiftUI's `DefaultButtonStyle`). Each built-in value is a + `public static let` **on `DefaultFoo`** (e.g. `DefaultColor.slate`), and the + leading-dot surface is a thin computed forwarder in + `extension Foo where Self == DefaultFoo { public static var slate: DefaultColor { .slate } }` + (the `where Self ==` constraint is required for `.slate`-in-`some Foo` leading-dot + syntax, and forces `DefaultFoo` to be a public type; the forwarder must stay a + computed `var` because a stored `static let` cannot live in an extension — it + resolves to the concrete `DefaultFoo.slate` constant, so there is no recursion). Fluent methods take `some Foo` so a downstream module can + add a custom value by conforming its own type: `struct BrandColor: Color + { let token = "brand" }` → `TW.bg(.brand, .s500)`. Literal families + (`Spacing`/`Size`) instead take the concrete `DefaultSpacing`/`DefaultSize` + so `.gap(4)`/`.p(2.5)` still work. +- Related bare utilities are still grouped into cohesive enum "sets" (e.g. + `Position`, `Flex`, `FlexDirection`, `ListStyle`) rather than a flat wall of + computed properties. +- For Tailwind v4 [arbitrary values](https://tailwindcss.com/docs/adding-custom-styles): + each extensible token family carries a `.arbitrary(_:)` static (e.g. + `.maxW(.arbitrary("48rem"))` → `max-w-[48rem]`, spaces→underscores), and a + developer can also conform a token type whose `token` is the bracketed form. + For a value on an **unmodeled** utility prefix, `TailwindStyle+Arbitrary.swift` + provides `.arbitrary(_ prefix:value:)` (→ `prefix-[value]`), + `.arbitrary(_ prefix:variable:)` (→ `prefix-(--var)`), and + `.custom(property:value:)` (→ `[property:value]`). The removed + `TailwindStyle+Custom.swift`/`Custom` type is gone. For any class not modeled at + all, the escape hatch remains the HTML library's own `class` API. +- Shades are enum cases `.s50`…`.s950` (Swift disallows the `.500` spelling and + leading underscores), e.g. `.bg(.blue, .s500)`. Shade is deliberately **not** + extensible: in v4 `blue-500` is a single `--color-blue-500` variable, so a + custom shade isn't a coherent concept — add a custom `Color` instead. + +## Tests + +Tests are offline and **dependency-free**: they assert `.rendered` string +equality only (e.g. `TW.flex.gap(4).rendered == "flex gap-4"`), so nothing in +the test target imports an HTML library. `TailwindClassAttribute` is covered by +conforming a local stub, which keeps that property true. Uses swift-testing +(`@Suite`/`@Test`/`#expect`), not XCTest. + +## Conventions + +- The MIT license header on every hand-written Swift file is managed by + `Scripts/header.sh` (invoked from `lint.sh` locally). Don't hand-maintain + headers. +- Strict concurrency is complete (Swift 6 mode). `@unchecked Sendable` is banned + by a custom SwiftLint rule — fix Sendability properly. + +## Memory & Corrections Convention + +`.claude/agent-notes.md` is the canonical, versioned corrections log for this repository — an +append-only record of the maintainer's corrections and standing **always/never** directives. + +- **Read `.claude/agent-notes.md` at the start of every work session, before doing any work.** It + is the source of truth for *how* to work in this repo. +- **Whenever the maintainer makes a correction or gives an always/never instruction, append one + line to `.claude/agent-notes.md` proactively (without being asked).** One line per directive, + newest at the bottom. If a directive supersedes an earlier one, update or remove the stale line + rather than leaving both. diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 160a1b6..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,17 +0,0 @@ -# Changelog - -## Unreleased - -### Added - -- Flexbox properties -- Aspect-ratio properties -- Breakpoint capabilities -- Changelog file #2 by @maeganwilson -- Changelog guidelines #2 by @maeganwilson -- Contributing guidelines #2 by @maeganwilson -- Danger #2 by @maeganwilson - -## Released - -:( \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md new file mode 120000 index 0000000..47dc3e3 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/CONTRIBUTING/Changelog_Guidelines.md b/CONTRIBUTING/Changelog_Guidelines.md deleted file mode 100644 index c3e0997..0000000 --- a/CONTRIBUTING/Changelog_Guidelines.md +++ /dev/null @@ -1,52 +0,0 @@ -# Changelog Guidelines - -Here are the guidelines for maintaining the Changelog. We follow [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) a bit closely. Remember, a changelog is for humans so make sure entries are readable. - -## Guiding principles - -- Changelogs are for humans to understand -- There should be an entry for each version -- Unreleased changes will be at the top of the list -- The project follows [semantic versioning](https://semver.org) meaning Major.Minor.Patch -- Type of changes should be grouped -- Versions and sections should be linkable -- Add a PR number and a GitHub tag at the end of each entry -- Mark **breaking changes** and move them to the top - -### Example of structure - -``` -## [Version] - Date in YYYY-MM-DD - -### Type of change - -- **Breaking** description #pr_number by @username_goes_here -- first item of type #pr_number by @username_goes_here -- second item of type #pr_number by @username_goes_here -- third item of type #pr_number by @username_goes_here -``` - - -## Types of changes - -- Added: new features -- Changed: changes in existing functionality -- Deprecated: soon-to-be-removed features -- Removed: now removed features -- Fixed: bug fixes - -## Example - -``` -## v2.0 - 2022-08-01 - -### Added - -- Flexbox properties #pr_number by @username_goes_here -- Aspect-ratio properties #pr_number by @username_goes_here -- Breakpoint capabilities #pr_number by @username_goes_here - -## Changed - -- How hover works #pr_number by @username_goes_here -``` \ No newline at end of file diff --git a/CONTRIBUTING/Contributing.md b/CONTRIBUTING/Contributing.md deleted file mode 100644 index 8cf6fc0..0000000 --- a/CONTRIBUTING/Contributing.md +++ /dev/null @@ -1,12 +0,0 @@ -# Contributing - -Welcome! I'm glad you want to contribute! Tailwind is a big project and getting it converted over to Swift is a big process, so I'll take any help I can get! - -There are some guidelines that I want to mention/ - -## Guidelines - -- Commit messages *should* follow [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) as much as possible. This keeps the git commit history looking nice and clean. -- Keep Pull Requests under 600 changes -- Make sure to add to the [changelog](/CHANGELOG.md) and follow those [guidelines](./Changelog_Guidelines.md) -- Have fun! \ No newline at end of file diff --git a/Dangerfile.swift b/Dangerfile.swift deleted file mode 100644 index 011c2e4..0000000 --- a/Dangerfile.swift +++ /dev/null @@ -1,27 +0,0 @@ -import Danger -let danger = Danger() - -let editedFiles = danger.git.modifiedFiles + danger.git.createdFiles -let hasChangelog = danger.git.modifiedFiles.contains("CHANGELOG.md") - -let PRThreshold: Int = 600; // Number of changes allowed per PR - -if (!hasChangelog) { - warn(""" - Any changes to the package should be reflected in the [changelog](https://github.com/maeganwilson/TailwindKit/blob/main/CHANGELOG.md#unreleased) - - Add a note and follow the [guidelines](https://github.com/maeganwilson/TailwindKit/blob/main/CONTRIBUTING/Changelog_Guidelines.md#changelog-guidelines). - """) -} - -if danger.github.pullRequest.title.contains("WIP") { - warn("PR is classed as Work in Progress") -} - -if danger.github.pullRequest.changedFiles! >= PRThreshold { - fail("PR is too big, please break it up into smaller pull requests") -} - -if danger.github.pullRequest.body!.count < 10 { - fail("Include a description of PR changes") -} \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ef95d3b --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 BrightDigit + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Package.swift b/Package.swift index 7d1239c..3e08973 100644 --- a/Package.swift +++ b/Package.swift @@ -1,28 +1,24 @@ -// swift-tools-version: 5.6 -// The swift-tools-version declares the minimum version of Swift required to build this package. +// swift-tools-version:6.4 +// swiftlint:disable explicit_acl explicit_top_level_acl import PackageDescription let package = Package( - name: "TailwindKit", - products: [ - // Products define the executables and libraries a package produces, and make them visible to other packages. - .library( - name: "TailwindKit", - targets: ["TailwindKit"]), - ], - dependencies: [ - // Dependencies declare other packages that this package depends on. - // .package(url: /* package url */, from: "1.0.0"), - ], - targets: [ - // Targets are the basic building blocks of a package. A target can define a module or a test suite. - // Targets can depend on other targets in this package, and on products in packages this package depends on. - .target( - name: "TailwindKit", - dependencies: []), - .testTarget( - name: "TailwindKitTests", - dependencies: ["TailwindKit"]), - ] + name: "TailwindKit", + platforms: [.macOS(.v13)], + products: [ + .library( + name: "TailwindKit", + targets: ["TailwindKit"] + ) + ], + targets: [ + .target( + name: "TailwindKit" + ), + .testTarget( + name: "TailwindKitTests", + dependencies: ["TailwindKit"] + ) + ] ) diff --git a/README.md b/README.md index b7c9f3e..758b886 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,186 @@ +![TailwindKit Logo](Sources/TailwindKit/TailwindKit.docc/Resources/TailwindKitLogo.svg) + # TailwindKit -A Swift package that allows type safety when using [Tailwind CSS](https://tailwindcss.com) -## Why +[![Swift Versions](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fbrightdigit%2FTailwindKit%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/brightdigit/TailwindKit) +[![Platforms](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fbrightdigit%2FTailwindKit%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/brightdigit/TailwindKit) +[![Documentation](https://img.shields.io/badge/docc-read_documentation-blue)](https://swiftpackageindex.com/brightdigit/TailwindKit/documentation) +[![License](https://img.shields.io/github/license/brightdigit/TailwindKit)](LICENSE) +[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/brightdigit/TailwindKit/TailwindKit.yml?label=actions&logo=github&branch=main)](https://github.com/brightdigit/TailwindKit/actions) +[![Maintainability](https://qlty.sh/gh/brightdigit/projects/TailwindKit/maintainability.svg)](https://qlty.sh/gh/brightdigit/projects/TailwindKit) +[![Codecov](https://img.shields.io/codecov/c/github/brightdigit/TailwindKit)](https://codecov.io/gh/brightdigit/TailwindKit) +[![CodeFactor Grade](https://img.shields.io/codefactor/grade/github/brightdigit/TailwindKit)](https://www.codefactor.io/repository/github/brightdigit/TailwindKit) + +Type-safe Tailwind CSS v4 utility classes for Swift. + +--- + +## What is TailwindKit? + +Server-side Swift HTML markup is full of stringly-typed CSS: `class="flex items-center gap-4"` is +just text, so a typo is a silently broken layout that no compiler and no test will catch. + +**TailwindKit is a small, immutable value builder that emits [Tailwind CSS v4](https://tailwindcss.com) +utility class strings from checked Swift expressions.** Every utility is a property or a method, +every value is a typed token, and the class string only appears at the end, via `.rendered`. + +```swift +import TailwindKit + +TW.flex.items(.center).gap(4).bg(.blue, .s500).rendered +// "flex items-center gap-4 bg-blue-500" +``` + +`brightdigit.com` uses TailwindKit to author its component markup. + +> **Scope:** TailwindKit is **Tailwind v4 only**, and its modeled utility surface is deliberately +> **closed** — a set of Swift enums and methods that grows as consuming components need new +> classes, not a mirror of every class Tailwind can emit. The public API accepts no free-form class +> name; the only caller-supplied strings go through the explicit arbitrary-value API below. For a +> class that isn't modeled at all, the escape hatch is your HTML library's own `class` API. + +## Installation + +Add TailwindKit to your `Package.swift`: + +```swift +dependencies: [ + .package(url: "https://github.com/brightdigit/TailwindKit.git", from: "1.0.0") +] +``` + +Then add it to a target: + +```swift +.target( + name: "MySite", + dependencies: [.product(name: "TailwindKit", package: "TailwindKit")] +) +``` + +## Usage + +### The builder + +The core type is `TailwindStyleBuilder` — an immutable value builder where every member returns a +new builder. Bare utilities are computed properties; parameterized utilities are methods. `TW` is a +type alias for the builder, so a chain can start with the type name or with a leading dot. + +```swift +TW.flex.flexDirection(.col).justify(.between).items(.stretch).rendered +// "flex flex-col justify-between items-stretch" +``` + +The fluent surface is organized into one public capability protocol per CSS concern — +`ColorStyling`, `SpacingStyling`, `SizingStyling`, `PositioningStyling`, `DisplayStyling`, +`FlexGridStyling`, `TypographyStyling`, `BorderStyling`, `EffectsStyling`, `TransitionStyling`, +`ListStyling`, `VariantStyling` and `ArbitraryStyling` — all composed through the seam protocol +`TailwindStyle`. + +### With an HTML library + +**TailwindKit has no dependencies** — not even Foundation. `TailwindStyleBuilder.rendered` is just a +`String`, so it drops into any HTML library: + +```swift +Node.div(.class(TW.flex.items(.center).gap(4).rendered), .text("Hi")) +``` + +For nicer call sites, conform that library's attribute type to `TailwindClassAttribute`. Its single +requirement is `class(_:)` — the factory HTML libraries already declare — so the conformance is a +declaration with **nothing to implement**, and the `.tailwind(_:)` sugar comes with it: + +```swift +import Plot +import TailwindKit + +extension Node: TailwindClassAttribute where Context: HTMLContext {} +extension Attribute: TailwindClassAttribute where Context: HTMLContext {} + +Node.div(.tailwind(.flex.items(.center).gap(4)), .text("Hi")) +//
Hi
+``` + +One conditional conformance covers every context, and leading-dot inference keeps working through +the protocol extension, so `.tailwind(…)` reads exactly like a native factory. + +Types whose class assignment is an *instance* modifier rather than a static factory — Plot's +`Component`, say — can't use the protocol, because Swift does not allow retroactively conforming one +protocol to another. Write the one-liner directly instead: + +```swift +extension Component { + public func tailwind( + _ style: TailwindStyleBuilder, + replaceExisting: Bool = false + ) -> Component { + self.class(style.rendered, replaceExisting: replaceExisting) + } +} + +Image("logo.png").tailwind(.rounded(.lg)) +// +``` + +### Responsive and state variants + +A variant takes a nested style and prefixes every token it produced. Prefixes stack by nesting. + +```swift +TW.block.lg(.hidden).rendered // "block lg:hidden" +TW.md(.hover(.bg(.blue, .s700))).rendered // "md:hover:bg-blue-700" +``` + +### Custom token values + +The token families Tailwind v4 backs with an extensible `@theme` namespace — `Color`, `Spacing`, +`Size`, `MaxWidth`, `TextSize`, `FontWeight`, `Radius`, `Shadow`, `DropShadow`, `Tracking` and +`Ease` — are protocols. Conform your own type to register a value the built-ins don't cover: + +```swift +struct BrandColor: Color { let token = "brand" } + +TW.bg(BrandColor(), .s500).rendered // "bg-brand-500" +``` + +The families that map to fixed CSS keywords (`Shade`, `Position`, `Flex`, `FlexDirection`, +`ListStyle`, `Align`, `Justify`, `TextAlign`, `VerticalAlign`, `ObjectFit`, `BorderSide`) stay +closed enums, because a custom value there would be meaningless. + +### Arbitrary values + +For the occasional [arbitrary value](https://tailwindcss.com/docs/adding-custom-styles) Tailwind v4 +supports, the utility prefix is supplied by you — only the value is arbitrary: + +```swift +TW.arbitrary("top", value: "117px").rendered // "top-[117px]" +TW.arbitrary("bg", variable: "--brand").rendered // "bg-(--brand)" +TW.arbitrary("grid-cols", value: "1fr 500px").rendered +// "grid-cols-[1fr_500px]" (spaces become underscores) +TW.custom(property: "mask-type", value: "luminance").rendered +// "[mask-type:luminance]" +``` + +Each extensible token family also carries an `.arbitrary(_:)` static, e.g. +`TW.maxW(.arbitrary("48rem"))` → `max-w-[48rem]`. + +## Testing + +```bash +swift test +``` + +`Tests/TailwindKitTests` uses swift-testing (`@Suite`/`@Test`/`#expect`). The tests are offline and +depend on no HTML library: they assert `.rendered` string equality only, e.g. +`TW.flex.gap(4).rendered == "flex gap-4"`. The `TailwindClassAttribute` seam is covered by +conforming a local stand-in type. + +## Requirements -This package allows the user of Tailwind CSS in Swift. There are use cases for writing HTML in Swift and that HTML needs to be styled. Tailwind CSS is a popular CSS framework that allows developers to easily add styles to the HTML element by specifying a class. Tailwind classes would be all strings in Swift, so this makes those strings type safe. +- Swift 6.4+ +- macOS 13+, or Ubuntu 24.04 (Noble) -## Can I contribute? +## License -You sure can! Checkout the [Contributing](/CONTRIBUTING/Contributing.md) doc. \ No newline at end of file +[MIT](LICENSE) © BrightDigit diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md new file mode 100644 index 0000000..3556cc7 --- /dev/null +++ b/RELEASE_NOTES.md @@ -0,0 +1,66 @@ +# Release Notes + +## Unreleased + +Wave 1 merge (brightdigit/TailwindKit #1, head `brightdigit-com-260717`) — subrepo +tracking branch synced into the default branch via `git subrepo push`. This replaces the +2022-era prototype (`Flexbox.swift`, `Layout/`, `Shared/Breakpoints.swift`) with a +Tailwind **v4-only** builder. + +### Library + +- New immutable value builder `TailwindStyleBuilder` (aliased `TW`) that accumulates + Tailwind v4 utility tokens and renders them with `.rendered`. Bare utilities are + computed properties, parameterized utilities are methods, and static mirrors let a + chain start with a leading dot. +- The fluent surface is split into ~13 public capability protocols, one per CSS concern + (`ColorStyling`, `SpacingStyling`, `FlexGridStyling`, `TypographyStyling`, + `BorderStyling`, `EffectsStyling`, `PositioningStyling`, `SizingStyling`, + `DisplayStyling`, `ListStyling`, `TransitionStyling`, `VariantStyling`, + `ArbitraryStyling`), each witnessed through the public seam protocol `TailwindStyle`. + The seam takes `some TailwindClass` / `some Variant` rather than `String`, so there is + no raw-string entry point into the public API. +- Value tokens are split by whether Tailwind v4 makes them customizable. Families backed + by an extensible `@theme` namespace (`Color`, `Spacing`, `Size`, `MaxWidth`, + `TextSize`, `FontWeight`, `Radius`, `Shadow`, `DropShadow`, `Tracking`, `Ease`) are + modeled as a protocol plus a `Default…` type with an internal init, so downstream + modules can register custom values by conforming their own type. Fixed CSS-keyword + families (`Shade`, `Position`, `Flex`, `FlexDirection`, `ListStyle`, `Align`, + `Justify`, `TextAlign`, `VerticalAlign`, `ObjectFit`, `BorderSide`) stay closed enums. +- Responsive and state variants nest and stack: `TW.md(.hover(.bg(.blue, .s700)))` + renders `md:hover:bg-blue-700`. +- Arbitrary-value support for Tailwind v4 square-bracket and CSS-variable notation, via + per-family `.arbitrary(_:)` statics plus `arbitrary(_:value:)`, + `arbitrary(_:variable:)` and `custom(property:value:)`. +- **The package has no dependencies at all** — not even Foundation. HTML-library support is + opt-in through the `TailwindClassAttribute` seam: its single requirement is `class(_:)`, + the factory HTML libraries already declare, so conforming an element type takes an empty + extension — no forwarding body — and the `.tailwind(_:)` sugar comes with it, with + leading-dot inference intact. Consumers own the conformance, so TailwindKit no longer + depends on Plot. +- Added `LICENSE` (MIT © BrightDigit); the package previously shipped with none. +- Added a `TailwindKit.docc` catalog and `.spi.yml` so Swift Package Index builds + documentation for the `TailwindKit` target. + +### Tests + +- Replaced `AspectRatioTests`, `BreakpointTests` and `FlexboxTests` with four + swift-testing suites — `TailwindStyleTests`, `TailwindStyleCoverageTests`, + `TailwindStyleExtensibilityTests` and `TailwindStyleSetsAndCustomTests` — that assert + `.rendered` string equality only and never import an HTML library. `TailwindClassAttributeTests` + covers the integration seam by conforming a local stub. + +### CI + +- Replaced the `macos-12` `Test Package` and Danger `Pull Request Check` workflows, which + could no longer be scheduled on any runner, with the standard BrightDigit package + workflow `TailwindKit.yml` (Ubuntu, macOS, Apple platforms, Windows and Android on + Swift 6.4) plus the shared `check-unsafe-flags`, `claude`, `claude-code-review`, + `cleanup-caches` and `swift-source-compat` workflows. +- `fail-fast: true` on every matrix leg; the Ubuntu coverage step uses + `sersoft-gmbh/swift-coverage-action@v5`; `build-macos-platforms` drops the + `ENABLE_WATCHOS` gate and adds a visionOS leg. +- Added `.devcontainer` on `swiftlang/swift:nightly-6.4.x-noble`, `.mise.toml`-pinned lint + tooling, `Scripts/lint.sh` + `Scripts/header.sh`, `.swift-format`, `.swiftlint.yml`, + `.periphery.yml`, `codecov.yml` and `.github/dependabot.yml`. +- Removed the abandoned `CHANGELOG.md`, `CONTRIBUTING/` directory and `Dangerfile.swift`. diff --git a/Scripts/header.sh b/Scripts/header.sh new file mode 100755 index 0000000..c571c18 --- /dev/null +++ b/Scripts/header.sh @@ -0,0 +1,104 @@ +#!/bin/bash + +# Function to print usage +usage() { + echo "Usage: $0 -d directory -c creator -o company -p package [-y year]" + echo " -d directory Directory to read from (including subdirectories)" + echo " -c creator Name of the creator" + echo " -o company Name of the company with the copyright" + echo " -p package Package or library name" + echo " -y year Copyright year (optional, defaults to current year)" + exit 1 +} + +# Get the current year if not provided +current_year=$(date +"%Y") + +# Default values +year="$current_year" + +# Parse arguments +while getopts ":d:c:o:p:y:" opt; do + case $opt in + d) directory="$OPTARG" ;; + c) creator="$OPTARG" ;; + o) company="$OPTARG" ;; + p) package="$OPTARG" ;; + y) year="$OPTARG" ;; + *) usage ;; + esac +done + +# Check for mandatory arguments +if [ -z "$directory" ] || [ -z "$creator" ] || [ -z "$company" ] || [ -z "$package" ]; then + usage +fi + +# Define the header template +header_template="// +// %s +// %s +// +// Created by %s. +// Copyright © %s %s. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the \"Software\"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +//" + +# Loop through each Swift file in the specified directory and subdirectories +find "$directory" -type f -name "*.swift" | while read -r file; do + # Skip files in the Generated directory + if [[ "$file" == *"/Generated/"* ]]; then + echo "Skipping $file (generated file)" + continue + fi + + # Check if the first line is the swift-format-ignore indicator + first_line=$(head -n 1 "$file") + if [[ "$first_line" == "// swift-format-ignore-file" ]]; then + echo "Skipping $file due to swift-format-ignore directive." + continue + fi + + # Create the header with the current filename + filename=$(basename "$file") + header=$(printf "$header_template" "$filename" "$package" "$creator" "$year" "$company") + + # Remove all consecutive lines at the beginning which start with "// ", contain only whitespace, or only "//" + awk ' + BEGIN { skip = 1 } + { + if (skip && ($0 ~ /^\/\/ / || $0 ~ /^\/\/$/ || $0 ~ /^$/)) { + next + } + skip = 0 + print + }' "$file" > temp_file + + # Add the header to the cleaned file + (echo "$header"; echo; cat temp_file) > "$file" + + # Remove the temporary file + rm temp_file +done + +echo "Headers added or files skipped appropriately across all Swift files in the directory and subdirectories." diff --git a/Scripts/lint.sh b/Scripts/lint.sh new file mode 100755 index 0000000..954f226 --- /dev/null +++ b/Scripts/lint.sh @@ -0,0 +1,104 @@ +#!/bin/bash + +# Remove set -e to allow script to continue running +# set -e # Exit on any error + +ERRORS=0 + +run_command() { + "$@" || ERRORS=$((ERRORS + 1)) +} + +if [ "$LINT_MODE" = "INSTALL" ]; then + exit +fi + +echo "LintMode: $LINT_MODE" + +# More portable way to get script directory +if [ -z "$SRCROOT" ]; then + SCRIPT_DIR=$(dirname "$(readlink -f "$0")") + PACKAGE_DIR="${SCRIPT_DIR}/.." +else + PACKAGE_DIR="${SRCROOT}" +fi + +# Detect if mise is available +# Check common installation paths for mise +MISE_PATHS=( + "/opt/homebrew/bin/mise" + "/usr/local/bin/mise" + "$HOME/.local/bin/mise" +) + +MISE_BIN="" +for mise_path in "${MISE_PATHS[@]}"; do + if [ -x "$mise_path" ]; then + MISE_BIN="$mise_path" + break + fi +done + +# Fallback to PATH lookup +if [ -z "$MISE_BIN" ] && command -v mise &> /dev/null; then + MISE_BIN="mise" +fi + +if [ -n "$MISE_BIN" ]; then + TOOL_CMD="$MISE_BIN exec --" +else + echo "Error: mise is not installed" + echo "Install mise: https://mise.jdx.dev/getting-started.html" + echo "Checked paths: ${MISE_PATHS[*]}" + exit 1 +fi + +if [ "$LINT_MODE" = "NONE" ]; then + exit +elif [ "$LINT_MODE" = "STRICT" ]; then + SWIFTFORMAT_LINT_OPTIONS="--strict" + SWIFTLINT_OPTIONS="--strict" +else + SWIFTFORMAT_LINT_OPTIONS="" + SWIFTLINT_OPTIONS="" +fi + +pushd $PACKAGE_DIR + +# Bootstrap tools (mise will install based on .mise.toml) +run_command "$MISE_BIN" install + +if [ -z "$CI" ]; then + run_command $TOOL_CMD swift-format format --configuration .swift-format --recursive --parallel --in-place Sources Tests + run_command $TOOL_CMD swiftlint --fix +fi + +if [ -z "$FORMAT_ONLY" ]; then + run_command $TOOL_CMD swift-format lint --configuration .swift-format --recursive --parallel $SWIFTFORMAT_LINT_OPTIONS Sources Tests + run_command $TOOL_CMD swiftlint lint $SWIFTLINT_OPTIONS + # Check for compilation errors + run_command swift build --build-tests +fi + +# header.sh rewrites file headers in place, so it only runs locally — never in CI. +if [ -z "$CI" ]; then + $PACKAGE_DIR/Scripts/header.sh -d $PACKAGE_DIR/Sources -c "Leo Dion" -o "BrightDigit" -p "TailwindKit" +fi + +if [ -z "$CI" ]; then + # Swift 6.4's default 'swiftbuild' build system writes the index store to + # .build/index-build/...; periphery 3.7.4 looks for it under .build/debug/index/store. + # Force the native build system so periphery finds the index store. + run_command $TOOL_CMD periphery scan $PERIPHERY_OPTIONS --disable-update-check -- --build-system native +fi + +popd + +# Exit with error code if any errors occurred +if [ $ERRORS -gt 0 ]; then + echo "Linting completed with $ERRORS error(s)" + exit 1 +else + echo "Linting completed successfully" + exit 0 +fi diff --git a/Sources/TailwindKit/Core/DefaultTailwindClass.swift b/Sources/TailwindKit/Core/DefaultTailwindClass.swift new file mode 100644 index 0000000..ddeb260 --- /dev/null +++ b/Sources/TailwindKit/Core/DefaultTailwindClass.swift @@ -0,0 +1,43 @@ +// +// DefaultTailwindClass.swift +// TailwindKit +// +// Created by Leo Dion. +// Copyright © 2026 BrightDigit. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// + +/// The built-in ``TailwindClass`` used by every modeled utility. +/// +/// A `public` type (it is the concrete value the capability witnesses pass to +/// the seam) with an `internal` initializer, so it is **not constructible by +/// name** outside the module — like ``DefaultColor``. This is +/// what keeps the public seam from becoming a raw-string entry point. +public struct DefaultTailwindClass: TailwindClass { + /// The rendered utility class, e.g. `"bg-blue-500"`. + public let className: String + + internal init(_ className: String) { + self.className = className + } +} diff --git a/Sources/TailwindKit/Core/DefaultVariant.swift b/Sources/TailwindKit/Core/DefaultVariant.swift new file mode 100644 index 0000000..288eec6 --- /dev/null +++ b/Sources/TailwindKit/Core/DefaultVariant.swift @@ -0,0 +1,94 @@ +// +// DefaultVariant.swift +// TailwindKit +// +// Created by Leo Dion. +// Copyright © 2026 BrightDigit. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// + +/// The built-in Tailwind variant prefixes. +/// +/// A `public` type (the return type of the static members below) with an +/// `internal` initializer, so callers reference `.md`/`.hover` but never +/// construct it directly — like ``DefaultColor``. +public struct DefaultVariant: Variant { + // swiftlint:disable identifier_name + /// `sm:` — ≥ 40rem breakpoint. + public static let sm = DefaultVariant("sm") + /// `md:` — ≥ 48rem breakpoint. + public static let md = DefaultVariant("md") + /// `lg:` — ≥ 64rem breakpoint. + public static let lg = DefaultVariant("lg") + /// `xl:` — ≥ 80rem breakpoint. + public static let xl = DefaultVariant("xl") + // swiftlint:enable identifier_name + /// `2xl:` — ≥ 96rem breakpoint. + public static let xl2 = DefaultVariant("2xl") + /// `hover:` state variant. + public static let hover = DefaultVariant("hover") + /// `focus:` state variant. + public static let focus = DefaultVariant("focus") + /// `active:` state variant. + public static let active = DefaultVariant("active") + /// `disabled:` state variant. + public static let disabled = DefaultVariant("disabled") + /// `group-hover:` state variant. + public static let groupHover = DefaultVariant("group-hover") + /// `dark:` color-scheme variant. + public static let dark = DefaultVariant("dark") + + /// The rendered prefix, e.g. `"md"`, `"hover"`. + public let token: String + + internal init(_ token: String) { + self.token = token + } +} + +extension Variant where Self == DefaultVariant { + // swiftlint:disable identifier_name + /// `sm:` — ≥ 40rem breakpoint. + public static var sm: DefaultVariant { .sm } + /// `md:` — ≥ 48rem breakpoint. + public static var md: DefaultVariant { .md } + /// `lg:` — ≥ 64rem breakpoint. + public static var lg: DefaultVariant { .lg } + /// `xl:` — ≥ 80rem breakpoint. + public static var xl: DefaultVariant { .xl } + // swiftlint:enable identifier_name + /// `2xl:` — ≥ 96rem breakpoint. + public static var xl2: DefaultVariant { .xl2 } + /// `hover:` state variant. + public static var hover: DefaultVariant { .hover } + /// `focus:` state variant. + public static var focus: DefaultVariant { .focus } + /// `active:` state variant. + public static var active: DefaultVariant { .active } + /// `disabled:` state variant. + public static var disabled: DefaultVariant { .disabled } + /// `group-hover:` state variant. + public static var groupHover: DefaultVariant { .groupHover } + /// `dark:` color-scheme variant. + public static var dark: DefaultVariant { .dark } +} diff --git a/Sources/TailwindKit/Core/String+ArbitraryValue.swift b/Sources/TailwindKit/Core/String+ArbitraryValue.swift new file mode 100644 index 0000000..0266d7b --- /dev/null +++ b/Sources/TailwindKit/Core/String+ArbitraryValue.swift @@ -0,0 +1,45 @@ +// +// String+ArbitraryValue.swift +// TailwindKit +// +// Created by Leo Dion. +// Copyright © 2026 BrightDigit. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// + +extension String { + /// This Tailwind + /// [arbitrary value](https://tailwindcss.com/docs/adding-custom-styles) with + /// every space replaced by an underscore. + /// + /// A class name cannot contain a space, so Tailwind writes arbitrary values + /// with underscores and converts them back at build time: `[0_1px_2px_black]` + /// is the shadow `0 1px 2px black`. + /// + /// Written as a `map` over the characters rather than + /// `replacingOccurrences(of:with:)` so that TailwindKit depends on no module at + /// all — not even Foundation. + internal var escapingSpaces: String { + String(map { $0 == " " ? "_" : $0 }) + } +} diff --git a/Sources/TailwindKit/Core/TW.swift b/Sources/TailwindKit/Core/TW.swift new file mode 100644 index 0000000..2549f63 --- /dev/null +++ b/Sources/TailwindKit/Core/TW.swift @@ -0,0 +1,34 @@ +// +// TW.swift +// TailwindKit +// +// Created by Leo Dion. +// Copyright © 2026 BrightDigit. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// + +/// Convenient alias for ``TailwindStyleBuilder`` so chains can read `TW.flex.gap(4)`. +/// +/// The name is intentionally two characters — `TW` is the mandated public +/// spelling — so `type_name`'s minimum-length rule is disabled on this line. +public typealias TW = TailwindStyleBuilder // swiftlint:disable:this type_name diff --git a/Sources/TailwindKit/Core/TailwindClass.swift b/Sources/TailwindKit/Core/TailwindClass.swift new file mode 100644 index 0000000..6cb3a6f --- /dev/null +++ b/Sources/TailwindKit/Core/TailwindClass.swift @@ -0,0 +1,50 @@ +// +// TailwindClass.swift +// TailwindKit +// +// Created by Leo Dion. +// Copyright © 2026 BrightDigit. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// + +/// A fully-formed Tailwind utility class fragment — the whole `"bg-blue-500"`, +/// `"flex"`, or `"md:hover:gap-4"` that ``TailwindStyleBuilder`` appends to its token +/// list. +/// +/// `TailwindClass` is the **seam value** the public builder primitive +/// ``TailwindStyleBuilder/appending(_:)`` accepts. It exists so the seam can be +/// `public` (required for the capability-protocol architecture — see +/// ``TailwindStyle``) *without* the public API ever accepting a raw +/// `String`: the built-in utilities construct a ``DefaultTailwindClass``, +/// whose initializer is `internal`, so a caller cannot mint one from an +/// arbitrary string. This preserves TailwindKit's invariant that the modeled +/// surface is closed and type-safe. +/// +/// Unlike ``TailwindToken`` (a *value fragment* like `blue`/`500`), a +/// `TailwindClass` is an *entire* utility class. A downstream module can still +/// conform its own type as a deliberate escape hatch, but the ordinary path is +/// the leading-dot fluent members. +public protocol TailwindClass { + /// The rendered utility class, e.g. `"bg-blue-500"`. + var className: String { get } +} diff --git a/Sources/TailwindKit/Core/TailwindStyle.swift b/Sources/TailwindKit/Core/TailwindStyle.swift new file mode 100644 index 0000000..009dc06 --- /dev/null +++ b/Sources/TailwindKit/Core/TailwindStyle.swift @@ -0,0 +1,64 @@ +// +// TailwindStyle.swift +// TailwindKit +// +// Created by Leo Dion. +// Copyright © 2026 BrightDigit. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// + +/// The shared **seam** the TailwindKit capability protocols implement against. +/// +/// Each capability (``ColorStyling``, ``SpacingStyling``, …) provides its fluent +/// members in a protocol extension constrained on `Self: TailwindStyle`, +/// composing new styles through the two primitives declared here, so +/// ``TailwindStyleBuilder`` itself is only storage plus `init`/``TailwindStyleBuilder/rendered`` +/// — it carries no fluent method bodies. This mirrors how `ButtondownKit`'s +/// capability protocols implement against `UnderlyingClientProtocol.underlying`. +/// +/// This protocol must be **public**: the capability protocols' members are +/// public requirements witnessed by those constrained extensions, and Swift +/// forbids a `public` member in an extension whose generic constraint refers to +/// a non-public protocol ("cannot declare a public instance method in an +/// extension with internal requirements"). +/// +/// Crucially — and unlike a naive port of the `underlying` seam — neither +/// primitive accepts a raw `String`. ``appending(_:)`` takes a ``TailwindClass`` +/// and ``prefixing(_:_:)`` takes a ``Variant``, both of whose built-in +/// conformers have `internal` initializers. So exposing the seam publicly does +/// **not** open a raw-string hole in the API; the modeled surface stays closed. +public protocol TailwindStyle { + /// Returns a new style with `tailwindClass` appended. + /// + /// The single composition primitive behind every non-variant utility. Built-in + /// utilities pass a ``DefaultTailwindClass``; a downstream module may pass its + /// own ``TailwindClass`` conformer. + func appending(_ tailwindClass: some TailwindClass) -> Self + + /// Returns a new style with every token of `other` prefixed by `variant`. + /// + /// Models responsive/state variants; prefixes stack, so + /// `.md(.hover(.bg(.blue, .s700)))` renders `"md:hover:bg-blue-700"`. + func prefixing(_ variant: some Variant, _ other: TailwindStyleBuilder) + -> Self +} diff --git a/Sources/TailwindKit/Core/TailwindStyleBuilder.swift b/Sources/TailwindKit/Core/TailwindStyleBuilder.swift new file mode 100644 index 0000000..8b40a9d --- /dev/null +++ b/Sources/TailwindKit/Core/TailwindStyleBuilder.swift @@ -0,0 +1,116 @@ +// +// TailwindStyleBuilder.swift +// TailwindKit +// +// Created by Leo Dion. +// Copyright © 2026 BrightDigit. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// + +/// A type-safe, fluent builder for [Tailwind CSS v4](https://tailwindcss.com) +/// utility class strings. +/// +/// `TailwindStyleBuilder` is a pure value type with **no dependencies at all** — +/// no HTML library, not even Foundation. Every member — bare utilities exposed as computed properties +/// and parameterized utilities exposed as methods — returns a new +/// `TailwindStyleBuilder`, so styles are composed by chaining: +/// +/// ```swift +/// TW.flex.items(.center).gap(4).bg(.blue, .s500).rendered +/// // "flex items-center gap-4 bg-blue-500" +/// ``` +/// +/// The final class string is produced by ``rendered``, which is all an HTML +/// library needs. Conform an element type to ``TailwindClassAttribute`` to +/// attach a style with `.tailwind(_:)` instead: +/// +/// ```swift +/// Node.div(.tailwind(.flex.items(.center).gap(4)), .text("Hi")) +/// ``` +/// +/// The set of modeled utilities is intentionally **closed** and grown +/// component-driven: add cases as components need them. For any class not yet +/// modeled, the escape hatch is the HTML library's own `class` API — +/// `TailwindStyleBuilder` itself never accepts raw strings. +public struct TailwindStyleBuilder: Sendable, Equatable, Hashable { + /// The ordered, fully-prefixed utility tokens (e.g. `"items-center"`, + /// `"md:gap-4"`), rendered space-separated by ``rendered``. + private let tokens: [String] + + /// The composed Tailwind class string, tokens joined by a single space. + /// + /// ```swift + /// TW.flex.gap(4).rendered // "flex gap-4" + /// ``` + public var rendered: String { + tokens.joined(separator: " ") + } + + /// Creates an empty style. + /// + /// Chain utilities to build it up, or start a chain from a static member + /// such as `.flex`. + public init() { + self.tokens = [] + } + + private init(tokens: [String]) { + self.tokens = tokens + } + + /// Returns a new style with the raw token string `token` appended. + /// + /// File-private: the only raw-string composition point. The public seam + /// (``appending(_:)`` taking a ``TailwindClass``) forwards here, so no + /// raw-string entry point is ever exposed. + private func appendingToken(_ token: String) -> TailwindStyleBuilder { + TailwindStyleBuilder(tokens: tokens + [token]) + } + + /// Returns a new style with every token of `other` prefixed by + /// `"\(prefix):"` and appended. + /// + /// Used to model responsive/state variants (e.g. `md`, `hover`); prefixes + /// stack, so `.md(.hover(.bg(.blue, .s700)))` renders `"md:hover:bg-blue-700"`. + private func prefixingToken(_ prefix: String, _ other: TailwindStyleBuilder) + -> TailwindStyleBuilder + { + TailwindStyleBuilder(tokens: tokens + other.tokens.map { "\(prefix):\($0)" }) + } +} + +// The public seam (see ``TailwindStyle``). Both primitives forward to the +// file-private string helpers above; retyping the *public* surface to +// ``TailwindClass`` / ``Variant`` is what lets the seam be public without ever +// accepting a raw `String`. +extension TailwindStyleBuilder: TailwindStyle { + /// Returns a new style with `tailwindClass` appended. + public func appending(_ tailwindClass: some TailwindClass) -> Self { + appendingToken(tailwindClass.className) + } + + /// Returns a new style with every token of `other` prefixed by `variant`. + public func prefixing(_ variant: some Variant, _ other: TailwindStyleBuilder) -> Self { + prefixingToken(variant.token, other) + } +} diff --git a/Sources/TailwindKit/Core/TailwindToken.swift b/Sources/TailwindKit/Core/TailwindToken.swift new file mode 100644 index 0000000..4790413 --- /dev/null +++ b/Sources/TailwindKit/Core/TailwindToken.swift @@ -0,0 +1,63 @@ +// +// TailwindToken.swift +// TailwindKit +// +// Created by Leo Dion. +// Copyright © 2026 BrightDigit. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// + +/// A single value fragment in a Tailwind utility class — the `blue` in +/// `bg-blue-500`, the `lg` in `rounded-lg`, the `4` in `gap-4`. +/// +/// `TailwindToken` is the shared seam for Tailwind v4's **theme-scale** value +/// families (the `@theme` namespaces `--color-*`, `--text-*`, `--radius-*`, …). +/// Each such family is modeled as a protocol refining `TailwindToken`, with the +/// documented built-in values exposed as static members on a `Default…` +/// conforming type — mirroring how SwiftUI models `ButtonStyle`, `TextFieldStyle`, +/// etc. Because these scales are extensible in Tailwind (you add values via +/// `@theme`), the Swift model is open too: conform your own type to add a custom +/// color, size, radius, and so on. +/// +/// ```swift +/// // Built-in, via the leading-dot static member: +/// TW.bg(.blue, .s500).rendered // "bg-blue-500" +/// +/// // Custom, by conforming your own token type in your module: +/// struct BrandColor: Color { let token = "brand" } +/// extension Color where Self == BrandColor { +/// static var brand: BrandColor { .init() } +/// } +/// TW.bg(.brand, .s500).rendered // "bg-brand-500" +/// ``` +/// +/// Tailwind's **fixed keyword sets** (position, object-fit, flex-direction, the +/// color *shade* steps, …) are *not* modeled with this protocol — a custom value +/// there is not a coherent concept, so they remain closed enums. +public protocol TailwindToken: Sendable { + /// The rendered fragment, e.g. `"blue"`, `"lg"`, `"4"`. + /// + /// Consumed by ``TailwindStyleBuilder`` builder methods when composing a class + /// string; not intended to be read directly by callers. + var token: String { get } +} diff --git a/Sources/TailwindKit/Core/Variant.swift b/Sources/TailwindKit/Core/Variant.swift new file mode 100644 index 0000000..e70a588 --- /dev/null +++ b/Sources/TailwindKit/Core/Variant.swift @@ -0,0 +1,49 @@ +// +// Variant.swift +// TailwindKit +// +// Created by Leo Dion. +// Copyright © 2026 BrightDigit. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// + +/// A Tailwind **variant** prefix — the `md` in `md:flex`, the `hover` in +/// `hover:bg-blue-700`. +/// +/// `Variant` is the value passed to ``TailwindStyleBuilder/prefixing(_:_:)`` and +/// exposed through the responsive/state fluent members (`.md`, `.hover`, …). +/// Variants compose by nesting — `.md(.hover(.bg(.blue, .s700)))` stacks the +/// prefixes into `"md:hover:bg-blue-700"`. +/// +/// Like ``Color``, `Variant` is **extensible** (Tailwind lets +/// you register custom variants, e.g. via `@custom-variant`): conform your own +/// type to add one — +/// +/// ```swift +/// struct SupportsGrid: Variant { let token = "supports-[display:grid]" } +/// TW().prefixing(SupportsGrid(), .flex) // "supports-[display:grid]:flex" +/// ``` +/// +/// The documented built-ins are exposed as static members on +/// ``DefaultVariant`` via the leading-dot syntax (`.md`, …). +public protocol Variant: TailwindToken {} diff --git a/Sources/TailwindKit/Flexbox.swift b/Sources/TailwindKit/Flexbox.swift deleted file mode 100644 index 558124f..0000000 --- a/Sources/TailwindKit/Flexbox.swift +++ /dev/null @@ -1,18 +0,0 @@ -// -// Flexbox.swift -// -// -// Created by Maegan Wilson on 8/16/22. -// - -import Foundation - -public enum FlexBox: String { - case flex = "flex" - case wrap = "flex-wrap" - case row = "flex-row" - case rowReverse = "flex-row-reverse" - case column = "flex-col" - case columnReverse = "flex-col-reverse" - case grow = "grow" -} diff --git a/Sources/TailwindKit/Integration/TailwindClassAttribute.swift b/Sources/TailwindKit/Integration/TailwindClassAttribute.swift new file mode 100644 index 0000000..1865437 --- /dev/null +++ b/Sources/TailwindKit/Integration/TailwindClassAttribute.swift @@ -0,0 +1,90 @@ +// +// TailwindClassAttribute.swift +// TailwindKit +// +// Created by Leo Dion. +// Copyright © 2026 BrightDigit. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// + +/// An attribute-producing type that can be built from a `class` string. +/// +/// This is the **HTML-library-independent seam**. TailwindKit models Tailwind +/// utilities but depends on no HTML library; conforming a library's attribute or +/// node type to this protocol is all that is needed to gain the ``tailwind(_:)`` +/// sugar below. +/// +/// The single requirement is spelled ``class(_:)`` — the name HTML libraries +/// already give this factory — so a conformance is a **declaration with no +/// implementation**. For [Plot](https://github.com/JohnSundell/Plot), whose +/// `Node` and `Attribute` both declare +/// `public static func class(_ className: String) -> Self` under +/// `Context: HTMLContext`, the existing member satisfies the requirement +/// directly: +/// +/// ```swift +/// extension Node: TailwindClassAttribute where Context: HTMLContext {} +/// extension Attribute: TailwindClassAttribute where Context: HTMLContext {} +/// ``` +/// +/// One conditional conformance covers every context, and leading-dot inference +/// keeps working through the protocol extension, so `.tailwind(…)` reads exactly +/// as a native factory would: +/// +/// ```swift +/// Node.div(.tailwind(.flex.items(.center).gap(4))) +/// //
+/// ``` +/// +/// Types whose class assignment is an *instance* modifier rather than a static +/// factory — Plot's `Component`, say — cannot use this protocol, because a +/// protocol cannot be retroactively conformed to another protocol. Write the +/// one-line sugar directly on those instead. +public protocol TailwindClassAttribute { + /// Creates a value representing a `class` attribute set to `className`. + /// + /// - Parameter className: The space-separated class string to assign. + /// - Returns: The created value. + static func `class`(_ className: String) -> Self +} + +extension TailwindClassAttribute { + /// Renders a ``TailwindStyleBuilder`` into this element's `class` attribute. + /// + /// Sugar for ``class(_:)`` applied to + /// ``TailwindStyleBuilder/rendered``: + /// + /// ```swift + /// Node.div(.tailwind(.flex.items(.center).gap(4))) + /// //
+ /// ``` + /// + /// For any class TailwindKit does not model, use the HTML library's own + /// `class` API directly. + /// + /// - Parameter style: The Tailwind style to render. + /// - Returns: The created value. + public static func tailwind(_ style: TailwindStyleBuilder) -> Self { + .class(style.rendered) + } +} diff --git a/Sources/TailwindKit/Layout/AspectRatio.swift b/Sources/TailwindKit/Layout/AspectRatio.swift deleted file mode 100644 index b869645..0000000 --- a/Sources/TailwindKit/Layout/AspectRatio.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// AspectRatio.swift -// -// -// Created by Maegan Wilson on 8/16/22. -// - -import Foundation - -public extension Tailwind { - static func aspectRatio(_ prop: Aspect? = nil) -> String { - if let aspectRatio = prop { - return aspectRatio.class - } - return Aspect.auto.class - } -} - -public enum Aspect: String { - case auto = "aspect-auto" - case square = "aspect-square" - case video = "aspect-video" - - var `class`: String { self.rawValue } -} diff --git a/Sources/TailwindKit/Layout/Display.swift b/Sources/TailwindKit/Layout/Display.swift deleted file mode 100644 index 6f7d9da..0000000 --- a/Sources/TailwindKit/Layout/Display.swift +++ /dev/null @@ -1,44 +0,0 @@ -// -// Display.swift -// -// -// Created by Maegan Wilson on 8/16/22. -// - -import Foundation - -public extension Tailwind { - static func display(_ prop: Displays) -> String { - if prop == .flex { - return flex([.flex]) - } - // TODO: Make grid like flex - return prop.class - } -} - -public enum Displays: String { - case block - case inlineBlock = "inline-block" - case inline - case flex - case inlineFlex = "inline-flex" - case table - case inlineTable = "inline-table" - case tableCaption = "table-caption" - case tableCell = "table-cell" - case tableColumn = "table-column" - case tableColumnGroup = "table-column-group" - case tableFooterGroup = "table-footer-group" - case tableHeaderGroup = "table-header-group" - case tableRowGroup = "table-row-group" - case tableRow = "table-row" - case flowRoot = "flow-root" - case grid - case inlineGrid = "inline-grid" - case contents = "contents" - case listItem = "listItem" - case hidden - - var `class`: String { self.rawValue } -} diff --git a/Sources/TailwindKit/Shared/Breakpoints.swift b/Sources/TailwindKit/Shared/Breakpoints.swift deleted file mode 100644 index b3496d1..0000000 --- a/Sources/TailwindKit/Shared/Breakpoints.swift +++ /dev/null @@ -1,24 +0,0 @@ -// -// Breakpoints.swift -// -// -// Created by Maegan Wilson on 8/16/22. -// - -import Foundation - -public extension Tailwind { - static func breakpoint(_ bp: Breakpoints, prop: String) -> String { - return "\(bp.size):\(prop)" - } -} - -public enum Breakpoints: String { - case sm - case md - case lg - case xl - case xxl - - var size: String { self.rawValue } -} diff --git a/Sources/TailwindKit/Styling/ArbitraryStyling.swift b/Sources/TailwindKit/Styling/ArbitraryStyling.swift new file mode 100644 index 0000000..ce66063 --- /dev/null +++ b/Sources/TailwindKit/Styling/ArbitraryStyling.swift @@ -0,0 +1,88 @@ +// +// ArbitraryStyling.swift +// TailwindKit +// +// Created by Leo Dion. +// Copyright © 2026 BrightDigit. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// + +/// The **arbitrary value** escape hatch utilities. +/// +/// A capability protocol whose members are witnessed against the +/// ``TailwindStyle`` seam; ``TailwindStyleBuilder`` conforms to it. See +/// ``TailwindStyle`` for why the surface is organized this way. +/// +/// These members intentionally take raw `String` arguments: they are the +/// escape hatch for expressing Tailwind classes that have no strongly typed +/// counterpart. Spaces in values are escaped to underscores per Tailwind's +/// arbitrary-value syntax. +public protocol ArbitraryStyling { + /// `-[]`, e.g. `.arbitrary("top", value: "117px")` → `top-[117px]`. + /// + /// Spaces in `value` are escaped to underscores. + func arbitrary(_ prefix: String, value: String) -> Self + /// `-()`, e.g. `.arbitrary("bg", variable: "--brand")` → `bg-(--brand)`. + func arbitrary(_ prefix: String, variable name: String) -> Self + /// `[:]`, e.g. `.custom(property: "mask-type", value: "luminance")`. + /// + /// Spaces in `value` are escaped to underscores. + func custom(property: String, value: String) -> Self +} + +extension ArbitraryStyling where Self: TailwindStyle { + /// `-[]`, e.g. `.arbitrary("top", value: "117px")` → `top-[117px]`. + /// + /// Spaces in `value` are escaped to underscores. + public func arbitrary(_ prefix: String, value: String) -> Self { + appending(DefaultTailwindClass("\(prefix)-[\(value.escapingSpaces)]")) + } + /// `-()`, e.g. `.arbitrary("bg", variable: "--brand")` → `bg-(--brand)`. + public func arbitrary(_ prefix: String, variable name: String) -> Self { + appending(DefaultTailwindClass("\(prefix)-(\(name))")) + } + /// `[:]`, e.g. `.custom(property: "mask-type", value: "luminance")`. + /// + /// Spaces in `value` are escaped to underscores. + public func custom(property: String, value: String) -> Self { + appending(DefaultTailwindClass("[\(property):\(value.escapingSpaces)]")) + } +} + +extension TailwindStyleBuilder: ArbitraryStyling {} + +// Static mirrors so an arbitrary utility can start a chain with a leading dot. +extension TailwindStyleBuilder { + /// `-[]`. + public static func arbitrary(_ prefix: String, value: String) -> TailwindStyleBuilder { + TailwindStyleBuilder().arbitrary(prefix, value: value) + } + /// `-()`. + public static func arbitrary(_ prefix: String, variable name: String) -> TailwindStyleBuilder { + TailwindStyleBuilder().arbitrary(prefix, variable: name) + } + /// `[:]`. + public static func custom(property: String, value: String) -> TailwindStyleBuilder { + TailwindStyleBuilder().custom(property: property, value: value) + } +} diff --git a/Sources/TailwindKit/Styling/BorderStyling.swift b/Sources/TailwindKit/Styling/BorderStyling.swift new file mode 100644 index 0000000..efe61e6 --- /dev/null +++ b/Sources/TailwindKit/Styling/BorderStyling.swift @@ -0,0 +1,106 @@ +// +// BorderStyling.swift +// TailwindKit +// +// Created by Leo Dion. +// Copyright © 2026 BrightDigit. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// + +/// The **border** and **border-radius** utilities. +/// +/// A capability protocol whose members are witnessed against the +/// ``TailwindStyle`` seam; ``TailwindStyleBuilder`` conforms to it. See +/// ``TailwindStyle`` for why the surface is organized this way. +public protocol BorderStyling { + /// `border`. + var border: Self { get } + /// `rounded`. + var rounded: Self { get } + /// `border-none`. + var borderNone: Self { get } + + /// `border-`, e.g. `.border(2)` → `border-2`. + func border(_ width: Int) -> Self + /// `border--`, e.g. `.border(.t, 2)` → `border-t-2`. + func border(_ side: BorderSide, _ width: Int) -> Self + /// `rounded-`, e.g. `.rounded(.lg)` → `rounded-lg`. + func rounded(_ radius: some Radius) -> Self +} + +extension BorderStyling where Self: TailwindStyle { + // MARK: Bare + + /// `border`. + public var border: Self { appending(DefaultTailwindClass("border")) } + /// `rounded`. + public var rounded: Self { appending(DefaultTailwindClass("rounded")) } + /// `border-none`. + public var borderNone: Self { + appending(DefaultTailwindClass("border-none")) + } + + // MARK: Parameterized + + /// `border-`, e.g. `.border(2)` → `border-2`. + public func border(_ width: Int) -> Self { + appending(DefaultTailwindClass("border-\(width)")) + } + /// `border--`, e.g. `.border(.t, 2)` → `border-t-2`. + public func border(_ side: BorderSide, _ width: Int) -> Self { + appending(DefaultTailwindClass("border-\(side.token)-\(width)")) + } + /// `rounded-`, e.g. `.rounded(.lg)` → `rounded-lg`. + public func rounded(_ radius: some Radius) -> Self { + radius.token.isEmpty + ? appending(DefaultTailwindClass("rounded")) + : appending(DefaultTailwindClass("rounded-\(radius.token)")) + } +} + +extension TailwindStyleBuilder: BorderStyling {} + +// Static mirrors so a border utility can start a chain with a leading dot. +extension TailwindStyleBuilder { + /// `border`. + public static var border: TailwindStyleBuilder { TailwindStyleBuilder().border } + /// `rounded`. + public static var rounded: TailwindStyleBuilder { TailwindStyleBuilder().rounded } + /// `border-none`. + public static var borderNone: TailwindStyleBuilder { TailwindStyleBuilder().borderNone } +} + +extension TailwindStyleBuilder { + /// `border-`. + public static func border(_ width: Int) -> TailwindStyleBuilder { + TailwindStyleBuilder().border(width) + } + /// `border--`. + public static func border(_ side: BorderSide, _ width: Int) -> TailwindStyleBuilder { + TailwindStyleBuilder().border(side, width) + } + /// `rounded-`. + public static func rounded(_ radius: some Radius) -> TailwindStyleBuilder { + TailwindStyleBuilder().rounded(radius) + } +} diff --git a/Sources/TailwindKit/Styling/ColorStyling.swift b/Sources/TailwindKit/Styling/ColorStyling.swift new file mode 100644 index 0000000..c67acfa --- /dev/null +++ b/Sources/TailwindKit/Styling/ColorStyling.swift @@ -0,0 +1,178 @@ +// +// ColorStyling.swift +// TailwindKit +// +// Created by Leo Dion. +// Copyright © 2026 BrightDigit. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// + +/// The background/text/border **color** utilities. +/// +/// A capability protocol whose members are witnessed against the +/// ``TailwindStyle`` seam; ``TailwindStyleBuilder`` conforms to it. See +/// ``TailwindStyle`` for why the surface is organized this way. +public protocol ColorStyling { + /// `bg-white`. + var bgWhite: Self { get } + /// `bg-black`. + var bgBlack: Self { get } + /// `bg-transparent`. + var bgTransparent: Self { get } + + /// `bg--`, e.g. `.bg(.blue, .s500)`. + func bg(_ color: some Color, _ shade: Shade) -> Self + /// `border--`, e.g. `.borderColor(.gray, .s200)`. + func borderColor(_ color: some Color, _ shade: Shade) -> Self + /// `text--`, e.g. `.text(.blue, .s500)`. + func text(_ color: some Color, _ shade: Shade) -> Self + + /// `bg-white/`, e.g. `.bgWhite(opacity: 90)` → `bg-white/90`. + func bgWhite(opacity: Int) -> Self + /// `bg-black/`, e.g. `.bgBlack(opacity: 30)` → `bg-black/30`. + func bgBlack(opacity: Int) -> Self + /// `bg--/`, e.g. `.bg(.gray, .s500, opacity: 50)`. + func bg(_ color: some Color, _ shade: Shade, opacity: Int) + -> Self + /// `text--/`. + func text(_ color: some Color, _ shade: Shade, opacity: Int) + -> Self + /// `border--/`, e.g. `.borderColor(.gray, .s400, opacity: 10)`. + func borderColor(_ color: some Color, _ shade: Shade, opacity: Int) + -> Self +} + +extension ColorStyling where Self: TailwindStyle { + // MARK: Bare + + /// `bg-white`. + public var bgWhite: Self { appending(DefaultTailwindClass("bg-white")) } + /// `bg-black`. + public var bgBlack: Self { appending(DefaultTailwindClass("bg-black")) } + /// `bg-transparent`. + public var bgTransparent: Self { + appending(DefaultTailwindClass("bg-transparent")) + } + + // MARK: Color + shade + + /// `bg--`, e.g. `.bg(.blue, .s500)`. + public func bg(_ color: some Color, _ shade: Shade) -> Self { + appending(DefaultTailwindClass("bg-\(color.token)-\(shade.token)")) + } + /// `border--`, e.g. `.borderColor(.gray, .s200)`. + public func borderColor(_ color: some Color, _ shade: Shade) + -> Self + { + appending(DefaultTailwindClass("border-\(color.token)-\(shade.token)")) + } + /// `text--`, e.g. `.text(.blue, .s500)`. + public func text(_ color: some Color, _ shade: Shade) -> Self { + appending(DefaultTailwindClass("text-\(color.token)-\(shade.token)")) + } + + // MARK: Color + shade + opacity + + /// `bg-white/`, e.g. `.bgWhite(opacity: 90)` → `bg-white/90`. + public func bgWhite(opacity: Int) -> Self { + appending(DefaultTailwindClass("bg-white/\(opacity)")) + } + /// `bg-black/`, e.g. `.bgBlack(opacity: 30)` → `bg-black/30`. + public func bgBlack(opacity: Int) -> Self { + appending(DefaultTailwindClass("bg-black/\(opacity)")) + } + /// `bg--/`, e.g. `.bg(.gray, .s500, opacity: 50)`. + public func bg(_ color: some Color, _ shade: Shade, opacity: Int) + -> Self + { + appending( + DefaultTailwindClass("bg-\(color.token)-\(shade.token)/\(opacity)") + ) + } + /// `text--/`. + public func text(_ color: some Color, _ shade: Shade, opacity: Int) + -> Self + { + appending( + DefaultTailwindClass("text-\(color.token)-\(shade.token)/\(opacity)") + ) + } + /// `border--/`, e.g. `.borderColor(.gray, .s400, opacity: 10)`. + public func borderColor( + _ color: some Color, _ shade: Shade, opacity: Int + ) -> Self { + appending( + DefaultTailwindClass("border-\(color.token)-\(shade.token)/\(opacity)") + ) + } +} + +extension TailwindStyleBuilder: ColorStyling {} + +// Static mirrors so a color utility can start a chain with a leading dot. +extension TailwindStyleBuilder { + /// `bg-white`. + public static var bgWhite: TailwindStyleBuilder { TailwindStyleBuilder().bgWhite } + /// `bg-black`. + public static var bgBlack: TailwindStyleBuilder { TailwindStyleBuilder().bgBlack } + /// `bg-transparent`. + public static var bgTransparent: TailwindStyleBuilder { TailwindStyleBuilder().bgTransparent } +} + +extension TailwindStyleBuilder { + /// `bg--`. + public static func bg(_ color: some Color, _ shade: Shade) -> TailwindStyleBuilder { + TailwindStyleBuilder().bg(color, shade) + } + /// `border--`. + public static func borderColor(_ color: some Color, _ shade: Shade) -> TailwindStyleBuilder { + TailwindStyleBuilder().borderColor(color, shade) + } + /// `text--`. + public static func text(_ color: some Color, _ shade: Shade) -> TailwindStyleBuilder { + TailwindStyleBuilder().text(color, shade) + } + /// `bg-white/`. + public static func bgWhite(opacity: Int) -> TailwindStyleBuilder { + TailwindStyleBuilder().bgWhite(opacity: opacity) + } + /// `bg-black/`. + public static func bgBlack(opacity: Int) -> TailwindStyleBuilder { + TailwindStyleBuilder().bgBlack(opacity: opacity) + } + /// `bg--/`. + public static func bg(_ color: some Color, _ shade: Shade, opacity: Int) -> TailwindStyleBuilder { + TailwindStyleBuilder().bg(color, shade, opacity: opacity) + } + /// `text--/`. + public static func text(_ color: some Color, _ shade: Shade, opacity: Int) -> TailwindStyleBuilder + { + TailwindStyleBuilder().text(color, shade, opacity: opacity) + } + /// `border--/`. + public static func borderColor(_ color: some Color, _ shade: Shade, opacity: Int) + -> TailwindStyleBuilder + { + TailwindStyleBuilder().borderColor(color, shade, opacity: opacity) + } +} diff --git a/Sources/TailwindKit/Styling/DisplayStyling.swift b/Sources/TailwindKit/Styling/DisplayStyling.swift new file mode 100644 index 0000000..07de2d5 --- /dev/null +++ b/Sources/TailwindKit/Styling/DisplayStyling.swift @@ -0,0 +1,105 @@ +// +// DisplayStyling.swift +// TailwindKit +// +// Created by Leo Dion. +// Copyright © 2026 BrightDigit. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// + +/// The **display** utilities. +/// +/// A capability protocol whose members are witnessed against the +/// ``TailwindStyle`` seam; ``TailwindStyleBuilder`` conforms to it. See +/// ``TailwindStyle`` for why the surface is organized this way. +public protocol DisplayStyling { + /// `flex`. + var flex: Self { get } + /// `inline-flex`. + var inlineFlex: Self { get } + /// `grid`. + var grid: Self { get } + /// `block`. + var block: Self { get } + /// `inline-block`. + var inlineBlock: Self { get } + /// `inline`. + var inline: Self { get } + /// `hidden`. + var hidden: Self { get } + /// `container`. + var container: Self { get } + /// `contents`. + var contents: Self { get } +} + +extension DisplayStyling where Self: TailwindStyle { + // MARK: Bare + + /// `flex`. + public var flex: Self { appending(DefaultTailwindClass("flex")) } + /// `inline-flex`. + public var inlineFlex: Self { + appending(DefaultTailwindClass("inline-flex")) + } + /// `grid`. + public var grid: Self { appending(DefaultTailwindClass("grid")) } + /// `block`. + public var block: Self { appending(DefaultTailwindClass("block")) } + /// `inline-block`. + public var inlineBlock: Self { + appending(DefaultTailwindClass("inline-block")) + } + /// `inline`. + public var inline: Self { appending(DefaultTailwindClass("inline")) } + /// `hidden`. + public var hidden: Self { appending(DefaultTailwindClass("hidden")) } + /// `container`. + public var container: Self { appending(DefaultTailwindClass("container")) } + /// `contents`. + public var contents: Self { appending(DefaultTailwindClass("contents")) } +} + +extension TailwindStyleBuilder: DisplayStyling {} + +// Static mirrors so a display utility can start a chain with a leading dot. +extension TailwindStyleBuilder { + /// `flex`. + public static var flex: TailwindStyleBuilder { TailwindStyleBuilder().flex } + /// `inline-flex`. + public static var inlineFlex: TailwindStyleBuilder { TailwindStyleBuilder().inlineFlex } + /// `grid`. + public static var grid: TailwindStyleBuilder { TailwindStyleBuilder().grid } + /// `block`. + public static var block: TailwindStyleBuilder { TailwindStyleBuilder().block } + /// `inline-block`. + public static var inlineBlock: TailwindStyleBuilder { TailwindStyleBuilder().inlineBlock } + /// `inline`. + public static var inline: TailwindStyleBuilder { TailwindStyleBuilder().inline } + /// `hidden`. + public static var hidden: TailwindStyleBuilder { TailwindStyleBuilder().hidden } + /// `container`. + public static var container: TailwindStyleBuilder { TailwindStyleBuilder().container } + /// `contents`. + public static var contents: TailwindStyleBuilder { TailwindStyleBuilder().contents } +} diff --git a/Sources/TailwindKit/Styling/EffectsStyling.swift b/Sources/TailwindKit/Styling/EffectsStyling.swift new file mode 100644 index 0000000..bd994ec --- /dev/null +++ b/Sources/TailwindKit/Styling/EffectsStyling.swift @@ -0,0 +1,161 @@ +// +// EffectsStyling.swift +// TailwindKit +// +// Created by Leo Dion. +// Copyright © 2026 BrightDigit. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// + +/// Shadow, ring, opacity, object-fit, and filter utilities. +/// +/// A capability protocol witnessed against the ``TailwindStyle`` seam; +/// ``TailwindStyleBuilder`` conforms to it. See ``TailwindStyle`` for the +/// architecture rationale. +public protocol EffectsStyling { + /// `invert` (`invert(100%)`). + var invert: Self { get } + /// `grayscale` (`grayscale(100%)`). + var grayscale: Self { get } + /// `backdrop-grayscale`. + var backdropGrayscale: Self { get } + + /// `shadow-`, e.g. `.shadow(.lg)`. + func shadow(_ shadow: some Shadow) -> Self + /// `drop-shadow-`, e.g. `.dropShadow(.xl)`. + func dropShadow(_ shadow: some DropShadow) -> Self + /// `ring-`, e.g. `.ring(4)`. + func ring(_ width: Int) -> Self + /// `opacity-`, e.g. `.opacity(90)`. + func opacity(_ value: Int) -> Self + /// `object-`, e.g. `.object(.cover)`. + func object(_ fit: ObjectFit) -> Self + /// `backdrop-blur-`, e.g. `.backdropBlur(.lg)`. + func backdropBlur(_ radius: some Radius) -> Self + /// `backdrop-brightness-`, e.g. `.backdropBrightness(50)`. + func backdropBrightness(_ value: Int) -> Self + /// `hue-rotate-`, e.g. `.hueRotate(180)`. + func hueRotate(_ degrees: Int) -> Self +} + +extension EffectsStyling where Self: TailwindStyle { + // MARK: Filters (bare) + + /// `invert` (`invert(100%)`). + public var invert: Self { appending(DefaultTailwindClass("invert")) } + /// `grayscale` (`grayscale(100%)`). + public var grayscale: Self { appending(DefaultTailwindClass("grayscale")) } + /// `backdrop-grayscale`. + public var backdropGrayscale: Self { + appending(DefaultTailwindClass("backdrop-grayscale")) + } + + // MARK: Effects + + /// `shadow-`, e.g. `.shadow(.lg)`. + public func shadow(_ shadow: some Shadow) -> Self { + appending(DefaultTailwindClass("shadow-\(shadow.token)")) + } + /// `drop-shadow-`, e.g. `.dropShadow(.xl)`. + public func dropShadow(_ shadow: some DropShadow) -> Self { + appending(DefaultTailwindClass("drop-shadow-\(shadow.token)")) + } + /// `ring-`, e.g. `.ring(4)`. + public func ring(_ width: Int) -> Self { + appending(DefaultTailwindClass("ring-\(width)")) + } + /// `opacity-`, e.g. `.opacity(90)`. + public func opacity(_ value: Int) -> Self { + appending(DefaultTailwindClass("opacity-\(value)")) + } + /// `object-`, e.g. `.object(.cover)`. + public func object(_ fit: ObjectFit) -> Self { + appending(DefaultTailwindClass("object-\(fit.token)")) + } + + // MARK: Filters (parameterized) + + /// `backdrop-blur-`, e.g. `.backdropBlur(.lg)`. + public func backdropBlur(_ radius: some Radius) -> Self { + radius.token.isEmpty + ? appending(DefaultTailwindClass("backdrop-blur")) + : appending(DefaultTailwindClass("backdrop-blur-\(radius.token)")) + } + /// `backdrop-brightness-`, e.g. `.backdropBrightness(50)`. + public func backdropBrightness(_ value: Int) -> Self { + appending(DefaultTailwindClass("backdrop-brightness-\(value)")) + } + /// `hue-rotate-`, e.g. `.hueRotate(180)`. + public func hueRotate(_ degrees: Int) -> Self { + appending(DefaultTailwindClass("hue-rotate-\(degrees)")) + } +} + +extension TailwindStyleBuilder: EffectsStyling {} + +// Static mirrors so an effect/filter utility can start a chain with a leading dot. +extension TailwindStyleBuilder { + /// `invert`. + public static var invert: TailwindStyleBuilder { TailwindStyleBuilder().invert } + /// `grayscale`. + public static var grayscale: TailwindStyleBuilder { TailwindStyleBuilder().grayscale } + /// `backdrop-grayscale`. + public static var backdropGrayscale: TailwindStyleBuilder { + TailwindStyleBuilder().backdropGrayscale + } +} + +extension TailwindStyleBuilder { + /// `shadow-`. + public static func shadow(_ shadow: some Shadow) -> TailwindStyleBuilder { + TailwindStyleBuilder().shadow(shadow) + } + /// `drop-shadow-`. + public static func dropShadow(_ shadow: some DropShadow) -> TailwindStyleBuilder { + TailwindStyleBuilder().dropShadow(shadow) + } + /// `ring-`. + public static func ring(_ width: Int) -> TailwindStyleBuilder { + TailwindStyleBuilder().ring(width) + } + /// `opacity-`. + public static func opacity(_ value: Int) -> TailwindStyleBuilder { + TailwindStyleBuilder().opacity(value) + } + /// `object-`. + public static func object(_ fit: ObjectFit) -> TailwindStyleBuilder { + TailwindStyleBuilder().object(fit) + } + /// `backdrop-blur-`. + public static func backdropBlur(_ radius: some Radius) -> TailwindStyleBuilder { + TailwindStyleBuilder().backdropBlur(radius) + } + /// `backdrop-brightness-`. + public static func backdropBrightness(_ value: Int) -> TailwindStyleBuilder { + TailwindStyleBuilder().backdropBrightness(value) + } + /// `hue-rotate-`. + public static func hueRotate(_ degrees: Int) -> TailwindStyleBuilder { + TailwindStyleBuilder().hueRotate(degrees) + } +} diff --git a/Sources/TailwindKit/Styling/FlexGridStyling.swift b/Sources/TailwindKit/Styling/FlexGridStyling.swift new file mode 100644 index 0000000..6337b32 --- /dev/null +++ b/Sources/TailwindKit/Styling/FlexGridStyling.swift @@ -0,0 +1,164 @@ +// +// FlexGridStyling.swift +// TailwindKit +// +// Created by Leo Dion. +// Copyright © 2026 BrightDigit. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// + +/// Flexbox & grid layout utilities — direction, wrapping, growth, gaps, and +/// item/content alignment. +/// +/// A capability protocol witnessed against the ``TailwindStyle`` seam; +/// ``TailwindStyleBuilder`` conforms to it. See ``TailwindStyle`` for the +/// architecture rationale. +public protocol FlexGridStyling { + /// `flex-wrap`. + var flexWrap: Self { get } + /// `grow`. + var grow: Self { get } + /// `shrink`. + var shrink: Self { get } + /// `grow-0`. + var grow0: Self { get } + /// `shrink-0`. + var shrink0: Self { get } + + /// `items-` — cross-axis alignment, e.g. `.items(.center)`. + func items(_ align: Align) -> Self + /// `justify-` — main-axis distribution, e.g. `.justify(.between)`. + func justify(_ value: Justify) -> Self + /// `grid-cols-`, e.g. `.gridCols(3)`. + func gridCols(_ count: Int) -> Self + /// `gap-`, e.g. `.gap(4)`. + func gap(_ amount: DefaultSpacing) -> Self + /// `gap-x-`. + func gapX(_ amount: DefaultSpacing) -> Self + /// `gap-y-`. + func gapY(_ amount: DefaultSpacing) -> Self + /// `flex-` shorthand, e.g. `.flex(.one)` → `flex-1`. + func flex(_ value: Flex) -> Self + /// `flex-`, e.g. `.flexDirection(.col)` → `flex-col`. + func flexDirection(_ value: FlexDirection) -> Self + /// `self-`, e.g. `.selfAlign(.start)` → `self-start`. + func selfAlign(_ align: Align) -> Self + /// `justify-items-`, e.g. `.justifyItems(.end)`. + func justifyItems(_ align: Align) -> Self + /// `justify-self-`, e.g. `.justifySelf(.center)`. + func justifySelf(_ align: Align) -> Self + /// `content-`, e.g. `.content(.between)` → `content-between`. + func content(_ value: Justify) -> Self + /// `place-items-`, e.g. `.placeItems(.stretch)`. + func placeItems(_ align: Align) -> Self + /// `place-self-`, e.g. `.placeSelf(.center)`. + func placeSelf(_ align: Align) -> Self + /// `space-x-`, e.g. `.spaceX(1)`. + func spaceX(_ amount: DefaultSpacing) -> Self + /// `space-y-`. + func spaceY(_ amount: DefaultSpacing) -> Self +} + +extension FlexGridStyling where Self: TailwindStyle { + // MARK: Bare + + /// `flex-wrap`. + public var flexWrap: Self { appending(DefaultTailwindClass("flex-wrap")) } + /// `grow`. + public var grow: Self { appending(DefaultTailwindClass("grow")) } + /// `shrink`. + public var shrink: Self { appending(DefaultTailwindClass("shrink")) } + /// `grow-0`. + public var grow0: Self { appending(DefaultTailwindClass("grow-0")) } + /// `shrink-0`. + public var shrink0: Self { appending(DefaultTailwindClass("shrink-0")) } + + // MARK: Flex & grid + + /// `items-` — cross-axis alignment, e.g. `.items(.center)`. + public func items(_ align: Align) -> Self { + appending(DefaultTailwindClass("items-\(align.token)")) + } + /// `justify-` — main-axis distribution, e.g. `.justify(.between)`. + public func justify(_ value: Justify) -> Self { + appending(DefaultTailwindClass("justify-\(value.token)")) + } + /// `grid-cols-`, e.g. `.gridCols(3)`. + public func gridCols(_ count: Int) -> Self { + appending(DefaultTailwindClass("grid-cols-\(count)")) + } + /// `gap-`, e.g. `.gap(4)`. + public func gap(_ amount: DefaultSpacing) -> Self { + appending(DefaultTailwindClass(amount.className(prefix: "gap"))) + } + /// `gap-x-`. + public func gapX(_ amount: DefaultSpacing) -> Self { + appending(DefaultTailwindClass(amount.className(prefix: "gap-x"))) + } + /// `gap-y-`. + public func gapY(_ amount: DefaultSpacing) -> Self { + appending(DefaultTailwindClass(amount.className(prefix: "gap-y"))) + } + /// `flex-` shorthand, e.g. `.flex(.one)` → `flex-1`. + public func flex(_ value: Flex) -> Self { + appending(DefaultTailwindClass("flex-\(value.token)")) + } + /// `flex-`, e.g. `.flexDirection(.col)` → `flex-col`. + public func flexDirection(_ value: FlexDirection) -> Self { + appending(DefaultTailwindClass("flex-\(value.token)")) + } + /// `self-`, e.g. `.selfAlign(.start)` → `self-start`. + public func selfAlign(_ align: Align) -> Self { + appending(DefaultTailwindClass("self-\(align.token)")) + } + /// `justify-items-`, e.g. `.justifyItems(.end)`. + public func justifyItems(_ align: Align) -> Self { + appending(DefaultTailwindClass("justify-items-\(align.token)")) + } + /// `justify-self-`, e.g. `.justifySelf(.center)`. + public func justifySelf(_ align: Align) -> Self { + appending(DefaultTailwindClass("justify-self-\(align.token)")) + } + /// `content-`, e.g. `.content(.between)` → `content-between`. + public func content(_ value: Justify) -> Self { + appending(DefaultTailwindClass("content-\(value.token)")) + } + /// `place-items-`, e.g. `.placeItems(.stretch)`. + public func placeItems(_ align: Align) -> Self { + appending(DefaultTailwindClass("place-items-\(align.token)")) + } + /// `place-self-`, e.g. `.placeSelf(.center)`. + public func placeSelf(_ align: Align) -> Self { + appending(DefaultTailwindClass("place-self-\(align.token)")) + } + /// `space-x-`, e.g. `.spaceX(1)`; `.spaceX(.neg(2))` → `-space-x-2`. + public func spaceX(_ amount: DefaultSpacing) -> Self { + appending(DefaultTailwindClass(amount.className(prefix: "space-x"))) + } + /// `space-y-`; `.spaceY(.neg(2))` → `-space-y-2`. + public func spaceY(_ amount: DefaultSpacing) -> Self { + appending(DefaultTailwindClass(amount.className(prefix: "space-y"))) + } +} + +extension TailwindStyleBuilder: FlexGridStyling {} diff --git a/Sources/TailwindKit/Styling/ListStyling.swift b/Sources/TailwindKit/Styling/ListStyling.swift new file mode 100644 index 0000000..ea328e4 --- /dev/null +++ b/Sources/TailwindKit/Styling/ListStyling.swift @@ -0,0 +1,55 @@ +// +// ListStyling.swift +// TailwindKit +// +// Created by Leo Dion. +// Copyright © 2026 BrightDigit. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// + +/// The list-style utilities. +/// +/// A capability protocol whose members are witnessed against the +/// ``TailwindStyle`` seam; ``TailwindStyleBuilder`` conforms to it. See +/// ``TailwindStyle`` for why the surface is organized this way. +public protocol ListStyling { + /// `list-