@ikas/code-components-mcp 2.7.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/data/framework.json +53 -26
  2. package/data/section-templates/account-info-section/children/AccountFavorites/ikas-config-snippet.json +13 -0
  3. package/data/section-templates/account-info-section/children/AccountOrders/index.tsx +1 -1
  4. package/data/section-templates/account-info-section/ikas-config-snippet.json +19 -0
  5. package/data/section-templates/add-to-cart/ikas-config-snippet.json +17 -0
  6. package/data/section-templates/add-to-cart/utils/cartLimits.ts +4 -3
  7. package/data/section-templates/blog-home-section/ikas-config-snippet.json +2 -0
  8. package/data/section-templates/blog-home-section/index.tsx +2 -1
  9. package/data/section-templates/blog-post-section/ikas-config-snippet.json +2 -0
  10. package/data/section-templates/blog-post-section/index.tsx +3 -2
  11. package/data/section-templates/bundle-products/hooks/useBundleProducts.ts +7 -6
  12. package/data/section-templates/bundle-products/ikas-config-snippet.json +20 -0
  13. package/data/section-templates/cart-section/components/EmptyState/index.tsx +1 -1
  14. package/data/section-templates/cart-section/sub-components/CartItem/index.tsx +9 -0
  15. package/data/section-templates/cart-section/utils/cartLimits.ts +24 -0
  16. package/data/section-templates/cart-section/utils/cartLineLimits.ts +100 -0
  17. package/data/section-templates/category-images-section/children/CategoryImageItem/ikas-config-snippet.json +4 -0
  18. package/data/section-templates/category-images-section/ikas-config-snippet.json +15 -0
  19. package/data/section-templates/category-list-section/children/CardProductName/ikas-config-snippet.json +2 -1
  20. package/data/section-templates/category-list-section/ikas-config-snippet.json +21 -0
  21. package/data/section-templates/category-list-section/index.tsx +2 -1
  22. package/data/section-templates/component-renderer/additional/ProductDetail/index.tsx +5 -1
  23. package/data/section-templates/component-renderer/ikas-config-snippet.json +13 -0
  24. package/data/section-templates/favorites/ikas-config-snippet.json +18 -1
  25. package/data/section-templates/features-section/ikas-config-snippet.json +13 -0
  26. package/data/section-templates/footer-section/ikas-config-snippet.json +15 -0
  27. package/data/section-templates/forgot-password-section/components/ForgotPasswordForm/index.tsx +1 -1
  28. package/data/section-templates/header-section/children/Announcements/ikas-config-snippet.json +7 -0
  29. package/data/section-templates/header-section/children/CookieBar/ikas-config-snippet.json +3 -0
  30. package/data/section-templates/header-section/children/Navbar/components/CartSidebar/index.tsx +2 -1
  31. package/data/section-templates/header-section/children/Navbar/components/SearchModal/index.tsx +2 -1
  32. package/data/section-templates/header-section/children/Navbar/ikas-config-snippet.json +27 -0
  33. package/data/section-templates/header-section/children/Navbar/index.tsx +6 -5
  34. package/data/section-templates/header-section/ikas-config-snippet.json +13 -0
  35. package/data/section-templates/header-section/sub-components/CartItem/index.tsx +9 -0
  36. package/data/section-templates/header-section/utils/cartLimits.ts +24 -0
  37. package/data/section-templates/header-section/utils/cartLineLimits.ts +100 -0
  38. package/data/section-templates/hero-slider-section/children/HeroSliderItem/ikas-config-snippet.json +18 -0
  39. package/data/section-templates/hero-slider-section/children/HeroSliderItem/index.tsx +12 -7
  40. package/data/section-templates/hero-slider-section/ikas-config-snippet.json +13 -0
  41. package/data/section-templates/image-handling/ikas-config-snippet.json +52 -0
  42. package/data/section-templates/image-handling/index.tsx +5 -1
  43. package/data/section-templates/login-section/ikas-config-snippet.json +2 -0
  44. package/data/section-templates/navigation/components/CartSidebar/index.tsx +2 -1
  45. package/data/section-templates/navigation/components/SearchModal/index.tsx +2 -1
  46. package/data/section-templates/navigation/ikas-config-snippet.json +27 -0
  47. package/data/section-templates/navigation/index.tsx +6 -5
  48. package/data/section-templates/navigation/sub-components/CartItem/index.tsx +9 -0
  49. package/data/section-templates/navigation/utils/cartLimits.ts +24 -0
  50. package/data/section-templates/navigation/utils/cartLineLimits.ts +100 -0
  51. package/data/section-templates/product-detail-section/children/ProductDetailAddToCart/ikas-config-snippet.json +17 -0
  52. package/data/section-templates/product-detail-section/children/ProductDetailBackInStock/ikas-config-snippet.json +16 -0
  53. package/data/section-templates/product-detail-section/children/ProductDetailBundleFurniture/ikas-config-snippet.json +18 -0
  54. package/data/section-templates/product-detail-section/children/ProductDetailBundleProduct/ikas-config-snippet.json +20 -0
  55. package/data/section-templates/product-detail-section/children/ProductDetailDescription/ikas-config-snippet.json +27 -0
  56. package/data/section-templates/product-detail-section/children/ProductDetailFeatures/ikas-config-snippet.json +29 -0
  57. package/data/section-templates/product-detail-section/children/ProductDetailNameFavorite/ikas-config-snippet.json +18 -1
  58. package/data/section-templates/product-detail-section/children/ProductDetailOffer/ikas-config-snippet.json +20 -0
  59. package/data/section-templates/product-detail-section/children/ProductDetailOptionSet/ikas-config-snippet.json +16 -0
  60. package/data/section-templates/product-detail-section/children/ProductDetailPrices/ikas-config-snippet.json +16 -0
  61. package/data/section-templates/product-detail-section/children/ProductDetailProductGroup/ikas-config-snippet.json +16 -0
  62. package/data/section-templates/product-detail-section/children/ProductDetailSku/ikas-config-snippet.json +16 -0
  63. package/data/section-templates/product-detail-section/children/ProductDetailVariant/ikas-config-snippet.json +17 -0
  64. package/data/section-templates/product-detail-section/hooks/useBundleProducts.ts +7 -6
  65. package/data/section-templates/product-detail-section/ikas-config-snippet.json +52 -0
  66. package/data/section-templates/product-detail-section/index.tsx +5 -1
  67. package/data/section-templates/product-detail-section/utils/cartLimits.ts +4 -3
  68. package/data/section-templates/product-pricing/ikas-config-snippet.json +16 -0
  69. package/data/section-templates/product-slider-section/children/CardProductName/ikas-config-snippet.json +2 -1
  70. package/data/section-templates/product-slider-section/ikas-config-snippet.json +17 -0
  71. package/data/section-templates/register-section/ikas-config-snippet.json +2 -0
  72. package/data/section-templates/variant-selection/ikas-config-snippet.json +17 -0
  73. package/data/storefront-api.json +301 -17
  74. package/data/storefront-types.json +221 -20
  75. package/dist/index.js +408 -26
  76. package/dist/index.js.map +1 -1
  77. package/package.json +1 -1
@@ -4,7 +4,7 @@
4
4
  "project-structure": {
5
5
  "title": "Project Structure",
6
6
  "description": "How an ikas code components project is organized",
7
- "content": "An ikas code components project follows this structure:\n\n```\nmy-project/\n├── src/\n│ ├── global.css # Optional: project-wide unscoped CSS (variables, resets)\n│ └── components/\n│ ├── MyComponent/\n│ │ ├── index.tsx # Component implementation (Preact)\n│ │ ├── types.ts # TypeScript props interface\n│ │ └── styles.css # Scoped component styles\n│ └── index.ts # Component exports barrel\n├── ikas.config.json # Component definitions, props, metadata\n├── package.json\n├── tsconfig.json\n└── vite.config.ts\n```\n\nEach component lives in its own directory under `src/components/`. The component's entry point is `index.tsx`, which exports a default Preact function component. The `types.ts` file defines the props interface matching the props declared in `ikas.config.json`. The `styles.css` file contains CSS that is automatically scoped to the component.\n\n### Project with Sub-Components\n\nWhen components grow complex, extract sub-components into `src/sub-components/`. See `get_framework_guide(\"sub-component-patterns\")` for full details.\n\n```\nmy-project/\n├── src/\n│ ├── components/\n│ │ ├── ProductList/\n│ │ │ ├── index.tsx # Imports from ../../sub-components/...\n│ │ │ ├── types.ts # Auto-generated (CLI-managed)\n│ │ │ └── styles.css # @import \"../../sub-components/.../styles.css\"\n│ │ └── index.ts\n│ └── sub-components/\n│ ├── ProductCard/\n│ │ ├── index.tsx # Sub-component with inline Props\n│ │ └── styles.css # Sub-component styles\n│ └── FilterSidebar/\n│ ├── index.tsx\n│ └── styles.css\n├── ikas.config.json\n├── package.json\n├── tsconfig.json\n└── vite.config.ts\n```\n\n**Key:** `src/components/` = registered components (in ikas.config.json). `src/sub-components/` = internal helpers (NOT in ikas.config.json).",
7
+ "content": "An ikas code components project follows this structure:\n\n```\nmy-project/\n├── src/\n│ ├── global.css # Optional: project-wide unscoped CSS (variables, resets)\n│ └── components/\n│ ├── MyComponent/\n│ │ ├── index.tsx # Component implementation (Preact)\n│ │ ├── types.ts # TypeScript props interface\n│ │ └── styles.css # Scoped component styles\n│ └── index.ts # Component exports barrel\n├── ikas.config.json # Component definitions, props, metadata\n├── package.json\n├── tsconfig.json\n└── vite.config.ts\n```\n\nEach component lives in its own directory under `src/components/`. The component's entry point is `index.tsx`, which exports a default Preact function component. The `types.ts` file defines the props interface matching the props declared in `ikas.config.json`. The `styles.css` file contains CSS that is automatically scoped to the component.\n\n### Project with Sub-Components\n\nWhen components grow complex, extract sub-components into `src/sub-components/`. See `get_framework_guide(\"sub-component-patterns\")` for full details.\n\n```\nmy-project/\n├── src/\n│ ├── components/\n│ │ ├── ProductList/\n│ │ │ ├── index.tsx # Imports from ../../sub-components/...\n│ │ │ ├── types.ts # Auto-generated (CLI-managed)\n│ │ │ └── styles.css # component styles (sub-component styles.css collected automatically)\n│ │ └── index.ts\n│ └── sub-components/\n│ ├── ProductCard/\n│ │ ├── index.tsx # Sub-component with inline Props\n│ │ └── styles.css # Sub-component styles\n│ └── FilterSidebar/\n│ ├── index.tsx\n│ └── styles.css\n├── ikas.config.json\n├── package.json\n├── tsconfig.json\n└── vite.config.ts\n```\n\n**Key:** `src/components/` = registered components (in ikas.config.json). `src/sub-components/` = internal helpers (NOT in ikas.config.json).",
8
8
  "tags": [
9
9
  "structure",
10
10
  "project",
@@ -35,7 +35,7 @@
35
35
  "prop-types": {
36
36
  "title": "Available Prop Types",
37
37
  "description": "All prop types that can be used in ikas.config.json",
38
- "content": "Props define what the store editor can configure for each component. Each prop has a `type` that determines the editor UI and the TypeScript type received in your component.\n\n| Type | Editor UI | TypeScript Type | Description |\n|------|-----------|----------------|-------------|\n| `TEXT` | Text input | `string` | Single-line text |\n| `RICH_TEXT` | Rich text editor | `string` | HTML rich text content |\n| `NUMBER` | Number input | `number` | Numeric value. Authored `defaultValue` must be a finite number — an empty string, a non-numeric string (e.g. `12px`), NaN or Infinity are rejected by the CLI. |\n| `NUMBER_RANGE` | Number range input | `IkasNumberRange` | Number range with min, max, interval, and unit |\n| `BOOLEAN` | Toggle switch | `boolean` | True/false toggle |\n| `IMAGE` | Image picker | `IkasImage | null` | Image from editor. Use `getDefaultSrc(image)` for URL |\n| `IMAGE_LIST` | Image list picker | `IkasImageList` | Multiple images from editor |\n| `VIDEO` | Video picker | `IkasVideo | null` | Video from editor |\n| `SVG` | SVG upload | `string` | Raw inline SVG markup (the `<svg>…</svg>` source). Normalize with `normalizeSvg(value, { idPrefix })` before rendering via `dangerouslySetInnerHTML`. NOT served through the image CDN — this is the way to ship logos/icons as vectors. |\n| `SVG_LIST` | SVG list upload | `string[]` | List of raw inline SVG markup strings. Normalize each with `normalizeSvg(svg, { idPrefix })` (unique per item) before rendering with `dangerouslySetInnerHTML`. |\n| `DATE` | Date picker | `Date | string` | Date value |\n| `LINK` | Link editor | `IkasNavigationLink | null` | Navigation link. Read at runtime as `.href`/`.label`/`.subLinks`; authored `defaultValue` is a typed object (`linkType`+`externalLink`/`pageType`+`subLinks`). See the LINK section below. |\n| `LIST_OF_LINK` | Link list editor | `IkasNavigationLinkList` | List of navigation links. Authored `defaultValue` is `{ \"links\": [ <link>, … ] }`. See the LINK section below. |\n| `COLOR` | Color picker | `string` | CSS color value (hex, rgb, etc.) |\n| `PRODUCT` | Product picker | `IkasProduct | null` | Single product reference |\n| `PRODUCT_LIST` | Product list picker | `IkasProductList` | Product list with `.data` (products array), `.filters`, `.sort`, `.page`, etc. |\n| `PRODUCT_ATTRIBUTE` | Product attribute picker | `IkasProductAttributeDetail | null` | Wrapper `{ product, attributePropValue }` — NOT the value itself; read it with `getAttributeDetailValues(prop)` |\n| `PRODUCT_ATTRIBUTE_LIST` | Product attribute list picker | `IkasProductAttributeList` | Wrapper `{ product, attributeListPropValue }` — a single object, NOT an array; read it with `getAttributeListValues(prop)` |\n| `CATEGORY` | Category picker | `IkasCategory | null` | Single category reference |\n| `CATEGORY_LIST` | Category list picker | `IkasCategoryList` | Multiple category references |\n| `BRAND` | Brand picker | `IkasBrand | null` | Single brand reference |\n| `BRAND_LIST` | Brand list picker | `IkasBrandList` | Multiple brand references |\n| `BLOG` | Blog post picker | `IkasBlog | null` | Single blog post reference |\n| `BLOG_LIST` | Blog post list picker | `IkasBlogList` | Multiple blog post references |\n| `BLOG_CATEGORY` | Blog category picker | `IkasBlogCategory | null` | Single blog category reference |\n| `BLOG_CATEGORY_LIST` | Blog category list picker | `IkasBlogCategoryList` | Multiple blog category references |\n| `TYPE` | Type selector | Depends on typeId | Structured type (padding, margin, size, etc.). Available for both components and sections (sections have a restricted whitelist). |\n| `ENUM` | Dropdown selector | `string` | Enum-based style type (flex-direction, justify-content, align-items, etc.). Uses `enumTypeId`. Available for both components and sections. |\n| `COMPONENT` | Component slot | `any` | A single child component slot. Store owners can place a component in this slot from the editor. Render with `<IkasComponentRenderer>`. Before using, see `get_migration_guide(\"component-composition-decision-guide\")`. |\n| `COMPONENT_LIST` | Component list slot | `any` | A list of child components. Store owners can add multiple components from the editor. Render with `<IkasComponentRenderer>`. Before using, see `get_migration_guide(\"component-composition-decision-guide\")`. |\n\n### Dynamic props have NO default value\n\nMerchant-data reference types resolve from the store's live data at render time, so they cannot carry a static `defaultValue`: IMAGE, IMAGE_LIST, VIDEO, PRODUCT, PRODUCT_LIST, PRODUCT_ATTRIBUTE, PRODUCT_ATTRIBUTE_LIST, BRAND, BRAND_LIST, CATEGORY, CATEGORY_LIST, BLOG, BLOG_LIST, BLOG_CATEGORY, BLOG_CATEGORY_LIST, RAFFLE, RAFFLE_LIST. The CLI (`add-prop`/`update-prop`) rejects a `defaultValue` on these with an error, and the editor strips any that slips through a hand-edited config. Omit `defaultValue` entirely for these props. (Scalar, LINK, COMPONENT, TYPE and SVG props DO support defaults.)\n\n### COMPONENT & COMPONENT_LIST props (child component slots)\n\nThese prop types enable **slot-based** architectures where store owners can drag child components into your section/component from the editor.\n\n- `COMPONENT` — a single child component slot\n- `COMPONENT_LIST` — a list of child components\n\n**Rendering:** Use the `<IkasComponentRenderer>` wrapper from `@ikas/bp-storefront`:\n```tsx\nimport { IkasComponentRenderer } from \"@ikas/bp-storefront\";\nimport { Props } from \"./types\";\n\nexport function MySection({ title, cardList, ...props }: Props) {\n return (\n <section>\n <h2>{title}</h2>\n <div className=\"cards\">\n {/* COMPONENT_LIST — render a list of child components */}\n <IkasComponentRenderer\n id=\"card-list\"\n components={cardList as any[]}\n parentProps={props}\n />\n </div>\n </section>\n );\n}\nexport default MySection;\n```\n\n**Key rules:**\n- Always pass `parentProps={props}` so child components can access parent data via dynamic values\n- Cast the prop value: `components={myList as any[]}` for COMPONENT_LIST, `components={[myComp] as any[]}` for COMPONENT\n- `<IkasComponentRenderer>` handles rendering, styling, and reactivity of child components automatically\n\n**Config example (COMPONENT_LIST):**\n```json\n{\n \"name\": \"cardList\",\n \"displayName\": \"Card List\",\n \"type\": \"COMPONENT_LIST\"\n}\n```\n\n**Config example (COMPONENT):**\n```json\n{\n \"name\": \"headerSlot\",\n \"displayName\": \"Header Slot\",\n \"type\": \"COMPONENT\"\n}\n```\n\n### Restricting which components can appear (`filteredComponentIds`)\n\nA COMPONENT or COMPONENT_LIST prop may include a `filteredComponentIds: string[]` field to limit which sibling components can be placed inside it. Each entry must be the **opaque random id** of a component already defined in `ikas.config.json` — e.g. `\"7ojrigep-Eml9n5sN3i\"`.\n\n**Ids are not derivable from component names. Do NOT compose them as `${projectId}-${name}`.** The CLI will reject any unknown id with a structured error listing the valid `{id, name}` pairs.\n\n**Recommended workflow:**\n\n1. Create the child component(s) first. The CLI prints the new id in its JSON response:\n ```bash\n npx ikas-component config add-component --name Navbar --type component\n # → { \"success\": true, \"componentId\": \"7ojrigep-Eml9n5sN3i\", ... }\n ```\n2. Capture the `componentId` and reuse it in the parent's `filteredComponentIds`:\n ```bash\n npx ikas-component config add-component --name Header --type section \\\n --props '[{\"name\":\"components\",\"type\":\"COMPONENT_LIST\",\"filteredComponentIds\":[\"7ojrigep-Eml9n5sN3i\"]}]'\n ```\n\nOr create the parent first without `filteredComponentIds`, then attach it once children exist:\n```bash\nnpx ikas-component config add-prop Header components --type COMPONENT_LIST \\\n --filteredComponentIds '[\"7ojrigep-Eml9n5sN3i\"]'\n```\n\n**Discovering existing ids:** `npx ikas-component config list` returns a JSON document with every component's `{ id, name, type, props… }`. Use that when joining a project mid-flight.\n\n### IMAGE type example:\n```json\n{\n \"name\": \"heroImage\",\n \"displayName\": \"Hero Image\",\n \"type\": \"IMAGE\",\n \"required\": false\n}\n```\nAccess in component: `getDefaultSrc(props.heroImage)` (import `getDefaultSrc` from `@ikas/bp-storefront`)\n\n### SVG and SVG_LIST props (inline vector graphics)\n\nUse `SVG` / `SVG_LIST` when you need a **vector** asset (logo, icon, decorative shape) that must scale crisply and be styleable with CSS — things the raster image CDN cannot do. The editor uploads the file and stores the **raw `<svg>…</svg>` markup as a string**; it is NOT uploaded to the image CDN, so there is no URL and no `IkasImage` wrapper. Uploads are sanitized by the editor at upload time — XSS vectors (`<script>`, `on*` handlers, `javascript:` hrefs, `<foreignObject>`) are stripped — in addition to the existing 64 KB cap and rejection of SVGs containing embedded base64 raster images.\n\n- `SVG` → `string` (one SVG's markup)\n- `SVG_LIST` → `string[]` (multiple SVGs; the editor allows selecting several files at once)\n\n**Rendering:** inject the markup directly. Because it is the same `<svg>` source the user uploaded, you can target it with CSS (e.g. `.icon svg { width: 24px; fill: currentColor; }`).\n\n**Normalize before injecting:** call `normalizeSvg(value, { idPrefix })` from `@ikas/bp-storefront` before setting `dangerouslySetInnerHTML`, so internal ids/`clipPath`/`url(#…)` references get scoped per instance and don't collide when the same SVG (or multiple `SVG_LIST` items) render more than once on a page. For `SVG_LIST`, give each item a deterministic per-item `idPrefix`, e.g. `` `${propKey}-${i}` ``. By default `normalizeSvg` also strips fixed `width`/`height` and ensures a `viewBox` (so CSS controls size); pass `{ color: \"currentColor\" }` to recolor single-color icons via CSS `color` (omit it for multi-color SVGs). This is opt-in for code-components — the theme's built-in SVG element normalizes automatically, but your own `dangerouslySetInnerHTML` injections must call it explicitly.\n```tsx\nimport { normalizeSvg } from \"@ikas/bp-storefront\";\nimport { Props } from \"./types\";\n\nexport function Logo({ logo, partnerLogos }: Props) {\n return (\n <div className=\"logos\">\n {logo && (\n <span className=\"icon\" dangerouslySetInnerHTML={{ __html: normalizeSvg(logo, { idPrefix: \"logo\" }) }} />\n )}\n {(partnerLogos ?? []).map((svg, i) => (\n <span key={i} className=\"icon\" dangerouslySetInnerHTML={{ __html: normalizeSvg(svg, { idPrefix: `partner-logo-${i}` }) }} />\n ))}\n </div>\n );\n}\nexport default Logo;\n```\n\n**Config example (SVG):**\n```json\n{\n \"name\": \"logo\",\n \"displayName\": \"Logo\",\n \"type\": \"SVG\"\n}\n```\n\n**Config example (SVG_LIST):**\n```json\n{\n \"name\": \"partnerLogos\",\n \"displayName\": \"Partner Logos\",\n \"type\": \"SVG_LIST\"\n}\n```\n\n**CLI command:**\n```bash\nnpx ikas-component config add-prop --component MyComp --name logo --displayName Logo --type SVG\n```\n\n**When NOT to use:** for photos/raster artwork or anything that should be optimized/resized by the CDN, use `IMAGE` / `IMAGE_LIST` instead. SVG is only for hand-authored vector markup.\n\n**Providing a default value:** A default value is a raw <svg>\u2026</svg> string (SVG) or an array of them (SVG_LIST). It must be a single well-formed <svg> root, \u2264 64 KB, with no embedded base64 raster images; it is sanitized on load. Invalid defaults are rejected by the CLI (add-prop / add-component hard-fail with the reason) and silently dropped by the editor when the component is placed, so verify your default is valid. It must also RENDER VISIBLY: an open path with no enclosed area (e.g. the single horizontal line M4 12h16) is invisible under the default fill:black; stroke:none. Give the shape real area and set a color - prefer fill=currentColor (or an explicit stroke with stroke-width) so the icon inherits the theme text color. Example: \"defaultValue\": \"<svg viewBox=\\\"0 0 24 24\\\"><path fill=\\\"currentColor\\\" d=\\\"M12 2 2 22h20z\\\"/></svg>\".\n\n### SVG normalization & sanitization -- the theme-developer standard\n\n**Responsibility split (read this first):**\n- **Security/sanitization is the editor's job, not yours.** Every SVG is sanitized (DOMPurify) on upload, on programmatic writes, AND at render -- you never sanitize in component code.\n- **Normalization (size / color / id-scoping) is `normalizeSvg`'s job.** The theme's built-in SVG element applies it automatically; in your own code component you MUST call `normalizeSvg(value, { idPrefix })` before `dangerouslySetInnerHTML`. There is ONE shared util -- do not reinvent per theme: `import { normalizeSvg } from \"@ikas/bp-storefront\"`.\n\n`normalizeSvg(svg, options)` options: `{ idPrefix: string; scopeIds?: boolean = true; color?: \"currentColor\"; size?: boolean = true }`.\n\n**1. Size.** `size: true` (default) synthesizes a `viewBox` from numeric (unitless/px) `width`/`height` when missing, then strips `width`/`height` so CSS controls size. If there is no viewBox AND size cannot be synthesized (e.g. `%`/`em` dims), width/height are kept (so the icon is not left with zero intrinsic size). Merchants are NOT required to upload viewBox'd or size-less SVGs -- normalize handles it. Size icons with CSS: `.icon svg { width: 24px; height: 24px; }`.\n\n**2. Color.** Opt-in `{ color: \"currentColor\" }` rewrites `fill`/`stroke` (attributes AND `style:` declarations) to `currentColor`, but PRESERVES `none` and `url(...)` (gradients/patterns). So outline icons (`fill=\"none\" stroke=\"...\"`) keep `fill:none` and get `stroke:currentColor` -- no special-casing needed. For MULTI-COLOR SVGs, OMIT `color` to keep the original colors. Rule of thumb: single-color icons -> pass `currentColor`; multi-color -> omit.\n\n**3. Collision (id / clipPath / url(#...)).** Solved in code, not by the editor. `scopeIds: true` (default) prefixes every declared `id` and every `url(#...)` / `href=\"#...\"` reference with `idPrefix`, so the same SVG rendered multiple times (or multiple SVG_LIST items) cannot collide. Give each render an instance-unique prefix -- the built-in element uses its element id; for SVG_LIST use a per-item prefix like `` `${propKey}-${i}` ``.\n\n**4. Sanitization -- what the editor strips.** Beyond the 64 KB cap and base64-raster rejection, the editor strips `<script>`, `on*` event handlers (onload/onclick/onerror/...), `javascript:` hrefs, and `<foreignObject>`. This runs on file upload, on programmatic `update_section_prop` writes, and again at render -- so stored and rendered markup is always safe. `normalizeSvg` is NOT a sanitizer (pure string transforms); security lives in the separate sanitize/validate layer and is automatic.\n\n**5. One shared pattern.** Yes -- `normalizeSvg` from `@ikas/bp-storefront` is the single, isomorphic (SSR/browser/node) util. Do not hand-roll size/color/id-scoping per theme.\n\n**Naming.** The editor shows each SVG's `class` attribute as its display name in the list; SVG / SVG_LIST items with no class render as `svg-1`, `svg-2`, .... Set `class=\"my-icon\"` in the markup to name it.\n\n### NUMBER_RANGE prop (bounded numeric slider)\n\nA `NUMBER_RANGE` prop renders a **slider + number input** and gives the store owner one bounded number with an optional unit. Configure the slider with a **required** `numberRangeData` object on the prop (`min` and `max` are mandatory; `interval` and `unit` are optional). A NUMBER_RANGE prop authored without it is rejected:\n\n- `min` (integer) — lower bound\n- `max` (integer) — upper bound, must be greater than `min`\n- `interval` (positive integer, optional) — the step increment; typed values snap to `min + k·interval`, and a `0`/negative interval is dropped (step falls back to 1)\n- `unit` (string, optional) — suffix shown next to the number input (e.g. `\"px\"`, `\"%\"`)\n\n**Runtime read shape** is `IkasNumberRange`: read `props.myRange.value` (a number) and `props.myRange.unit` (string or null) — e.g. `props.gap.value + (props.gap.unit ?? \"px\")`.\n\n**Authored `defaultValue`** is a typed object `{ \"value\": <number>, \"unit\": \"px\" | null }` — NOT a bare number and NOT a JSON string. When the prop defines `numberRangeData`, the CLI validates that `value` is within `[min, max]` and lands on the interval grid (`min + k·interval`); off-range or off-step defaults are rejected.\n\n**Config example:**\n```json\n{ \"name\": \"gap\", \"displayName\": \"Gap\", \"type\": \"NUMBER_RANGE\", \"numberRangeData\": { \"min\": 0, \"max\": 100, \"interval\": 5, \"unit\": \"px\" }, \"defaultValue\": { \"value\": 20, \"unit\": \"px\" } }\n```\n\n**CLI command:**\n```bash\nnpx ikas-component config add-prop --component MyComp --name gap --displayName Gap --type NUMBER_RANGE --numberRangeData '{\"min\":0,\"max\":100,\"interval\":5,\"unit\":\"px\"}' --defaultValue '{\"value\":20,\"unit\":\"px\"}'\n```\n\n**Update the config or default later** (send a new `--numberRangeData` to change it; `--numberRangeData none` is rejected while the prop stays NUMBER_RANGE, since min/max are required):\n```bash\nnpx ikas-component config update-prop --component MyComp --prop gap --numberRangeData '{\"min\":0,\"max\":200,\"interval\":10,\"unit\":\"px\"}'\n```\n\n### PRODUCT_ATTRIBUTE and PRODUCT_ATTRIBUTE_LIST props (product custom fields)\n\n**CRITICAL — these props do NOT hand you attribute values.** What your component receives is a *wrapper* pairing the picker selection with the product it resolves against. Reading `prop.value` (or mapping over the prop) references fields that do not exist at runtime: `check` and `build` stay clean, every field is `undefined`, and the component silently renders nothing.\n\nThree distinct shapes are involved — do not confuse them:\n\n| Where | Shape |\n|-------|-------|\n| Value stored by the editor (visible via `get_section_values`) | `{ \"attributeId\": \"…\", \"usePageData\": true }` — the list variant uses `attributeIds: [...]` |\n| Runtime prop your component receives | `IkasProductAttributeDetail` = `{ product, attributePropValue }` — the list variant is `IkasProductAttributeList` = `{ product, attributeListPropValue }` |\n| Resolved attribute values | Reachable ONLY through the helpers below: `getAttributeDetailValues()` → `IkasProductAttributeValue[]`, `getAttributeListValues()` → `IkasProductAttributeMap[]` (each entry is `{ attribute, values }`) |\n\n**Read them with the helpers from `@ikas/bp-storefront`:**\n```tsx\nimport { getAttributeDetailValues, getAttributeListValues } from \"@ikas/bp-storefront\";\n\n// PRODUCT_ATTRIBUTE → attribute: IkasProductAttributeDetail | null\nif (!attribute?.attributePropValue?.attributeId) return null;\nconst html = getAttributeDetailValues(attribute)\n .map((v) => v.value)\n .filter(Boolean)\n .join(\"\");\n\n// PRODUCT_ATTRIBUTE_LIST → attributeList: IkasProductAttributeList\n// getAttributeListValues returns IkasProductAttributeMap[] — grouped per attribute, NOT a flat value list\nconst groups = getAttributeListValues(attributeList);\ngroups.forEach((g) => console.log(g.attribute.name, g.values));\n```\n\n**Second trap — a resolved value's `value` is often `null`.** `getAttributeDetailValues()` returning items does NOT mean you have text to render. For the choice-style attribute types (`CHOICE`, `MULTIPLE_CHOICE`, `COLOR_THUMBNAIL_MULTIPLE_CHOICE`) the selection lives in `productAttributeOptionId` / `productAttributeOption` and `value` is `null` by design, so `.map((v) => v.value)` yields empty strings and the component looks broken again. Read the label defensively:\n\n```tsx\nconst text = getAttributeDetailValues(attribute)\n .map((v) => v.value ?? v.productAttributeOption?.name ?? \"\")\n .filter(Boolean)\n .join(\", \");\n```\n\nWhich field carries the content depends on `v.productAttribute?.type`: `TEXT`/`NUMERIC`/`HTML`/`DATE`/`DATETIME`/`BOOLEAN` → `value`; the choice types → `productAttributeOption.name`; `IMAGE` → `images` / `imageIds`; `TABLE` → parse with `getIkasProductAttributeTableValue(v)`; `PRODUCT` → `getIkasProductAttrributeProductIds(v)` (that export name really is misspelled — see `get_framework_guide(\"imports\")`). Check the type with `get_type_definition(\"IkasProductAttributeValue\")` before assuming a field is populated.\n\n`PRODUCT_ATTRIBUTE_LIST` is a **single object, not an array** — `attributeList.map(...)` throws at runtime; the selected ids live at `attributeList.attributeListPropValue.attributeIds`. Both prop types are merchant-data types, so neither can carry a `defaultValue`. Details: `get_function_doc(\"getAttributeDetailValues\")`, `get_type_definition(\"IkasProductAttributeDetail\")`, `get_type_definition(\"IkasProductAttributeList\")`.\n\n### LINK and LIST_OF_LINK props (navigation links)\n\n**CRITICAL — the authored `defaultValue` shape is NOT the runtime read shape.** In component code you READ a link as `props.myLink.href` / `.label` / `.subLinks`. But the `defaultValue` you author in `ikas.config.json` MUST be the typed object shown below. Do NOT pass `{ \"href\": \"…\", \"label\": \"…\" }` (legacy shape) and do NOT pass the value as a JSON string — the CLI rejects both.\n\n**LINK** `defaultValue` is a single link object:\n```json\n{ \"linkType\": \"EXTERNAL\", \"label\": \"Shop now\", \"externalLink\": \"https://example.com\", \"subLinks\": [] }\n```\nor, to link to a store page:\n```json\n{ \"linkType\": \"PAGE\", \"label\": \"Home\", \"pageType\": \"INDEX\", \"subLinks\": [] }\n```\n\n**LIST_OF_LINK** `defaultValue` wraps an array of link objects in `{ \"links\": [...] }`:\n```json\n{ \"links\": [\n { \"linkType\": \"PAGE\", \"label\": \"Home\", \"pageType\": \"INDEX\", \"subLinks\": [] },\n { \"linkType\": \"EXTERNAL\", \"label\": \"Blog\", \"externalLink\": \"https://example.com/blog\", \"subLinks\": [] }\n] }\n```\n\n**Rules for every link object:**\n- `linkType` is REQUIRED and must be one of `PAGE` or `EXTERNAL`. `FILE` links are NOT authorable in a code-component default (they reference a store-specific uploaded file) — the CLI rejects them.\n- Each link MUST carry a destination for its `linkType` — the CLI rejects a link that points nowhere. `EXTERNAL` → a non-empty `externalLink` URL. `PAGE` → a `pageType` (e.g. `INDEX`); do NOT invent a `pageId` — it is per-store and filled automatically when the theme is installed, so author only `pageType`.\n- `subLinks` must be an array (use `[]` when empty); each entry is itself a link object with the same shape (for dropdown/nested menus).\n- NEVER use a JSON string, and NEVER use the legacy `{ label, href }` shape.\n\n**Config example (LINK):**\n```json\n{ \"name\": \"ctaLink\", \"displayName\": \"CTA Link\", \"type\": \"LINK\", \"defaultValue\": { \"linkType\": \"EXTERNAL\", \"label\": \"Shop now\", \"externalLink\": \"https://example.com\", \"subLinks\": [] } }\n```\n\n**Config example (LIST_OF_LINK):**\n```json\n{ \"name\": \"menuLinks\", \"displayName\": \"Menu Links\", \"type\": \"LIST_OF_LINK\", \"defaultValue\": { \"links\": [ { \"linkType\": \"PAGE\", \"label\": \"Home\", \"pageType\": \"INDEX\", \"subLinks\": [] } ] } }\n```\n\n**CLI command (LIST_OF_LINK):**\n```bash\nnpx ikas-component config add-prop --component MyComp --name menuLinks --displayName \"Menu Links\" --type LIST_OF_LINK --defaultValue '{\"links\":[{\"linkType\":\"PAGE\",\"label\":\"Home\",\"pageType\":\"INDEX\",\"subLinks\":[]}]}'\n```\n\n### Prop grouping\nProps can be assigned to groups via `groupId` for organized editor sidebar display. See `get_framework_guide(\"prop-groups\")` for details.\n\n### Style Props: TYPE and ENUM\n\nThere are two prop types for style values:\n\n- **TYPE** — Structured types with numeric values and units (padding, margin, border-radius, sizes, etc.). Uses `typeId`.\n- **ENUM** — Enum types rendered as dropdown selectors (flex-direction, justify-content, align-items, etc.). Uses `enumTypeId`.\n\nBoth are available for components and sections. For sections, TYPE props are limited to a whitelist of style types. Use `list-types --component-type section` to see section-allowed types.\n\n### TYPE prop (structured types)\nThe `TYPE` prop lets you use structured storefront types like PaddingStyleType, MarginStyleType, SizeStyleType, etc. Available for both components and sections (sections have a restricted whitelist of style types).\n\n**Workflow:**\n1. Run `npx ikas-component config list-types` to get available types (requires dev server running with editor connected)\n2. Use the `typeId` from the output when adding the prop\n3. For sections: `npx ikas-component config list-types --component-type section` to see only section-allowed types\n\n**Example config:**\n```json\n{\n \"name\": \"spacing\",\n \"displayName\": \"Spacing\",\n \"type\": \"TYPE\",\n \"typeId\": \"@ikas/bp-storefront-models-PaddingStyleType\"\n}\n```\n\n**Providing a default value:** Style TYPE props accept a `defaultValue` object — size/style types (Padding, Margin, Width, Height, Gap, BorderRadius, Size, …) take `{ \"value\": <number>, \"unit\": \"px\" | \"rem\" | \"%\" | \"vh\" | \"vw\" }` (or `{ \"css\": \"<raw css>\" }`). Add it to the prop object, e.g. `\"defaultValue\": { \"value\": 16, \"unit\": \"px\" }`. For an `_array` typeId the default is an array of these objects; the `--defaultValue` flag also accepts this JSON as a string. Only `css`, `value` and `unit` keys are allowed on a size/style default object — any other field is rejected.\n\n**Array example** (append `_array` to typeId):\n```json\n{\n \"name\": \"margins\",\n \"displayName\": \"Margins\",\n \"type\": \"TYPE\",\n \"typeId\": \"@ikas/bp-storefront-models-MarginStyleType_array\"\n}\n```\nThis generates `margins?: MarginStyleType[]` in types.ts.\n\n**CLI command:**\n```bash\nnpx ikas-component config add-prop --component MyComp --name spacing --displayName Spacing --type TYPE --typeId \"@ikas/bp-storefront-models-PaddingStyleType\"\n```\n\n### ENUM prop (enum style types)\nThe `ENUM` prop lets you use enum-based types that render as dropdown selectors. There are two kinds of enum types:\n\n1. **Built-in enums** (prefix `@ikas/`): FlexDirectionStyleType, JustifyContentStyleType, AlignItemsStyleType, etc. Available from `list-types` when editor is connected.\n2. **Custom enums**: Created with `config add-enum`. Works offline, no editor needed.\n3. **Font Style enum** (sentinel `__patternElementEnum__`): lets store owners pick one of the theme's typography tokens. Built-in — no `add-enum` and no editor connection needed. See \"Font Style enum (typography picker)\" below.\n\n**IMPORTANT:** `add-prop --type ENUM` validates that the `enumTypeId` references an existing enum. You MUST create custom enums first with `config add-enum` before using them. The command will reject unknown enum IDs.\n\n**Custom enum workflow (recommended for AI-driven generation):**\n```bash\n# Step 1: Create the enum FIRST\nnpx ikas-component config add-enum --name \"AspectRatio\" --options '{\"Square\":\"1/1\",\"Landscape\":\"16/9\",\"Portrait\":\"3/4\"}'\n# Returns: {\"success\":true,\"enumId\":\"aBcDeFgHiJ\",...}\n\n# Step 2: Use the returned enumId in add-prop\nnpx ikas-component config add-prop --component MyComp --name aspectRatio --displayName \"Aspect Ratio\" --type ENUM --enumTypeId aBcDeFgHiJ\n```\n\n**Built-in enum workflow:**\n1. Run `npx ikas-component config list-types` — enum types have `category: \"enum\"` in the output\n2. Use the `enumTypeId` from the output when adding the prop\n\n**Example config (built-in enum):**\n```json\n{\n \"name\": \"direction\",\n \"displayName\": \"Direction\",\n \"type\": \"ENUM\",\n \"enumTypeId\": \"@ikas/bp-storefront-models-FlexDirectionStyleType\"\n}\n```\nThis generates `direction?: string` in types.ts.\n\n**CLI command (built-in enum):**\n```bash\nnpx ikas-component config add-prop --component MyComp --name direction --displayName Direction --type ENUM --enumTypeId \"@ikas/bp-storefront-models-FlexDirectionStyleType\"\n```\n\n**Note:** `list-types` requires dev server with editor connected. Custom enums (`config add-enum`) work offline.\n\n### Font Style enum (typography picker)\nUse the built-in sentinel `enumTypeId: \"__patternElementEnum__\"` to let store owners pick one of the theme's typography tokens (a \"Font Style\" prop). It works exactly like a built-in enum: no `config add-enum` call and no editor connection required.\n\n**Example config:**\n```json\n{\n \"name\": \"fontStyle\",\n \"displayName\": \"Font Style\",\n \"type\": \"ENUM\",\n \"enumTypeId\": \"__patternElementEnum__\",\n \"required\": false\n}\n```\nThis generates `fontStyle?: string` in types.ts.\n\n**CLI command:**\n```bash\nnpx ikas-component config add-prop --component MyComp --name fontStyle --displayName \"Font Style\" --type ENUM --enumTypeId __patternElementEnum__\n```\n\n**Runtime:** the prop value is the chosen typography's **id** (a plain string), not the typography object itself. Resolve it with `getThemeTypography()` (see `get_framework_guide(\"theme-globals\")`) and apply its `className`:\n```tsx\nimport { getThemeTypography } from \"@ikas/bp-storefront\";\nimport type { Props } from \"./types\"; // fontStyle?: string\n\nexport function MyCard({ fontStyle }: Props) {\n const t = getThemeTypography().find((t) => t.id === fontStyle);\n return <p className={t?.className}>...</p>; // _<id> class applies the theme's typography CSS\n}\n```",
38
+ "content": "Props define what the store editor can configure for each component. Each prop has a `type` that determines the editor UI and the TypeScript type received in your component.\n\n| Type | Editor UI | TypeScript Type | Description |\n|------|-----------|----------------|-------------|\n| `TEXT` | Text input | `string` | Single-line text |\n| `RICH_TEXT` | Rich text editor | `string` | HTML rich text content |\n| `NUMBER` | Number input | `number` | Numeric value. Authored `defaultValue` must be a finite number — an empty string, a non-numeric string (e.g. `12px`), NaN or Infinity are rejected by the CLI. |\n| `NUMBER_RANGE` | Number range input | `IkasNumberRange` | Number range with min, max, interval, and unit |\n| `BOOLEAN` | Toggle switch | `boolean` | True/false toggle |\n| `IMAGE` | Image picker | `IkasImage | null` | Image from editor. Use `getDefaultSrc(image)` for URL |\n| `IMAGE_LIST` | Image list picker | `IkasImageList` | Multiple images from editor |\n| `VIDEO` | Video picker | `IkasVideo | null` | Video from editor |\n| `SVG` | SVG upload | `string` | Raw inline SVG markup (the `<svg>…</svg>` source). Normalize with `normalizeSvg(value, { idPrefix })` before rendering via `dangerouslySetInnerHTML`. NOT served through the image CDN — this is the way to ship logos/icons as vectors. |\n| `SVG_LIST` | SVG list upload | `string[]` | List of raw inline SVG markup strings. Normalize each with `normalizeSvg(svg, { idPrefix })` (unique per item) before rendering with `dangerouslySetInnerHTML`. |\n| `DATE` | Date picker | `Date | string` | Date value |\n| `LINK` | Link editor | `IkasNavigationLink | null` | Navigation link. Read at runtime as `.href`/`.label`/`.subLinks`; authored `defaultValue` is a typed object (`linkType`+`externalLink`/`pageType`+`subLinks`). See the LINK section below. |\n| `LIST_OF_LINK` | Link list editor | `IkasNavigationLinkList` | List of navigation links. Authored `defaultValue` is `{ \"links\": [ <link>, … ] }`. See the LINK section below. |\n| `COLOR` | Color picker | `string` | CSS color value (hex, rgb, etc.) |\n| `PRODUCT` | Product picker | `IkasProduct | null` | Single product reference |\n| `PRODUCT_LIST` | Product list picker | `IkasProductList` | Product list with `.data` (products array), `.filters`, `.sort`, `.page`, etc. |\n| `PRODUCT_ATTRIBUTE` | Product attribute picker | `IkasProductAttributeDetail | null` | Wrapper `{ product, attributePropValue }` — NOT the value itself; read it with `getAttributeDetailValues(prop)` |\n| `PRODUCT_ATTRIBUTE_LIST` | Product attribute list picker | `IkasProductAttributeList` | Wrapper `{ product, attributeListPropValue }` — a single object, NOT an array; read it with `getAttributeListValues(prop)` |\n| `CATEGORY` | Category picker | `IkasCategory | null` | Single category reference |\n| `CATEGORY_LIST` | Category list picker | `IkasCategoryList` | Multiple category references |\n| `BRAND` | Brand picker | `IkasBrand | null` | Single brand reference |\n| `BRAND_LIST` | Brand list picker | `IkasBrandList` | Multiple brand references |\n| `BLOG` | Blog post picker | `IkasBlog | null` | Single blog post reference |\n| `BLOG_LIST` | Blog post list picker | `IkasBlogList` | Multiple blog post references |\n| `BLOG_CATEGORY` | Blog category picker | `IkasBlogCategory | null` | Single blog category reference |\n| `BLOG_CATEGORY_LIST` | Blog category list picker | `IkasBlogCategoryList` | Multiple blog category references |\n| `TYPE` | Type selector | Depends on typeId | Structured type (padding, margin, size, etc.). Available for both components and sections (sections have a restricted whitelist). |\n| `ENUM` | Dropdown selector | `string` | Enum-based style type (flex-direction, justify-content, align-items, etc.). Uses `enumTypeId`. Available for both components and sections. |\n| `COMPONENT` | Component slot | `any` | A single child component slot. Store owners can place a component in this slot from the editor. Render with `<IkasComponentRenderer>`. Before using, see `get_migration_guide(\"component-composition-decision-guide\")`. |\n| `COMPONENT_LIST` | Component list slot | `any` | A list of child components. Store owners can add multiple components from the editor. Render with `<IkasComponentRenderer>`. Before using, see `get_migration_guide(\"component-composition-decision-guide\")`. |\n\n### Dynamic props have NO default value\n\nMerchant-data reference types resolve from the store's live data at render time, so they cannot carry a static `defaultValue`: IMAGE, IMAGE_LIST, VIDEO, PRODUCT, PRODUCT_LIST, PRODUCT_ATTRIBUTE, PRODUCT_ATTRIBUTE_LIST, BRAND, BRAND_LIST, CATEGORY, CATEGORY_LIST, BLOG, BLOG_LIST, BLOG_CATEGORY, BLOG_CATEGORY_LIST, RAFFLE, RAFFLE_LIST. The CLI (`add-prop`/`update-prop`) rejects a `defaultValue` on these with an error, and the editor strips any that slips through a hand-edited config. Omit `defaultValue` entirely for these props. (Scalar, LINK, COMPONENT, TYPE and SVG props DO support defaults.)\n\n### COMPONENT & COMPONENT_LIST props (child component slots)\n\nThese prop types enable **slot-based** architectures where store owners can drag child components into your section/component from the editor.\n\n- `COMPONENT` — a single child component slot\n- `COMPONENT_LIST` — a list of child components\n\n**Rendering:** Use the `<IkasComponentRenderer>` wrapper from `@ikas/bp-storefront`:\n```tsx\nimport { IkasComponentRenderer } from \"@ikas/bp-storefront\";\nimport { Props } from \"./types\";\n\nexport function MySection({ title, cardList, ...props }: Props) {\n return (\n <section>\n <h2>{title}</h2>\n <div className=\"cards\">\n {/* COMPONENT_LIST — render a list of child components */}\n <IkasComponentRenderer\n id=\"card-list\"\n components={cardList as any[]}\n parentProps={props}\n />\n </div>\n </section>\n );\n}\nexport default MySection;\n```\n\n**Key rules:**\n- Always pass `parentProps={props}` so child components can access parent data via dynamic values\n- Cast the prop value: `components={myList as any[]}` for COMPONENT_LIST, `components={[myComp] as any[]}` for COMPONENT\n- `<IkasComponentRenderer>` handles rendering, styling, and reactivity of child components automatically\n\n**Config example (COMPONENT_LIST):**\n```json\n{\n \"name\": \"cardList\",\n \"displayName\": \"Card List\",\n \"type\": \"COMPONENT_LIST\"\n}\n```\n\n**Config example (COMPONENT):**\n```json\n{\n \"name\": \"headerSlot\",\n \"displayName\": \"Header Slot\",\n \"type\": \"COMPONENT\"\n}\n```\n\n### Restricting which components can appear (`filteredComponentIds`)\n\nA COMPONENT or COMPONENT_LIST prop may include a `filteredComponentIds: string[]` field to limit which sibling components can be placed inside it. Each entry must be the **opaque random id** of a component already defined in `ikas.config.json` — e.g. `\"7ojrigep-Eml9n5sN3i\"`.\n\n**Ids are not derivable from component names. Do NOT compose them as `${projectId}-${name}`.** The CLI will reject any unknown id with a structured error listing the valid `{id, name}` pairs.\n\n**Recommended workflow:**\n\n1. Create the child component(s) first. The CLI prints the new id in its JSON response:\n ```bash\n npx ikas-component config add-component --name Navbar --type component\n # → { \"success\": true, \"componentId\": \"7ojrigep-Eml9n5sN3i\", ... }\n ```\n2. Capture the `componentId` and reuse it in the parent's `filteredComponentIds`:\n ```bash\n npx ikas-component config add-component --name Header --type section \\\n --props '[{\"name\":\"components\",\"type\":\"COMPONENT_LIST\",\"filteredComponentIds\":[\"7ojrigep-Eml9n5sN3i\"]}]'\n ```\n\nOr create the parent first without `filteredComponentIds`, then attach it once children exist:\n```bash\nnpx ikas-component config add-prop Header components --type COMPONENT_LIST \\\n --filteredComponentIds '[\"7ojrigep-Eml9n5sN3i\"]'\n```\n\n**Discovering existing ids:** `npx ikas-component config list` returns a JSON document with every component's `{ id, name, type, props… }`. Use that when joining a project mid-flight.\n\n### IMAGE type example:\n```json\n{\n \"name\": \"heroImage\",\n \"displayName\": \"Hero Image\",\n \"type\": \"IMAGE\",\n \"required\": false\n}\n```\nAccess in component: `getDefaultSrc(props.heroImage)` (import `getDefaultSrc` from `@ikas/bp-storefront`)\n\n### SVG and SVG_LIST props (inline vector graphics)\n\nUse `SVG` / `SVG_LIST` when you need a **vector** asset (logo, icon, decorative shape) that must scale crisply and be styleable with CSS — things the raster image CDN cannot do. The editor uploads the file and stores the **raw `<svg>…</svg>` markup as a string**; it is NOT uploaded to the image CDN, so there is no URL and no `IkasImage` wrapper. Uploads are sanitized by the editor at upload time — XSS vectors (`<script>`, `on*` handlers, `javascript:` hrefs, `<foreignObject>`) are stripped — in addition to the existing 64 KB cap and rejection of SVGs containing embedded base64 raster images.\n\n- `SVG` → `string` (one SVG's markup)\n- `SVG_LIST` → `string[]` (multiple SVGs; the editor allows selecting several files at once)\n\n**Rendering:** inject the markup directly. Because it is the same `<svg>` source the user uploaded, you can target it with CSS (e.g. `.icon svg { width: 24px; fill: currentColor; }`).\n\n**Normalize before injecting:** call `normalizeSvg(value, { idPrefix })` from `@ikas/bp-storefront` before setting `dangerouslySetInnerHTML`, so internal ids/`clipPath`/`url(#…)` references get scoped per instance and don't collide when the same SVG (or multiple `SVG_LIST` items) render more than once on a page. For `SVG_LIST`, give each item a deterministic per-item `idPrefix`, e.g. `` `${propKey}-${i}` ``. By default `normalizeSvg` also strips fixed `width`/`height` and ensures a `viewBox` (so CSS controls size); pass `{ color: \"currentColor\" }` to recolor single-color icons via CSS `color` (omit it for multi-color SVGs). This is opt-in for code-components — the theme's built-in SVG element normalizes automatically, but your own `dangerouslySetInnerHTML` injections must call it explicitly.\n```tsx\nimport { normalizeSvg } from \"@ikas/bp-storefront\";\nimport { Props } from \"./types\";\n\nexport function Logo({ logo, partnerLogos }: Props) {\n return (\n <div className=\"logos\">\n {logo && (\n <span className=\"icon\" dangerouslySetInnerHTML={{ __html: normalizeSvg(logo, { idPrefix: \"logo\" }) }} />\n )}\n {(partnerLogos ?? []).map((svg, i) => (\n <span key={i} className=\"icon\" dangerouslySetInnerHTML={{ __html: normalizeSvg(svg, { idPrefix: `partner-logo-${i}` }) }} />\n ))}\n </div>\n );\n}\nexport default Logo;\n```\n\n**Config example (SVG):**\n```json\n{\n \"name\": \"logo\",\n \"displayName\": \"Logo\",\n \"type\": \"SVG\"\n}\n```\n\n**Config example (SVG_LIST):**\n```json\n{\n \"name\": \"partnerLogos\",\n \"displayName\": \"Partner Logos\",\n \"type\": \"SVG_LIST\"\n}\n```\n\n**CLI command:**\n```bash\nnpx ikas-component config add-prop --component MyComp --name logo --displayName Logo --type SVG\n```\n\n**When NOT to use:** for photos/raster artwork or anything that should be optimized/resized by the CDN, use `IMAGE` / `IMAGE_LIST` instead. SVG is only for hand-authored vector markup.\n\n**Providing a default value:** A default value is a raw <svg>…</svg> string (SVG) or an array of them (SVG_LIST). It must be a single well-formed <svg> root, ≤ 64 KB, with no embedded base64 raster images; it is sanitized on load. Invalid defaults are rejected by the CLI (add-prop / add-component hard-fail with the reason) and silently dropped by the editor when the component is placed, so verify your default is valid. It must also RENDER VISIBLY: an open path with no enclosed area (e.g. the single horizontal line M4 12h16) is invisible under the default fill:black; stroke:none. Give the shape real area and set a color - prefer fill=currentColor (or an explicit stroke with stroke-width) so the icon inherits the theme text color. Example: \"defaultValue\": \"<svg viewBox=\\\"0 0 24 24\\\"><path fill=\\\"currentColor\\\" d=\\\"M12 2 2 22h20z\\\"/></svg>\".\n\n### SVG normalization & sanitization -- the theme-developer standard\n\n**Responsibility split (read this first):**\n- **Security/sanitization is the editor's job, not yours.** Every SVG is sanitized (DOMPurify) on upload, on programmatic writes, AND at render -- you never sanitize in component code.\n- **Normalization (size / color / id-scoping) is `normalizeSvg`'s job.** The theme's built-in SVG element applies it automatically; in your own code component you MUST call `normalizeSvg(value, { idPrefix })` before `dangerouslySetInnerHTML`. There is ONE shared util -- do not reinvent per theme: `import { normalizeSvg } from \"@ikas/bp-storefront\"`.\n\n`normalizeSvg(svg, options)` options: `{ idPrefix: string; scopeIds?: boolean = true; color?: \"currentColor\"; size?: boolean = true }`.\n\n**1. Size.** `size: true` (default) synthesizes a `viewBox` from numeric (unitless/px) `width`/`height` when missing, then strips `width`/`height` so CSS controls size. If there is no viewBox AND size cannot be synthesized (e.g. `%`/`em` dims), width/height are kept (so the icon is not left with zero intrinsic size). Merchants are NOT required to upload viewBox'd or size-less SVGs -- normalize handles it. Size icons with CSS: `.icon svg { width: 24px; height: 24px; }`.\n\n**2. Color.** Opt-in `{ color: \"currentColor\" }` rewrites `fill`/`stroke` (attributes AND `style:` declarations) to `currentColor`, but PRESERVES `none` and `url(...)` (gradients/patterns). So outline icons (`fill=\"none\" stroke=\"...\"`) keep `fill:none` and get `stroke:currentColor` -- no special-casing needed. For MULTI-COLOR SVGs, OMIT `color` to keep the original colors. Rule of thumb: single-color icons -> pass `currentColor`; multi-color -> omit.\n\n**3. Collision (id / clipPath / url(#...)).** Solved in code, not by the editor. `scopeIds: true` (default) prefixes every declared `id` and every `url(#...)` / `href=\"#...\"` reference with `idPrefix`, so the same SVG rendered multiple times (or multiple SVG_LIST items) cannot collide. Give each render an instance-unique prefix -- the built-in element uses its element id; for SVG_LIST use a per-item prefix like `` `${propKey}-${i}` ``.\n\n**4. Sanitization -- what the editor strips.** Beyond the 64 KB cap and base64-raster rejection, the editor strips `<script>`, `on*` event handlers (onload/onclick/onerror/...), `javascript:` hrefs, and `<foreignObject>`. This runs on file upload, on programmatic `update_section_prop` writes, and again at render -- so stored and rendered markup is always safe. `normalizeSvg` is NOT a sanitizer (pure string transforms); security lives in the separate sanitize/validate layer and is automatic.\n\n**5. One shared pattern.** Yes -- `normalizeSvg` from `@ikas/bp-storefront` is the single, isomorphic (SSR/browser/node) util. Do not hand-roll size/color/id-scoping per theme.\n\n**Naming.** The editor shows each SVG's `class` attribute as its display name in the list; SVG / SVG_LIST items with no class render as `svg-1`, `svg-2`, .... Set `class=\"my-icon\"` in the markup to name it.\n\n### NUMBER_RANGE prop (bounded numeric slider)\n\nA `NUMBER_RANGE` prop renders a **slider + number input** and gives the store owner one bounded number with an optional unit. Configure the slider with a **required** `numberRangeData` object on the prop (`min` and `max` are mandatory; `interval` and `unit` are optional). A NUMBER_RANGE prop authored without it is rejected:\n\n- `min` (integer) — lower bound\n- `max` (integer) — upper bound, must be greater than `min`\n- `interval` (positive integer, optional) — the step increment; typed values snap to `min + k·interval`, and a `0`/negative interval is dropped (step falls back to 1)\n- `unit` (string, optional) — suffix shown next to the number input (e.g. `\"px\"`, `\"%\"`)\n\n**Runtime read shape** is `IkasNumberRange`: read `props.myRange.value` (a number) and `props.myRange.unit` (string or null) — e.g. `props.gap.value + (props.gap.unit ?? \"px\")`.\n\n**Authored `defaultValue`** is a typed object `{ \"value\": <number>, \"unit\": \"px\" | null }` — NOT a bare number and NOT a JSON string. When the prop defines `numberRangeData`, the CLI validates that `value` is within `[min, max]` and lands on the interval grid (`min + k·interval`); off-range or off-step defaults are rejected.\n\n**Config example:**\n```json\n{ \"name\": \"gap\", \"displayName\": \"Gap\", \"type\": \"NUMBER_RANGE\", \"numberRangeData\": { \"min\": 0, \"max\": 100, \"interval\": 5, \"unit\": \"px\" }, \"defaultValue\": { \"value\": 20, \"unit\": \"px\" } }\n```\n\n**CLI command:**\n```bash\nnpx ikas-component config add-prop --component MyComp --name gap --displayName Gap --type NUMBER_RANGE --numberRangeData '{\"min\":0,\"max\":100,\"interval\":5,\"unit\":\"px\"}' --defaultValue '{\"value\":20,\"unit\":\"px\"}'\n```\n\n**Update the config or default later** (send a new `--numberRangeData` to change it; `--numberRangeData none` is rejected while the prop stays NUMBER_RANGE, since min/max are required):\n```bash\nnpx ikas-component config update-prop --component MyComp --prop gap --numberRangeData '{\"min\":0,\"max\":200,\"interval\":10,\"unit\":\"px\"}'\n```\n\n### PRODUCT_ATTRIBUTE and PRODUCT_ATTRIBUTE_LIST props (product custom fields)\n\n**CRITICAL — these props do NOT hand you attribute values.** What your component receives is a *wrapper* pairing the picker selection with the product it resolves against. Reading `prop.value` (or mapping over the prop) references fields that do not exist at runtime: `check` and `build` stay clean, every field is `undefined`, and the component silently renders nothing.\n\nThree distinct shapes are involved — do not confuse them:\n\n| Where | Shape |\n|-------|-------|\n| Value stored by the editor (visible via `get_section_values`) | `{ \"attributeId\": \"…\", \"usePageData\": true }` — the list variant uses `attributeIds: [...]` |\n| Runtime prop your component receives | `IkasProductAttributeDetail` = `{ product, attributePropValue }` — the list variant is `IkasProductAttributeList` = `{ product, attributeListPropValue }` |\n| Resolved attribute values | Reachable ONLY through the helpers below: `getAttributeDetailValues()` → `IkasProductAttributeValue[]`, `getAttributeListValues()` → `IkasProductAttributeMap[]` (each entry is `{ attribute, values }`) |\n\n**Read them with the helpers from `@ikas/bp-storefront`:**\n```tsx\nimport { getAttributeDetailValues, getAttributeListValues } from \"@ikas/bp-storefront\";\n\n// PRODUCT_ATTRIBUTE → attribute: IkasProductAttributeDetail | null\nif (!attribute?.attributePropValue?.attributeId) return null;\nconst html = getAttributeDetailValues(attribute)\n .map((v) => v.value)\n .filter(Boolean)\n .join(\"\");\n\n// PRODUCT_ATTRIBUTE_LIST → attributeList: IkasProductAttributeList\n// getAttributeListValues returns IkasProductAttributeMap[] — grouped per attribute, NOT a flat value list\nconst groups = getAttributeListValues(attributeList);\ngroups.forEach((g) => console.log(g.attribute.name, g.values));\n```\n\n**Second trap — a resolved value's `value` is often `null`.** `getAttributeDetailValues()` returning items does NOT mean you have text to render. For the choice-style attribute types (`CHOICE`, `MULTIPLE_CHOICE`, `COLOR_THUMBNAIL_MULTIPLE_CHOICE`) the selection lives in `productAttributeOptionId` / `productAttributeOption` and `value` is `null` by design, so `.map((v) => v.value)` yields empty strings and the component looks broken again. Read the label defensively:\n\n```tsx\nconst text = getAttributeDetailValues(attribute)\n .map((v) => v.value ?? v.productAttributeOption?.name ?? \"\")\n .filter(Boolean)\n .join(\", \");\n```\n\nWhich field carries the content depends on `v.productAttribute?.type`: `TEXT`/`NUMERIC`/`HTML`/`DATE`/`DATETIME`/`BOOLEAN` → `value`; the choice types → `productAttributeOption.name`; `IMAGE` → `images` / `imageIds`; `TABLE` → parse with `getIkasProductAttributeTableValue(v)`; `PRODUCT` → `getIkasProductAttrributeProductIds(v)` (that export name really is misspelled — see `get_framework_guide(\"imports\")`). Check the type with `get_type_definition(\"IkasProductAttributeValue\")` before assuming a field is populated.\n\n`PRODUCT_ATTRIBUTE_LIST` is a **single object, not an array** — `attributeList.map(...)` throws at runtime; the selected ids live at `attributeList.attributeListPropValue.attributeIds`. Both prop types are merchant-data types, so neither can carry a `defaultValue`. Details: `get_function_doc(\"getAttributeDetailValues\")`, `get_type_definition(\"IkasProductAttributeDetail\")`, `get_type_definition(\"IkasProductAttributeList\")`.\n\n### LINK and LIST_OF_LINK props (navigation links)\n\n**CRITICAL — the authored `defaultValue` shape is NOT the runtime read shape.** In component code you READ a link as `props.myLink.href` / `.label` / `.subLinks`. But the `defaultValue` you author in `ikas.config.json` MUST be the typed object shown below. Do NOT pass `{ \"href\": \"…\", \"label\": \"…\" }` (legacy shape) and do NOT pass the value as a JSON string — the CLI rejects both.\n\n**LINK** `defaultValue` is a single link object:\n```json\n{ \"linkType\": \"EXTERNAL\", \"label\": \"Shop now\", \"externalLink\": \"https://example.com\", \"subLinks\": [] }\n```\nor, to link to a store page:\n```json\n{ \"linkType\": \"PAGE\", \"label\": \"Home\", \"pageType\": \"INDEX\", \"subLinks\": [] }\n```\n\n**LIST_OF_LINK** `defaultValue` wraps an array of link objects in `{ \"links\": [...] }`:\n```json\n{ \"links\": [\n { \"linkType\": \"PAGE\", \"label\": \"Home\", \"pageType\": \"INDEX\", \"subLinks\": [] },\n { \"linkType\": \"EXTERNAL\", \"label\": \"Blog\", \"externalLink\": \"https://example.com/blog\", \"subLinks\": [] }\n] }\n```\n\n**Rules for every link object:**\n- `linkType` is REQUIRED and must be one of `PAGE` or `EXTERNAL`. `FILE` links are NOT authorable in a code-component default (they reference a store-specific uploaded file) — the CLI rejects them.\n- Each link MUST carry a destination for its `linkType` — the CLI rejects a link that points nowhere. `EXTERNAL` → a non-empty `externalLink` URL. `PAGE` → a `pageType` (e.g. `INDEX`); do NOT invent a `pageId` — it is per-store and filled automatically when the theme is installed, so author only `pageType`.\n- `subLinks` must be an array (use `[]` when empty); each entry is itself a link object with the same shape (for dropdown/nested menus).\n- NEVER use a JSON string, and NEVER use the legacy `{ label, href }` shape.\n\n**Config example (LINK):**\n```json\n{ \"name\": \"ctaLink\", \"displayName\": \"CTA Link\", \"type\": \"LINK\", \"defaultValue\": { \"linkType\": \"EXTERNAL\", \"label\": \"Shop now\", \"externalLink\": \"https://example.com\", \"subLinks\": [] } }\n```\n\n**Config example (LIST_OF_LINK):**\n```json\n{ \"name\": \"menuLinks\", \"displayName\": \"Menu Links\", \"type\": \"LIST_OF_LINK\", \"defaultValue\": { \"links\": [ { \"linkType\": \"PAGE\", \"label\": \"Home\", \"pageType\": \"INDEX\", \"subLinks\": [] } ] } }\n```\n\n**CLI command (LIST_OF_LINK):**\n```bash\nnpx ikas-component config add-prop --component MyComp --name menuLinks --displayName \"Menu Links\" --type LIST_OF_LINK --defaultValue '{\"links\":[{\"linkType\":\"PAGE\",\"label\":\"Home\",\"pageType\":\"INDEX\",\"subLinks\":[]}]}'\n```\n\n### Prop grouping\nProps can be assigned to groups via `groupId` for organized editor sidebar display. See `get_framework_guide(\"prop-groups\")` for details.\n\n### Style Props: TYPE and ENUM\n\nThere are two prop types for style values:\n\n- **TYPE** — Structured types with numeric values and units (padding, margin, border-radius, sizes, etc.). Uses `typeId`.\n- **ENUM** — Enum types rendered as dropdown selectors (flex-direction, justify-content, align-items, etc.). Uses `enumTypeId`.\n\nBoth are available for components and sections. For sections, TYPE props are limited to a whitelist of style types. Use `list-types --component-type section` to see section-allowed types.\n\n### TYPE prop (structured types)\nThe `TYPE` prop lets you use structured storefront types like PaddingStyleType, MarginStyleType, SizeStyleType, etc. Available for both components and sections (sections have a restricted whitelist of style types).\n\n**Workflow:**\n1. Run `npx ikas-component config list-types` to get available types (requires dev server running with editor connected)\n2. Use the `typeId` from the output when adding the prop\n3. For sections: `npx ikas-component config list-types --component-type section` to see only section-allowed types\n\n**Example config:**\n```json\n{\n \"name\": \"spacing\",\n \"displayName\": \"Spacing\",\n \"type\": \"TYPE\",\n \"typeId\": \"@ikas/bp-storefront-models-PaddingStyleType\"\n}\n```\n\n**Providing a default value:** Style TYPE props accept a `defaultValue` object — size/style types (Padding, Margin, Width, Height, Gap, BorderRadius, Size, …) take `{ \"value\": <number>, \"unit\": \"px\" | \"rem\" | \"%\" | \"vh\" | \"vw\" }` (or `{ \"css\": \"<raw css>\" }`). Add it to the prop object, e.g. `\"defaultValue\": { \"value\": 16, \"unit\": \"px\" }`. For an `_array` typeId the default is an array of these objects; the `--defaultValue` flag also accepts this JSON as a string. Only `css`, `value` and `unit` keys are allowed on a size/style default object — any other field is rejected.\n\n**Array example** (append `_array` to typeId):\n```json\n{\n \"name\": \"margins\",\n \"displayName\": \"Margins\",\n \"type\": \"TYPE\",\n \"typeId\": \"@ikas/bp-storefront-models-MarginStyleType_array\"\n}\n```\nThis generates `margins?: MarginStyleType[]` in types.ts.\n\n**CLI command:**\n```bash\nnpx ikas-component config add-prop --component MyComp --name spacing --displayName Spacing --type TYPE --typeId \"@ikas/bp-storefront-models-PaddingStyleType\"\n```\n\n### ENUM prop (enum style types)\nThe `ENUM` prop lets you use enum-based types that render as dropdown selectors. There are two kinds of enum types:\n\n1. **Built-in enums** (prefix `@ikas/`): FlexDirectionStyleType, JustifyContentStyleType, AlignItemsStyleType, etc. Available from `list-types` when editor is connected.\n2. **Custom enums**: Created with `config add-enum`. Works offline, no editor needed.\n3. **Font Style enum** (sentinel `__patternElementEnum__`): lets store owners pick one of the theme's typography tokens. Built-in — no `add-enum` and no editor connection needed. See \"Font Style enum (typography picker)\" below.\n\n**IMPORTANT:** `add-prop --type ENUM` validates that the `enumTypeId` references an existing enum. You MUST create custom enums first with `config add-enum` before using them. The command will reject unknown enum IDs.\n\n**Custom enum workflow (recommended for AI-driven generation):**\n```bash\n# Step 1: Create the enum FIRST\nnpx ikas-component config add-enum --name \"AspectRatio\" --options '{\"Square\":\"1/1\",\"Landscape\":\"16/9\",\"Portrait\":\"3/4\"}'\n# Returns: {\"success\":true,\"enumId\":\"aBcDeFgHiJ\",...}\n\n# Step 2: Use the returned enumId in add-prop\nnpx ikas-component config add-prop --component MyComp --name aspectRatio --displayName \"Aspect Ratio\" --type ENUM --enumTypeId aBcDeFgHiJ\n```\n\n**Built-in enum workflow:**\n1. Run `npx ikas-component config list-types` — enum types have `category: \"enum\"` in the output\n2. Use the `enumTypeId` from the output when adding the prop\n\n**Example config (built-in enum):**\n```json\n{\n \"name\": \"direction\",\n \"displayName\": \"Direction\",\n \"type\": \"ENUM\",\n \"enumTypeId\": \"@ikas/bp-storefront-models-FlexDirectionStyleType\"\n}\n```\nThis generates `direction?: string` in types.ts.\n\n**CLI command (built-in enum):**\n```bash\nnpx ikas-component config add-prop --component MyComp --name direction --displayName Direction --type ENUM --enumTypeId \"@ikas/bp-storefront-models-FlexDirectionStyleType\"\n```\n\n**Note:** `list-types` requires dev server with editor connected. Custom enums (`config add-enum`) work offline.\n\n### Font Style enum (typography picker)\nUse the built-in sentinel `enumTypeId: \"__patternElementEnum__\"` to let store owners pick one of the theme's typography tokens (a \"Font Style\" prop). It works exactly like a built-in enum: no `config add-enum` call and no editor connection required.\n\n**Example config:**\n```json\n{\n \"name\": \"fontStyle\",\n \"displayName\": \"Font Style\",\n \"type\": \"ENUM\",\n \"enumTypeId\": \"__patternElementEnum__\",\n \"required\": false\n}\n```\nThis generates `fontStyle?: string` in types.ts.\n\n**CLI command:**\n```bash\nnpx ikas-component config add-prop --component MyComp --name fontStyle --displayName \"Font Style\" --type ENUM --enumTypeId __patternElementEnum__\n```\n\n**Runtime:** the prop value is the chosen typography's **id** (a plain string), not the typography object itself. Resolve it with `getThemeTypography()` (see `get_framework_guide(\"theme-globals\")`) and apply its `className`:\n```tsx\nimport { getThemeTypography } from \"@ikas/bp-storefront\";\nimport type { Props } from \"./types\"; // fontStyle?: string\n\nexport function MyCard({ fontStyle }: Props) {\n const t = getThemeTypography().find((t) => t.id === fontStyle);\n return <p className={t?.className}>...</p>; // _<id> class applies the theme's typography CSS\n}\n```",
39
39
  "tags": [
40
40
  "props",
41
41
  "types",
@@ -76,7 +76,7 @@
76
76
  "component-structure": {
77
77
  "title": "Component Structure",
78
78
  "description": "How to write a Preact component for ikas",
79
- "content": "Each component consists of three files. There are two patterns: **components** (child elements) and **sections** (page-level containers).\n\n## Component Pattern (child elements like buttons, cards, badges)\n\n### index.tsx - Component Implementation\n```tsx\nimport { Props } from \"./types\";\n\nexport function MyComponent({ title, showButton }: Props) {\n return (\n <div className=\"my-component\">\n <h1>{title}</h1>\n {showButton && <button>Click me</button>}\n </div>\n );\n}\n\nexport default MyComponent;\n```\n\n### types.ts - Props Interface\n```typescript\nexport interface Props {\n title: string; // TEXT prop -> string\n showButton?: boolean; // optional BOOLEAN prop\n count: number; // NUMBER prop -> number\n}\n```\n\n### styles.css\n```css\n.my-component {\n padding: 16px;\n}\n\n.my-component h1 {\n font-size: 24px;\n}\n```\n\n## Section Pattern (page-level containers like headers, hero banners, footers)\n\nSections use a `<section>` root element, full-width styling, and a `Props` interface. In `ikas.config.json` they have `\"type\": \"section\"`. **Every section MUST include a `backgroundColor` COLOR prop** (default: `#ffffff`) so store owners can customize the section background. Consider also adding `textColor` COLOR props for text elements sitting directly on the section background, so they remain readable when the background changes.\n\n### index.tsx - Section Implementation\n```tsx\nimport { Props } from \"./types\";\n\nexport function HeroBanner({ heading, subtitle, backgroundColor }: Props) {\n return (\n <section className=\"hero-banner\" style={backgroundColor ? { backgroundColor } : undefined}>\n <div className=\"hero-banner-inner\">\n <h2>{heading}</h2>\n {subtitle && <p>{subtitle}</p>}\n </div>\n </section>\n );\n}\n\nexport default HeroBanner;\n```\n\n### types.ts - Section Props Interface\n```typescript\nexport interface Props {\n heading: string;\n subtitle?: string;\n backgroundColor?: string;\n}\n```\n\n### styles.css - Full-width section styles\n```css\n.hero-banner {\n width: 100%;\n padding: 64px 24px;\n}\n\n.hero-banner-inner {\n max-width: 1200px;\n margin: 0 auto;\n}\n```\n\n## Key Rules\n- Export the component as both a named export and a default export: `export function X() {...}` + `export default X;`\n- Use Preact (not React) - but JSX syntax is the same\n- Import types from `./types` for props\n- Use `className` not `class` for CSS classes\n- Storefront functions and types come from `@ikas/bp-storefront`\n- CSS classes are automatically scoped to your component at build time. Use plain CSS class selectors - they won't conflict with other components or the page.\n- **All user-visible text MUST be TEXT props** — never hardcode strings in JSX. This ensures all text is translatable. Use `defaultValue` in config for English defaults.\n- **Sections MUST include a `backgroundColor` COLOR prop** (default: `#ffffff`). Apply via `style={backgroundColor ? { backgroundColor } : undefined}` on the root `<section>` element. Optionally add `textColor` for text directly on the section background.\n\n## Root Components Are Automatically Reactive\n\nThe ikas runtime wraps every root component render in a MobX `autorun()`, so **root exports are already reactive** — they automatically re-render when any MobX store they read (`cartStore`, `customerStore`, etc.) changes. You do **not** need `observer()` on root component exports.\n\n### Correct: Plain root export reading stores\n```tsx\nimport { cartStore } from \"@ikas/bp-storefront\";\nimport { Props } from \"./types\";\n\nexport function CartSummary({ title }: Props) {\n const itemCount = cartStore.cart?.orderLineItems.length ?? 0;\n return (\n <section className=\"cart-summary\">\n <h2>{title}</h2>\n <p>{itemCount} items in cart</p>\n </section>\n );\n}\n\nexport default CartSummary;\n```\n\n### Anti-pattern: Do NOT wrap root exports with observer\n```tsx\n// WRONG — observer() is redundant on root components\nconst CartSummary = observer(function CartSummary({ title }: Props) {\n ...\n});\nexport default CartSummary;\n```\n\n## Using observer for Sub-Components\n\nWhen you extract a **sub-component** that independently reads MobX stores, wrap it with `observer()` from `@ikas/component-utils` so it re-renders when store data changes.\n\n### When to use observer\n- A **sub-component** (not the root export) reads `cartStore.cart`, `customerStore.customer`, or any other MobX observable\n- You extract part of a component into a separate function that needs independent reactivity\n\n### When observer is NOT needed\n- **Root component exports** — the ikas runtime handles reactivity via `autorun()`\n- Components that only use props passed from parent — no store reads\n- Static components with no reactive data\n\n### Example: Root export with observer sub-component\n```tsx\nimport { observer } from \"@ikas/component-utils\";\nimport { cartStore } from \"@ikas/bp-storefront\";\nimport { Props } from \"./types\";\n\n// Sub-component: needs observer() for independent reactivity\nconst CartBadge = observer(function CartBadge() {\n const itemCount = cartStore.cart?.orderLineItems.length ?? 0;\n return <span className=\"cart-badge\">{itemCount}</span>;\n});\n\n// Root export: NO observer needed — autorun() handles reactivity\nexport function Header({ logo }: Props) {\n return (\n <header>\n <img src={logo} alt=\"Logo\" />\n <CartBadge />\n </header>\n );\n}\n\nexport default Header;\n```\n\n**Important:** When using `observer` on sub-components, define the component as a named function expression (not arrow function) and assign it to a `const`. This ensures proper display names in React DevTools.\n\n## Sub-Component File Organization\n\nWhen you extract sub-components, **ALWAYS** place them in `src/sub-components/` with their own folder containing `index.tsx` and `styles.css`. Never create flat `.tsx` files inside a component folder. See `get_framework_guide(\"sub-component-patterns\")` for the full pattern, directory structure, CSS @import rules, and examples.",
79
+ "content": "Each component consists of three files. There are two patterns: **components** (child elements) and **sections** (page-level containers).\n\n## Component Pattern (child elements like buttons, cards, badges)\n\n### index.tsx - Component Implementation\n```tsx\nimport { Props } from \"./types\";\n\nexport function MyComponent({ title, showButton }: Props) {\n return (\n <div className=\"my-component\">\n <h1>{title}</h1>\n {showButton && <button>Click me</button>}\n </div>\n );\n}\n\nexport default MyComponent;\n```\n\n### types.ts - Props Interface\n```typescript\nexport interface Props {\n title: string; // TEXT prop -> string\n showButton?: boolean; // optional BOOLEAN prop\n count: number; // NUMBER prop -> number\n}\n```\n\n### styles.css\n```css\n.my-component {\n padding: 16px;\n}\n\n.my-component h1 {\n font-size: 24px;\n}\n```\n\n## Section Pattern (page-level containers like headers, hero banners, footers)\n\nSections use a `<section>` root element, full-width styling, and a `Props` interface. In `ikas.config.json` they have `\"type\": \"section\"`. **Every section MUST include a `backgroundColor` COLOR prop** (default: `#ffffff`) so store owners can customize the section background. Consider also adding `textColor` COLOR props for text elements sitting directly on the section background, so they remain readable when the background changes.\n\n### index.tsx - Section Implementation\n```tsx\nimport { Props } from \"./types\";\n\nexport function HeroBanner({ heading, subtitle, backgroundColor }: Props) {\n return (\n <section className=\"hero-banner\" style={backgroundColor ? { backgroundColor } : undefined}>\n <div className=\"hero-banner-inner\">\n <h2>{heading}</h2>\n {subtitle && <p>{subtitle}</p>}\n </div>\n </section>\n );\n}\n\nexport default HeroBanner;\n```\n\n### types.ts - Section Props Interface\n```typescript\nexport interface Props {\n heading: string;\n subtitle?: string;\n backgroundColor?: string;\n}\n```\n\n### styles.css - Full-width section styles\n```css\n.hero-banner {\n width: 100%;\n padding: 64px 24px;\n}\n\n.hero-banner-inner {\n max-width: 1200px;\n margin: 0 auto;\n}\n```\n\n## Key Rules\n- Export the component as both a named export and a default export: `export function X() {...}` + `export default X;`\n- Use Preact (not React) - but JSX syntax is the same\n- Import types from `./types` for props\n- Use `className` not `class` for CSS classes\n- Storefront functions and types come from `@ikas/bp-storefront`\n- CSS classes are automatically scoped to your component at build time. Use plain CSS class selectors - they won't conflict with other components or the page.\n- **All user-visible text MUST be TEXT props** — never hardcode strings in JSX. This ensures all text is translatable. Use `defaultValue` in config for English defaults.\n- **Sections MUST include a `backgroundColor` COLOR prop** (default: `#ffffff`). Apply via `style={backgroundColor ? { backgroundColor } : undefined}` on the root `<section>` element. Optionally add `textColor` for text directly on the section background.\n\n## Root Components Are Automatically Reactive\n\nThe ikas runtime wraps every root component render in a MobX `autorun()`, so **root exports are already reactive** — they automatically re-render when any MobX store they read (`cartStore`, `customerStore`, etc.) changes. You do **not** need `observer()` on root component exports.\n\n### Correct: Plain root export reading stores\n```tsx\nimport { cartStore } from \"@ikas/bp-storefront\";\nimport { Props } from \"./types\";\n\nexport function CartSummary({ title }: Props) {\n const itemCount = cartStore.cart?.orderLineItems.length ?? 0;\n return (\n <section className=\"cart-summary\">\n <h2>{title}</h2>\n <p>{itemCount} items in cart</p>\n </section>\n );\n}\n\nexport default CartSummary;\n```\n\n### Anti-pattern: Do NOT wrap root exports with observer\n```tsx\n// WRONG — observer() is redundant on root components\nconst CartSummary = observer(function CartSummary({ title }: Props) {\n ...\n});\nexport default CartSummary;\n```\n\n## Using observer for Sub-Components\n\nWhen you extract a **sub-component** that independently reads MobX stores, wrap it with `observer()` from `@ikas/component-utils` so it re-renders when store data changes.\n\n### When to use observer\n- A **sub-component** (not the root export) reads `cartStore.cart`, `customerStore.customer`, or any other MobX observable\n- You extract part of a component into a separate function that needs independent reactivity\n\n### When observer is NOT needed\n- **Root component exports** — the ikas runtime handles reactivity via `autorun()`\n- Components that only use props passed from parent — no store reads\n- Static components with no reactive data\n\n### Example: Root export with observer sub-component\n```tsx\nimport { observer } from \"@ikas/component-utils\";\nimport { cartStore } from \"@ikas/bp-storefront\";\nimport { Props } from \"./types\";\n\n// Sub-component: needs observer() for independent reactivity\nconst CartBadge = observer(function CartBadge() {\n const itemCount = cartStore.cart?.orderLineItems.length ?? 0;\n return <span className=\"cart-badge\">{itemCount}</span>;\n});\n\n// Root export: NO observer needed — autorun() handles reactivity\nexport function Header({ logo }: Props) {\n return (\n <header>\n <img src={logo} alt=\"Logo\" />\n <CartBadge />\n </header>\n );\n}\n\nexport default Header;\n```\n\n**Important:** When using `observer` on sub-components, define the component as a named function expression (not arrow function) and assign it to a `const`. This ensures proper display names in React DevTools.\n\n## Sub-Component File Organization\n\nWhen you extract sub-components, **ALWAYS** place them in `src/sub-components/` with their own folder containing `index.tsx` and `styles.css`. Never create flat `.tsx` files inside a component folder. See `get_framework_guide(\"sub-component-patterns\")` for the full pattern, directory structure, CSS collection rules, and examples.",
80
80
  "tags": [
81
81
  "component",
82
82
  "preact",
@@ -94,7 +94,7 @@
94
94
  "build-system": {
95
95
  "title": "Build System",
96
96
  "description": "How components are built and bundled",
97
- "content": "The build system uses Vite + esbuild to compile components.\n\n### Development\n```bash\nnpm run dev\n```\nStarts a dev server that:\n- Watches for file changes\n- Compiles components on the fly\n- Communicates with the ikas editor via WebSocket\n- Provides live updates in the editor preview\n\n### Production Build\n```bash\nnpm run build\n```\nBuilds optimized bundles:\n- Creates separate server and client bundles\n- Server bundle: used for SSR (no browser APIs)\n- Client bundle: used for hydration and interactivity\n- CSS is extracted and scoped per component\n- Tree-shakes unused code\n\n### What happens during build:\n1. TypeScript is compiled to JavaScript\n2. JSX is transformed (Preact's h function)\n3. CSS is scoped with unique prefixes\n4. Code is bundled per-component\n5. Externals (`preact`, `@ikas/component-utils`) are not bundled\n\n### Publishing\n```bash\nnpm run publish\n```\nUploads the built components to the ikas platform.",
97
+ "content": "The build system uses Vite + esbuild to compile components.\n\n### Development\n```bash\nikas theme dev\n```\nStarts a dev server that:\n- Watches for file changes\n- Compiles components on the fly\n- Communicates with the ikas editor via WebSocket (through a tunnel registered by the ikas CLI — see the dev-server guide)\n- Provides live updates in the editor preview\n\n### Production Build\n```bash\nnpm run build\n```\nBuilds optimized bundles:\n- Creates separate server and client bundles\n- Server bundle: used for SSR (no browser APIs)\n- Client bundle: used for hydration and interactivity\n- CSS is extracted and scoped per component\n- Tree-shakes unused code\n\n### What happens during build:\n1. TypeScript is compiled to JavaScript\n2. JSX is transformed (Preact's h function)\n3. CSS is scoped with unique prefixes\n4. Code is bundled per-component\n5. Externals (`preact`, `@ikas/component-utils`) are not bundled\n\n### Publishing\n```bash\nnpm run publish\n```\nUploads the built components to the ikas platform.",
98
98
  "tags": [
99
99
  "build",
100
100
  "vite",
@@ -109,7 +109,7 @@
109
109
  "css-scoping": {
110
110
  "title": "CSS Scoping Rules",
111
111
  "description": "How CSS is scoped to prevent conflicts between components",
112
- "content": "CSS files referenced in `ikas.config.json` are automatically scoped at build time.\n\n### How it works:\n- Each component's CSS selectors are prefixed with a unique scope identifier\n- `.my-class` becomes `.[scope]-my-class` in the output\n- This prevents style conflicts between different components on the same page\n\n### Best practices:\n- Use class selectors (`.my-class`) rather than element selectors (`div`, `h1`)\n- Avoid using `!important` - scoping handles isolation\n- Don't use global selectors or `@global` - they won't be scoped\n- Keep CSS in the component's `styles.css` file referenced in config\n- Nested selectors work: `.parent .child` both get scoped\n\n### Example:\n```css\n/* What you write */\n.product-card {\n padding: 16px;\n border: 1px solid #eee;\n}\n\n.product-card .title {\n font-size: 18px;\n font-weight: bold;\n}\n\n.product-card .price {\n color: #e53e3e;\n}\n```\n\nThe build system transforms this so your `.product-card`, `.title`, and `.price` classes are unique to your component and won't clash with any other component or theme styles.\n\n### Global CSS Exception\n\nThe one intentional exception to scoping is **Global CSS** — project-wide styles defined in `src/global.css` that are loaded unscoped before any component CSS. Global CSS is ideal for CSS custom properties (variables), resets, and shared utility classes. The loading order is: **Global CSS → Shared chunk CSS → Component CSS**, so global styles have the lowest specificity and component styles always win.\n\nSee `get_framework_guide(\"global-css\")` for full details on global CSS setup and usage.",
112
+ "content": "CSS files referenced in `ikas.config.json` are automatically scoped at build time.\n\n### How it works:\n- Each component's CSS selectors are prefixed with a unique scope identifier\n- `.my-class` becomes `.[scope]-my-class` in the output\n- This prevents style conflicts between different components on the same page\n\n### Best practices:\n- Use class selectors (`.my-class`) rather than element selectors (`div`, `h1`)\n- Avoid using `!important` - scoping handles isolation\n- Don't use global selectors or `@global` - they won't be scoped\n- Keep CSS in the component's `styles.css` file referenced in config, or in a sub-component's sibling `styles.css` — both are collected and scoped automatically on `dev`/`publish`\n- Nested selectors work: `.parent .child` both get scoped\n\n### Example:\n```css\n/* What you write */\n.product-card {\n padding: 16px;\n border: 1px solid #eee;\n}\n\n.product-card .title {\n font-size: 18px;\n font-weight: bold;\n}\n\n.product-card .price {\n color: #e53e3e;\n}\n```\n\nThe build system transforms this so your `.product-card`, `.title`, and `.price` classes are unique to your component and won't clash with any other component or theme styles.\n\n### Global CSS Exception\n\nThe one intentional exception to scoping is **Global CSS** — project-wide styles defined in `src/global.css` that are loaded unscoped before any component CSS. Global CSS is ideal for CSS custom properties (variables), resets, and shared utility classes. The loading order is: **Global CSS → Shared chunk CSS → Component CSS**, so global styles have the lowest specificity and component styles always win.\n\nSee `get_framework_guide(\"global-css\")` for full details on global CSS setup and usage.",
113
113
  "tags": [
114
114
  "css",
115
115
  "scoping",
@@ -122,7 +122,7 @@
122
122
  "global-css": {
123
123
  "title": "Global CSS",
124
124
  "description": "Project-wide unscoped CSS for variables, resets, and shared utilities",
125
- "content": "## Global CSS\n\nGlobal CSS lets you define project-wide styles that are shared across all components — without scoping. This is ideal for:\n\n- **CSS custom properties (variables)** — colors, spacing, typography tokens\n- **CSS resets** — normalize/reset base styles\n- **Base typography** — font-family, line-height defaults\n- **Utility classes** — common layout helpers\n\n### Setup\n\n1. Create a `src/global.css` file in your project root:\n\n```css\n/* src/global.css */\n:root {\n --color-primary: #2563eb;\n --color-secondary: #7c3aed;\n --color-text: #1f2937;\n --color-text-muted: #6b7280;\n --color-border: #e5e7eb;\n --color-background: #ffffff;\n\n --spacing-xs: 4px;\n --spacing-sm: 8px;\n --spacing-md: 16px;\n --spacing-lg: 24px;\n --spacing-xl: 48px;\n\n --font-sans: system-ui, -apple-system, sans-serif;\n --font-mono: ui-monospace, monospace;\n\n --radius-sm: 4px;\n --radius-md: 8px;\n --radius-lg: 16px;\n}\n```\n\n2. Add the `globalStyles` field to `ikas.config.json`:\n\n```json\n{\n \"name\": \"my-project\",\n \"version\": \"1.0.0\",\n \"globalStyles\": \"./src/global.css\",\n \"components\": [...]\n}\n```\n\n### Using Global CSS Variables in Components\n\nOnce defined in `global.css`, CSS custom properties are available in any component's `styles.css`:\n\n```css\n/* src/components/ProductCard/styles.css */\n.product-card {\n border: 1px solid var(--color-border);\n border-radius: var(--radius-md);\n padding: var(--spacing-md);\n font-family: var(--font-sans);\n}\n\n.product-card .title {\n color: var(--color-text);\n}\n\n.product-card .price {\n color: var(--color-primary);\n}\n```\n\n### Loading Order\n\nCSS is loaded in this order, from lowest to highest specificity:\n\n1. **Global CSS** (`global.css`) — unscoped, loaded first\n2. **Shared chunk CSS** — scoped styles from shared internal components\n3. **Component CSS** (`styles.css`) — scoped per-component styles\n\nBecause global CSS loads first and is unscoped, component-scoped styles will always override global styles when selectors conflict. This means you can safely define base defaults in `global.css` and override them in component `styles.css` files.\n\n### Key Differences from Component CSS\n\n| | Global CSS | Component CSS |\n|---|---|---|\n| **File** | `src/global.css` | `src/components/X/styles.css` |\n| **Scoping** | NOT scoped (no `.cc_` prefix) | Scoped with `.cc_{componentId}` prefix |\n| **Config** | `globalStyles` in ikas.config.json | `styles` on each component |\n| **Purpose** | CSS variables, resets, utilities | Component-specific styles |\n| **Load order** | First (lowest specificity) | Last (highest specificity) |\n\n### Best Practices\n\n- **Use CSS custom properties** for design tokens (colors, spacing, fonts) — they cascade naturally and components can reference them\n- **Keep global CSS minimal** — only put truly shared values here. Component-specific styles belong in the component's `styles.css`\n- **Avoid class selectors in global CSS** that target component internals — use custom properties instead for themeable values\n- **Don't duplicate** — if a style only applies to one component, put it in that component's `styles.css`\n\n### Project Structure with Global CSS\n\n```\nmy-project/\n├── src/\n│ ├── global.css # Project-wide unscoped CSS\n│ └── components/\n│ ├── ProductCard/\n│ │ ├── index.tsx\n│ │ ├── types.ts\n│ │ └── styles.css # Uses var(--color-primary) etc.\n│ └── index.ts\n├── ikas.config.json # Has globalStyles: \"./src/global.css\"\n├── package.json\n└── tsconfig.json\n```\n\nSee `get_framework_guide(\"css-scoping\")` for details on how component CSS scoping works.",
125
+ "content": "## Global CSS\n\nGlobal CSS lets you define project-wide styles that are shared across all components — without scoping. This is ideal for:\n\n- **CSS custom properties (variables)** — colors, spacing, typography tokens\n- **CSS resets** — normalize/reset base styles\n- **Base typography** — font-family, line-height defaults\n- **Utility classes** — common layout helpers\n\n### Setup\n\n1. Create a `src/global.css` file in your project root:\n\n```css\n/* src/global.css */\n:root {\n --color-primary: #2563eb;\n --color-secondary: #7c3aed;\n --color-text: #1f2937;\n --color-text-muted: #6b7280;\n --color-border: #e5e7eb;\n --color-background: #ffffff;\n\n --spacing-xs: 4px;\n --spacing-sm: 8px;\n --spacing-md: 16px;\n --spacing-lg: 24px;\n --spacing-xl: 48px;\n\n --font-sans: system-ui, -apple-system, sans-serif;\n --font-mono: ui-monospace, monospace;\n\n --radius-sm: 4px;\n --radius-md: 8px;\n --radius-lg: 16px;\n}\n```\n\n2. Add the `globalStyles` field to `ikas.config.json`:\n\n```json\n{\n \"name\": \"my-project\",\n \"version\": \"1.0.0\",\n \"globalStyles\": \"./src/global.css\",\n \"components\": [...]\n}\n```\n\n### Using Global CSS Variables in Components\n\nOnce defined in `global.css`, CSS custom properties are available in any component's `styles.css`:\n\n```css\n/* src/components/ProductCard/styles.css */\n.product-card {\n border: 1px solid var(--color-border);\n border-radius: var(--radius-md);\n padding: var(--spacing-md);\n font-family: var(--font-sans);\n}\n\n.product-card .title {\n color: var(--color-text);\n}\n\n.product-card .price {\n color: var(--color-primary);\n}\n```\n\n### Loading Order\n\nCSS is loaded in this order, from lowest to highest specificity:\n\n1. **Global CSS** (`global.css`) — unscoped, loaded first\n2. **Shared chunk CSS** — scoped styles from shared internal components (their sibling `styles.css` files, collected automatically)\n3. **Component CSS** (`styles.css`) — scoped per-component styles\n\nBecause global CSS loads first and is unscoped, component-scoped styles will always override global styles when selectors conflict. This means you can safely define base defaults in `global.css` and override them in component `styles.css` files.\n\n### Key Differences from Component CSS\n\n| | Global CSS | Component CSS |\n|---|---|---|\n| **File** | `src/global.css` | `src/components/X/styles.css` |\n| **Scoping** | NOT scoped (no `.cc_` prefix) | Scoped with `.cc_{componentId}` prefix |\n| **Config** | `globalStyles` in ikas.config.json | `styles` on each component |\n| **Purpose** | CSS variables, resets, utilities | Component-specific styles |\n| **Load order** | First (lowest specificity) | Last (highest specificity) |\n\n### Best Practices\n\n- **Use CSS custom properties** for design tokens (colors, spacing, fonts) — they cascade naturally and components can reference them\n- **Keep global CSS minimal** — only put truly shared values here. Component-specific styles belong in the component's `styles.css`\n- **Avoid class selectors in global CSS** that target component internals — use custom properties instead for themeable values\n- **Don't duplicate** — if a style only applies to one component, put it in that component's `styles.css`\n\n### Project Structure with Global CSS\n\n```\nmy-project/\n├── src/\n│ ├── global.css # Project-wide unscoped CSS\n│ └── components/\n│ ├── ProductCard/\n│ │ ├── index.tsx\n│ │ ├── types.ts\n│ │ └── styles.css # Uses var(--color-primary) etc.\n│ └── index.ts\n├── ikas.config.json # Has globalStyles: \"./src/global.css\"\n├── package.json\n└── tsconfig.json\n```\n\nSee `get_framework_guide(\"css-scoping\")` for details on how component CSS scoping works.",
126
126
  "tags": [
127
127
  "css",
128
128
  "global",
@@ -136,16 +136,20 @@
136
136
  },
137
137
  "dev-server": {
138
138
  "title": "Dev Server Usage",
139
- "description": "How to use the development server with the ikas editor",
140
- "content": "The dev server enables live development with the ikas editor.\n\n### Starting the dev server:\n```bash\nnpm run dev\n```\n\nThis starts a local server (default port 3000) that:\n1. Compiles your components\n2. Opens a WebSocket connection for live reload\n3. Watches file changes and recompiles automatically\n\n### Connecting to the editor:\n1. Open the ikas editor (editor.ikas.com)\n2. Go to your store's theme editor\n3. Open the \"Dev Components\" panel\n4. Enter your dev server URL (e.g., `http://localhost:3000`)\n5. Your components will appear in the component picker\n\n### Development workflow:\n1. Start dev server with `npm run dev`\n2. Connect the editor to your dev server\n3. Add/modify components in your code\n4. Changes appear automatically in the editor\n5. Use the editor to configure prop values and preview\n\n### Adding a new component:\n```bash\nnpm run add\n```\nThis interactive command:\n- Asks for component name\n- Creates the component directory and files\n- Updates `ikas.config.json` with the new component entry",
139
+ "description": "How to start the dev server with `ikas theme dev` and connect it to ikas Studio (the theme editor)",
140
+ "content": "The dev server enables live development with ikas Studio (the theme editor). Studio finds your local dev server through a WebSocket routing record registered by the `ikas` CLI — you never enter a dev server URL manually.\n\n### Official workflow (ikas CLI):\n\n1. Install the ikas CLI globally:\n```bash\nnpm install ikas -g\n```\n\n2. Link your project folder to the editor (create a new project or link an existing one). Copy the exact command from the \"Code Components\" panel in Studio — it includes your editor URL:\n```bash\nikas theme init -e https://{store}.myikas.com/admin/storefront/{storefrontId}/editor/{themeId}\n```\n\n3. Start the dev server from the project folder:\n```bash\nikas theme dev\n```\nThis command:\n- Compiles your components and watches file changes (live reload over WebSocket, local port 5201)\n- Opens a secure tunnel to the local dev server\n- Registers the tunnel's `wss://` URL with ikas so Studio can reach your dev server (the routing stays valid for 8 hours and is cleared when you stop the terminal session)\n\n4. In Studio, open the \"Code Components\" panel and click **Connect**. Your components appear in the component picker.\n\n### Important — do NOT start with `npm run dev`\nRunning the project-local dev server directly (`npm run dev` or `ikas-component dev`) only starts a local server on `127.0.0.1:5201`. It does NOT open the tunnel and does NOT register the WebSocket routing, so Studio cannot find or connect to your dev server. Always start development with `ikas theme dev`.\n\n### Development workflow:\n1. Start the dev server with `ikas theme dev`\n2. Click Connect in Studio's Code Components panel\n3. Add/modify components in your code\n4. Changes appear automatically in the editor\n5. Use the editor to configure prop values and preview\n\n### Adding a new component:\n```bash\nnpm run add\n```\nThis interactive command:\n- Asks for component name\n- Creates the component directory and files\n- Updates `ikas.config.json` with the new component entry",
141
141
  "tags": [
142
142
  "dev",
143
143
  "server",
144
144
  "development",
145
145
  "editor",
146
+ "studio",
146
147
  "live-reload",
147
148
  "websocket",
148
- "workflow"
149
+ "workflow",
150
+ "tunnel",
151
+ "connect",
152
+ "routing"
149
153
  ]
150
154
  },
151
155
  "imports": {
@@ -182,7 +186,7 @@
182
186
  "common-pitfalls": {
183
187
  "title": "Common Pitfalls",
184
188
  "description": "Frequent mistakes LLMs and developers make when building ikas code components",
185
- "content": "## Common Pitfalls\n\nThese are the most common mistakes when building ikas code components. Avoid them for correct, working code.\n\n### 1. Root Component Should NOT Use observer\n\nThe ikas runtime wraps root component renders in `autorun()`, making them automatically reactive. Wrapping a root export with `observer()` is redundant and misleading.\n\n**Wrong** — observer on root export:\n```tsx\nimport { observer } from \"@ikas/component-utils\";\nimport { cartStore } from \"@ikas/bp-storefront\";\n\nconst CartSection = observer(function CartSection({ title }: Props) {\n const items = cartStore.cart?.orderLineItems ?? [];\n return <section>{title}: {items.length} items</section>;\n});\nexport default CartSection;\n```\n\n**Correct** — plain named export:\n```tsx\nimport { cartStore } from \"@ikas/bp-storefront\";\n\nexport function CartSection({ title }: Props) {\n const items = cartStore.cart?.orderLineItems ?? [];\n return <section>{title}: {items.length} items</section>;\n}\n\nexport default CartSection;\n```\n\n### 2. Observer Sub-Component Naming\n\nWhen using `observer()` on **sub-components**, use a named function expression — not an arrow function — for proper DevTools display names.\n\n**Wrong** — arrow function loses display name:\n```tsx\nconst CartBadge = observer(() => {\n return <span>{cartStore.cart?.orderLineItems.length ?? 0}</span>;\n});\n```\n\n**Correct** — named function expression:\n```tsx\nconst CartBadge = observer(function CartBadge() {\n return <span>{cartStore.cart?.orderLineItems.length ?? 0}</span>;\n});\n```\n\n### 3. Mutation Semantics\n\nMany storefront functions (122+) return `void` and **mutate their arguments in place**. Do NOT try to capture a return value:\n\n```tsx\n// WRONG — selectVariantValue returns void, not a new product\nconst updated = selectVariantValue(product, value);\n\n// CORRECT — mutates product in place, observer re-renders automatically\nselectVariantValue(product, dvv.variantValue);\n```\n\nOther mutation functions: `initLoginForm()`, `setLoginFormEmail()`, `clearFilter()`, `selectFilterValue()`.\n\n### 4. CSS Scoping Limits\n\nOnly **class selectors** in `styles.css` are reliably scoped. Element selectors are NOT scoped:\n\n```css\n/* SAFE — scoped to your component */\n.product-card { padding: 16px; }\n.product-card .title { font-size: 18px; }\n\n/* UNSAFE — NOT reliably scoped, may affect other components */\ndiv { margin: 0; }\nh1 { font-size: 24px; }\n```\n\nAlways use class selectors for all styles.\n\n### 5. Prop Null Handling\n\nProps from the editor can be `undefined` when the store owner hasn't set them. Always use optional chaining:\n\n```tsx\n// WRONG — will crash if product is undefined\n<h1>{props.product.name}</h1>\n\n// CORRECT\n<h1>{props.product?.name}</h1>\n{props.heroImage && <img src={getDefaultSrc(props.heroImage)} />}\n```\n\n### 6. IkasProductImage vs IkasImage\n\n`variant.images` is `IkasProductImage[]`, NOT `IkasImage[]`. You must access the `.image` property to get the `IkasImage` needed by CDN helpers:\n\n```tsx\n// WRONG — productImage is IkasProductImage, not IkasImage\ngetDefaultSrc(productImage);\n\n// CORRECT — access .image to get IkasImage\ngetDefaultSrc(productImage.image);\n\n// Full pattern:\nconst images: IkasImage[] = variant.images\n .map((pi) => pi.image)\n .filter((img): img is IkasImage => img != null);\n```\n\n### 7. Type Assertion Pattern\n\nSome storefront functions have type inference gaps. Use `as unknown as` casts when needed — this is a known pattern:\n\n```tsx\nconst inStock = hasProductStock(product) as unknown as boolean;\nconst finalPrice = getProductVariantFormattedFinalPrice(variant) as unknown as string;\nconst canAddToCart = isAddToCartEnabled(product) as unknown as boolean;\n```\n\nThis applies to functions like `hasProductStock`, `hasProductVariantStock`, `isAddToCartEnabled`, `hasProductVariantDiscount`, `getProductVariantDiscountPercentage`, `getProductVariantFormattedFinalPrice`, `getProductVariantFormattedSellPrice`, `getProductVariantFormattedDiscountAmount`, and `getProductVariantFormattedCampaignPrice`.\n\nNote: `getProductVariantMainImage` returns `IkasProductImage | undefined` (NOT `IkasImage`). Access `.image` to get the `IkasImage` for CDN helpers like `getDefaultSrc()`.\n\n### 8. Store Data Null Safety\n\nStore data (`customerStore.customer`, `cartStore.cart`, `baseStore`) is `null` before initialization completes. Always guard access:\n\n```tsx\n// WRONG — crashes if customer is null\n<h1>{customerStore.customer.firstName}</h1>\n\n// CORRECT — null check first\nif (!customerStore.customer) return <div>Loading...</div>;\n<h1>{customerStore.customer.firstName}</h1>\n\n// Also correct — optional chaining\n<h1>{customerStore.customer?.firstName ?? \"Guest\"}</h1>\n```\n\nSame for `cartStore.cart` — always use `cartStore.cart?.orderLineItems ?? []`.\n\n### 9. ProductList/BlogList Data Access\n\n`productList.data` is the correct way to access products in a product list. Similarly, `blogList.data` for blogs. The display names `.products` / `.blogs` are only used by the blueprint editor — they do NOT exist at runtime:\n\n```tsx\n// CORRECT — use .data for both product lists and blog lists\nconst products = productList?.data ?? [];\nconst blogs = blogList?.data ?? [];\n\n// WRONG — .products / .blogs are display names, not actual fields\nconst products = productList?.products ?? [];\nconst blogs = blogList?.blogs ?? [];\n```\n\n### 10. Form Field Access Pattern\n\nForm fields are objects with `.value`, `.label`, `.hasError`, `.message`. Never access the field directly as a primitive:\n\n```tsx\n// WRONG — loginForm.email is a field object, not a string\n<input value={loginForm.email} />\n\n// CORRECT — access .value for the actual value\n<input value={loginForm.email.value} />\n{loginForm.email.hasError && <span>{loginForm.email.message}</span>}\n```\n\n### 11. Optional Chaining for Editor Props\n\nAll props from `ikas.config.json` can be `undefined` in the editor before the store owner sets them. Always use optional chaining and defaults:\n\n```tsx\n// WRONG — will crash in the editor\n<h1>{props.title}</h1>\n<img src={getDefaultSrc(props.image)} />\n{props.links.links.map(...)}\n\n// CORRECT — safe access with defaults\n<h1>{props.title ?? \"Default Title\"}</h1>\n{props.image && <img src={getDefaultSrc(props.image)} />}\n{(props.links?.links ?? []).map(...)}\n```\n\n### 12. Event Handler Typing\n\nPreact uses different event types than React. Use `(e: Event)` not `(e: React.ChangeEvent)`. Access values with casting. Preact uses `onInput` not `onChange` for text inputs:\n\n```tsx\n// WRONG — React patterns don't work in Preact\nonChange={(e: React.ChangeEvent<HTMLInputElement>) => setValue(e.target.value)}\n\n// CORRECT — Preact event handling\nonInput={(e: Event) => setValue((e.target as HTMLInputElement).value)}\n```\n\nFor select elements:\n```tsx\nonChange={(e: Event) => setOption((e.target as HTMLSelectElement).value)}\n```\n\n### 13. Function Parameter Order\n\nMany storefront functions take specific parameter orders. Always verify with `get_function_doc()` before using:\n\n```tsx\n// WRONG — submitLoginForm only takes the form, not the store\nsubmitLoginForm(customerStore, loginForm);\n\n// CORRECT\nsubmitLoginForm(loginForm);\n\n// WRONG — wrong parameter order for addItemToCart\naddItemToCart(product, variant, 1);\n\n// CORRECT — variant first, then product, then quantity\naddItemToCart(variant, product, 1);\n\n// WRONG — selectVariantValue takes product and variantValue\nselectVariantValue(variant, value);\n\n// CORRECT\nselectVariantValue(product, dvv.variantValue);\n```\n\nWhen in doubt, use the `get_function_doc(functionName)` MCP tool to check the exact signature.\n\n### 14. Missing backgroundColor Prop on Sections\n\nEvery section MUST include a `backgroundColor` COLOR prop so store owners can customize the section background. Without it, the section has a hardcoded background that cannot be changed in the editor.\n\n**Wrong** — section with no backgroundColor prop:\n```json\n// ikas.config.json\n{ \"id\": \"my-section\", \"type\": \"section\", \"props\": [\n { \"name\": \"title\", \"type\": \"TEXT\" }\n]}\n```\n```tsx\nexport function MySection({ title }: Props) {\n return <section className=\"my-section\"><h1>{title}</h1></section>;\n}\n```\n\n**Correct** — section with backgroundColor prop:\n```json\n// ikas.config.json\n{ \"id\": \"my-section\", \"type\": \"section\", \"props\": [\n { \"name\": \"title\", \"type\": \"TEXT\" },\n { \"name\": \"backgroundColor\", \"displayName\": \"Background Color\", \"type\": \"COLOR\", \"defaultValue\": \"#ffffff\" }\n]}\n```\n```tsx\nexport function MySection({ title, backgroundColor = \"#ffffff\" }: Props) {\n return (\n <section className=\"my-section\" style={backgroundColor ? { backgroundColor } : undefined}>\n <h1>{title}</h1>\n </section>\n );\n}\n```\n\nOptionally, also consider adding `textColor` COLOR props for text elements sitting directly on the section background, so they remain readable when the store owner changes the background color.\n\n### 15. Forgetting to Group Props for Complex Sections\n\nSections with 5+ props should use prop groups to organize the editor sidebar. Without groups, store owners see a long flat list of unrelated props.\n\n**Better** — organize related props into groups:\n```json\n{\n \"propGroups\": [\n { \"id\": \"content\", \"name\": \"Content\" },\n { \"id\": \"appearance\", \"name\": \"Appearance\" }\n ],\n \"props\": [\n { \"name\": \"heading\", \"groupId\": \"content\", ... },\n { \"name\": \"bgColor\", \"groupId\": \"appearance\", ... }\n ]\n}\n```\n\nSee `get_framework_guide(\"prop-groups\")` for full details.\n\n### 16. Hardcoded Static Text in Components\n\nAll user-visible text MUST be TEXT props — never hardcode strings in JSX. Hardcoded text cannot be translated for multilingual storefronts.\n\n**Wrong** — hardcoded strings:\n```tsx\nexport function LoginSection({ backgroundColor }: Props) {\n return (\n <section style={backgroundColor ? { backgroundColor } : undefined}>\n <h1>Sign In</h1>\n <button>{form.isSubmitting ? \"Signing in...\" : \"Sign In\"}</button>\n <p>Don't have an account? <a href=\"/register\">Create one</a></p>\n </section>\n );\n}\n```\n\n**Correct** — all text as TEXT props with defaultValues:\n```json\n// ikas.config.json\n{ \"props\": [\n { \"name\": \"title\", \"type\": \"TEXT\", \"defaultValue\": \"Sign In\", \"groupId\": \"texts\" },\n { \"name\": \"submitButtonText\", \"type\": \"TEXT\", \"defaultValue\": \"Sign In\", \"groupId\": \"texts\" },\n { \"name\": \"submittingButtonText\", \"type\": \"TEXT\", \"defaultValue\": \"Signing in...\", \"groupId\": \"texts\" },\n { \"name\": \"noAccountText\", \"type\": \"TEXT\", \"defaultValue\": \"Don't have an account?\", \"groupId\": \"texts\" },\n { \"name\": \"createAccountLinkText\", \"type\": \"TEXT\", \"defaultValue\": \"Create one\", \"groupId\": \"texts\" }\n],\n\"propGroups\": [{ \"id\": \"texts\", \"name\": \"Texts\" }]}\n```\n```tsx\nexport function LoginSection({ title = \"Sign In\", submitButtonText = \"Sign In\",\n submittingButtonText = \"Signing in...\", noAccountText = \"Don't have an account?\",\n createAccountLinkText = \"Create one\", backgroundColor }: Props) {\n return (\n <section style={backgroundColor ? { backgroundColor } : undefined}>\n <h1>{title}</h1>\n <button>{form.isSubmitting ? submittingButtonText : submitButtonText}</button>\n <p>{noAccountText} <a href=\"/register\">{createAccountLinkText}</a></p>\n </section>\n );\n}\n```\n\nFor button loading states, use two separate TEXT props (e.g., `submitButtonText` + `submittingButtonText`). Group text props under a \"Texts\" propGroup when the component has 5+ props.\n\n### 17. IkasOrderLineItemOption.values is an Array, Not a Scalar\n\n`IkasOrderLineItemOption` (the per-item options on cart/order line items) has a `.values` field that is an **array** of `IkasOrderLineItemOptionValue`, NOT a scalar `.value`. Each value in the array has its own `.name` / `.value` / `.formattedPrice`.\n\n```tsx\n// WRONG — there is no .value on IkasOrderLineItemOption\n<span>{option.value}</span>\n\n// CORRECT — .values is an array; map over it\n{option.values.map((v) => (\n <span key={v.name}>{v.name}: {v.value}</span>\n))}\n```\n\nThis is the most common confusion when rendering order summary lines or cart line item options. See `get_migration_guide(\"prop-runtime-shapes\")` for the broader catalog of order-shape gotchas.\n\n### 18. IkasOrderAdjustment Has No .formattedAmount — Use the Helper\n\n`IkasOrderAdjustment` does not expose a `.formattedAmount` property directly. Call the helper `getOrderAdjustmentFormattedAmount(adjustment)` from `@ikas/bp-storefront` — it returns the formatted currency string with the correct sign (negated for decrements).\n\n```tsx\nimport { getOrderAdjustmentFormattedAmount } from \"@ikas/bp-storefront\";\n\n// WRONG — .formattedAmount does not exist\n<td>{adjustment.formattedAmount}</td>\n\n// CORRECT\n<td>{getOrderAdjustmentFormattedAmount(adjustment)}</td>\n```\n\nSee `get_function_doc(\"getOrderAdjustmentFormattedAmount\")` for the exact signature.\n\n### 19. Old-System Property Patterns That Don't Exist in the New System\n\nSeveral `@ikas/storefront` properties look like they should still work but don't exist on the corresponding `@ikas/bp-storefront` types. Use the helper function instead. **If TypeScript reports TS2339 (\"Property X does not exist on type Y\") on a `.selectedVariant`, `.mainImage`, `.href`, or `.checkoutUrl` access, you're hitting one of these.**\n\n| Old pattern | New replacement |\n|---|---|\n| `product.selectedVariant` | `getSelectedProductVariant(product)` → `IkasProductVariant \\| undefined` |\n| `product.href` | `getProductHref(product)` (one of several `get*Href` helpers — see `navigation-patterns`) |\n| `variant.mainImage` | `getProductVariantMainImage(variant)` → `IkasProductImage`, then access `.image` for the `IkasImage` |\n| `cartStore.checkoutUrl` | `getCheckoutUrlFromCartStore(cartStore)` (handles auth-state branching internally) |\n\nThe variant-to-image chain is 4 hops (each carries metadata the next doesn't). See `get_framework_guide(\"image-handling\")` for the canonical recipe.\n\n### Deep SDK imports (`@ikas/bp-storefront/dist/...`)\n\n**Wrong** — reaching into a private subpath when a root helper seems missing:\n```tsx\n// breaks at runtime: no window global for this subpath, and the build rejects it\nimport { apiSaveCart } from \"@ikas/bp-storefront/dist/functions/api/cart\";\n```\n\n**Correct** — use the public root export (coupon has dedicated form helpers):\n```tsx\nimport {\n customerStore,\n getCouponCodeForm,\n setCouponCodeFormCouponCode,\n submitCouponCodeForm,\n} from \"@ikas/bp-storefront\";\n```\n\nRule: every import from the storefront SDK must come from the BARE package name — never a `/dist/` or `/src/` subpath.",
189
+ "content": "## Common Pitfalls\n\nThese are the most common mistakes when building ikas code components. Avoid them for correct, working code.\n\n### 1. Root Component Should NOT Use observer\n\nThe ikas runtime wraps root component renders in `autorun()`, making them automatically reactive. Wrapping a root export with `observer()` is redundant and misleading.\n\n**Wrong** — observer on root export:\n```tsx\nimport { observer } from \"@ikas/component-utils\";\nimport { cartStore } from \"@ikas/bp-storefront\";\n\nconst CartSection = observer(function CartSection({ title }: Props) {\n const items = cartStore.cart?.orderLineItems ?? [];\n return <section>{title}: {items.length} items</section>;\n});\nexport default CartSection;\n```\n\n**Correct** — plain named export:\n```tsx\nimport { cartStore } from \"@ikas/bp-storefront\";\n\nexport function CartSection({ title }: Props) {\n const items = cartStore.cart?.orderLineItems ?? [];\n return <section>{title}: {items.length} items</section>;\n}\n\nexport default CartSection;\n```\n\n### 2. Observer Sub-Component Naming\n\nWhen using `observer()` on **sub-components**, use a named function expression — not an arrow function — for proper DevTools display names.\n\n**Wrong** — arrow function loses display name:\n```tsx\nconst CartBadge = observer(() => {\n return <span>{cartStore.cart?.orderLineItems.length ?? 0}</span>;\n});\n```\n\n**Correct** — named function expression:\n```tsx\nconst CartBadge = observer(function CartBadge() {\n return <span>{cartStore.cart?.orderLineItems.length ?? 0}</span>;\n});\n```\n\n### 3. Mutation Semantics\n\nMany storefront functions (122+) return `void` and **mutate their arguments in place**. Do NOT try to capture a return value:\n\n```tsx\n// WRONG — selectVariantValue returns void, not a new product\nconst updated = selectVariantValue(product, value);\n\n// CORRECT — mutates product in place, observer re-renders automatically\nselectVariantValue(product, dvv.variantValue);\n```\n\nOther mutation functions: `initLoginForm()`, `setLoginFormEmail()`, `clearFilter()`, `selectFilterValue()`.\n\n### 4. CSS Scoping Limits\n\nOnly **class selectors** in `styles.css` are reliably scoped. Element selectors are NOT scoped:\n\n```css\n/* SAFE — scoped to your component */\n.product-card { padding: 16px; }\n.product-card .title { font-size: 18px; }\n\n/* UNSAFE — NOT reliably scoped, may affect other components */\ndiv { margin: 0; }\nh1 { font-size: 24px; }\n```\n\nAlways use class selectors for all styles.\n\n### 5. Prop Null Handling\n\nProps from the editor can be `undefined` when the store owner hasn't set them. Always use optional chaining:\n\n```tsx\n// WRONG — will crash if product is undefined\n<h1>{props.product.name}</h1>\n\n// CORRECT\n<h1>{props.product?.name}</h1>\n{props.heroImage && <img src={getDefaultSrc(props.heroImage)} />}\n```\n\n### 6. IkasProductImage vs IkasImage\n\n`variant.images` is `IkasProductImage[]`, NOT `IkasImage[]`. You must access the `.image` property to get the `IkasImage` needed by CDN helpers:\n\n```tsx\n// WRONG — productImage is IkasProductImage, not IkasImage\ngetDefaultSrc(productImage);\n\n// CORRECT — access .image to get IkasImage\ngetDefaultSrc(productImage.image);\n\n// Full pattern:\nconst images: IkasImage[] = variant.images\n .map((pi) => pi.image)\n .filter((img): img is IkasImage => img != null);\n```\n\n### 7. Type Assertion Pattern\n\nSome storefront functions have type inference gaps. Use `as unknown as` casts when needed — this is a known pattern:\n\n```tsx\nconst inStock = hasProductStock(product) as unknown as boolean;\nconst finalPrice = getProductVariantFormattedFinalPrice(variant) as unknown as string;\nconst canAddToCart = isAddToCartEnabled(product) as unknown as boolean;\n```\n\nThis applies to functions like `hasProductStock`, `hasProductVariantStock`, `isAddToCartEnabled`, `hasProductVariantDiscount`, `getProductVariantDiscountPercentage`, `getProductVariantFormattedFinalPrice`, `getProductVariantFormattedSellPrice`, `getProductVariantFormattedDiscountAmount`, and `getProductVariantFormattedCampaignPrice`.\n\nNote: `getProductVariantMainImage` returns `IkasProductImage | undefined` (NOT `IkasImage`). Access `.image` to get the `IkasImage` for CDN helpers like `getDefaultSrc()`.\n\n### 8. Store Data Null Safety\n\nStore data (`customerStore.customer`, `cartStore.cart`, `baseStore`) is `null` before initialization completes. Always guard access:\n\n```tsx\n// WRONG — crashes if customer is null\n<h1>{customerStore.customer.firstName}</h1>\n\n// CORRECT — null check first\nif (!customerStore.customer) return <div>Loading...</div>;\n<h1>{customerStore.customer.firstName}</h1>\n\n// Also correct — optional chaining\n<h1>{customerStore.customer?.firstName ?? \"Guest\"}</h1>\n```\n\nSame for `cartStore.cart` — always use `cartStore.cart?.orderLineItems ?? []`.\n\n### 9. ProductList/BlogList Data Access\n\n`productList.data` is the correct way to access products in a product list. Similarly, `blogList.data` for blogs. The display names `.products` / `.blogs` are only used by the blueprint editor — they do NOT exist at runtime:\n\n```tsx\n// CORRECT — use .data for both product lists and blog lists\nconst products = productList?.data ?? [];\nconst blogs = blogList?.data ?? [];\n\n// WRONG — .products / .blogs are display names, not actual fields\nconst products = productList?.products ?? [];\nconst blogs = blogList?.blogs ?? [];\n```\n\n### 10. Form Field Access Pattern\n\nForm fields are objects with `.value`, `.label`, `.hasError`, `.message`. Never access the field directly as a primitive:\n\n```tsx\n// WRONG — loginForm.email is a field object, not a string\n<input value={loginForm.email} />\n\n// CORRECT — access .value for the actual value\n<input value={loginForm.email.value} />\n{loginForm.email.hasError && <span>{loginForm.email.message}</span>}\n```\n\n### 11. Optional Chaining for Editor Props\n\nAll props from `ikas.config.json` can be `undefined` in the editor before the store owner sets them. Always use optional chaining and defaults:\n\n```tsx\n// WRONG — will crash in the editor\n<h1>{props.title}</h1>\n<img src={getDefaultSrc(props.image)} />\n{props.links.links.map(...)}\n\n// CORRECT — safe access with defaults\n<h1>{props.title ?? \"Default Title\"}</h1>\n{props.image && <img src={getDefaultSrc(props.image)} />}\n{(props.links?.links ?? []).map(...)}\n```\n\n### 12. Event Handler Typing\n\nPreact uses different event types than React. Use `(e: Event)` not `(e: React.ChangeEvent)`. Access values with casting. Preact uses `onInput` not `onChange` for text inputs:\n\n```tsx\n// WRONG — React patterns don't work in Preact\nonChange={(e: React.ChangeEvent<HTMLInputElement>) => setValue(e.target.value)}\n\n// CORRECT — Preact event handling\nonInput={(e: Event) => setValue((e.target as HTMLInputElement).value)}\n```\n\nFor select elements:\n```tsx\nonChange={(e: Event) => setOption((e.target as HTMLSelectElement).value)}\n```\n\n### 13. Function Parameter Order\n\nMany storefront functions take specific parameter orders. Always verify with `get_function_doc()` before using:\n\n```tsx\n// WRONG — submitLoginForm only takes the form, not the store\nsubmitLoginForm(customerStore, loginForm);\n\n// CORRECT\nsubmitLoginForm(loginForm);\n\n// WRONG — wrong parameter order for addItemToCart\naddItemToCart(product, variant, 1);\n\n// CORRECT — variant first, then product, then quantity\naddItemToCart(variant, product, 1);\n\n// WRONG — selectVariantValue takes product and variantValue\nselectVariantValue(variant, value);\n\n// CORRECT\nselectVariantValue(product, dvv.variantValue);\n```\n\nWhen in doubt, use the `get_function_doc(functionName)` MCP tool to check the exact signature.\n\n### 14. Missing backgroundColor Prop on Sections\n\nEvery section MUST include a `backgroundColor` COLOR prop so store owners can customize the section background. Without it, the section has a hardcoded background that cannot be changed in the editor.\n\n**Wrong** — section with no backgroundColor prop:\n```json\n// ikas.config.json\n{ \"id\": \"my-section\", \"type\": \"section\", \"props\": [\n { \"name\": \"title\", \"type\": \"TEXT\" }\n]}\n```\n```tsx\nexport function MySection({ title }: Props) {\n return <section className=\"my-section\"><h1>{title}</h1></section>;\n}\n```\n\n**Correct** — section with backgroundColor prop:\n```json\n// ikas.config.json\n{ \"id\": \"my-section\", \"type\": \"section\", \"props\": [\n { \"name\": \"title\", \"type\": \"TEXT\" },\n { \"name\": \"backgroundColor\", \"displayName\": \"Background Color\", \"type\": \"COLOR\", \"defaultValue\": \"#ffffff\" }\n]}\n```\n```tsx\nexport function MySection({ title, backgroundColor = \"#ffffff\" }: Props) {\n return (\n <section className=\"my-section\" style={backgroundColor ? { backgroundColor } : undefined}>\n <h1>{title}</h1>\n </section>\n );\n}\n```\n\nOptionally, also consider adding `textColor` COLOR props for text elements sitting directly on the section background, so they remain readable when the store owner changes the background color.\n\n### 15. Forgetting to Group Props for Complex Sections\n\nSections with 5+ props should use prop groups to organize the editor sidebar. Without groups, store owners see a long flat list of unrelated props.\n\n**Better** — organize related props into groups:\n```json\n{\n \"propGroups\": [\n { \"id\": \"content\", \"name\": \"Content\" },\n { \"id\": \"appearance\", \"name\": \"Appearance\" }\n ],\n \"props\": [\n { \"name\": \"heading\", \"groupId\": \"content\", ... },\n { \"name\": \"bgColor\", \"groupId\": \"appearance\", ... }\n ]\n}\n```\n\nSee `get_framework_guide(\"prop-groups\")` for full details.\n\n### 16. Hardcoded Static Text in Components\n\nAll user-visible text MUST be TEXT props — never hardcode strings in JSX. Hardcoded text cannot be translated for multilingual storefronts.\n\n**Wrong** — hardcoded strings:\n```tsx\nexport function LoginSection({ backgroundColor }: Props) {\n return (\n <section style={backgroundColor ? { backgroundColor } : undefined}>\n <h1>Sign In</h1>\n <button>{form.isSubmitting ? \"Signing in...\" : \"Sign In\"}</button>\n <p>Don't have an account? <a href=\"/register\">Create one</a></p>\n </section>\n );\n}\n```\n\n**Correct** — all text as TEXT props with defaultValues:\n```json\n// ikas.config.json\n{ \"props\": [\n { \"name\": \"title\", \"type\": \"TEXT\", \"defaultValue\": \"Sign In\", \"groupId\": \"texts\" },\n { \"name\": \"submitButtonText\", \"type\": \"TEXT\", \"defaultValue\": \"Sign In\", \"groupId\": \"texts\" },\n { \"name\": \"submittingButtonText\", \"type\": \"TEXT\", \"defaultValue\": \"Signing in...\", \"groupId\": \"texts\" },\n { \"name\": \"noAccountText\", \"type\": \"TEXT\", \"defaultValue\": \"Don't have an account?\", \"groupId\": \"texts\" },\n { \"name\": \"createAccountLinkText\", \"type\": \"TEXT\", \"defaultValue\": \"Create one\", \"groupId\": \"texts\" }\n],\n\"propGroups\": [{ \"id\": \"texts\", \"name\": \"Texts\" }]}\n```\n```tsx\nexport function LoginSection({ title = \"Sign In\", submitButtonText = \"Sign In\",\n submittingButtonText = \"Signing in...\", noAccountText = \"Don't have an account?\",\n createAccountLinkText = \"Create one\", backgroundColor }: Props) {\n return (\n <section style={backgroundColor ? { backgroundColor } : undefined}>\n <h1>{title}</h1>\n <button>{form.isSubmitting ? submittingButtonText : submitButtonText}</button>\n <p>{noAccountText} <a href=\"/register\">{createAccountLinkText}</a></p>\n </section>\n );\n}\n```\n\nFor button loading states, use two separate TEXT props (e.g., `submitButtonText` + `submittingButtonText`). Group text props under a \"Texts\" propGroup when the component has 5+ props.\n\n### 17. IkasOrderLineItemOption.values is an Array, Not a Scalar\n\n`IkasOrderLineItemOption` (the per-item options on cart/order line items) has a `.values` field that is an **array** of `IkasOrderLineItemOptionValue`, NOT a scalar `.value`. Each value in the array has its own `.name` / `.value` / `.formattedPrice`.\n\n```tsx\n// WRONG — there is no .value on IkasOrderLineItemOption\n<span>{option.value}</span>\n\n// CORRECT — .values is an array; map over it\n{option.values.map((v) => (\n <span key={v.name}>{v.name}: {v.value}</span>\n))}\n```\n\nThis is the most common confusion when rendering order summary lines or cart line item options. See `get_migration_guide(\"prop-runtime-shapes\")` for the broader catalog of order-shape gotchas.\n\n### 18. IkasOrderAdjustment Has No .formattedAmount — Use the Helper\n\n`IkasOrderAdjustment` does not expose a `.formattedAmount` property directly. Call the helper `getOrderAdjustmentFormattedAmount(adjustment)` from `@ikas/bp-storefront` — it returns the formatted currency string with the correct sign (negated for decrements).\n\n```tsx\nimport { getOrderAdjustmentFormattedAmount } from \"@ikas/bp-storefront\";\n\n// WRONG — .formattedAmount does not exist\n<td>{adjustment.formattedAmount}</td>\n\n// CORRECT\n<td>{getOrderAdjustmentFormattedAmount(adjustment)}</td>\n```\n\nSee `get_function_doc(\"getOrderAdjustmentFormattedAmount\")` for the exact signature.\n\n### 19. Old-System Property Patterns That Don't Exist in the New System\n\nSeveral `@ikas/storefront` properties look like they should still work but don't exist on the corresponding `@ikas/bp-storefront` types. Use the helper function instead. **If TypeScript reports TS2339 (\"Property X does not exist on type Y\") on a `.selectedVariant`, `.mainImage`, `.href`, or `.checkoutUrl` access, you're hitting one of these.**\n\n| Old pattern | New replacement |\n|---|---|\n| `product.selectedVariant` | `getSelectedProductVariant(product)` → `IkasProductVariant \\| undefined` |\n| `product.href` | `getProductHref(product)` (one of several `get*Href` helpers — see `navigation-patterns`) |\n| `variant.mainImage` | `getProductVariantMainImage(variant)` → `IkasProductImage`, then access `.image` for the `IkasImage` |\n| `cartStore.checkoutUrl` | `getCheckoutUrlFromCartStore(cartStore)` (handles auth-state branching internally) |\n\nThe variant-to-image chain is 4 hops (each carries metadata the next doesn't). See `get_framework_guide(\"image-handling\")` for the canonical recipe.\n\n### 20. Intl.NumberFormat for Currency Amounts\n\nNever format money with `Intl.NumberFormat` — it falls back to the browser locale and ignores the merchant's currency format settings, so its output clashes with platform-formatted prices on the same screen. For model-bound prices use the `get*FormattedPrice` helpers. For free-standing amounts (remaining amount to free shipping, gift wrap threshold, bulk discount limits, cart limit warnings) use `formatCurrency(amount, currencyCode, currencySymbol)` from `@ikas/bp-storefront`.\n\nNote: `Intl.DateTimeFormat(IkasStorefrontConfig.getCurrentLocale(), ...)` IS the correct pattern for dates — do not mirror it for money.\n\n```tsx\n// WRONG — browser-locale format (\"₺14.478,5\") next to platform prices (\"₺ 1,950.00\")\nconst remaining = new Intl.NumberFormat(undefined, { style: \"currency\", currency: \"TRY\" }).format(amount);\n\n// CORRECT — merchant currency format settings\nimport { formatCurrency } from \"@ikas/bp-storefront\";\n\nconst remaining = formatCurrency(amount, cart.currencyCode, cart.currencySymbol);\n```\n\nSee `get_function_doc(\"formatCurrency\")` for the exact signature.\n\n### Deep SDK imports (`@ikas/bp-storefront/dist/...`)\n\n**Wrong** — reaching into a private subpath when a root helper seems missing:\n```tsx\n// breaks at runtime: no window global for this subpath, and the build rejects it\nimport { apiSaveCart } from \"@ikas/bp-storefront/dist/functions/api/cart\";\n```\n\n**Correct** — use the public root export (coupon has dedicated form helpers):\n```tsx\nimport {\n customerStore,\n getCouponCodeForm,\n setCouponCodeFormCouponCode,\n submitCouponCodeForm,\n} from \"@ikas/bp-storefront\";\n```\n\nRule: every import from the storefront SDK must come from the BARE package name — never a `/dist/` or `/src/` subpath.",
186
190
  "tags": [
187
191
  "pitfalls",
188
192
  "gotchas",
@@ -197,13 +201,17 @@
197
201
  "parameters",
198
202
  "static-text",
199
203
  "translation",
200
- "i18n"
204
+ "i18n",
205
+ "currency",
206
+ "formatCurrency",
207
+ "NumberFormat",
208
+ "price-format"
201
209
  ]
202
210
  },
203
211
  "sub-component-patterns": {
204
212
  "title": "Sub-Component File Organization",
205
213
  "description": "How to organize sub-components in their own folders under src/sub-components/ with proper imports and CSS",
206
- "content": "## Sub-Component File Organization\n\n**ALWAYS create sub-components in `src/sub-components/` with their own folder containing `index.tsx` and `styles.css`. NEVER create flat .tsx files inside a component folder.**\n\n### Directory Structure\n\n```\nsrc/\n├── components/\n│ ├── ProductList/\n│ │ ├── index.tsx # imports from ../../sub-components/...\n│ │ ├── types.ts # auto-generated (CLI-managed)\n│ │ └── styles.css # @import \"../../sub-components/.../styles.css\"\n│ └── index.ts\n└── sub-components/\n ├── ProductCard/\n │ ├── index.tsx # sub-component\n │ └── styles.css # sub-component styles\n └── FilterSidebar/\n ├── index.tsx # sub-component\n └── styles.css # sub-component styles\n```\n\n### Key Rules\n\n1. **`src/components/`** = registered components (listed in `ikas.config.json`)\n2. **`src/sub-components/`** = internal helpers (NOT in `ikas.config.json`)\n3. Sub-components do **NOT** have `types.ts` — define `Props` interface inline in `index.tsx`\n4. Sub-components that read MobX stores need `observer()` from `@ikas/component-utils`\n5. Sub-components that only receive props do NOT need `observer()`\n6. CSS is scoped with the parent component's `.cc_` prefix (same scope — no conflicts)\n7. Sub-components can be shared across multiple parent sections\n\n### CSS Import Pattern\n\nIn the parent component's `styles.css`, import sub-component styles with `@import`:\n\n```css\n/* src/components/ProductList/styles.css */\n@import \"../../sub-components/ProductCard/styles.css\";\n@import \"../../sub-components/FilterSidebar/styles.css\";\n\n.product-list-section {\n width: 100%;\n padding: 40px 24px;\n}\n```\n\nThe build system's CSS import resolver recursively resolves `@import` statements with relative paths. All imported CSS gets scoped with the parent component's `.cc_{componentId}` prefix.\n\n### TSX Import Pattern\n\n```tsx\n// src/components/ProductList/index.tsx\nimport ProductCard from \"../../sub-components/ProductCard\";\nimport FilterSidebar from \"../../sub-components/FilterSidebar\";\nimport { Props } from \"./types\";\n\nexport function ProductListSection({ productList, title }: Props) {\n const products = productList?.data ?? [];\n return (\n <section className=\"product-list-section\">\n <FilterSidebar productList={productList} />\n <div className=\"product-grid\">\n {products.map((product) => (\n <ProductCard key={product.id} product={product} />\n ))}\n </div>\n </section>\n );\n}\n\nexport default ProductListSection;\n```\n\n### Sub-Component Example\n\n```tsx\n// src/sub-components/ProductCard/index.tsx\nimport {\n IkasProduct,\n getSelectedProductVariant,\n getProductVariantFormattedFinalPrice,\n getProductVariantMainImage,\n getSelectedProductVariantHref,\n getDefaultSrc,\n} from \"@ikas/bp-storefront\";\n\ninterface Props {\n product: IkasProduct;\n}\n\nexport default function ProductCard({ product }: Props) {\n const variant = getSelectedProductVariant(product);\n const productImage = getProductVariantMainImage(variant);\n const image = productImage?.image ?? null;\n const price = getProductVariantFormattedFinalPrice(variant) as unknown as string;\n\n return (\n <a href={getSelectedProductVariantHref(product)} className=\"product-card\">\n {image && <img src={getDefaultSrc(image)} alt={product.name} className=\"product-card-image\" />}\n <h3 className=\"product-card-name\">{product.name}</h3>\n <span className=\"product-card-price\">{price}</span>\n </a>\n );\n}\n```\n\nNotice:\n- `Props` is defined inline — no separate `types.ts` file\n- No `observer()` needed because this component only uses props passed from the parent\n- Default export like registered components\n\n### When to Extract Sub-Components\n\n- A section's `index.tsx` exceeds ~150 lines\n- A distinct UI block (card, sidebar, modal) has its own styles and logic\n- The same UI block is used by multiple parent sections\n- A part of the component independently reads MobX stores (extract + wrap with `observer()`)\n\n### When observer() Is Needed on Sub-Components\n\n```tsx\n// src/sub-components/CartBadge/index.tsx\nimport { observer } from \"@ikas/component-utils\";\nimport { cartStore } from \"@ikas/bp-storefront\";\n\n// This sub-component independently reads a MobX store → needs observer()\nconst CartBadge = observer(function CartBadge() {\n const count = cartStore.cart?.orderLineItems.length ?? 0;\n return <span className=\"cart-badge\">{count}</span>;\n});\n\nexport default CartBadge;\n```",
214
+ "content": "## Sub-Component File Organization\n\n**ALWAYS create sub-components in `src/sub-components/` with their own folder containing `index.tsx` and `styles.css`. NEVER create flat .tsx files inside a component folder.**\n\n### Directory Structure\n\n```\nsrc/\n├── components/\n│ ├── ProductList/\n│ │ ├── index.tsx # imports from ../../sub-components/...\n│ │ ├── types.ts # auto-generated (CLI-managed)\n│ │ └── styles.css # component styles (sub-component styles.css collected automatically)\n│ └── index.ts\n└── sub-components/\n ├── ProductCard/\n │ ├── index.tsx # sub-component\n │ └── styles.css # sub-component styles\n └── FilterSidebar/\n ├── index.tsx # sub-component\n └── styles.css # sub-component styles\n```\n\n### Key Rules\n\n1. **`src/components/`** = registered components (listed in `ikas.config.json`)\n2. **`src/sub-components/`** = internal helpers (NOT in `ikas.config.json`)\n3. Sub-components do **NOT** have `types.ts` — define `Props` interface inline in `index.tsx`\n4. Sub-components that read MobX stores need `observer()` from `@ikas/component-utils`\n5. Sub-components that only receive props do NOT need `observer()`\n6. CSS is scoped with the parent component's `.cc_` prefix (same scope — no conflicts)\n7. Sub-components can be shared across multiple parent sections\n\n### Sub-Component CSS (collected automatically)\n\nA sub-component's sibling `styles.css` is picked up WITHOUT any import: `dev` and `publish` walk each component's import graph and collect every `styles.css` sitting next to a source file it uses. CSS of a sub-component used by ONE component is inlined into that component's CSS; CSS of a SHARED sub-component is emitted once as shared chunk CSS, scoped for every consumer. Either way it ends up under the component's `.cc_{componentId}` prefix. The section templates rely on this — none of them write `@import`.\n\n```css\n/* src/components/ProductList/styles.css — no @import needed */\n.product-list-section {\n width: 100%;\n padding: 40px 24px;\n}\n```\n\n`@import \"../../sub-components/ProductCard/styles.css\";` in the parent's `styles.css` still works (the resolver inlines relative imports recursively) and is only REQUIRED for the standalone `build` command, which compiles one component at a time and sees nothing but the config's `styles` file and its `@import`s. The compiler skips an `@import` whose file is already covered by the component's shared chunk CSS, so writing it never duplicates rules. Never `import \"./styles.css\"` from TSX — CSS only ever flows through the two paths above.\n\n### TSX Import Pattern\n\n```tsx\n// src/components/ProductList/index.tsx\nimport ProductCard from \"../../sub-components/ProductCard\";\nimport FilterSidebar from \"../../sub-components/FilterSidebar\";\nimport { Props } from \"./types\";\n\nexport function ProductListSection({ productList, title }: Props) {\n const products = productList?.data ?? [];\n return (\n <section className=\"product-list-section\">\n <FilterSidebar productList={productList} />\n <div className=\"product-grid\">\n {products.map((product) => (\n <ProductCard key={product.id} product={product} />\n ))}\n </div>\n </section>\n );\n}\n\nexport default ProductListSection;\n```\n\n### Sub-Component Example\n\n```tsx\n// src/sub-components/ProductCard/index.tsx\nimport {\n IkasProduct,\n getSelectedProductVariant,\n getProductVariantFormattedFinalPrice,\n getProductVariantMainImage,\n getSelectedProductVariantHref,\n getDefaultSrc,\n} from \"@ikas/bp-storefront\";\n\ninterface Props {\n product: IkasProduct;\n}\n\nexport default function ProductCard({ product }: Props) {\n const variant = getSelectedProductVariant(product);\n const productImage = getProductVariantMainImage(variant);\n const image = productImage?.image ?? null;\n const price = getProductVariantFormattedFinalPrice(variant) as unknown as string;\n\n return (\n <a href={getSelectedProductVariantHref(product)} className=\"product-card\">\n {image && <img src={getDefaultSrc(image)} alt={product.name} className=\"product-card-image\" />}\n <h3 className=\"product-card-name\">{product.name}</h3>\n <span className=\"product-card-price\">{price}</span>\n </a>\n );\n}\n```\n\nNotice:\n- `Props` is defined inline — no separate `types.ts` file\n- No `observer()` needed because this component only uses props passed from the parent\n- Default export like registered components\n\n### When to Extract Sub-Components\n\n- A section's `index.tsx` exceeds ~150 lines\n- A distinct UI block (card, sidebar, modal) has its own styles and logic\n- The same UI block is used by multiple parent sections\n- A part of the component independently reads MobX stores (extract + wrap with `observer()`)\n\n### When observer() Is Needed on Sub-Components\n\n```tsx\n// src/sub-components/CartBadge/index.tsx\nimport { observer } from \"@ikas/component-utils\";\nimport { cartStore } from \"@ikas/bp-storefront\";\n\n// This sub-component independently reads a MobX store → needs observer()\nconst CartBadge = observer(function CartBadge() {\n const count = cartStore.cart?.orderLineItems.length ?? 0;\n return <span className=\"cart-badge\">{count}</span>;\n});\n\nexport default CartBadge;\n```",
207
215
  "tags": [
208
216
  "sub-component",
209
217
  "folder",
@@ -212,13 +220,16 @@
212
220
  "extract",
213
221
  "refactor",
214
222
  "css",
215
- "import"
223
+ "import",
224
+ "chunk",
225
+ "shared",
226
+ "styles.css"
216
227
  ]
217
228
  },
218
229
  "ai-workflow": {
219
230
  "title": "AI Agent Workflow for Building ikas Components",
220
231
  "description": "Step-by-step guide for AI coding agents building ikas storefront components using CLI commands and MCP tools",
221
- "content": "## AI Agent Workflow\n\nThis is the recommended step-by-step workflow for AI agents building ikas code components. Follow these steps in order for reliable, error-free results.\n\n**IMPORTANT: NEVER create or edit `types.ts` manually — it is auto-generated by the CLI.** The CLI commands below update BOTH `ikas.config.json` AND `types.ts` automatically.\n\n### Step 1: Create Component with Props\n\nUse `get_section_template(sectionType)` to get a starter template — it includes a ready-to-run CLI command with `--props`.\n\n**Important:** When creating a section, always include a `backgroundColor` COLOR prop (default: `#ffffff`). Optionally consider adding `textColor` for text elements directly on the section background.\n\n**Important:** When creating a header or footer section, use `--isHeader` or `--isFooter` flags on the `add-component` command. This marks the section as the store's common header/footer so it appears on all pages automatically:\n```bash\nnpx ikas-component config add-component --name \"Header\" --type section --isHeader --props '[...]'\nnpx ikas-component config add-component --name \"Footer\" --type section --isFooter --props '[...]'\n```\n\n**Important:** Ensure ALL user-visible text (headings, buttons, labels, empty states, loading text) is exposed as TEXT props. Never hardcode text strings in JSX. Use `defaultValue` for English defaults. For button loading states, use two separate props (e.g., `submitButtonText` + `submittingButtonText`). Group text props under a \"Texts\" propGroup when 5+ props exist.\n\nThen run the single `add-component --props` command to create the component scaffold WITH all props in one step:\n```bash\nnpx ikas-component config add-component --name \"HeroSection\" --type section --props '[{\"name\":\"title\",\"displayName\":\"Title\",\"type\":\"TEXT\",\"required\":true},{\"name\":\"backgroundImage\",\"displayName\":\"Background Image\",\"type\":\"IMAGE\"},{\"name\":\"showButton\",\"displayName\":\"Show Button\",\"type\":\"BOOLEAN\"}]'\n```\n\nThis creates the component directory with `index.tsx`, `types.ts` (with correct Props interface), `styles.css`, updates `ikas.config.json`, and updates the barrel export. The output is JSON:\n```json\n{\"success\": true, \"componentId\": \"abc123-hero-section\", \"componentName\": \"HeroSection\", \"type\": \"section\", \"propsCount\": 3, \"files\": [...]}\n```\n\nThe `--props` flag accepts a JSON array of prop objects. Each prop needs `name` + `type` at minimum. `displayName` is auto-generated from camelCase name if omitted (e.g. `backgroundImage` → `\"Background Image\"`).\n\nTo add more props later, use `add-prop`:\n```bash\nnpx ikas-component config add-prop --component \"HeroSection\" --name \"subtitle\" --displayName \"Subtitle\" --type TEXT\n```\n\n### Step 2: Get Reference Material\n\nBefore writing component code, use MCP tools to get the right patterns:\n- `get_section_template(sectionType)` — Get the API integration pattern reference for common section types (product-detail, cart, login, header, footer, etc.). Study the function calls and data access patterns only.\n- `get_framework_guide(\"common-pitfalls\")` — Review common mistakes to avoid\n- `get_framework_guide(\"component-structure\")` — Review component structure patterns\n- `get_function_doc(functionName)` — Look up exact function signatures before using them\n- `get_model_guide(typeName)` — Get comprehensive info about a model type\n\n### Step 2.5: Design Your Component (IMPORTANT)\n\nBefore writing code, plan an ORIGINAL visual design:\n- Do NOT reproduce layout, CSS class names, or HTML structure from templates/examples\n- Templates and examples demonstrate correct API usage only — they are not designs to copy\n- **KEEP from references:** imports, function calls, data access patterns, form handling flows, type casts, null safety patterns\n- **CREATE fresh:** all JSX/HTML structure, all CSS class names and rules, all visual layout and spacing, all UX patterns (loading states, empty states, transitions, responsive breakpoints)\n- Think about the specific store's brand and design language when creating your component\n\n### Step 3: Write the Component Code\n\nEdit `src/components/{ComponentName}/index.tsx` with the implementation. **Do NOT edit `types.ts`** — it was already generated correctly in Step 1. Key rules:\n- Import props from `./types` (auto-generated in Step 1)\n- Import storefront functions from `@ikas/bp-storefront`\n- Root export should use named + default export: `export function X({ ... }: Props) { ... }` + `export default X;`\n- Only wrap sub-components with `observer()` when they independently read MobX stores\n- Use optional chaining for all props: `props.title ?? \"Default\"`\n- Use `as unknown as boolean` cast for functions like `hasProductStock`, `isAddToCartEnabled`\n- **Sections MUST apply backgroundColor**: destructure `backgroundColor = \"#ffffff\"` and add `style={backgroundColor ? { backgroundColor } : undefined}` on the root `<section>` element\n\n### Step 3.5: Organize Props into Groups (if 5+ props)\n\nIf the component has 5 or more props, organize them into groups for better editor UX:\n```bash\nnpx ikas-component config add-prop-group --component \"HeroSection\" --id content --name \"Content\"\nnpx ikas-component config add-prop-group --component \"HeroSection\" --id appearance --name \"Appearance\"\nnpx ikas-component config update-prop --component \"HeroSection\" --prop title --group content\nnpx ikas-component config update-prop --component \"HeroSection\" --prop backgroundImage --group appearance\n```\n\n### Step 4: Write Styles\n\nEdit `src/components/{ComponentName}/styles.css`. Key rules:\n- Use class selectors only (`.my-class`), never bare element selectors\n- CSS is auto-scoped at build time — no manual namespacing needed\n- For sections: `width: 100%; padding: 64px 24px;` with inner max-width container\n\n### Step 5: Verify with Type Checking\n\nRun the lightweight type checker:\n```bash\nnpx ikas-component check --json\n```\n\nSuccess output:\n```json\n{\"success\": true, \"errors\": []}\n```\n\nError output:\n```json\n{\"success\": false, \"errorCount\": 2, \"errors\": [{\"file\": \"src/components/Hero/index.tsx\", \"line\": 15, \"column\": 3, \"code\": \"TS2339\", \"message\": \"Property 'title' does not exist on type 'Props'\"}]}\n```\n\n### Step 6: Fix Errors and Re-check\n\nFor each error:\n1. Read the file and line number from the error\n2. Fix the issue (common fixes below)\n3. Re-run `npx ikas-component check --json`\n\n**Common error fixes:**\n- `Property 'x' does not exist on type 'Props'` — Prop wasn't added via CLI. Run `npx ikas-component config add-prop`.\n- `Cannot find module '@ikas/bp-storefront'` — Normal in type-check if node_modules not fully installed. Focus on component-level errors.\n- `Type 'X' is not assignable to type 'Y'` — Check function signature with `get_function_doc()`.\n\n### Step 7: Full Build Validation\n\nOnce type checking passes, run the full build:\n```bash\nnpx ikas-component build\n```\n\nThis runs type checking + esbuild compilation + CSS scoping.\n\n### Quick Reference: CLI Commands\n\n| Command | Purpose |\n|---------|--------|\n| `npx ikas-component config add-component --name X --type section --props '[...]'` | **Primary** — create component with all props |\n| `npx ikas-component config add-component --name X --type section --isHeader --props '[...]'` | Create header section |\n| `npx ikas-component config add-component --name X --type section --isFooter --props '[...]'` | Create footer section |\n| `npx ikas-component config add-component --name X --type section` | Create component with no props |\n| `npx ikas-component config add-prop --component X --name y --displayName Y --type TEXT` | Add a prop incrementally |\n| `npx ikas-component config update-prop --component X --prop y --required true` | Update a prop |\n| `npx ikas-component config remove-prop --component X --prop y` | Remove a prop |\n| `npx ikas-component config remove-component --name X` | Remove a component |\n| `npx ikas-component config list` | List all components and props |\n| `npx ikas-component check --json` | Type-check with JSON output |\n| `npx ikas-component build` | Full production build |\n\n### Quick Reference: MCP Tools\n\n| Tool | When to Use |\n|------|------------|\n| `get_section_template(type)` | Starting a new section — get API integration pattern reference + CLI command (create original design, don't copy layout) |\n| `get_framework_guide(topic)` | Understanding patterns, pitfalls, architecture |\n| `get_function_doc(name)` | Looking up exact function signature |\n| `get_model_guide(type)` | Working with a model type (IkasProduct, IkasCart, etc.) |\n| `get_prop_types()` | Checking available prop types for ikas.config.json |\n| `search_docs(query)` | Finding relevant functions/docs by keyword |\n\n### Reuse the theme's global settings\n\nBefore hardcoding colors or typography, call `list_theme_globals` to discover the theme's existing global variables and design tokens, and read them at runtime via `getThemeColors()` / `getThemeSetting()` / `getThemeTypography()` from `@ikas/bp-storefront`. You can also create new ones with `create_theme_global`. See `get_framework_guide(\"theme-globals\")`.",
232
+ "content": "## AI Agent Workflow\n\nThis is the recommended step-by-step workflow for AI agents building ikas code components. Follow these steps in order for reliable, error-free results.\n\n**IMPORTANT: NEVER create or edit `types.ts` manually — it is auto-generated by the CLI.** The CLI commands below update BOTH `ikas.config.json` AND `types.ts` automatically.\n\n### Step 1: Create Component with Props\n\nUse `get_section_template(sectionType)` to get a starter template — it includes a ready-to-run CLI command with `--props`.\n\n**Important:** When creating a section, always include a `backgroundColor` COLOR prop (default: `#ffffff`). Optionally consider adding `textColor` for text elements directly on the section background.\n\n**Important:** When creating a header or footer section, use `--isHeader` or `--isFooter` flags on the `add-component` command. This marks the section as the store's common header/footer so it appears on all pages automatically:\n```bash\nnpx ikas-component config add-component --name \"Header\" --type section --isHeader --props '[...]'\nnpx ikas-component config add-component --name \"Footer\" --type section --isFooter --props '[...]'\n```\n\n**Important:** Ensure ALL user-visible text (headings, buttons, labels, empty states, loading text) is exposed as TEXT props. Never hardcode text strings in JSX. Use `defaultValue` for English defaults. For button loading states, use two separate props (e.g., `submitButtonText` + `submittingButtonText`). Group text props under a \"Texts\" propGroup when 5+ props exist.\n\nThen run the single `add-component --props` command to create the component scaffold WITH all props in one step:\n```bash\nnpx ikas-component config add-component --name \"HeroSection\" --type section --props '[{\"name\":\"title\",\"displayName\":\"Title\",\"type\":\"TEXT\",\"required\":true},{\"name\":\"backgroundImage\",\"displayName\":\"Background Image\",\"type\":\"IMAGE\"},{\"name\":\"showButton\",\"displayName\":\"Show Button\",\"type\":\"BOOLEAN\"}]'\n```\n\nThis creates the component directory with `index.tsx`, `types.ts` (with correct Props interface), `styles.css`, updates `ikas.config.json`, and updates the barrel export. The output is JSON:\n```json\n{\"success\": true, \"componentId\": \"abc123-hero-section\", \"componentName\": \"HeroSection\", \"type\": \"section\", \"propsCount\": 3, \"files\": [...]}\n```\n\nThe `--props` flag accepts a JSON array of prop objects. Each prop needs `name` + `type` at minimum. `displayName` is auto-generated from camelCase name if omitted (e.g. `backgroundImage` → `\"Background Image\"`).\n\nTo add more props later, use `add-prop`:\n```bash\nnpx ikas-component config add-prop --component \"HeroSection\" --name \"subtitle\" --displayName \"Subtitle\" --type TEXT\n```\n\n### Step 2: Get Reference Material\n\nBefore writing component code, use MCP tools to get the right patterns:\n- `get_section_template(sectionType)` — Get the API integration pattern reference for common section types (product-detail, cart, login, header, footer, etc.). Study the function calls and data access patterns only.\n- `get_framework_guide(\"common-pitfalls\")` — Review common mistakes to avoid\n- `get_framework_guide(\"component-structure\")` — Review component structure patterns\n- `get_function_doc(functionName)` — Look up exact function signatures before using them\n- `get_model_guide(typeName)` — Get comprehensive info about a model type\n\n### Step 2.5: Design Your Component (IMPORTANT)\n\nBefore writing code, plan an ORIGINAL visual design:\n- Do NOT reproduce layout, CSS class names, or HTML structure from templates/examples\n- Templates and examples demonstrate correct API usage only — they are not designs to copy\n- **KEEP from references:** imports, function calls, data access patterns, form handling flows, type casts, null safety patterns\n- **CREATE fresh:** all JSX/HTML structure, all CSS class names and rules, all visual layout and spacing, all UX patterns (loading states, empty states, transitions, responsive breakpoints)\n- Think about the specific store's brand and design language when creating your component\n\n### Step 3: Write the Component Code\n\nEdit `src/components/{ComponentName}/index.tsx` with the implementation. **Do NOT edit `types.ts`** — it was already generated correctly in Step 1. Key rules:\n- Import props from `./types` (auto-generated in Step 1)\n- Import storefront functions from `@ikas/bp-storefront`\n- Root export should use named + default export: `export function X({ ... }: Props) { ... }` + `export default X;`\n- Only wrap sub-components with `observer()` when they independently read MobX stores\n- Use optional chaining for all props: `props.title ?? \"Default\"`\n- Use `as unknown as boolean` cast for functions like `hasProductStock`, `isAddToCartEnabled`\n- **Sections MUST apply backgroundColor**: destructure `backgroundColor = \"#ffffff\"` and add `style={backgroundColor ? { backgroundColor } : undefined}` on the root `<section>` element\n\n### Step 3.5: Organize Props into Groups (if 5+ props)\n\nIf the component has 5 or more props, organize them into groups for better editor UX:\n```bash\nnpx ikas-component config add-prop-group --component \"HeroSection\" --id content --name \"Content\"\nnpx ikas-component config add-prop-group --component \"HeroSection\" --id appearance --name \"Appearance\"\nnpx ikas-component config update-prop --component \"HeroSection\" --prop title --group content\nnpx ikas-component config update-prop --component \"HeroSection\" --prop backgroundImage --group appearance\n```\n\n### Step 4: Write Styles\n\nEdit `src/components/{ComponentName}/styles.css`. Key rules:\n- Use class selectors only (`.my-class`), never bare element selectors\n- CSS is auto-scoped at build time — no manual namespacing needed\n- Keep a sub-component's CSS in its OWN folder's `styles.css`. Every command (`dev`, `publish`, `build`) collects the sibling `styles.css` of each imported sub-component automatically. Never copy a sub-component's rules into the parent's `styles.css`, and never `import \"./styles.css\"` from TSX.\n- For sections: `width: 100%; padding: 64px 24px;` with inner max-width container\n\n### Step 5: Verify with Type Checking\n\nRun the lightweight type checker:\n```bash\nnpx ikas-component check --json\n```\n\nSuccess output:\n```json\n{\"success\": true, \"errors\": []}\n```\n\nError output:\n```json\n{\"success\": false, \"errorCount\": 2, \"errors\": [{\"file\": \"src/components/Hero/index.tsx\", \"line\": 15, \"column\": 3, \"code\": \"TS2339\", \"message\": \"Property 'title' does not exist on type 'Props'\"}]}\n```\n\n### Step 6: Fix Errors and Re-check\n\nFor each error:\n1. Read the file and line number from the error\n2. Fix the issue (common fixes below)\n3. Re-run `npx ikas-component check --json`\n\n**Common error fixes:**\n- `Property 'x' does not exist on type 'Props'` — Prop wasn't added via CLI. Run `npx ikas-component config add-prop`.\n- `Cannot find module '@ikas/bp-storefront'` — Normal in type-check if node_modules not fully installed. Focus on component-level errors.\n- `Type 'X' is not assignable to type 'Y'` — Check function signature with `get_function_doc()`.\n\n### Step 7: Full Build Validation\n\nOnce type checking passes, run the full build:\n```bash\nnpx ikas-component build\n```\n\nThis runs type checking + esbuild compilation + CSS scoping. It catches what `check` cannot: deep `@ikas/bp-storefront/dist/...` imports and disallowed external packages are esbuild-level errors, invisible to `tsc`.\n\n`build` is a VALIDATION step only — nothing reads its `dist/` output. The editor gets components over the `dev` WebSocket (`import_section`), and releases go out via `publish`. So do NOT restructure source code to make `dist/` look a certain way, and do not treat a difference between `dist/` and the editor's copy as a bug: `build` compiles each component in isolation, so by design it has no shared chunks, no `canvasClientJs`, and no `global.css`.\n\n### Quick Reference: CLI Commands\n\n| Command | Purpose |\n|---------|--------|\n| `npx ikas-component config add-component --name X --type section --props '[...]'` | **Primary** — create component with all props |\n| `npx ikas-component config add-component --name X --type section --isHeader --props '[...]'` | Create header section |\n| `npx ikas-component config add-component --name X --type section --isFooter --props '[...]'` | Create footer section |\n| `npx ikas-component config add-component --name X --type section` | Create component with no props |\n| `npx ikas-component config add-prop --component X --name y --displayName Y --type TEXT` | Add a prop incrementally |\n| `npx ikas-component config update-prop --component X --prop y --required true` | Update a prop |\n| `npx ikas-component config remove-prop --component X --prop y` | Remove a prop |\n| `npx ikas-component config remove-component --name X` | Remove a component |\n| `npx ikas-component config list` | List all components and props |\n| `npx ikas-component check --json` | Type-check with JSON output |\n| `npx ikas-component build` | Full production build |\n\n### Quick Reference: MCP Tools\n\n| Tool | When to Use |\n|------|------------|\n| `get_section_template(type)` | Starting a new section — get API integration pattern reference + CLI command (create original design, don't copy layout) |\n| `get_framework_guide(topic)` | Understanding patterns, pitfalls, architecture |\n| `get_function_doc(name)` | Looking up exact function signature |\n| `get_model_guide(type)` | Working with a model type (IkasProduct, IkasCart, etc.) |\n| `get_prop_types()` | Checking available prop types for ikas.config.json |\n| `search_docs(query)` | Finding relevant functions/docs by keyword |\n\n### Reuse the theme's global settings\n\nBefore hardcoding colors or typography, call `list_theme_globals` to discover the theme's existing global variables and design tokens, and read them at runtime via `getThemeColors()` / `getThemeSetting()` / `getThemeTypography()` from `@ikas/bp-storefront`. You can also create new ones with `create_theme_global`. See `get_framework_guide(\"theme-globals\")`.",
222
233
  "tags": [
223
234
  "ai",
224
235
  "workflow",
@@ -232,20 +243,23 @@
232
243
  "form-handling": {
233
244
  "title": "Form Handling",
234
245
  "description": "How to use the form model pattern for login, registration, address, and other forms",
235
- "content": "## Form Handling Pattern\n\nikas storefront uses a consistent form model pattern across all form types: `init*Form()` → `set*FormField()` → `submit*Form()`.\n\n### Form Model Structure\n\nEach form field has:\n```typescript\n{\n value: string; // Current field value\n hasError: boolean; // Whether validation failed\n message?: string; // Error message to display\n label: string; // Display label\n placeholder: string; // Input placeholder\n}\n```\n\nEach form tracks:\n```typescript\n{\n isSubmitted: boolean; // Has submit been attempted\n isSubmitting: boolean; // Is submission in progress\n isSuccess?: boolean; // Did last submit succeed\n isFailure?: boolean; // Did last submit fail\n responseMessage?: string; // Server response message\n}\n```\n\n### Login Form Example\n\n```tsx\nimport { useEffect } from \"preact/hooks\";\nimport {\n customerStore,\n initLoginForm,\n setLoginFormEmail,\n setLoginFormPassword,\n submitLoginForm,\n Router,\n} from \"@ikas/bp-storefront\";\n\n// Root export — no observer() needed, ikas runtime handles reactivity via autorun()\nexport function LoginForm() {\n const loginForm = customerStore.loginForm;\n\n useEffect(() => {\n initLoginForm(loginForm);\n }, []);\n\n const handleSubmit = async (e: Event) => {\n e.preventDefault();\n const success = await submitLoginForm(loginForm);\n if (success) {\n Router.navigate(\"/account\");\n }\n };\n\n return (\n <form onSubmit={handleSubmit}>\n {loginForm.isFailure && <div>{loginForm.responseMessage}</div>}\n\n <input\n type=\"email\"\n value={loginForm.email.value}\n onInput={(e) => setLoginFormEmail(loginForm, e.target.value)}\n />\n {loginForm.email.hasError && <span>{loginForm.email.message}</span>}\n\n <input\n type=\"password\"\n value={loginForm.password.value}\n onInput={(e) => setLoginFormPassword(loginForm, e.target.value)}\n />\n {loginForm.password.hasError && <span>{loginForm.password.message}</span>}\n\n <button type=\"submit\" disabled={loginForm.isSubmitting}>\n {loginForm.isSubmitting ? \"Signing in...\" : \"Sign In\"}\n </button>\n </form>\n );\n}\n\nexport default LoginForm;\n```\n\n### Available Form Types\n\n| Form | Init | Setter Functions | Submit |\n|------|------|-----------------|--------|\n| Login | `initLoginForm(form)` | `setLoginFormEmail()`, `setLoginFormPassword()` | `submitLoginForm(form)` |\n| Register | `initRegisterForm(form)` | `setRegisterFormEmail()`, `setRegisterFormPassword()`, `setRegisterFormFirstName()`, `setRegisterFormLastName()` | `submitRegisterForm(form)` |\n| Forgot Password | `initForgotPasswordForm(form)` | `setForgotPasswordFormEmail()` | `submitForgotPasswordForm(form)` |\n| Address | `initAddressForm(form)` | `setAddressFormField()` for each field | `submitAddressForm(form)` |\n| Contact | `initContactForm(form)` | `setContactFormField()` for each field | `submitContactForm(form)` |\n| Account Info | `initAccountInfoForm(form)` | `setAccountInfoFormField()` for each field | `submitAccountInfoForm(form)` |\n| Newsletter | `initNewsletterSubscriptionForm(form)` | `setNewsletterEmail()` | `submitNewsletterSubscriptionForm(form)` |\n| Coupon Code | `getCouponCodeForm(customerStore)` → `initCouponCodeForm(form)` | `setCouponCodeFormCouponCode(form, value)` | `submitCouponCodeForm(form)` (remove with `removeCouponCodeForm(form)`) |\n\n**Address is the exception to this page.** It follows the same init/set/submit contract, but its\nfield set and row layout are resolved from the selected country at runtime via\n`addressForm.addressFormat` \u002d\u002d you cannot lay it out statically. Call\n`get_framework_guide({ topic: \"address\u002dform\u002dpatterns\" })` before building any address form.\n\n### Key Rules\n\n1. **Always call init first** — `init*Form()` sets up default field values, labels, and placeholders\n2. **Setter functions auto-validate** — if `form.isSubmitted` is true, calling any setter re-validates the form automatically\n3. **Check field.hasError for display** — show error messages only when `field.hasError` is true\n4. **Root components are automatically reactive** — forms use MobX observables which are automatically tracked in root components via `autorun()`. Use `observer()` only if you extract form logic into a sub-component\n5. **Submit returns boolean** — `submit*Form()` returns `true` on success, `false` on validation error or server failure",
246
+ "content": "## Form Handling Pattern\n\nikas storefront uses a consistent form model pattern across all form types: `init*Form()` → `set*FormField()` → `submit*Form()`.\n\n### Form Model Structure\n\nEach form field has:\n```typescript\n{\n value: string; // Current field value\n hasError: boolean; // Whether validation failed\n message?: string; // Error message to display\n label: string; // Display label\n placeholder: string; // Input placeholder\n}\n```\n\nEach form tracks:\n```typescript\n{\n isSubmitted: boolean; // Has submit been attempted\n isSubmitting: boolean; // Is submission in progress\n isSuccess?: boolean; // Did last submit succeed\n isFailure?: boolean; // Did last submit fail\n responseMessage?: string; // Server response message\n}\n```\n\n### Login Form Example\n\n```tsx\nimport { useEffect } from \"preact/hooks\";\nimport {\n customerStore,\n getLoginForm,\n initLoginForm,\n setLoginFormEmail,\n setLoginFormPassword,\n submitLoginForm,\n Router,\n} from \"@ikas/bp-storefront\";\n\n// Root export — no observer() needed, ikas runtime handles reactivity via autorun()\nexport function LoginForm() {\n // Forms are reached through get*Form(customerStore) accessors — the store\n // holds them in private fields (`_loginForm`), so `customerStore.loginForm`\n // does not compile.\n const loginForm = getLoginForm(customerStore);\n\n useEffect(() => {\n initLoginForm(loginForm);\n }, []);\n\n const handleSubmit = async (e: Event) => {\n e.preventDefault();\n const success = await submitLoginForm(loginForm);\n if (success) {\n Router.navigate(\"/account\");\n }\n };\n\n return (\n <form onSubmit={handleSubmit}>\n {loginForm.isFailure && <div>{loginForm.responseMessage}</div>}\n\n <input\n type=\"email\"\n value={loginForm.email.value}\n onInput={(e) => setLoginFormEmail(loginForm, e.target.value)}\n />\n {loginForm.email.hasError && <span>{loginForm.email.message}</span>}\n\n <input\n type=\"password\"\n value={loginForm.password.value}\n onInput={(e) => setLoginFormPassword(loginForm, e.target.value)}\n />\n {loginForm.password.hasError && <span>{loginForm.password.message}</span>}\n\n <button type=\"submit\" disabled={loginForm.isSubmitting}>\n {loginForm.isSubmitting ? \"Signing in...\" : \"Sign In\"}\n </button>\n </form>\n );\n}\n\nexport default LoginForm;\n```\n\n### Available Form Types\n\n| Form | Init | Setter Functions | Submit |\n|------|------|-----------------|--------|\n| Login | `initLoginForm(form)` | `setLoginFormEmail()`, `setLoginFormPassword()` | `submitLoginForm(form)` |\n| Register | `initRegisterForm(form)` | `setRegisterFormEmail()`, `setRegisterFormPassword()`, `setRegisterFormFirstName()`, `setRegisterFormLastName()` | `submitRegisterForm(form)` |\n| Forgot Password | `initForgotPasswordForm(form)` | `setForgotPasswordFormEmail()` | `submitForgotPasswordForm(form)` |\n| Address | `initAddressForm(form)` | `setAddressFormField()` for each field | `submitAddressForm(form)` |\n| Contact | `initContactForm(form)` | `setContactFormField()` for each field | `submitContactForm(form)` |\n| Account Info | `initAccountInfoForm(form)` | `setAccountInfoFormField()` for each field | `submitAccountInfoForm(form)` |\n| Newsletter | `initNewsletterSubscriptionForm(form)` | `setNewsletterEmail()` | `submitNewsletterSubscriptionForm(form)` |\n| Coupon Code | `getCouponCodeForm(customerStore)` → `initCouponCodeForm(form)` | `setCouponCodeFormCouponCode(form, value)` | `submitCouponCodeForm(form)` (remove with `removeCouponCodeForm(form)`) |\n| Deactivate Customer | `getDeactivateCustomerForm(customerStore)` → `initDeactivateCustomerForm(form)` | `setDeactivateCustomerFormPassword(form, value)` | `submitDeactivateCustomerForm(form)` (call `logout(customerStore)` after success) |\n\n**Address is the exception to this page.** It follows the same init/set/submit contract, but its\nfield set and row layout are resolved from the selected country at runtime via\n`addressForm.addressFormat` -- you cannot lay it out statically. Call\n`get_framework_guide({ topic: \"address-form-patterns\" })` before building any address form.\n\n### Key Rules\n\n1. **Always call init first** — `init*Form()` sets up default field values, labels, and placeholders\n2. **Setter functions auto-validate** — if `form.isSubmitted` is true, calling any setter re-validates the form automatically\n3. **Check field.hasError for display** — show error messages only when `field.hasError` is true\n4. **Root components are automatically reactive** — forms use MobX observables which are automatically tracked in root components via `autorun()`. Use `observer()` only if you extract form logic into a sub-component\n5. **Submit returns boolean** — `submit*Form()` returns `true` on success, `false` on validation error or server failure",
236
247
  "tags": [
237
248
  "form",
238
249
  "login",
239
250
  "register",
240
251
  "address",
241
252
  "validation",
242
- "input"
253
+ "input",
254
+ "password",
255
+ "account",
256
+ "deactivate"
243
257
  ]
244
258
  },
245
259
  "async-data-patterns": {
246
260
  "title": "Async Data & Loading Patterns",
247
261
  "description": "How to handle async operations, loading states, and store data in ikas components",
248
- "content": "## Async Data & Loading Patterns\n\n### 1. Store State is Null Until Initialized\n\n**Note:** Root component exports are automatically reactive via the ikas runtime's `autorun()` — no `observer()` needed. The examples below show `observer()` on **sub-components** that independently read store data.\n\nStore data (`cartStore.cart`, `customerStore.customer`) is `null` until the store initializes. Use null-safe access:\n\n```tsx\nimport { observer } from \"@ikas/component-utils\";\nimport { cartStore } from \"@ikas/bp-storefront\";\n\n// Sub-component: needs observer() for independent reactivity\nconst CartBadge = observer(function CartBadge() {\n // cart is null until initialized — use optional chaining\n const itemCount = cartStore.cart?.orderLineItems.length ?? 0;\n return <span className=\"cart-badge\">{itemCount}</span>;\n});\n```\n\n### 2. Loading Pattern for Async Operations\n\nUse `useState` for local loading flags. Always use `try/finally` to clear the loading state:\n\n```tsx\nimport { useState } from \"preact/hooks\";\nimport { addItemToCart } from \"@ikas/bp-storefront\";\n\nconst [isLoading, setIsLoading] = useState(false);\n\nconst handleAddToCart = async () => {\n if (isLoading) return; // prevent double-click\n setIsLoading(true);\n try {\n await addItemToCart(variant, product, 1);\n } finally {\n setIsLoading(false);\n }\n};\n\n// In JSX:\n<button disabled={isLoading} onClick={handleAddToCart}>\n {isLoading ? \"Adding...\" : \"Add to Cart\"}\n</button>\n```\n\n### 3. Cart Operation Results\n\n`addItemToCart` returns a result object. Check for validation errors:\n\n```tsx\nconst result = await addItemToCart(variant, product, 1);\nif (result.success) {\n // Item added successfully\n} else if (result.validationError === \"INSUFFICIENT_STOCK\") {\n // Not enough stock\n} else if (result.validationError === \"INVALID_PRODUCT_OPTION_VALUES\") {\n // Variant options not fully selected\n}\n```\n\n### 4. Form Submission Results\n\nForm submit functions return `boolean` and set status flags on the form:\n\n```tsx\nconst success = await submitLoginForm(loginForm);\nif (success) {\n // loginForm.isSuccess is true\n Router.navigate(\"/account\");\n} else {\n // loginForm.isFailure is true\n // loginForm.responseMessage has the error message\n console.log(loginForm.responseMessage);\n}\n```\n\n### 5. Observer Auto Re-rendering\n\nStore updates automatically trigger re-renders. Root components get this via `autorun()`, sub-components via `observer()`. You do NOT need manual state management for store-derived values:\n\n```tsx\n// WRONG — unnecessary useState for store data\nconst [cartItems, setCartItems] = useState([]);\nuseEffect(() => { setCartItems(cartStore.cart?.orderLineItems ?? []); }, [cartStore.cart]);\n\n// CORRECT — observer sub-component for independent reactivity\nconst CartList = observer(function CartList() {\n const items = cartStore.cart?.orderLineItems ?? [];\n return (\n <div>\n {items.map((item) => (\n <div key={item.id}>{item.variant?.name}</div>\n ))}\n </div>\n );\n});\n\n// Root export uses CartList — no observer needed on root\nexport function CartPage({ title }: Props) {\n return (\n <section>\n <h1>{title}</h1>\n <CartList />\n </section>\n );\n}\n\nexport default CartPage;\n```\n\n### 6. Pagination / Data Fetching\n\nList stores (blog, brand, category) use async pagination functions:\n\n```tsx\nimport { hasBlogListNextPage, getBlogListNextPage } from \"@ikas/bp-storefront\";\n\n// Check if more pages exist\nif (hasBlogListNextPage(blogList)) {\n // Fetch next page — mutates blogList in place, observer re-renders\n await getBlogListNextPage(blogList);\n}\n```\n\nThese functions mutate the list model in place. If your component uses `observer()`, it will re-render automatically when new data arrives.",
262
+ "content": "## Async Data & Loading Patterns\n\n### 1. Store State is Null Until Initialized\n\n**Note:** Root component exports are automatically reactive via the ikas runtime's `autorun()` — no `observer()` needed. The examples below show `observer()` on **sub-components** that independently read store data.\n\nStore data (`cartStore.cart`, `customerStore.customer`) is `null` until the store initializes. Use null-safe access:\n\n```tsx\nimport { observer } from \"@ikas/component-utils\";\nimport { cartStore } from \"@ikas/bp-storefront\";\n\n// Sub-component: needs observer() for independent reactivity\nconst CartBadge = observer(function CartBadge() {\n // cart is null until initialized — use optional chaining\n const itemCount = cartStore.cart?.orderLineItems.length ?? 0;\n return <span className=\"cart-badge\">{itemCount}</span>;\n});\n```\n\n### 2. Loading Pattern for Async Operations\n\nUse `useState` for local loading flags. Always use `try/finally` to clear the loading state:\n\n```tsx\nimport { useState } from \"preact/hooks\";\nimport { addItemToCart } from \"@ikas/bp-storefront\";\n\nconst [isLoading, setIsLoading] = useState(false);\n\nconst handleAddToCart = async () => {\n if (isLoading) return; // prevent double-click\n setIsLoading(true);\n try {\n await addItemToCart(variant, product, 1);\n } finally {\n setIsLoading(false);\n }\n};\n\n// In JSX:\n<button disabled={isLoading} onClick={handleAddToCart}>\n {isLoading ? \"Adding...\" : \"Add to Cart\"}\n</button>\n```\n\n### 3. Cart Operation Results\n\n`addItemToCart` returns a result object. Check for validation errors:\n\n```tsx\nconst result = await addItemToCart(variant, product, 1);\nif (result.success) {\n // Item added successfully\n} else if (result.validationError === \"INSUFFICIENT_STOCK\") {\n // Not enough stock\n} else if (result.validationError === \"INVALID_PRODUCT_OPTION_VALUES\") {\n // Variant options not fully selected\n}\n```\n\n### 4. Form Submission Results\n\nForm submit functions return `boolean` and set status flags on the form:\n\n```tsx\nconst success = await submitLoginForm(loginForm);\nif (success) {\n // loginForm.isSuccess is true\n Router.navigate(\"/account\");\n} else {\n // loginForm.isFailure is true\n // loginForm.responseMessage has the error message\n console.log(loginForm.responseMessage);\n}\n```\n\n### 5. Observer Auto Re-rendering\n\nStore updates automatically trigger re-renders. Root components get this via `autorun()`, sub-components via `observer()`. You do NOT need manual state management for store-derived values:\n\n```tsx\n// WRONG — unnecessary useState for store data\nconst [cartItems, setCartItems] = useState([]);\nuseEffect(() => { setCartItems(cartStore.cart?.orderLineItems ?? []); }, [cartStore.cart]);\n\n// CORRECT — observer sub-component for independent reactivity\nconst CartList = observer(function CartList() {\n const items = cartStore.cart?.orderLineItems ?? [];\n return (\n <div>\n {items.map((item) => (\n <div key={item.id}>{item.variant?.name}</div>\n ))}\n </div>\n );\n});\n\n// Root export uses CartList — no observer needed on root\nexport function CartPage({ title }: Props) {\n return (\n <section>\n <h1>{title}</h1>\n <CartList />\n </section>\n );\n}\n\nexport default CartPage;\n```\n\n### 6. Pagination / Data Fetching\n\nList stores (blog, brand, category) use async pagination functions:\n\n```tsx\nimport { hasBlogListNextPage, getBlogListNextPage } from \"@ikas/bp-storefront\";\n\n// Check if more pages exist\nif (hasBlogListNextPage(blogList)) {\n // Fetch next page — mutates blogList in place, observer re-renders\n await getBlogListNextPage(blogList);\n}\n```\n\nThese functions mutate the list model in place. If your component uses `observer()`, it will re-render automatically when new data arrives.\n\nTo batch-fetch full products by id — e.g. enriching cart lines with the `salesChannels` limits or per-variant `stock` they don't carry — use `bs_searchProductsById(baseStore, { productIds })`: one request for all ids. See the \"Enforcing Limits on Cart Lines\" section in the `cart-patterns` guide for the full pattern.",
249
263
  "tags": [
250
264
  "async",
251
265
  "loading",
@@ -322,7 +336,7 @@
322
336
  "cart-patterns": {
323
337
  "title": "Cart Management Patterns (Serel Reference)",
324
338
  "description": "Serel CartPage section with CartItem sub-component, OrderSummary/CouponCode/EmptyState local components, cartStore patterns, and checkout flow",
325
- "content": "## Cart Management Patterns (Serel Reference)\n\nThe serel CartPage is a section that uses local internal components (OrderSummary, CouponCode, EmptyState) and the shared `CartItem` sub-component from `src/sub-components/CartItem/`. Unlike most sections, CartPage does NOT use IkasComponentRenderer — it directly composes its UI from sub-components.\n\n### CartPage Section Structure\n\n```tsx\nimport { cartStore } from \"@ikas/bp-storefront\";\nimport CartItem from \"../../sub-components/CartItem\";\nimport { Props } from \"./types\";\n\nexport function CartPage({ backgroundColor, emptyCartText, ...props }: Props) {\n const cart = cartStore.cart;\n const lineItems = cart?.orderLineItems ?? [];\n const isEmpty = lineItems.length === 0;\n\n if (isEmpty) return <EmptyState text={emptyCartText} />;\n\n return (\n <section className=\"cart-page\" style={backgroundColor ? { backgroundColor } : undefined}>\n <div className=\"cart-page-inner\">\n <div className=\"cart-items\">\n {lineItems.map((item) => (\n <CartItem key={item.id} item={item} />\n ))}\n </div>\n <div className=\"cart-sidebar\">\n <CouponCode cart={cart} />\n <OrderSummary cart={cart} />\n </div>\n </div>\n </section>\n );\n}\nexport default CartPage;\n```\n\n### CartItem Sub-Component\n\nThe `CartItem` sub-component (in `src/sub-components/CartItem/`) displays a single line item with image, variant name, quantity controls, price, and remove button:\n\n```tsx\nimport {\n getOrderLineItemFormattedFinalPrice,\n getOrderLineItemFormattedUnitPrice,\n getIkasOrderLineVariantMainImage,\n getDefaultSrc,\n changeItemQuantity,\n removeItem,\n IkasOrderLineItem,\n} from \"@ikas/bp-storefront\";\nimport QuantitySelector from \"../QuantitySelector\";\n\ninterface Props { item: IkasOrderLineItem; }\n\nexport default function CartItem({ item }: Props) {\n const image = item.variant ? getIkasOrderLineVariantMainImage(item.variant) : null;\n\n return (\n <div className=\"cart-item\">\n {image && <img src={getDefaultSrc(image)} alt={item.variant?.name} />}\n <div className=\"cart-item-info\">\n <span>{item.variant?.name}</span>\n <span>{getOrderLineItemFormattedUnitPrice(item)}</span>\n </div>\n <QuantitySelector\n quantity={item.quantity}\n onIncrement={() => changeItemQuantity(item, item.quantity + 1)}\n onDecrement={() => changeItemQuantity(item, Math.max(1, item.quantity - 1))}\n />\n <span>{getOrderLineItemFormattedFinalPrice(item)}</span>\n <button onClick={() => removeItem(item)}>Remove</button>\n </div>\n );\n}\n```\n\n### OrderSummary Local Component\n\nDisplays cart totals using `getIkasOrderFormattedTotalFinalPrice(cart)` and `getIkasOrderFormattedTotalPrice(cart)`, plus a checkout button:\n\n```tsx\nimport { Router, getIkasOrderFormattedTotalFinalPrice } from \"@ikas/bp-storefront\";\n\nfunction OrderSummary({ cart }) {\n return (\n <div className=\"order-summary\">\n <span>Total: {getIkasOrderFormattedTotalFinalPrice(cart)}</span>\n <button onClick={() => Router.navigateToPage(\"CHECKOUT\")}>Checkout</button>\n </div>\n );\n}\n```\n\n### CouponCode Local Component\n\nCoupon code uses the standard form model. Get the form from `customerStore` via `getCouponCodeForm`, init it once, drive the input with `setCouponCodeFormCouponCode`, and submit/remove with the form helpers. Do NOT call `saveCart`/`apiSaveCart` or any deep `@ikas/bp-storefront/dist/...` import — the coupon has dedicated public exports:\n\n```tsx\nimport { useEffect } from \"preact/hooks\";\nimport {\n customerStore,\n getCouponCodeForm,\n initCouponCodeForm,\n setCouponCodeFormCouponCode,\n submitCouponCodeForm,\n removeCouponCodeForm,\n} from \"@ikas/bp-storefront\";\nimport { observer } from \"@ikas/component-utils\";\n\n// observer() because this sub-component reads the MobX coupon form\nconst CouponCode = observer(function CouponCode({ appliedCoupon }) {\n const couponForm = getCouponCodeForm(customerStore);\n\n useEffect(() => {\n initCouponCodeForm(couponForm);\n }, [couponForm]);\n\n const handleSubmit = async (e: Event) => {\n e.preventDefault();\n await submitCouponCodeForm(couponForm);\n };\n\n if (appliedCoupon) {\n return (\n <div className=\"coupon\">\n <span>{appliedCoupon}</span>\n <button type=\"button\" onClick={() => removeCouponCodeForm(couponForm)}>Remove</button>\n </div>\n );\n }\n\n return (\n <form className=\"coupon\" onSubmit={handleSubmit}>\n <input\n placeholder={couponForm.couponCode?.placeholder ?? \"Coupon code\"}\n value={couponForm.couponCode?.value ?? \"\"}\n onInput={(e) =>\n setCouponCodeFormCouponCode(couponForm, (e.target as HTMLInputElement).value)\n }\n />\n <button type=\"submit\" disabled={couponForm.isSubmitting}>\n {couponForm.isSubmitting ? \"Applying...\" : \"Apply\"}\n </button>\n {couponForm.isFailure && couponForm.responseMessage && (\n <p className=\"coupon-error\">{couponForm.responseMessage}</p>\n )}\n </form>\n );\n});\n```\n\n### cartStore Usage Patterns\n\nThe `cartStore` is a MobX store available globally. Root components are automatically reactive via autorun, so reads from `cartStore.cart` trigger re-renders:\n\n```tsx\nimport { cartStore } from \"@ikas/bp-storefront\";\n\n// Always null-safe:\nconst cart = cartStore.cart;\nconst lineItems = cart?.orderLineItems ?? [];\nconst itemCount = lineItems.length;\nconst isEmpty = itemCount === 0;\n```\n\n### Quantity Limits (min/max per cart)\n\nA product's sales channel can cap how many units go into one cart. The limits live on the product's `salesChannels`, matched to the active channel:\n\n```tsx\nimport { IkasStorefrontConfig } from \"@ikas/bp-storefront\";\n\nconst channel = product.salesChannels?.find((sc) => sc.id === IkasStorefrontConfig.salesChannelId);\nconst min = channel?.minQuantityPerCart ?? 1;\nconst max = channel?.maxQuantityPerCart; // null/undefined = no cap\n```\n\nApply these to the quantity stepper: seed the initial quantity to `min`, and cap increments at `max`. `addItemToCart(variant, product, qty)` also clamps to the same limits internally — but silently, so enforce them in the UI too or the customer sees the number snap with no explanation.\n\n> `IkasStorefrontConfig.salesChannelId` is a property. The older `getSalesChannelId()` method does not exist in this SDK.\n\n### Cart Operation validationError (complete list)\n\n`addItemToCart` / `changeItemQuantity` return `{ success, validationError? }`. The full set of `validationError` values is exactly three:\n\n| Value | Meaning |\n|-------|---------|\n| `INSUFFICIENT_STOCK` | Not enough stock for the requested quantity |\n| `INVALID_PRODUCT_OPTION_VALUES` | Required product options not fully or validly selected |\n| `EMPTY_CART` | The operation needs a non-empty cart |\n\nThere is **no** `MAX_QUANTITY_PER_CART_*` / `MIN_QUANTITY_PER_CART_*` error — quantity limits are clamped silently (see above), never surfaced as a validation error. Prevent limit violations in the stepper rather than branching on error codes that do not exist.\n\n### Campaign Offer Lines in the Cart\n\nCampaign discounts surface as order-level adjustment rows, not as edits on the line items:\n\n```tsx\n{cart.orderAdjustments?.map((adj) => (\n <div key={adj.name} className=\"cart-adjustment\">\n <span>{adj.name}</span>\n <span>{formatCurrency(adj.amount, adj.currencyCode, adj.currencySymbol)}</span>\n </div>\n))}\n```\n\nWhen a campaign auto-adds a bundled or gift line (a \"buy 1 get N\" offer), `isOrderLineItemAutoCreated(cart, item)` returns `true` for that line. Use it to badge the line and hide its quantity/remove controls — the customer cannot edit an auto-created line directly:\n\n```tsx\nimport { isOrderLineItemAutoCreated } from \"@ikas/bp-storefront\";\n\n{lineItems.map((item) => (\n <CartItem key={item.id} item={item} readOnly={isOrderLineItemAutoCreated(cart, item)} />\n))}\n```\n\n### Key Pattern: Section Without IkasComponentRenderer\n\nCartPage demonstrates that not all sections need COMPONENT_LIST slots. Simple sections can directly compose sub-components and local components when the layout is fixed and does not need editor-level child component placement.",
339
+ "content": "## Cart Management Patterns (Serel Reference)\n\nThe serel CartPage is a section that uses local internal components (OrderSummary, CouponCode, EmptyState) and the shared `CartItem` sub-component from `src/sub-components/CartItem/`. Unlike most sections, CartPage does NOT use IkasComponentRenderer — it directly composes its UI from sub-components.\n\n### CartPage Section Structure\n\n```tsx\nimport { cartStore } from \"@ikas/bp-storefront\";\nimport CartItem from \"../../sub-components/CartItem\";\nimport { Props } from \"./types\";\n\nexport function CartPage({ backgroundColor, emptyCartText, ...props }: Props) {\n const cart = cartStore.cart;\n const lineItems = cart?.orderLineItems ?? [];\n const isEmpty = lineItems.length === 0;\n\n if (isEmpty) return <EmptyState text={emptyCartText} />;\n\n return (\n <section className=\"cart-page\" style={backgroundColor ? { backgroundColor } : undefined}>\n <div className=\"cart-page-inner\">\n <div className=\"cart-items\">\n {lineItems.map((item) => (\n <CartItem key={item.id} item={item} />\n ))}\n </div>\n <div className=\"cart-sidebar\">\n <CouponCode cart={cart} />\n <OrderSummary cart={cart} />\n </div>\n </div>\n </section>\n );\n}\nexport default CartPage;\n```\n\n### CartItem Sub-Component\n\nThe `CartItem` sub-component (in `src/sub-components/CartItem/`) displays a single line item with image, variant name, quantity controls, price, and remove button:\n\n```tsx\nimport {\n getOrderLineItemFormattedFinalPrice,\n getOrderLineItemFormattedUnitPrice,\n getIkasOrderLineVariantMainImage,\n getDefaultSrc,\n changeItemQuantity,\n removeItem,\n IkasOrderLineItem,\n} from \"@ikas/bp-storefront\";\nimport QuantitySelector from \"../QuantitySelector\";\n\ninterface Props { item: IkasOrderLineItem; }\n\nexport default function CartItem({ item }: Props) {\n const image = item.variant ? getIkasOrderLineVariantMainImage(item.variant) : null;\n\n return (\n <div className=\"cart-item\">\n {image && <img src={getDefaultSrc(image)} alt={item.variant?.name} />}\n <div className=\"cart-item-info\">\n <span>{item.variant?.name}</span>\n <span>{getOrderLineItemFormattedUnitPrice(item)}</span>\n </div>\n <QuantitySelector\n quantity={item.quantity}\n onIncrement={() => changeItemQuantity(item, item.quantity + 1)}\n onDecrement={() => changeItemQuantity(item, Math.max(1, item.quantity - 1))}\n />\n <span>{getOrderLineItemFormattedFinalPrice(item)}</span>\n <button onClick={() => removeItem(item)}>Remove</button>\n </div>\n );\n}\n```\n\n### OrderSummary Local Component\n\nDisplays cart totals using `getIkasOrderFormattedTotalFinalPrice(cart)` and `getIkasOrderFormattedTotalPrice(cart)`, plus a checkout button:\n\n```tsx\nimport { Router, getIkasOrderFormattedTotalFinalPrice } from \"@ikas/bp-storefront\";\n\nfunction OrderSummary({ cart }) {\n return (\n <div className=\"order-summary\">\n <span>Total: {getIkasOrderFormattedTotalFinalPrice(cart)}</span>\n <button onClick={() => Router.navigateToPage(\"CHECKOUT\")}>Checkout</button>\n </div>\n );\n}\n```\n\n### CouponCode Local Component\n\nCoupon code uses the standard form model. Get the form from `customerStore` via `getCouponCodeForm`, init it once, drive the input with `setCouponCodeFormCouponCode`, and submit/remove with the form helpers. Do NOT call `saveCart`/`apiSaveCart` or any deep `@ikas/bp-storefront/dist/...` import — the coupon has dedicated public exports:\n\n```tsx\nimport { useEffect } from \"preact/hooks\";\nimport {\n customerStore,\n getCouponCodeForm,\n initCouponCodeForm,\n setCouponCodeFormCouponCode,\n submitCouponCodeForm,\n removeCouponCodeForm,\n} from \"@ikas/bp-storefront\";\nimport { observer } from \"@ikas/component-utils\";\n\n// observer() because this sub-component reads the MobX coupon form\nconst CouponCode = observer(function CouponCode({ appliedCoupon }) {\n const couponForm = getCouponCodeForm(customerStore);\n\n useEffect(() => {\n initCouponCodeForm(couponForm);\n }, [couponForm]);\n\n const handleSubmit = async (e: Event) => {\n e.preventDefault();\n await submitCouponCodeForm(couponForm);\n };\n\n if (appliedCoupon) {\n return (\n <div className=\"coupon\">\n <span>{appliedCoupon}</span>\n <button type=\"button\" onClick={() => removeCouponCodeForm(couponForm)}>Remove</button>\n </div>\n );\n }\n\n return (\n <form className=\"coupon\" onSubmit={handleSubmit}>\n <input\n placeholder={couponForm.couponCode?.placeholder ?? \"Coupon code\"}\n value={couponForm.couponCode?.value ?? \"\"}\n onInput={(e) =>\n setCouponCodeFormCouponCode(couponForm, (e.target as HTMLInputElement).value)\n }\n />\n <button type=\"submit\" disabled={couponForm.isSubmitting}>\n {couponForm.isSubmitting ? \"Applying...\" : \"Apply\"}\n </button>\n {couponForm.isFailure && couponForm.responseMessage && (\n <p className=\"coupon-error\">{couponForm.responseMessage}</p>\n )}\n </form>\n );\n});\n```\n\n### cartStore Usage Patterns\n\nThe `cartStore` is a MobX store available globally. Root components are automatically reactive via autorun, so reads from `cartStore.cart` trigger re-renders:\n\n```tsx\nimport { cartStore } from \"@ikas/bp-storefront\";\n\n// Always null-safe:\nconst cart = cartStore.cart;\nconst lineItems = cart?.orderLineItems ?? [];\nconst itemCount = lineItems.length;\nconst isEmpty = itemCount === 0;\n```\n\n### Quantity Limits (min/max per cart)\n\nA product's sales channel can cap how many units go into one cart. The limits live on the product's `salesChannels`, matched to the active channel:\n\n```tsx\nimport { IkasStorefrontConfig } from \"@ikas/bp-storefront\";\n\nconst channel = product.salesChannels?.find((sc) => sc.id === IkasStorefrontConfig.salesChannelId);\nconst min = channel?.minQuantityPerCart ?? 1;\nconst max = channel?.maxQuantityPerCart; // null/undefined = no cap\n```\n\nApply these to the quantity stepper: seed the initial quantity to `min`, and cap increments at `max`. `addItemToCart(variant, product, qty)` clamps to the same limits internally only when it creates a **new** cart line — and silently, so enforce them in the UI too or the customer sees the number snap with no explanation.\n\n> **The internal clamp only runs when a NEW cart line is created.** If the variant already has a line in the cart, `addItemToCart` delegates to `changeItemQuantity(existing, existing.quantity + qty)` before the clamp is reached — and `changeItemQuantity` never clamps. Cart page / cart drawer steppers therefore get no SDK enforcement at all; enforce the limits in the UI (see \"Enforcing Limits on Cart Lines\" below).\n\n> `IkasStorefrontConfig.salesChannelId` is a property. The older `getSalesChannelId()` method does not exist in this SDK.\n\n### Cart Operation validationError (complete list)\n\n`addItemToCart` / `changeItemQuantity` return `IkasCartOperationResult` — `{ success, validationError?, response? }`. The `validationError` union has exactly three values, but at runtime only `addItemToCart` ever sets it (client-side pre-validation before the API call). `changeItemQuantity` does no client-side validation and never returns a `validationError` — branch on `success` (and `response.errorCodes` for details), not on `validationError`, for cart-line quantity changes:\n\n| Value | Meaning |\n|-------|---------|\n| `INSUFFICIENT_STOCK` | Not enough stock for the requested quantity |\n| `INVALID_PRODUCT_OPTION_VALUES` | Required product options not fully or validly selected |\n| `EMPTY_CART` | The operation needs a non-empty cart (declared in the type union, but no current code path emits it) |\n\nQuantity limits are never surfaced as a `validationError` — there is **no** `MAX_QUANTITY_PER_CART_*` / `MIN_QUANTITY_PER_CART_*` value beyond the three above. They surface one level lower instead: when a mutation would push a line past `maxQuantityPerCart`, the API rejects it with the GraphQL error code `MAX_QUANTITY_PER_CART_LIMIT_REACHED` (an `extensions.code` value the API client copies into `response.errorCodes`). `addItemToCart` and `changeItemQuantity` go through the same mutation, so this is the reactive signal on the cart-line path — exactly where the SDK never clamps:\n\n```tsx\nimport { APIErrorCode, changeItemQuantity } from \"@ikas/bp-storefront\";\n\nconst result = await changeItemQuantity(item, qty);\nif (!result.success && result.response?.errorCodes?.includes(APIErrorCode.MAX_QUANTITY_PER_CART_LIMIT_REACHED)) {\n // The sales channel's per-cart cap rejected the quantity — tell the customer.\n}\n```\n\nTreat the error code as the fallback, not the UX: prevent limit violations proactively in the stepper (see \"Quantity Limits\" above and \"Enforcing Limits on Cart Lines\" below) so the customer never hits the rejection in the first place.\n\n### Enforcing Limits on Cart Lines\n\nCart lines cannot tell you the limits: `IkasOrderLineItem.variant` is an `IkasOrderLineVariant`, which carries **neither** `salesChannels` nor `stock` — both live only on `IkasProduct` / `IkasProductVariant`. To enforce `minQuantityPerCart` / `maxQuantityPerCart` (or stock caps) on the cart page / drawer, batch-fetch the line products once with `bs_searchProductsById` and map the limits by product id:\n\n```tsx\nimport { baseStore, bs_searchProductsById, cartStore, IkasStorefrontConfig } from \"@ikas/bp-storefront\";\n\n// Collect the distinct productIds of the cart lines and fetch them in ONE request:\nconst productIds = [\n ...new Set(\n (cartStore.cart?.orderLineItems ?? [])\n .map((item) => item.variant.productId)\n .filter((id): id is string => !!id)\n ),\n];\nconst { products } = await bs_searchProductsById(baseStore, { productIds });\n\nconst limitsByProductId = new Map<string, { min: number; max: number | null }>();\nfor (const product of products ?? []) {\n const channel = product.salesChannels?.find((sc) => sc.id === IkasStorefrontConfig.salesChannelId);\n limitsByProductId.set(product.id, {\n min: channel?.minQuantityPerCart ?? 1,\n max: channel?.maxQuantityPerCart ?? null,\n });\n}\n\n// In the line's stepper:\nconst limits = limitsByProductId.get(item.variant.productId ?? \"\");\nconst atMax = limits?.max != null && item.quantity >= limits.max;\n// disable the + button when atMax; block decrements below limits.min the same way\n```\n\n`bs_searchProductsById` returns full `IkasProduct` objects, so `salesChannels` (already filtered to the active sales channel) and per-variant `stock` (summed over the sales channel's configured stock locations) come in the same response — one fetch covers both quantity limits and stock caps. Fetch once per cart open and cache by product id rather than fetching per line; when lines render independently, collect the ids over a tick and flush a single batched request.\n\n### Campaign Offer Lines in the Cart\n\nCampaign discounts surface as order-level adjustment rows, not as edits on the line items. Format the adjustment amount with `formatCurrency` — the root export that applies the merchant's currency format settings:\n\n```tsx\nimport { formatCurrency } from \"@ikas/bp-storefront\";\n\n{cart.orderAdjustments?.map((adj) => (\n <div key={adj.name} className=\"cart-adjustment\">\n <span>{adj.name}</span>\n <span>{formatCurrency(adj.amount, adj.currencyCode, adj.currencySymbol)}</span>\n </div>\n))}\n```\n\nWhen a campaign auto-adds a bundled or gift line (a \"buy 1 get N\" offer), `isOrderLineItemAutoCreated(cart, item)` returns `true` for that line. Use it to badge the line and hide its quantity/remove controls — the customer cannot edit an auto-created line directly:\n\n```tsx\nimport { isOrderLineItemAutoCreated } from \"@ikas/bp-storefront\";\n\n{lineItems.map((item) => (\n <CartItem key={item.id} item={item} readOnly={isOrderLineItemAutoCreated(cart, item)} />\n))}\n```\n\n### Key Pattern: Section Without IkasComponentRenderer\n\nCartPage demonstrates that not all sections need COMPONENT_LIST slots. Simple sections can directly compose sub-components and local components when the layout is fixed and does not need editor-level child component placement.",
326
340
  "tags": [
327
341
  "cart",
328
342
  "checkout",
@@ -331,8 +345,14 @@
331
345
  "CouponCode",
332
346
  "cartStore",
333
347
  "quantity",
348
+ "quantity limits",
349
+ "maxQuantityPerCart",
350
+ "minQuantityPerCart",
351
+ "bs_searchProductsById",
334
352
  "sub-component",
335
- "serel"
353
+ "serel",
354
+ "currency",
355
+ "formatCurrency"
336
356
  ]
337
357
  },
338
358
  "address-form-patterns": {
@@ -359,7 +379,7 @@
359
379
  "account-patterns": {
360
380
  "title": "Account & Dashboard Patterns",
361
381
  "description": "Orders list, order detail, address management, favorites, and account info forms",
362
- "content": "## Account & Dashboard Patterns\n\nAccount sections typically use a tab-based layout with orders, addresses, favorites, and account info.\n\n### Orders List\n\n```tsx\nimport {\n customerStore,\n getOrders,\n getIkasOrderFormattedTotalFinalPrice,\n getIkasOrderTotalItemCount,\n getIkasOrderFormattedOrderedAt,\n getIkasOrderPackageStatusTranslation,\n getIkasOrderHref,\n} from \"@ikas/bp-storefront\";\n\n// Fetch orders on mount\nuseEffect(() => {\n getOrders(customerStore);\n}, []);\n\nconst orders = customerStore.orders ?? [];\n\n{orders.map((order) => (\n <a key={order.id} href={getIkasOrderHref(order)} className=\"order-card\">\n <span>Order #{order.orderNumber}</span>\n <span>{getIkasOrderFormattedOrderedAt(order)}</span>\n <span>{getIkasOrderTotalItemCount(order)} items</span>\n <span>{getIkasOrderFormattedTotalFinalPrice(order)}</span>\n <span>{getIkasOrderPackageStatusTranslation(order)}</span>\n </a>\n))}\n```\n\n### Order Detail\n\n```tsx\nimport {\n getIkasOrderLineVariantMainImage,\n getDefaultSrc,\n} from \"@ikas/bp-storefront\";\n\n// order.orderLineItems contains line items\n{order.orderLineItems.map((item) => {\n const image = item.variant\n ? getIkasOrderLineVariantMainImage(item.variant)\n : null;\n return (\n <div key={item.id}>\n {image && <img src={getDefaultSrc(image)} />}\n <span>{item.variant?.name}</span>\n <span>Qty: {item.quantity}</span>\n </div>\n );\n})}\n```\n\n### Address Management\n\nAddress forms are country-driven: the field set and the row layout come from\n`addressForm.addressFormat`, not from a list you write. Call\n`get_framework_guide({ topic: \"address-form-patterns\" })` before building one.\n\n```tsx\nimport {\n getEmptyAddressForm,\n getIkasCustomerAddressForm,\n initAddressForm,\n submitAddressForm,\n deleteCustomerAddress,\n customerStore,\n} from \"@ikas/bp-storefront\";\n\nconst addresses = customerStore.customer?.addresses ?? [];\n\n// Create: getEmptyAddressForm takes the STORE.\n// Edit: getIkasCustomerAddressForm takes the ADDRESS.\nconst addressForm = address ? getIkasCustomerAddressForm(address) : getEmptyAddressForm(customerStore);\n\n// init is async and loads the country format + location lists; gate render on it.\nawait initAddressForm(addressForm, address);\n\n// Render rows from addressForm.addressFormat, set values via setAddressForm*(addressForm, value),\n// then submit (it validates and returns a boolean):\nconst ok = await submitAddressForm(addressForm);\n\n// Delete takes the ADDRESS OBJECT, not an id:\nawait deleteCustomerAddress(customerStore, address);\n```\n\n### Favorites\n\n```tsx\nimport {\n getFavoriteProducts,\n isFavoriteIkasProduct,\n removeIkasProductFromFavorites,\n} from \"@ikas/bp-storefront\";\n\n// Fetch favorites\nuseEffect(() => {\n getFavoriteProducts(customerStore);\n}, []);\n\nconst favorites = customerStore.favoriteProducts ?? [];\n```\n\n### Account Info Form\n\n```tsx\nimport {\n getAccountInfoForm,\n initAccountInfoForm,\n setAccountInfoFormFirstName,\n setAccountInfoFormLastName,\n setAccountInfoFormPhone,\n submitAccountInfoForm,\n} from \"@ikas/bp-storefront\";\n\nconst accountForm = getAccountInfoForm(customerStore);\n\nuseEffect(() => {\n initAccountInfoForm(accountForm);\n}, []);\n\nconst handleSave = async (e: Event) => {\n e.preventDefault();\n await submitAccountInfoForm(accountForm);\n};\n```\n\n### Tab Navigation Pattern\n\nProduction themes use a tab-based layout:\n\n```tsx\nconst [activeTab, setActiveTab] = useState(\"orders\");\n\nconst tabs = [\n { id: \"orders\", label: \"Orders\" },\n { id: \"addresses\", label: \"Addresses\" },\n { id: \"favorites\", label: \"Favorites\" },\n { id: \"account\", label: \"Account Info\" },\n];\n\n<div className=\"account-tabs\">\n {tabs.map((tab) => (\n <button\n key={tab.id}\n className={activeTab === tab.id ? \"active\" : \"\"}\n onClick={() => setActiveTab(tab.id)}\n >\n {tab.label}\n </button>\n ))}\n</div>\n\n{activeTab === \"orders\" && <OrdersList />}\n{activeTab === \"addresses\" && <AddressList />}\n{activeTab === \"favorites\" && <FavoritesList />}\n{activeTab === \"account\" && <AccountInfoForm />}\n```",
382
+ "content": "## Account & Dashboard Patterns\n\nAccount sections typically use a tab-based layout with orders, addresses, favorites, and account info.\n\n> **`customerStore` has exactly one public field: `customer`.** Everything else on the store is\n> underscore-prefixed internal state. Order and favorite lists are **not** fields on the store —\n> they come from the `Promise` that `getOrders()` / `getFavoriteProducts()` return. Reading\n> `customerStore.orders` or `customerStore.favoriteProducts` is a TypeScript error (TS2339 /\n> TS2551), not a silent empty list.\n>\n> This is the one place where copying data into `useState` is correct. The\n> \"don't mirror store data in `useState`\" rule in `async-data-patterns` §5 is about\n> store-backed observable fields; orders and favorites have no such field to observe.\n\n### Orders List\n\n```tsx\nimport { useEffect, useState } from \"preact/hooks\";\nimport {\n customerStore,\n getOrders,\n IkasOrder,\n getIkasOrderFormattedTotalFinalPrice,\n getIkasOrderTotalItemCount,\n getIkasOrderFormattedOrderedAt,\n getIkasOrderPackageStatusTranslation,\n getIkasOrderHref,\n} from \"@ikas/bp-storefront\";\n\n// getOrders() RESOLVES with the orders — it writes nothing to the store.\n// Keep the result in local state; there is no `customerStore.orders`.\nconst [orders, setOrders] = useState<IkasOrder[]>([]);\nconst [loading, setLoading] = useState(true);\n\nuseEffect(() => {\n let cancelled = false;\n getOrders(customerStore)\n .then((result) => {\n if (!cancelled) setOrders(result ?? []);\n })\n .finally(() => {\n if (!cancelled) setLoading(false);\n });\n return () => {\n cancelled = true;\n };\n}, []);\n\n{orders.map((order) => (\n <a key={order.id} href={getIkasOrderHref(order)} className=\"order-card\">\n <span>Order #{order.orderNumber}</span>\n <span>{getIkasOrderFormattedOrderedAt(order)}</span>\n <span>{getIkasOrderTotalItemCount(order)} items</span>\n <span>{getIkasOrderFormattedTotalFinalPrice(order)}</span>\n <span>{getIkasOrderPackageStatusTranslation(order)}</span>\n </a>\n))}\n```\n\n### Order Detail\n\n```tsx\nimport {\n getIkasOrderLineVariantMainImage,\n getDefaultSrc,\n} from \"@ikas/bp-storefront\";\n\n// order.orderLineItems contains line items\n{order.orderLineItems.map((item) => {\n const image = item.variant\n ? getIkasOrderLineVariantMainImage(item.variant)\n : null;\n return (\n <div key={item.id}>\n {image && <img src={getDefaultSrc(image)} />}\n <span>{item.variant?.name}</span>\n <span>Qty: {item.quantity}</span>\n </div>\n );\n})}\n```\n\n### Address Management\n\nAddress forms are country-driven: the field set and the row layout come from\n`addressForm.addressFormat`, not from a list you write. Call\n`get_framework_guide({ topic: \"address-form-patterns\" })` before building one.\n\n```tsx\nimport {\n getEmptyAddressForm,\n getIkasCustomerAddressForm,\n initAddressForm,\n submitAddressForm,\n deleteCustomerAddress,\n customerStore,\n} from \"@ikas/bp-storefront\";\n\nconst addresses = customerStore.customer?.addresses ?? [];\n\n// Create: getEmptyAddressForm takes the STORE.\n// Edit: getIkasCustomerAddressForm takes the ADDRESS.\nconst addressForm = address ? getIkasCustomerAddressForm(address) : getEmptyAddressForm(customerStore);\n\n// init is async and loads the country format + location lists; gate render on it.\nawait initAddressForm(addressForm, address);\n\n// Render rows from addressForm.addressFormat, set values via setAddressForm*(addressForm, value),\n// then submit (it validates and returns a boolean):\nconst ok = await submitAddressForm(addressForm);\n\n// Delete takes the ADDRESS OBJECT, not an id:\nawait deleteCustomerAddress(customerStore, address);\n```\n\n### Favorites\n\n```tsx\nimport { useEffect, useState } from \"preact/hooks\";\nimport {\n customerStore,\n getFavoriteProducts,\n IkasProduct,\n} from \"@ikas/bp-storefront\";\n\n// Same rule as orders: getFavoriteProducts() resolves with the products.\n// There is no `customerStore.favoriteProducts` field.\nconst [favorites, setFavorites] = useState<IkasProduct[]>([]);\nconst [loading, setLoading] = useState(true);\n\nuseEffect(() => {\n let cancelled = false;\n getFavoriteProducts(customerStore)\n .then((result) => {\n if (!cancelled) setFavorites(result ?? []);\n })\n .finally(() => {\n if (!cancelled) setLoading(false);\n });\n return () => {\n cancelled = true;\n };\n}, []);\n```\n\nThe favorites **list** is a fetched snapshot, but the favorite **flag** is store-backed and\nreactive — `isFavoriteIkasProduct(product)` reads the store synchronously, so heart icons inside\nan `observer()` sub-component update on their own:\n\n```tsx\nimport { observer } from \"@ikas/component-utils\";\nimport {\n isFavoriteIkasProduct,\n addIkasProductToFavorites,\n removeIkasProductFromFavorites,\n} from \"@ikas/bp-storefront\";\n\nconst FavoriteButton = observer(function FavoriteButton({ product }: { product: IkasProduct }) {\n const isFavorite = isFavoriteIkasProduct(product);\n return (\n <button\n onClick={() =>\n isFavorite\n ? removeIkasProductFromFavorites(product)\n : addIkasProductToFavorites(product)\n }\n >\n {isFavorite ? \"\\u2665\" : \"\\u2661\"}\n </button>\n );\n});\n```\n\nBecause the list is a snapshot, removing a favorite does **not** re-render it. Drop the item from\nyour local array as well:\n\n```tsx\nonFavoriteRemove={() => setFavorites((prev) => prev.filter((f) => f.id !== product.id))}\n```\n\nNote: `getFavoriteProducts` fetches at most 100 products in one call.\n\n### Account Info Form\n\n```tsx\nimport {\n getAccountInfoForm,\n initAccountInfoForm,\n setAccountInfoFormFirstName,\n setAccountInfoFormLastName,\n setAccountInfoFormPhone,\n submitAccountInfoForm,\n} from \"@ikas/bp-storefront\";\n\nconst accountForm = getAccountInfoForm(customerStore);\n\nuseEffect(() => {\n initAccountInfoForm(accountForm);\n}, []);\n\nconst handleSave = async (e: Event) => {\n e.preventDefault();\n await submitAccountInfoForm(accountForm);\n};\n```\n\n### Delete Account (Deactivate Customer)\n\nAccount deletion is a form like any other — the customer confirms with their password. The form\ndoes **not** clear the session, so call `logout(customerStore)` yourself once it succeeds.\n\n```tsx\nimport {\n customerStore,\n getDeactivateCustomerForm,\n initDeactivateCustomerForm,\n setDeactivateCustomerFormPassword,\n submitDeactivateCustomerForm,\n logout,\n Router,\n} from \"@ikas/bp-storefront\";\n\nconst deactivateForm = getDeactivateCustomerForm(customerStore);\n\nuseEffect(() => {\n initDeactivateCustomerForm(deactivateForm);\n}, []);\n\nconst handleDelete = async (e: Event) => {\n e.preventDefault();\n const success = await submitDeactivateCustomerForm(deactivateForm);\n if (success) {\n await logout(customerStore);\n Router.navigateToPage(\"INDEX\");\n }\n};\n\n<form onSubmit={handleDelete}>\n {deactivateForm.isFailure && <div>{deactivateForm.responseMessage}</div>}\n\n <input\n type=\"password\"\n value={deactivateForm.password.value}\n onInput={(e) => setDeactivateCustomerFormPassword(deactivateForm, e.target.value)}\n />\n {deactivateForm.password.hasError && <span>{deactivateForm.password.message}</span>}\n\n <button type=\"submit\" disabled={deactivateForm.isSubmitting}>\n {deactivateForm.isSubmitting ? \"Deleting...\" : \"Delete Account\"}\n </button>\n</form>\n```\n\n`submit` already turns the API error for an existing deletion request into a translated\n`responseMessage` — render `responseMessage` rather than inspecting the API response yourself.\nDeletion is irreversible, so gate the form behind a confirmation step in your own UI.\n\n### Tab Navigation Pattern\n\nProduction themes use a tab-based layout:\n\n```tsx\nconst [activeTab, setActiveTab] = useState(\"orders\");\n\nconst tabs = [\n { id: \"orders\", label: \"Orders\" },\n { id: \"addresses\", label: \"Addresses\" },\n { id: \"favorites\", label: \"Favorites\" },\n { id: \"account\", label: \"Account Info\" },\n];\n\n<div className=\"account-tabs\">\n {tabs.map((tab) => (\n <button\n key={tab.id}\n className={activeTab === tab.id ? \"active\" : \"\"}\n onClick={() => setActiveTab(tab.id)}\n >\n {tab.label}\n </button>\n ))}\n</div>\n\n{activeTab === \"orders\" && <OrdersList />}\n{activeTab === \"addresses\" && <AddressList />}\n{activeTab === \"favorites\" && <FavoritesList />}\n{activeTab === \"account\" && <AccountInfoForm />}\n```",
363
383
  "tags": [
364
384
  "account",
365
385
  "orders",
@@ -367,7 +387,10 @@
367
387
  "favorites",
368
388
  "dashboard",
369
389
  "customer",
370
- "tabs"
390
+ "tabs",
391
+ "deactivate",
392
+ "delete account",
393
+ "password"
371
394
  ]
372
395
  },
373
396
  "header-footer-patterns": {
@@ -555,7 +578,7 @@
555
578
  "config-advanced-features": {
556
579
  "title": "Advanced ikas.config.json Features",
557
580
  "description": "filteredComponentIds, privateVarMap, isHeader/isFooter, propGroups, custom enum types, typeId/enumTypeId for advanced config patterns",
558
- "content": "## Advanced ikas.config.json Features\n\nBeyond basic component and prop definitions, `ikas.config.json` supports advanced features for complex theme architectures.\n\n### filteredComponentIds — Restricting Component Slots\n\n`filteredComponentIds` on a `COMPONENT_LIST` prop limits which child components can be placed in that slot. Without it, any component can be added.\n\n```json\n{\n \"name\": \"components\",\n \"type\": \"COMPONENT_LIST\",\n \"filteredComponentIds\": [\n \"nb34u3yu-navbar\",\n \"nb34u3yu-announcements\",\n \"nb34u3yu-cookie-bar\"\n ]\n}\n```\n\nThe IDs use the full component ID format: `{projectId}-{kebab-case-name}`. Check your component IDs with `npx ikas-component config list`.\n\n### privateVarMap — Section-to-Child Data Passing\n\nExposes a typed variable from a section to its child components. At runtime, the section must pass the actual data via the `map` prop on `IkasComponentRenderer`.\n\n```json\n{\n \"name\": \"components\",\n \"type\": \"COMPONENT_LIST\",\n \"filteredComponentIds\": [\"nb34u3yu-card-product-price\"],\n \"privateVarMap\": {\n \"product\": {\n \"id\": \"nb34u3yu-product-slider-product\",\n \"typeId\": \"@ikas/bp-storefront-models-IkasProduct\"\n }\n }\n}\n```\n\n- `product` = variable name children receive\n- `id` = unique identifier (project-section-variable format)\n- `typeId` = model type reference (`@ikas/bp-storefront-models-TypeName`)\n\nSee `get_framework_guide(\"private-var-map\")` for full details.\n\n### isHeader / isFooter — Global Sections\n\nMark a section to appear on every page:\n\n```json\n{\n \"id\": \"header\",\n \"name\": \"Header\",\n \"type\": \"section\",\n \"isHeader\": true,\n \"props\": [...]\n}\n```\n\nRules:\n- Only one component can have `isHeader: true`\n- Only one component can have `isFooter: true`\n- Only applies to `type: \"section\"` components\n- The editor automatically adds these to all pages\n\nCLI:\n```bash\nnpx ikas-component config add-component --name \"Header\" --type section --isHeader --props '[...]'\nnpx ikas-component config add-component --name \"Footer\" --type section --isFooter --props '[...]'\n```\n\n### propGroups — Organizing Props\n\nGroup props into collapsible sections in the editor sidebar:\n\n```json\n{\n \"propGroups\": [\n { \"id\": \"content\", \"name\": \"Content\" },\n {\n \"id\": \"style\", \"name\": \"Style\",\n \"children\": [\n { \"id\": \"style.colors\", \"name\": \"Colors\" }\n ]\n }\n ],\n \"props\": [\n { \"name\": \"title\", \"type\": \"TEXT\", \"groupId\": \"content\" },\n { \"name\": \"bgColor\", \"type\": \"COLOR\", \"groupId\": \"style.colors\" }\n ]\n}\n```\n\nCLI:\n```bash\nnpx ikas-component config add-prop-group --component \"MySection\" --id content --name \"Content\"\nnpx ikas-component config add-prop-group --component \"MySection\" --id colors --name \"Colors\" --parent style\nnpx ikas-component config update-prop --component \"MySection\" --prop title --group content\n```\n\nSee `get_framework_guide(\"prop-groups\")` for full details.\n\n### TYPE Props — Structured Style Types\n\nThe `TYPE` prop type uses `typeId` to reference structured style types (padding, margin, border-radius, etc.):\n\n```json\n{\n \"name\": \"spacing\",\n \"type\": \"TYPE\",\n \"typeId\": \"@ikas/bp-storefront-models-PaddingStyleType\"\n}\n```\n\nAppend `_array` for array types: `\"@ikas/bp-storefront-models-MarginStyleType_array\"`\n\nDiscover available types:\n```bash\nnpx ikas-component config list-types # all types\nnpx ikas-component config list-types --component-type section # section-allowed types only\n```\n\n### ENUM Props — Enum Style Types\n\nThe `ENUM` prop type uses `enumTypeId` for dropdown selectors:\n\n```json\n{\n \"name\": \"direction\",\n \"type\": \"ENUM\",\n \"enumTypeId\": \"@ikas/bp-storefront-models-FlexDirectionStyleType\"\n}\n```\n\nCommon enum types: FlexDirectionStyleType, JustifyContentStyleType, AlignItemsStyleType, TextAlignStyleType, ObjectFitStyleType.\n\nCLI:\n```bash\nnpx ikas-component config add-prop --component MyComp --name direction --displayName Direction --type ENUM --enumTypeId \"@ikas/bp-storefront-models-FlexDirectionStyleType\"\n```\n\n### CLI Config Commands Reference\n\n| Command | Purpose |\n|---------|--------|\n| `config add-component --name X --type section --props '[...]'` | Create component with props |\n| `config add-prop --component X --name y --type TYPE --typeId Z` | Add structured type prop |\n| `config add-prop --component X --name y --type ENUM --enumTypeId Z` | Add enum prop |\n| `config add-prop-group --component X --id g --name \"Group\"` | Create prop group |\n| `config update-prop --component X --prop y --group g` | Assign prop to group |\n| `config list-types` | List available TYPE and ENUM types |\n| `config list` | List all components and props |",
581
+ "content": "## Advanced ikas.config.json Features\n\nBeyond basic component and prop definitions, `ikas.config.json` supports advanced features for complex theme architectures.\n\n### filteredComponentIds — Restricting Component Slots\n\n`filteredComponentIds` on a `COMPONENT_LIST` prop limits which child components can be placed in that slot. Without it, any component can be added.\n\n```json\n{\n \"name\": \"components\",\n \"type\": \"COMPONENT_LIST\",\n \"filteredComponentIds\": [\n \"nb34u3yu-navbar\",\n \"nb34u3yu-announcements\",\n \"nb34u3yu-cookie-bar\"\n ]\n}\n```\n\nThe IDs use the full component ID format: `{projectId}-{kebab-case-name}`. Check your component IDs with `npx ikas-component config list`.\n\n### privateVarMap — Section-to-Child Data Passing\n\nExposes a typed variable from a section to its child components. At runtime, the section must pass the actual data via the `map` prop on `IkasComponentRenderer`.\n\n```json\n{\n \"name\": \"components\",\n \"type\": \"COMPONENT_LIST\",\n \"filteredComponentIds\": [\"nb34u3yu-card-product-price\"],\n \"privateVarMap\": {\n \"product\": {\n \"id\": \"nb34u3yu-product-slider-product\",\n \"typeId\": \"@ikas/bp-storefront-models-IkasProduct\"\n }\n }\n}\n```\n\n- `product` = variable name children receive\n- `id` = unique identifier (project-section-variable format)\n- `typeId` = model type reference (`@ikas/bp-storefront-models-TypeName`)\n\nSee `get_framework_guide(\"private-var-map\")` for full details.\n\n### isHeader / isFooter — Global Sections\n\nMark a section to appear on every page:\n\n```json\n{\n \"id\": \"header\",\n \"name\": \"Header\",\n \"type\": \"section\",\n \"isHeader\": true,\n \"props\": [...]\n}\n```\n\nRules:\n- Only one component can have `isHeader: true`\n- Only one component can have `isFooter: true`\n- Only applies to `type: \"section\"` components\n- The editor automatically adds these to all pages\n- Their PROP VALUES are shared theme-wide, not per page: a global section keeps ONE record of values, stored on the INDEX (Home) page's placement. Reading or writing them from any page (`get_section_values` / `update_section_prop` / `update_page_sections`) resolves to that single record, and those tools return a `common` block saying so. Two consequences when filling content: a change made from any page changes the header/footer on ALL pages, and the props are normally already filled with the merchant's content — so read the current values first and change only what was asked instead of blind-filling props that merely look empty.\n\nCLI:\n```bash\nnpx ikas-component config add-component --name \"Header\" --type section --isHeader --props '[...]'\nnpx ikas-component config add-component --name \"Footer\" --type section --isFooter --props '[...]'\n```\n\n### propGroups — Organizing Props\n\nGroup props into collapsible sections in the editor sidebar:\n\n```json\n{\n \"propGroups\": [\n { \"id\": \"content\", \"name\": \"Content\" },\n {\n \"id\": \"style\", \"name\": \"Style\",\n \"children\": [\n { \"id\": \"style.colors\", \"name\": \"Colors\" }\n ]\n }\n ],\n \"props\": [\n { \"name\": \"title\", \"type\": \"TEXT\", \"groupId\": \"content\" },\n { \"name\": \"bgColor\", \"type\": \"COLOR\", \"groupId\": \"style.colors\" }\n ]\n}\n```\n\nCLI:\n```bash\nnpx ikas-component config add-prop-group --component \"MySection\" --id content --name \"Content\"\nnpx ikas-component config add-prop-group --component \"MySection\" --id colors --name \"Colors\" --parent style\nnpx ikas-component config update-prop --component \"MySection\" --prop title --group content\n```\n\nSee `get_framework_guide(\"prop-groups\")` for full details.\n\n### TYPE Props — Structured Style Types\n\nThe `TYPE` prop type uses `typeId` to reference structured style types (padding, margin, border-radius, etc.):\n\n```json\n{\n \"name\": \"spacing\",\n \"type\": \"TYPE\",\n \"typeId\": \"@ikas/bp-storefront-models-PaddingStyleType\"\n}\n```\n\nAppend `_array` for array types: `\"@ikas/bp-storefront-models-MarginStyleType_array\"`\n\nDiscover available types:\n```bash\nnpx ikas-component config list-types # all types\nnpx ikas-component config list-types --component-type section # section-allowed types only\n```\n\n### ENUM Props — Enum Style Types\n\nThe `ENUM` prop type uses `enumTypeId` for dropdown selectors:\n\n```json\n{\n \"name\": \"direction\",\n \"type\": \"ENUM\",\n \"enumTypeId\": \"@ikas/bp-storefront-models-FlexDirectionStyleType\"\n}\n```\n\nCommon enum types: FlexDirectionStyleType, JustifyContentStyleType, AlignItemsStyleType, TextAlignStyleType, ObjectFitStyleType.\n\nCLI:\n```bash\nnpx ikas-component config add-prop --component MyComp --name direction --displayName Direction --type ENUM --enumTypeId \"@ikas/bp-storefront-models-FlexDirectionStyleType\"\n```\n\n### CLI Config Commands Reference\n\n| Command | Purpose |\n|---------|--------|\n| `config add-component --name X --type section --props '[...]'` | Create component with props |\n| `config add-prop --component X --name y --type TYPE --typeId Z` | Add structured type prop |\n| `config add-prop --component X --name y --type ENUM --enumTypeId Z` | Add enum prop |\n| `config add-prop-group --component X --id g --name \"Group\"` | Create prop group |\n| `config update-prop --component X --prop y --group g` | Assign prop to group |\n| `config list-types` | List available TYPE and ENUM types |\n| `config list` | List all components and props |",
559
582
  "tags": [
560
583
  "config",
561
584
  "filteredComponentIds",
@@ -591,8 +614,8 @@
591
614
  },
592
615
  "image-handling": {
593
616
  "title": "Image Handling",
594
- "description": "How to render images from IkasImage, IkasProduct variants, and IkasProductImage wrappers. Covers the canonical variant-to-image chain, all-variant-images mapping, non-product images, background images, and responsive srcsets.",
595
- "content": "## Image Handling\n\nThe canonical recipe for rendering an image. The product-variant case is 4 hops because each step carries metadata the next doesn't (variant selection → that variant's image set → metadata wrapper → CDN-ready image):\n\n```tsx\nimport {\n getSelectedProductVariant,\n getProductVariantMainImage,\n getDefaultSrc,\n getSrc,\n createMediaSrcset,\n IkasImage,\n} from \"@ikas/bp-storefront\";\n\nconst variant = getSelectedProductVariant(product); // IkasProductVariant | undefined\nconst productImage = variant && getProductVariantMainImage(variant); // IkasProductImage | undefined\nconst image = productImage?.image; // IkasImage | undefined — what CDN helpers need\n\nif (image) {\n return (\n <>\n <img src={getDefaultSrc(image)} alt={product.name} /> {/* default size */}\n <img src={getSrc(image, { width: 400 })} alt=\"\" /> {/* explicit width */}\n <img srcSet={createMediaSrcset(image)} alt=\"\" /> {/* responsive srcset */}\n </>\n );\n}\n```\n\n## All Variant Images (gallery)\n\nMap over `variant.images` and unwrap each `.image`. `IkasProductImage` carries metadata like `order` and `isMain`; the actual `IkasImage` (what the CDN helpers need) is the `.image` property on each.\n\n```tsx\nconst images: IkasImage[] = (variant?.images ?? [])\n .map((pi) => pi.image)\n .filter((img): img is IkasImage => img != null);\n```\n\n## Non-Product Images (logo, banner, IMAGE prop)\n\nThese skip the variant hop — they're already `IkasImage`:\n\n```tsx\n{props.logo && <img src={getDefaultSrc(props.logo)} alt=\"\" />}\n```\n\n## Background Images\n\n```tsx\n<div style={{ backgroundImage: image ? `url(${getDefaultSrc(image)})` : \"none\" }} />\n```\n\n## See Also\n\n- `get_framework_guide(\"common-pitfalls\")` §19 — full property-rename catalog (`selectedVariant`, `mainImage`, `href`, `checkoutUrl`)\n- `get_section_template(\"image-handling\")` — full Product Detail section with gallery + zoom + srcset\n- `get_function_doc(\"getDefaultSrc\")` / `get_function_doc(\"getSrc\")` / `get_function_doc(\"createMediaSrcset\")` — exact signatures\n- `get_type_definition(\"IkasImage\")` / `get_type_definition(\"IkasProductImage\")` — exact shapes",
617
+ "description": "How to render images AND VIDEOS from IkasImage, IkasProduct variants, and IkasProductImage wrappers. Covers the canonical variant-to-image chain, the mandatory isVideo branch for product media, all-variant-images galleries, non-product images, background images, and responsive srcsets.",
618
+ "content": "## Image Handling\n\nThe canonical recipe for rendering an image. The product-variant case is 4 hops because each step carries metadata the next doesn't (variant selection → that variant's image set → metadata wrapper → CDN-ready image):\n\n```tsx\nimport {\n getSelectedProductVariant,\n getProductVariantMainImage,\n getDefaultSrc,\n getSrc,\n createMediaSrcset,\n IkasImage,\n} from \"@ikas/bp-storefront\";\n\nconst variant = getSelectedProductVariant(product); // IkasProductVariant | undefined\nconst productImage = variant && getProductVariantMainImage(variant); // IkasProductImage | undefined\nconst image = productImage?.image; // IkasImage | undefined — what CDN helpers need\n\n// The main media item can itself be a VIDEO (image.isVideo) — see \"Video Media\" below.\nif (image && !image.isVideo) {\n return (\n <>\n <img src={getDefaultSrc(image)} alt={product.name} /> {/* default size */}\n <img src={getSrc(image, 400)} alt=\"\" /> {/* explicit width — number, not an object */}\n <img srcSet={createMediaSrcset(image)} alt=\"\" /> {/* responsive srcset */}\n </>\n );\n}\n```\n\n## All Variant Images (gallery)\n\nMap over `variant.images` and unwrap each `.image`. `IkasProductImage` carries metadata like `order` and `isMain`; the actual `IkasImage` (what the CDN helpers need) is the `.image` property on each.\n\n```tsx\nconst images: IkasImage[] = (variant?.images ?? [])\n .map((pi) => pi.image)\n .filter((img): img is IkasImage => img != null);\n```\n\n**This list can contain VIDEOS.** Never render it as plain `<img>` — see below.\n\n## Video Media (`isVideo`)\n\nProduct media mixes images and videos. For a video item the CDN has exactly one URL (the\noriginal `.mp4`): `getDefaultSrc`, `getSrc` and `getThumbnailSrc` all return it, the size\nargument is ignored, and there is **no poster/first-frame URL**. So an `<img>` with a video\nsrc is broken media, and `getThumbnailSrc` in a small box silently downloads the whole video.\n\nEvery media call site branches:\n\n```tsx\n{images.map((img, i) =>\n img.isVideo ? (\n <video\n key={i}\n className=\"gallery__media\"\n src={getDefaultSrc(img)} // not getSrc(img, n) — size is ignored for videos\n muted\n playsInline\n loop\n autoPlay // playing contexts only; omit where the media is a still\n >\n <track kind=\"captions\" />\n </video>\n ) : (\n <img\n key={i}\n className=\"gallery__media\"\n src={getDefaultSrc(img)}\n srcSet={createMediaSrcset(img)} // srcset applies to <img> only\n sizes=\"(max-width: 1023px) 100vw, 50vw\"\n alt={img.altText || `${product.name} ${i + 1}`}\n />\n )\n)}\n```\n\n- **Playing contexts** (PDP gallery, product card): `autoPlay muted loop playsInline`.\n- **Still contexts** (thumbnail rail, variant swatch, cart/order line, bundle item): no\n `autoPlay`, use `preload=\"metadata\"` — the browser holds the first frame, which is the only\n poster substitute available. Images in those contexts still use `getThumbnailSrc`, so guard\n it: `const imgSrc = img && !img.isVideo ? getThumbnailSrc(img) : null;`\n\nA theme usually has 8+ such call sites, so factor one media sub-component with an `autoPlay`\nflag instead of repeating the ternary.\n\nThree follow-on traps that pass typecheck and build, and are only caught by eye:\n\n1. `<video>` defaults to `object-fit: contain`, `<img>` to `fill` — set `object-fit: cover`\n explicitly or the video sits differently in the same box.\n2. CSS element selectors skip the video branch: `.card__media-wrap img { … }` never matches.\n Write `.card__media-wrap img, .card__media-wrap video { … }`, or style a shared class.\n3. An autoplaying loop is moving content, so it must honour `prefers-reduced-motion`. The\n `autoplay` attribute has no effect after load — pause via the element ref when the media\n query matches.\n\n## Non-Product Images (logo, banner, IMAGE prop)\n\nThese skip the variant hop — they're already `IkasImage`:\n\n```tsx\n{props.logo && <img src={getDefaultSrc(props.logo)} alt=\"\" />}\n```\n\n## Background Images\n\n```tsx\n<div style={{ backgroundImage: image ? `url(${getDefaultSrc(image)})` : \"none\" }} />\n```\n\n## See Also\n\n- `get_framework_guide(\"common-pitfalls\")` §19 — full property-rename catalog (`selectedVariant`, `mainImage`, `href`, `checkoutUrl`)\n- `get_section_template(\"image-handling\")` — full Product Detail section with gallery + zoom + srcset\n- `get_function_doc(\"getDefaultSrc\")` / `get_function_doc(\"getSrc\")` / `get_function_doc(\"createMediaSrcset\")` — exact signatures\n- `get_type_definition(\"IkasImage\")` / `get_type_definition(\"IkasProductImage\")` — exact shapes",
596
619
  "tags": [
597
620
  "image",
598
621
  "rendering",
@@ -603,13 +626,17 @@
603
626
  "IkasProductImage",
604
627
  "variant",
605
628
  "srcset",
606
- "gallery"
629
+ "gallery",
630
+ "video",
631
+ "isVideo",
632
+ "getThumbnailSrc",
633
+ "poster"
607
634
  ]
608
635
  },
609
636
  "theme-globals": {
610
637
  "title": "Theme Global Settings & Design Tokens",
611
638
  "description": "Read and create the theme's global variables and design tokens (colors, typography, breakpoints, keyframes, color schemes) from code components",
612
- "content": "The theme developer defines global settings in the editor's \"Styles\" panel. Code components can READ these at runtime and an AI agent can CREATE/LIST them via MCP tools. Prefer reusing the theme's existing tokens (colors, typography) over hardcoding values — it keeps components consistent with the store's design.\n\n### Read at runtime (in your .tsx)\n\nImport from `@ikas/bp-storefront`. These work in SSR, client hydration, and the editor canvas:\n\n```tsx\nimport {\n getThemeSetting, getThemeSettings, // global variables (Theme Settings)\n getThemeColors, getThemeTypography, // design tokens\n getThemeBreakpoints, getThemeKeyframes, getThemeColorSchemes,\n} from \"@ikas/bp-storefront\";\n\nconst brand = getThemeSetting(\"_AbC123XyZ\")?.value; // key = variableName, from list_theme_globals\nconst colors = getThemeColors(); // [{ id, name, resolved, cssVar }]\n// resolved = concrete value (e.g. \"#ff0000\"); cssVar = \"var(--<id>)\" (scheme-aware).\n// e.g. style={{ color: colors[0].cssVar }} or className={getThemeTypography()[0].className}\n```\n\nShapes: colors → `{ id, name, resolved, cssVar }`; typography → `{ id, name, resolved, className }`; breakpoints → `{ id, name, width }`; keyframes → `{ id, name, type, ref }`; color schemes → `{ schemes, values }`. Global variables → `{ name, displayName, type, value }` where `name` is the stable runtime key (`variableName`).\n\n### Responsive breakpoints in CSS\n\n`getThemeBreakpoints()` gives you each breakpoint's `width` in JS, but a CSS media query CANNOT use `var()` in its condition (it parses as valid-looking CSS and then fails SILENTLY). So to make a `@media` query follow a theme breakpoint, write the `min-width`/`max-width` yourself and use a `bp(<breakpointId>)` token for the value — the platform rewrites it to the breakpoint's concrete `<width>px` at render time (in BOTH the editor canvas and the published storefront), against the destination store's LIVE breakpoint width:\n\n```css\n/* styles.css — <breakpointId> from list_theme_globals (theme.breakpoints[].id) */\n.grid { grid-template-columns: repeat(3, 1fr); }\n\n/* applies at <= the breakpoint's width */\n@media (max-width: bp(<breakpointId>)) { .grid { grid-template-columns: 1fr; } }\n\n/* applies at > the breakpoint's width */\n@media (min-width: bp(<breakpointId>)) { .grid { grid-template-columns: repeat(4, 1fr); } }\n```\n\n- `bp(<id>)` resolves to `<width>px`. YOU pick the direction by writing `max-width` or `min-width`.\n- Use the breakpoint **id** (stable across renames), NEVER its name. Get ids from `list_theme_globals` (or the runtime `getThemeBreakpoints()` list).\n- Works anywhere in the condition, including `calc()` — e.g. for a non-overlapping upper bound use `@media (min-width: calc(bp(<id>) + 1px))` so it doesn't collide with a `max-width: bp(<id>)` block at the exact width. Inside `calc()` use PX ARITHMETIC ONLY (`+ 1px`, `* 2`, `- bp(<other>)`): the platform folds it to a concrete px value at render time, and a calc mixing other units (rem/em/vw/%) cannot fold — the whole media block is then silently dropped in production builds.\n- Portable: the token resolves to the destination store's own width, and the breakpoint ships automatically as a dependency when you reference it in CSS. Need one that might not exist everywhere? `create_theme_global` (kind `breakpoint`) it first.\n\n### Using a color scheme\n\nColor schemes have two parts: **slots** (the named color keys, e.g. Background/Text/Primary) and **palettes** (sets of colors for those slots). `getThemeColorSchemes()` returns:\n- `schemes`: the slots — `[{ id, name }]`.\n- `values`: the palettes — `[{ id, name, isDefault, className, colorsByScheme }]`, where `colorsByScheme` maps each **slot id** → `{ resolved, cssVar }`.\n\nA scheme color's `cssVar` is `var(--<slotId>)` and is **palette-scoped**: it only resolves inside an element carrying that palette's `className`. So apply the palette to a wrapper, then reference its slots inside:\n\n```tsx\nconst { values } = getThemeColorSchemes();\nconst palette = values.find((v) => v.isDefault) ?? values[0];\n// Reference slots by their id (from list_theme_globals → colorSchemes.schemes), resolving each\n// slot NAME → id ONCE here. NEVER match a slot by .name at runtime: slot names are NOT unique\n// (installing two design assets can create two \"Background\" slots), so\n// schemes.find(x => x.name === \"Background\") may silently pick the WRONG slot. A slot id is stable\n// and travels unchanged across stores, so referencing a slot by id is both correct AND portable.\nconst BACKGROUND = \"aB3xY7kLmN\", TEXT = \"pQ4rS2tUvW\", PRIMARY = \"zX8cV1bN0m\"; // real ids from list_theme_globals\nconst slot = (id: string) => palette?.colorsByScheme[id];\n\n// the palette className makes the slot vars resolve in this subtree\nreturn (\n <section\n className={palette?.className}\n style={{ background: slot(BACKGROUND)?.cssVar, color: slot(TEXT)?.cssVar }}\n >\n <button style={{ background: slot(PRIMARY)?.cssVar }}>Buy</button>\n </section>\n);\n```\n\nUse `colorsByScheme[slotId].resolved` if you need the concrete value instead of the live `var()`. Switching palettes at runtime is just swapping the wrapper's `className`.\n\n### Forcing a palette vs. inheriting the section's scheme\n\nSlot vars (`var(--<slotId>)`) resolve against whichever palette `className` sits on an **ancestor**, so you get two modes:\n\n- **Inherit the section's scheme (default, recommended):** do NOT add a palette `className` — just use the slot `cssVar`s. They resolve to the palette the section is set to. A section's color scheme is chosen in the editor (right panel → \"Color Scheme\"), which renders the section wrapper with that palette's class (`_<schemeId>`); leaving your slots unwrapped lets the merchant re-skin the component by switching the section's scheme, with no code change. The var NAMES are identical across palettes (only the value changes with the active ancestor class), so read the `{slotId → cssVar}` map from any palette and stay unwrapped:\n\n```tsx\nconst { values } = getThemeColorSchemes();\nconst palette = values.find((v) => v.isDefault) ?? values[0]; // any palette; var names match across all\n// slot ids from list_theme_globals → colorSchemes.schemes (resolve name → id once; NEVER match a\n// slot by .name at runtime — names are not unique, so a name lookup can pick the wrong slot).\nconst BACKGROUND = \"aB3xY7kLmN\", TEXT = \"pQ4rS2tUvW\", PRIMARY = \"zX8cV1bN0m\";\nconst slot = (id: string) => palette?.colorsByScheme[id]?.cssVar;\n\n// No palette className here → these inherit the SECTION's active scheme.\nreturn (\n <div style={{ background: slot(BACKGROUND), color: slot(TEXT) }}>\n <button style={{ background: slot(PRIMARY) }}>Buy</button>\n </div>\n);\n```\n\n- **Force a specific palette:** wrap the subtree in that palette's `className` (the example above). Use this only for a region that must always use one fixed palette regardless of the section's scheme.\n\n### Create / list via MCP (requires `ikas-component dev` + connected editor)\n\n- `list_theme_globals` — list every global variable and design token in the project (including ones created manually in the editor). **Call this FIRST** so you reuse existing tokens instead of duplicating them.\n- `create_theme_global` — create one, selected by `kind`:\n - `globalVariable` — `display_name` + `type` (TEXT|RICH_TEXT|IMAGE|COLOR|NUMBER|BOOLEAN|BORDER|SHADOW); `value` optional. Value shapes — TEXT/COLOR: string; RICH_TEXT: HTML string; NUMBER: number; BOOLEAN: boolean; IMAGE: `{ url }`; BORDER: `{ width: { value, unit }, style, color }`; SHADOW: `{ x, y, blur, spread, color, position: \"outside\"|\"inside\" }`.\n - `color` — `name` + `value` (hex).\n - `typography` — `name` + any of `font_family`/`font_size`/`font_weight`/`line_height`/`letter_spacing`.\n - `breakpoint` — `name` + `width`.\n - `keyframe` — `name` + `points` (`[{ point, styles? }]`); each style is `{ property, value }` with a CSS property name (opacity, transform, filter, background, color, …). Apply the keyframe's `ref` as a CSS `animation-name` and set timing (duration/iteration) where you apply it.\n - `colorScheme` — `name` + `colors` (`[{ slotId? | newSlotName?, value }]`); target an existing slot by `slotId` (its id from list_theme_globals → colorSchemes.schemes / colorsByScheme keys), or create/reuse one by `newSlotName` (use the standard slot names like \"Background\"/\"Text\"/\"PrimaryButton/Background\"). Exactly one per entry.\n\n**CLI equivalents** (if you call the ikas-component CLI directly instead of the MCP tools): read with `list-theme-globals`; create with — globalVariable→`create-global-variable`, color→`create-color`, typography→`create-text-style`, breakpoint→`create-breakpoint`, keyframe→`create-keyframe`, colorScheme→`create-color-scheme`. CLI flags are kebab-case (`--display-name`, `--font-size`, `--colors`, …) and the CLI must be run from the project root.\n\n**Update / delete:** `update_theme_global` (fix a global variable's value/type — identify by `name`) and `delete_theme_global` (`kind` globalVariable→`name`, or a design-token kind→`id`). CLI equivalents: `update-global-variable`, `delete-global-variable`, `delete-design-token`.\n\nAfter creating, the new item is readable via the runtime getters above (its key/id comes back in the create result and from `list_theme_globals`).\n\n### Live updates vs snapshots (important)\n\nTheme settings reach your component through two channels — pick the right one or edits won't reflect live:\n\n- **Live (CSS):** use `cssVar` (colors, and color-scheme colors) and `className` (typography text styles). These update **instantly** when the value is edited in the editor, because they map to CSS the editor regenerates live. Prefer these for anything visual.\n - Colors: `style={{ color: token.cssVar }}` (or `background`).\n - Typography: apply the text style's class — `className={t.className}` — do NOT spread `t.resolved` into an inline `style` if you want live updates.\n - Color-scheme colors are scoped to the palette: a `var(--<key>)` only resolves inside an element carrying that palette's `className`, so wrap the row: `<div className={paletteValue.className}>…<span style={{background: colorsByScheme[keyId].cssVar}}/>…</div>`.\n- **Snapshot (JS):** `resolved` values, breakpoint `width`, keyframe metadata, and global-variable `value`s are read from JS at render time. They reflect editor edits only when the component **re-renders/remounts** (e.g. its props change, or another action refreshes the canvas) — NOT instantly on a theme-token edit. This is expected, not a bug. Global-variable value edits do trigger a canvas refresh, so they reflect; design-token `resolved` values lag until the next refresh.\n\nRule of thumb: for visuals that must track editor edits live, reference `cssVar` / apply `className`; treat `resolved` and `value` as point-in-time reads.\n\n### Portability (shipping as a partner design asset)\n\nWhen this component is published as a partner design asset and installed into another store, only the globals it DECLARES as dependencies travel with it. Write components so their global usage stays portable:\n\n- **Expose theme global variables as props — don't hardcode keys.** A prop bound to a global variable (via its `privateVarMap`) is detected and ships with the asset. A `themeValue(\"_xyz\")` / `getThemeSetting(\"_xyz\")` call with a hardcoded key in your source is NOT detected, so that variable won't travel and resolves to nothing in the destination store. If you need a theme setting, add it as a prop and read the prop, not a hardcoded key.\n- **Iterate the runtime lists instead of hardcoding token ids.** `getThemeColors()`, `getThemeTypography()`, `getThemeKeyframes()`, `getThemeBreakpoints()`, and `getThemeColorSchemes()` return the DESTINATION store's own tokens — iterate them so the component adapts to whatever theme it lands in. A specific color/keyframe id hardcoded from the list won't exist in another store. (Color-SCHEME SLOT ids are the exception: a scheme travels in full with its slot ids intact and is matched by id on install — never re-keyed — so referencing a slot by `var(--<slotId>)` / `colorsByScheme[slotId]` stays valid across stores; resolving it by `.name` does not.)\n- **Travels automatically:** color schemes (in full — the slot/palette pattern above keeps working after install), types referenced by your props, nested code components, and shared modules.\n\nRule of thumb: read named settings through props and read colors/typography/etc. by iterating the runtime lists — both are portable; a hardcoded global id in source is not.",
639
+ "content": "The theme developer defines global settings in the editor's \"Styles\" panel. Code components can READ these at runtime and an AI agent can CREATE/LIST them via MCP tools. Prefer reusing the theme's existing tokens (colors, typography) over hardcoding values — it keeps components consistent with the store's design.\n\n### Read at runtime (in your .tsx)\n\nImport from `@ikas/bp-storefront`. These work in SSR, client hydration, and the editor canvas:\n\n```tsx\nimport {\n getThemeSetting, getThemeSettings, // global variables (Theme Settings)\n getThemeColors, getThemeTypography, // design tokens\n getThemeBreakpoints, getThemeKeyframes, getThemeColorSchemes,\n} from \"@ikas/bp-storefront\";\n\nconst brand = getThemeSetting(\"_AbC123XyZ\")?.value; // key = variableName, from list_theme_globals\nconst colors = getThemeColors(); // [{ id, name, resolved, cssVar }]\n// resolved = concrete value (e.g. \"#ff0000\"); cssVar = \"var(--<id>)\" (scheme-aware).\n// e.g. style={{ color: colors[0].cssVar }} or className={getThemeTypography()[0].className}\n```\n\nShapes: colors → `{ id, name, resolved, cssVar }`; typography → `{ id, name, resolved, className }`; breakpoints → `{ id, name, width }`; keyframes → `{ id, name, type, ref }`; color schemes → `{ schemes, values }`. Global variables → `{ name, displayName, type, value }` where `name` is the stable runtime key (`variableName`).\n\n### Responsive breakpoints in CSS\n\n`getThemeBreakpoints()` gives you each breakpoint's `width` in JS, but a CSS media query CANNOT use `var()` in its condition (it parses as valid-looking CSS and then fails SILENTLY). So to make a `@media` query follow a theme breakpoint, write the `min-width`/`max-width` yourself and use a `bp(<breakpointId>)` token for the value — the platform rewrites it to the breakpoint's concrete `<width>px` at render time (in BOTH the editor canvas and the published storefront), against the destination store's LIVE breakpoint width:\n\n```css\n/* styles.css — <breakpointId> from list_theme_globals (theme.breakpoints[].id) */\n.grid { grid-template-columns: repeat(3, 1fr); }\n\n/* applies at <= the breakpoint's width */\n@media (max-width: bp(<breakpointId>)) { .grid { grid-template-columns: 1fr; } }\n\n/* applies at > the breakpoint's width */\n@media (min-width: bp(<breakpointId>)) { .grid { grid-template-columns: repeat(4, 1fr); } }\n```\n\n- `bp(<id>)` resolves to `<width>px`. YOU pick the direction by writing `max-width` or `min-width`.\n- Use the breakpoint **id** (stable across renames), NEVER its name. Get ids from `list_theme_globals` (or the runtime `getThemeBreakpoints()` list).\n- Works anywhere in the condition, including `calc()` — e.g. for a non-overlapping upper bound use `@media (min-width: calc(bp(<id>) + 1px))` so it doesn't collide with a `max-width: bp(<id>)` block at the exact width. Inside `calc()` use PX ARITHMETIC ONLY (`+ 1px`, `* 2`, `- bp(<other>)`): the platform folds it to a concrete px value at render time, and a calc mixing other units (rem/em/vw/%) cannot fold — the whole media block is then silently dropped in production builds.\n- Portable: the token resolves to the destination store's own width, and the breakpoint ships automatically as a dependency when you reference it in CSS. Need one that might not exist everywhere? `create_theme_global` (kind `breakpoint`) it first.\n\n### Using a color scheme\n\nColor schemes have two parts: **slots** (the named color keys, e.g. Background/Text/Primary) and **palettes** (sets of colors for those slots). `getThemeColorSchemes()` returns:\n- `schemes`: the slots — `[{ id, name }]`.\n- `values`: the palettes — `[{ id, name, isDefault, className, colorsByScheme }]`, where `colorsByScheme` maps each **slot id** → `{ resolved, cssVar }`.\n\nA scheme color's `cssVar` is `var(--<slotId>)` and is **palette-scoped**: it only resolves inside an element carrying that palette's `className`. So apply the palette to a wrapper, then reference its slots inside:\n\n```tsx\nconst { values } = getThemeColorSchemes();\nconst palette = values.find((v) => v.isDefault) ?? values[0];\n// Reference slots by their id (from list_theme_globals → colorSchemes.schemes), resolving each\n// slot NAME → id ONCE here. NEVER match a slot by .name at runtime: slot names are NOT unique\n// (installing two design assets can create two \"Background\" slots), so\n// schemes.find(x => x.name === \"Background\") may silently pick the WRONG slot. A slot id is stable\n// and travels unchanged across stores, so referencing a slot by id is both correct AND portable.\nconst BACKGROUND = \"aB3xY7kLmN\", TEXT = \"pQ4rS2tUvW\", PRIMARY = \"zX8cV1bN0m\"; // real ids from list_theme_globals\nconst slot = (id: string) => palette?.colorsByScheme[id];\n\n// the palette className makes the slot vars resolve in this subtree\nreturn (\n <section\n className={palette?.className}\n style={{ background: slot(BACKGROUND)?.cssVar, color: slot(TEXT)?.cssVar }}\n >\n <button style={{ background: slot(PRIMARY)?.cssVar }}>Buy</button>\n </section>\n);\n```\n\nUse `colorsByScheme[slotId].resolved` if you need the concrete value instead of the live `var()`. Switching palettes at runtime is just swapping the wrapper's `className`.\n\n### Forcing a palette vs. inheriting the section's scheme\n\nSlot vars (`var(--<slotId>)`) resolve against whichever palette `className` sits on an **ancestor**, so you get two modes:\n\n- **Inherit the section's scheme (default, recommended):** do NOT add a palette `className` — just use the slot `cssVar`s. They resolve to the palette the section is set to. A section's color scheme is chosen in the editor (right panel → \"Color Scheme\"), which renders the section wrapper with that palette's class (`_<schemeId>`); leaving your slots unwrapped lets the merchant re-skin the component by switching the section's scheme, with no code change. The var NAMES are identical across palettes (only the value changes with the active ancestor class), so read the `{slotId → cssVar}` map from any palette and stay unwrapped:\n\n```tsx\nconst { values } = getThemeColorSchemes();\nconst palette = values.find((v) => v.isDefault) ?? values[0]; // any palette; var names match across all\n// slot ids from list_theme_globals → colorSchemes.schemes (resolve name → id once; NEVER match a\n// slot by .name at runtime — names are not unique, so a name lookup can pick the wrong slot).\nconst BACKGROUND = \"aB3xY7kLmN\", TEXT = \"pQ4rS2tUvW\", PRIMARY = \"zX8cV1bN0m\";\nconst slot = (id: string) => palette?.colorsByScheme[id]?.cssVar;\n\n// No palette className here → these inherit the SECTION's active scheme.\nreturn (\n <div style={{ background: slot(BACKGROUND), color: slot(TEXT) }}>\n <button style={{ background: slot(PRIMARY) }}>Buy</button>\n </div>\n);\n```\n\n- **Force a specific palette:** wrap the subtree in that palette's `className` (the example above). Use this only for a region that must always use one fixed palette regardless of the section's scheme.\n\n### Create / list via MCP (requires `ikas theme dev` + connected editor)\n\n- `list_theme_globals` — list every global variable and design token in the project (including ones created manually in the editor). **Call this FIRST** so you reuse existing tokens instead of duplicating them.\n- `create_theme_global` — create one, selected by `kind`:\n - `globalVariable` — `display_name` + `type` (TEXT|RICH_TEXT|IMAGE|COLOR|NUMBER|BOOLEAN|BORDER|SHADOW); `value` optional. Value shapes — TEXT/COLOR: string; RICH_TEXT: HTML string; NUMBER: number; BOOLEAN: boolean; IMAGE: `{ url }`; BORDER: `{ width: { value, unit }, style, color }`; SHADOW: `{ x, y, blur, spread, color, position: \"outside\"|\"inside\" }`.\n - `color` — `name` + `value` (hex).\n - `typography` — `name` + any of `font_family`/`font_size`/`font_weight`/`line_height`/`letter_spacing`.\n - `breakpoint` — `name` + `width`.\n - `keyframe` — `name` + `points` (`[{ point, styles? }]`); each style is `{ property, value }` with a CSS property name (opacity, transform, filter, background, color, …). Apply the keyframe's `ref` as a CSS `animation-name` and set timing (duration/iteration) where you apply it.\n - `colorScheme` — `name` + `colors` (`[{ slotId? | newSlotName?, value }]`); target an existing slot by `slotId` (its id from list_theme_globals → colorSchemes.schemes / colorsByScheme keys), or create/reuse one by `newSlotName` (use the standard slot names like \"Background\"/\"Text\"/\"PrimaryButton/Background\"). Exactly one per entry.\n\n**CLI equivalents** (if you call the ikas-component CLI directly instead of the MCP tools): read with `list-theme-globals`; create with — globalVariable→`create-global-variable`, color→`create-color`, typography→`create-text-style`, breakpoint→`create-breakpoint`, keyframe→`create-keyframe`, colorScheme→`create-color-scheme`. CLI flags are kebab-case (`--display-name`, `--font-size`, `--colors`, …) and the CLI must be run from the project root.\n\n**Update / delete:** `update_theme_global` (fix a global variable's value/type — identify by `name`) and `delete_theme_global` (`kind` globalVariable→`name`, or a design-token kind→`id`). CLI equivalents: `update-global-variable`, `delete-global-variable`, `delete-design-token`.\n\nAfter creating, the new item is readable via the runtime getters above (its key/id comes back in the create result and from `list_theme_globals`).\n\n### Live updates vs snapshots (important)\n\nTheme settings reach your component through two channels — pick the right one or edits won't reflect live:\n\n- **Live (CSS):** use `cssVar` (colors, and color-scheme colors) and `className` (typography text styles). These update **instantly** when the value is edited in the editor, because they map to CSS the editor regenerates live. Prefer these for anything visual.\n - Colors: `style={{ color: token.cssVar }}` (or `background`).\n - Typography: apply the text style's class — `className={t.className}` — do NOT spread `t.resolved` into an inline `style` if you want live updates.\n - Color-scheme colors are scoped to the palette: a `var(--<key>)` only resolves inside an element carrying that palette's `className`, so wrap the row: `<div className={paletteValue.className}>…<span style={{background: colorsByScheme[keyId].cssVar}}/>…</div>`.\n- **Snapshot (JS):** `resolved` values, breakpoint `width`, keyframe metadata, and global-variable `value`s are read from JS at render time. They reflect editor edits only when the component **re-renders/remounts** (e.g. its props change, or another action refreshes the canvas) — NOT instantly on a theme-token edit. This is expected, not a bug. Global-variable value edits do trigger a canvas refresh, so they reflect; design-token `resolved` values lag until the next refresh.\n\nRule of thumb: for visuals that must track editor edits live, reference `cssVar` / apply `className`; treat `resolved` and `value` as point-in-time reads.\n\n### Portability (shipping as a partner design asset)\n\nWhen this component is published as a partner design asset and installed into another store, only the globals it DECLARES as dependencies travel with it. Write components so their global usage stays portable:\n\n- **Expose theme global variables as props — don't hardcode keys.** A prop bound to a global variable (via its `privateVarMap`) is detected and ships with the asset. A `themeValue(\"_xyz\")` / `getThemeSetting(\"_xyz\")` call with a hardcoded key in your source is NOT detected, so that variable won't travel and resolves to nothing in the destination store. If you need a theme setting, add it as a prop and read the prop, not a hardcoded key.\n- **Iterate the runtime lists instead of hardcoding token ids.** `getThemeColors()`, `getThemeTypography()`, `getThemeKeyframes()`, `getThemeBreakpoints()`, and `getThemeColorSchemes()` return the DESTINATION store's own tokens — iterate them so the component adapts to whatever theme it lands in. A specific color/keyframe id hardcoded from the list won't exist in another store. (Color-SCHEME SLOT ids are the exception: a scheme travels in full with its slot ids intact and is matched by id on install — never re-keyed — so referencing a slot by `var(--<slotId>)` / `colorsByScheme[slotId]` stays valid across stores; resolving it by `.name` does not.)\n- **Travels automatically:** color schemes (in full — the slot/palette pattern above keeps working after install), types referenced by your props, nested code components, and shared modules.\n\nRule of thumb: read named settings through props and read colors/typography/etc. by iterating the runtime lists — both are portable; a hardcoded global id in source is not.",
613
640
  "tags": [
614
641
  "theme",
615
642
  "global variables",