[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of easy-shipping-setup/react/graphql/updateShippingPolicy.graphql from the easy-shipping-setup VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation updateShippingPolicy(
  $id: String!
  $name: String
  $shippingMethod: String
  $isHolidayActive: Boolean
  $isSaturdayActive: Boolean
  $isSundayActive: Boolean
  $largestMeasure: Float
  $maxMeasureSum: Float
  $isActive: Boolean
) {
  updateShippingPolicy(
    input: {
      id: $id
      name: $name
      shippingMethod: $shippingMethod
      isHolidayActive: $isHolidayActive
      isSaturdayActive: $isSaturdayActive
      isSundayActive: $isSundayActive
      largestMeasure: $largestMeasure
      maxMeasureSum: $maxMeasureSum
      isActive: $isActive
    }
  ) {
    id,
    name,
    shippingMethod,
    weekendAndHolidays {
      saturday,
      sunday,
      holiday
    },
    maxDimension {
      largestMeasure,
      maxMeasureSum
    },
    isActive
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of easy-shipping-setup/react/graphql/dock.graphql from the easy-shipping-setup VTEX app.

[Assistant]
Here's the implementation:

```graphql
query getAllDocks {
  listAllDocks {
    id,
    name,
    isActive
  }
}
```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of easy-shipping-setup/react/graphql/shipping.graphql from the easy-shipping-setup VTEX app.

[Assistant]
Here's the implementation:

```graphql
query getAllShippingPolicies {
  listAllShippingPolicies {
    items {
      id,
      name,
      shippingMethod,
      weekendAndHolidays {
        saturday,
        sunday,
        holiday
      },
      maxDimension {
        largestMeasure,
        maxMeasureSum
      },
      isActive
    }
  }
}
```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of easy-shipping-setup/react/graphql/createOrUpdatePromotion.graphql from the easy-shipping-setup VTEX app.

[Assistant]
Here's the implementation:

```graphql
mutation createOrUpdatePromotion(
  $newTotalValueFloor: Float,
  $promotionId: String,
  $beginDateUtc: String,
  $endDateUtc: String,
  $isActive: Boolean
) {
  createOrUpdatePromotion(
    newTotalValueFloor: $newTotalValueFloor,
    promotionId: $promotionId,
    beginDateUtc: $beginDateUtc,
    endDateUtc: $endDateUtc,
    isActive: $isActive
  ) {
    idCalculatorConfiguration,
    name,
    description,
    beginDateUtc,
    endDateUtc,
    lastModified,
    daysAgoOfPurchases,
    isActive,
    isArchived,
    isFeatured,
    activeDaysOfWeek,
    offset,
    activateGiftsMultiplier,
    newOffset,
    cumulative,
    nominalShippingDiscountValue,
    absoluteShippingDiscountValue,
    nominalDiscountValue,
    maximumUnitPriceDiscount,
    percentualDiscountValue,
    rebatePercentualDiscountValue,
    percentualShippingDiscountValue,
    percentualTax,
    shippingPercentualTax,
    percentualDiscountValueList1,
    percentualDiscountValueList2,
    skusGift {
      quantitySelectable,
      gifts {
        id,
        name,
        quantity,
        sellers {
          id,
          name,
        }
      }
    },
    nominalRewardValue,
    percentualRewardValue,
    orderStatusRewardValue,
    maxNumberOfAffectedItems,
    maxNumberOfAffectedItemsGroupKey,
    applyToAllShippings,
    nominalTax,
    origin,
    idSellerIsInclusive,
    idsSalesChannel,
    areSalesChannelIdsExclusive,
    marketingTags,
    marketingTagsAreNotInclusive,
    paymentsMethods,
    campaigns,
    categories,
    categoriesAreInclusive,
    brands,
    brandsAreInclusive,
    products,
    productsAreInclusive,
    skus,
    skusAreInclusive,
    collections1BuyTogether,
    minimumQuantityBuyTogether,
    quantityToAffectBuyTogether,
    enableBuyTogetherPerSku,
    listSku1BuyTogether,
    listSku2BuyTogether,
    totalValueFloor,
    totalValueCeling,
    totalValueMode,
    collections,
    collectionsIsInclusive,
    restrictionsBins,
    totalValuePurchase,
    slasIds,
    isSlaSelected,
    isFirstBuy,
    firstBuyIsProfileOptimistic,
    compareListPriceAndPrice,
    isDifferentListPriceAndPrice,
    zipCodeRanges,
    itemMaxPrice,
    itemMinPrice,
    isMinMaxInstallments,
    minInstallment,
    maxInstallment,
    clusterExpressions,
    clusterOperator,
    giftListTypes,
    affiliates,
    maxUsage,
    maxUsagePerClient,
    multipleUsePerClient,
    type,
    useNewProgressiveAlgorithm
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of easy-shipping-setup/react/graphql/freight.graphql from the easy-shipping-setup VTEX app.

[Assistant]
Here's the implementation:

```graphql
query getShippingRate($carrierId: String!, $zipCode: String!) {
  listShippingRate(carrierId: $carrierId, zipCode: $zipCode) {
    zipCodeStart
    zipCodeEnd
    weightStart
    weightEnd
    absoluteMoneyCost
    pricePercent
    pricePercentByWeight
    maxVolume
    timeCost
    country
    operationType
    polygon
    minimumValueInsurance
  }
}
```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/messages/pt.json from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/test": "teste",
  "store/test": "teste"
}
```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/messages/en.json from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/test": "test",
  "store/test": "test"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/messages/es.json from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "admin/test": "teste",
  "store/test": "teste"
}
```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/docs/README.md from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```markdown
##  ⚠ Maintenance ⚠
*Starting September 1st 2022, this application will no longer be maintained by VTEX. Code is released for free under the GNU/PL Agreement for you to use and modify at your convenience. The VTEX repository shall remain unchanged with the original version.*

---

# Fixed prices app

<!-- DOCS-IGNORE:start -->
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->
<!-- DOCS-IGNORE:end -->

Under the app's name, you should explain the topic, giving a **brief description** of its **functionality** in a store when installed.

Next, **add media** (either an image of a GIF) with the rendered components, so that users can better understand how the app works in practice.

![Media Placeholder](https://user-images.githubusercontent.com/52087100/71204177-42ca4f80-227e-11ea-89e6-e92e65370c69.png)

## Configuration

In this section, you first must **add the primary instructions** that will allow users to use the app's blocks in their store, such as:

1. Adding the app as a theme dependency in the `manifest.json` file;
2. Declaring the app's main block in a given theme template or inside another block from the theme.

Remember to add a table with all blocks exported by the app and their descriptions. You can verify an example of it on the [Search Result documentation](https://vtex.io/docs/components/all/vtex.search-result@3.56.1/).

Next, add the **props table** containing your block's props.

If the app exports more than one block, create several tables - one for each block. For example:

### `block-1` props

| Prop name    | Type            | Description    | Default value                                                                                |
| ------------ | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `XXXXX`      | `XXXXXX`       | XXXXXXXX         | `XXXXXX`        |

### `block-2` props

| Prop name    | Type            | Description    | Default value                                                                                |
| ------------ | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `XXXXX`      | `XXXXXX`       | XXXXXXXX         | `XXXXXX`        |

Prop types are:

- `string`
- `enum`
- `number`
- `boolean`
- `object`
- `array`

When documenting a prop whose type is `object` or `array` another prop table will be needed. You can create it following the example below:

- `propName` object:

| Prop name    | Type            | Description    | Default value                                                                                |
| ------------ | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `XXXXX`      | `XXXXXX`       | XXXXXXXX         | `XXXXXX`        |

Remember to also use this Configuration section to  **showcase any necessary disclaimer** related to the app and its blocks, such as the different behavior it may display during its configuration.

## Modus Operandi *(not mandatory)*

There are scenarios in which an app can behave differently in a store, according to how it was added to the catalog, for example. It's crucial to go through these **behavioral changes** in this section, allowing users to fully understand the **practical application** of the app in their store.

If you feel compelled to give further details about the app, such as it's **relationship with the VTEX admin**, don't hesitate to use this section.

## Customization

The first thing that should be present in this section is the sentence below, showing users the recipe pertaining to CSS customization in apps:

`In order to apply CSS customizations in this and other blocks, follow the instructions given in the recipe on [Using CSS Handles for store customization](https://vtex.io/docs/recipes/style/using-css-handles-for-store-customization).`

Thereafter, you should add a single column table with the available CSS handles for the app, like the one below. Note that the Handles must be ordered alphabetically.

| CSS Handles |
| ----------- |
| `XXXXX` |
| `XXXXX` |
| `XXXXX` |
| `XXXXX` |
| `XXXXX` |

If there are none, add the following sentence instead:

`No CSS Handles are available yet for the app customization.`

<!-- DOCS-IGNORE:start -->

## Contributors ✨

Thanks goes to these wonderful people:

<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->

This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!

<!-- DOCS-IGNORE:end -->

----

Check out some documentation models that are already live:
- [Breadcrumb](https://github.com/vtex-apps/breadcrumb)
- [Image](https://vtex.io/docs/components/general/vtex.store-components/image)
- [Condition Layout](https://vtex.io/docs/components/all/vtex.condition-layout@1.1.6/)
- [Add To Cart Button](https://vtex.io/docs/components/content-blocks/vtex.add-to-cart-button@0.9.0/)
- [Store Form](https://vtex.io/docs/components/all/vtex.store-form@0.3.4/)

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/graphql/schema.graphql from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```graphql
type Pricelist {
    tradePolicyId: String,
    value: Float,
    listPrice: Float,
    minQuantity: Int
}

type Query{
    getFixedPrice(skuId: String!, tableName: String!): [Pricelist]
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/node/service.json from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "memory": 512,
  "ttl": 10,
  "timeout": 200,
  "minReplicas": 2,
  "maxReplicas": 4,
  "workers": 2,
  "routes": {

    "prices": {
      "path": "/v0/demo/prices/:itemId/:priceTableId",
      "public": true
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/node/package.json from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "dependencies": {
    "co-body": "^6.0.0",
    "ramda": "^0.25.0"
  },
  "devDependencies": {
    "@types/co-body": "^0.0.3",
    "@types/jest": "^24.0.18",
    "@types/node": "^12.0.0",
    "@types/ramda": "types/npm-ramda#dist",
    "@vtex/api": "6.45.12",
    "@vtex/test-tools": "^1.0.0",
    "@vtex/tsconfig": "^0.5.6",
    "typescript": "3.9.7",
    "vtex.product-context": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-context@0.10.0/public/@types/vtex.product-context",
    "vtex.search-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.search-graphql@0.50.0/public/@types/vtex.search-graphql",
    "vtex.store-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-graphql@2.157.1/public/@types/vtex.store-graphql"
  },
  "scripts": {
    "lint": "tsc --noEmit --pretty"
  },
  "version": "0.2.0"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/node/index.ts from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { ClientsConfig, ServiceContext } from '@vtex/api'
import { LRUCache, method, Service } from '@vtex/api'
import { Clients } from './clients'
import { getPrices } from './middlewares/getPrices'
import { getFixedPrice } from './resolvers/fixedprices'

const TIMEOUT_MS = 2000

// Create a LRU memory cache for the Status client.
// The @vtex/api HttpClient respects Cache-Control headers and uses the provided cache.
const memoryCache = new LRUCache<string, any>({ max: 5000 })

metrics.trackCache('status', memoryCache)

// This is the configuration for clients available in `ctx.clients`.
const clients: ClientsConfig<Clients> = {
  // We pass our custom implementation of the clients bag, containing the Status client.
  implementation: Clients,
  options: {
    // All IO Clients will be initialized with these options, unless otherwise specified.
    default: {
      retries: 2,
      timeout: TIMEOUT_MS,
    },
    // This key will be merged with the default options and add this cache to our Status client.
    demo: {
      memoryCache,
    },
  },
}

declare global {
  // We declare a global Context type just to avoid re-writing ServiceContext<Clients, State> in every handler and resolver
  type Context = ServiceContext<Clients>
}

// Export a service that defines route handlers and client options.
export default new Service({
  clients,
  routes: {
    // `prices` is the route ID from service.json. It maps to an array of middlewares (or a single handler).
    prices: method({
      GET: [getPrices],
    }),
  },
  graphql: {
    resolvers: {
      Query: {
        getFixedPrice
      }
    }
  }
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/react/package.json from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "fixed-prices-app",
  "version": "0.0.0",
  "scripts": {
    "test": "vtex-test-tools test"
  },
  "dependencies": {
    "apollo-client": "^2.6.8",
    "react": "^16.12.0",
    "react-apollo": "^3.1.3",
    "react-dom": "^16.12.0",
    "react-intl": "^3.12.0"
  },
  "devDependencies": {
    "@apollo/react-testing": "^3.1.3",
    "@types/jest": "^25.1.4",
    "@types/node": "^13.9.8",
    "@types/react": "^16.9.31",
    "@vtex/test-tools": "^3.3.2",
    "@vtex/tsconfig": "^0.4.4",
    "apollo-cache-inmemory": "^1.6.5",
    "graphql": "^14.6.0",
    "typescript": "3.9.7",
    "vtex.product-context": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-context@0.10.0/public/@types/vtex.product-context",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.132.4/public/@types/vtex.render-runtime",
    "vtex.search-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.search-graphql@0.50.0/public/@types/vtex.search-graphql",
    "vtex.store-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-graphql@2.157.1/public/@types/vtex.store-graphql"
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/react/FixedPrice.tsx from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import ClientSide from './components/ClientSide'
import Prices from './components/Prices'

function FixedPrice() {

  return (
    <ClientSide>
      <Prices/>
    </ClientSide>
  )

}

export default FixedPrice

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/store/interfaces.json from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```json
{
    "fixed-price": {
        "component": "FixedPrice"
    }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/node/clients/prices.ts from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { InstanceOptions, IOContext } from '@vtex/api'
import { JanusClient } from '@vtex/api'

export default class PricesClient extends JanusClient {
  constructor(context: IOContext, options?: InstanceOptions) {
    super(context,
      {
        ...options,
        headers: {
          VtexIdClientAutCookie: context.authToken,
        },
      }
    )
  }

  public async getFixedPricesFromTable(itemId: string | string [], priceTableId: string | string [] ) {
    return this.http.getRaw(`http://api.vtex.com/${this.context.account}/pricing/prices/${itemId}/fixed/${priceTableId}`)
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/node/clients/index.ts from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { IOClients } from '@vtex/api'
import PricesClient from './prices'

// Extend the default IOClients implementation with our own custom clients.
export class Clients extends IOClients {

  public get prices() {
    return this.getOrSet('prices', PricesClient)
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/node/middlewares/getPrices.ts from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
export async function getPrices(ctx: Context, next: () => Promise<any>) {
  const {
    vtex: {
      route: { params },
    },

  } = ctx

  console.info('Received params:', params)

  const { itemId,
    priceTableId } = params

  console.info('Received itemId:', itemId)
  console.info('Received priceTableId:', priceTableId)

  const response = await ctx.clients.prices.getFixedPricesFromTable(itemId, priceTableId)

  console.info('Status response:', response)

  if (response.status === 200){
    ctx.status = response.status
    ctx.body = response.data
  } else {
    ctx.body = 'Error'
  }

  await next()
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/node/resolvers/fixedprices.ts from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
interface Args{
    skuId: string,
    tableName: string
}

export const getFixedPrice = async (
    _: any,
    { skuId, tableName }: Args,
    { clients }: Context
) => {
    const { data } = await clients.prices.getFixedPricesFromTable( skuId, tableName )
    return data
}
```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/react/typings/gql.d.ts from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module '*.gql' {
  import { DocumentNode } from 'graphql'

  const Schema: DocumentNode

  export default Schema
}

declare module '*.graphql' {
  import { DocumentNode } from 'graphql'

  const schema: DocumentNode

  export default schema
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/react/typings/css.d.ts from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module '*.css' {
  type Styles = {
    [selector: string]: string
  }

  const styles: Styles

  export default styles
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/react/components/ClientSide.tsx from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useEffect, useState } from 'react'
import type { PropsWithChildren } from 'react'

function ClientSide ({children}: PropsWithChildren<unknown>) {
  const [hydrated, setHydrated] = useState(false)

  useEffect(() => setHydrated(true), [])

  return hydrated ? <>{children}</> : null
}

export default ClientSide

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/react/components/Prices.tsx from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { useQuery } from 'react-apollo'
import getFixedPrice from '../graphql/getFixedPrice.gql'
import { useProduct } from 'vtex.product-context'

interface queryOpt {
  skuId: string,
  tableName: string
}

interface queryData {
  getFixedPrice: [
    {
      value: number,
      minQuantity: number
    }
  ]
}

function Prices() {

  // Get the product context value for the selected Sku
  const productContextValue = useProduct();
  const selectedItem = productContextValue?.selectedItem?.itemId || "";

  // CHANGE_HERE your table name
  const tableName = '2';

  const { data, loading, error } = useQuery<queryData, queryOpt>(getFixedPrice, {
    variables: {
      "skuId": selectedItem,
      "tableName": tableName
    }
  })

  if (selectedItem){
    if (loading){
      console.log("Loading");
    } else {
      if (error){
        console.log('----error----', error);
        return null;
      } else if (data){
        console.log('----data----', data.getFixedPrice);
      }
    }
  }

  // Customize the information to be displayed on the front here:
  return <div>
            <p>SkuId: {selectedItem}</p>
            <p>Fixed price: {data?.getFixedPrice[0].value}</p>
            <p>minQuantity: {data?.getFixedPrice[0].minQuantity}</p>
        </div>
}

export default Prices

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of fixed-prices-app/react/graphql/getFixedPrice.gql from the fixed-prices-app VTEX app.

[Assistant]
Here's the implementation:

```graphql
query test($skuId: String!, $tableName: String!){
  getFixedPrice(skuId: $skuId, tableName: $tableName)
  @context(provider: "vtexarg.fixed-app"){
    tradePolicyId
    value
    listPrice
    minQuantity
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-profile/messages/pt.json from the checkout-profile VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/checkout-profile-email-info": "Preencher informações para",
  "store/checkout-profile-logout-label": "Não é você? Sair",
  "store/checkout-profile-first-name-label": "Nome",
  "store/checkout-profile-last-name-label": "Sobrenome",
  "store/checkout-profile-phone-label": "Número de telefone",
  "store/checkout-profile-document-label": "Documento",
  "store/checkout-profile-save-info-label": "Salvar minhas informações para compras futuras.",
  "store/checkout-profile-newsletter-optin-label": "Quero receber email promocionais.",
  "store/checkout-profile-continue-button-label": "Continuar",
  "store/checkout-profile-field-required-message": "Campo é obrigatório",
  "store/checkout-profile-invalid-phone-message": "Número de telefone inválido",
  "store/checkout-profile-invalid-document-message": "CPF inválido",
  "store/checkout-profile-submit-error-message": "Aconteceu um erro ao enviar seus dados. Por favor, tente novamente."
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-profile/messages/en.json from the checkout-profile VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/checkout-profile-email-info": "Fill info for",
  "store/checkout-profile-logout-label": "Not you? Logout",
  "store/checkout-profile-first-name-label": "First name",
  "store/checkout-profile-last-name-label": "Last name",
  "store/checkout-profile-phone-label": "Phone number",
  "store/checkout-profile-document-label": "Document",
  "store/checkout-profile-save-info-label": "Save my info for future purchases.",
  "store/checkout-profile-newsletter-optin-label": "I want to receive the newsletter.",
  "store/checkout-profile-continue-button-label": "Continue",
  "store/checkout-profile-field-required-message": "Field is required",
  "store/checkout-profile-invalid-phone-message": "Invalid phone number",
  "store/checkout-profile-invalid-document-message": "Invalid document number",
  "store/checkout-profile-submit-error-message": "An error has ocurred when submitting your data. Please try again."
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-profile/messages/ar.json from the checkout-profile VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "store/checkout-profile-email-info": "املأ المعلومات لـ",
  "store/checkout-profile-logout-label": "هذا ليس أنت؟ سجل خروجك",
  "store/checkout-profile-first-name-label": "الإسم الأول",
  "store/checkout-profile-last-name-label": "الإسم الأخير",
  "store/checkout-profile-phone-label": "رقم الهاتف",
  "store/checkout-profile-document-label": "الوثيقة",
  "store/checkout-profile-save-info-label": "احفظ معلوماتي للمشتريات المستقبلية.",
  "store/checkout-profile-newsletter-optin-label": "أريد تلقي الرسائل الإخبارية.",
  "store/checkout-profile-continue-button-label": "مواصلة",
  "store/checkout-profile-field-required-message": "حقل مطلوب",
  "store/checkout-profile-invalid-phone-message": "رقم هاتف غير صالح",
  "store/checkout-profile-invalid-document-message": "رقم مستند غير صالح",
  "store/checkout-profile-submit-error-message": "حدث خطأ عند إرسال البيانات الخاصة بك. حاول مرة اخرى."
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-profile/docs/README.md from the checkout-profile VTEX app.

[Assistant]
Here's the implementation:

```markdown
# Checkout Profile

This app contains a Profile Form, and a Profile Preview component, used in the checkout to
update the information inside the `orderForm`.

![image](https://user-images.githubusercontent.com/10223856/77474172-65c44c80-6df5-11ea-9709-88c163dcaeef.png)

## Usage

To use this app, first include it in your `manifest.json` dependencies.

```json
{
  "dependencies": {
    "vtex.checkout-profile": "0.x"
  }
}
```

> If you are using TypeScript, you may also want to run `vtex setup` after the step above

Then, you can import the component and use it

```jsx
import React from 'react'
import { ProfilePreview, ProfileForm } from 'vtex.checkout-profile'

const Form = ({ isPreviewMode = false }) => {
  if (isPreviewMode) {
    return (
      <ProfilePreview />
    )
  }

  return (
    // no need to pass in any props, as the component
    // uses all information provided by the `order-manager` app.
    <ProfileForm />
  )
}
```

Note that you need to have `OrderFormProvider` from `vtex.order-manager` app somewhere above this
component in your tree.

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-profile/react/ProfileSummary.tsx from the checkout-profile VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { OrderForm } from 'vtex.order-manager'
import { FormattedMessage } from 'react-intl'
import { ButtonPlain } from 'vtex.styleguide'
import { useRuntime } from 'vtex.render-runtime'

const ProfileSummary: React.FC = () => {
  const { rootPath = '' } = useRuntime()
  const { orderForm } = OrderForm.useOrderForm()

  if (!orderForm.clientProfileData) {
    return null
  }

  const {
    clientProfileData: { firstName, lastName, email },
  } = orderForm

  const fullName = firstName && lastName && `${firstName} ${lastName}`

  return (
    <div className="flex flex-column c-muted-1">
      <div className="mb4 lh-title flex items-center">
        {fullName && <span>{fullName}</span>}{' '}
        {(!orderForm.canEditData || orderForm.loggedIn) && (
          <div className="ml4">
            <ButtonPlain
              href={`${rootPath}/checkout/changeToAnonymousUser/${orderForm.id}`}
              testId="profile-logout-button"
            >
              <FormattedMessage id="store/checkout-profile-logout-label" />
            </ButtonPlain>
          </div>
        )}
      </div>
      <span className="db lh-title">{email}</span>
    </div>
  )
}

export default ProfileSummary

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-profile/react/ProfileForm.tsx from the checkout-profile VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, {
  useState,
  useCallback,
  useRef,
  useReducer,
  useEffect,
  useMemo,
} from 'react'
import { defineMessages, useIntl, MessageDescriptor } from 'react-intl'
import { OrderForm } from 'vtex.order-manager'
import { OrderProfile } from 'vtex.order-profile'
import { Input, Checkbox, Button, ButtonPlain, IconEdit } from 'vtex.styleguide'
import { useRuntime } from 'vtex.render-runtime'
import { PhoneField, PhoneContext } from 'vtex.phone-field'
import { DocumentField } from 'vtex.document-field'
import { Router } from 'vtex.checkout-container'
import { useQuery } from 'react-apollo'

import phoneDataQuery from './graphql/phoneDataQuery.gql'

const messages = defineMessages({
  emailInfo: {
    id: 'store/checkout-profile-email-info',
  },
  firstNameLabel: {
    id: 'store/checkout-profile-first-name-label',
  },
  lastNameLabel: {
    id: 'store/checkout-profile-last-name-label',
  },
  phoneLabel: {
    id: 'store/checkout-profile-phone-label',
  },
  documentLabel: {
    id: 'store/checkout-profile-document-label',
  },
  saveInfoLabel: {
    id: 'store/checkout-profile-save-info-label',
  },
  newsletterOptinLabel: {
    id: 'store/checkout-profile-newsletter-optin-label',
  },
  continueButtonLabel: {
    id: 'store/checkout-profile-continue-button-label',
  },
  fieldRequiredMessage: {
    id: 'store/checkout-profile-field-required-message',
  },
  invalidPhoneMessage: {
    id: 'store/checkout-profile-invalid-phone-message',
  },
  invalidDocumentMessage: {
    id: 'store/checkout-profile-invalid-document-message',
  },
  submitErrorMessage: {
    id: 'store/checkout-profile-submit-error-message',
  },
})

type FieldState<T> = {
  value: T
  blur?: boolean
} & (
  | {
      error?: undefined
      isValid: true
    }
  | { error: MessageDescriptor; isValid: false }
)

type ProfileState = {
  firstName: FieldState<string>
  lastName: FieldState<string>
  phone: FieldState<string>
  documentType: FieldState<string>
  document: FieldState<string>
}

type ProfileAction = { field: keyof ProfileState } & (
  | {
      type: 'update'
      value: string
      isValid?: boolean
    }
  | {
      type: 'set_error'
      isValid: boolean
      error: MessageDescriptor | undefined
    }
  | { type: 'blur' }
  | { type: 'focus' }
)

const profileReducer = (
  profile: ProfileState,
  action: ProfileAction
): ProfileState => {
  const { field } = action
  switch (action.type) {
    case 'update': {
      const { value, isValid } = action
      const newField = {
        ...profile[field],
        value,
        isValid: isValid ?? profile[field].isValid,
      }

      return {
        ...profile,
        [field]: newField,
      }
    }
    case 'set_error': {
      const { error, isValid } = action
      return {
        ...profile,
        [field]: {
          ...profile[field],
          error,
          isValid,
        },
      }
    }
    case 'blur': {
      return {
        ...profile,
        [field]: {
          ...profile[field],
          blur: true,
        },
      }
    }
    case 'focus': {
      return {
        ...profile,
        [field]: { ...profile[field], focus: true },
      }
    }
    default: {
      return profile
    }
  }
}

const ProfileForm: React.FC = () => {
  const { orderForm } = OrderForm.useOrderForm()
  const {
    setOrderProfile,
    setClientPreferencesData,
  } = OrderProfile.useOrderProfile()
  const { navigate } = useRuntime()
  const intl = useIntl()
  const history = Router.useHistory()

  const { data } = useQuery(phoneDataQuery)

  const [loading, setLoading] = useState(false)
  const [submitFailed, setSubmitFailed] = useState(false)
  const phoneContainerRef = useRef<HTMLDivElement>(null)
  const phoneInputRef = useRef<HTMLInputElement>(null)

  const [persistInfo, setPersistInfo] = useState(false)
  const [optInNewsletter, setOptInNewsletter] = useState(
    orderForm.clientPreferencesData?.optInNewsletter ?? false
  )

  const [profileData, dispatch] = useReducer<
    React.Reducer<ProfileState, ProfileAction>
  >(profileReducer, {
    firstName: {
      value: orderForm.clientProfileData?.firstName ?? '',
      isValid: true,
    },
    lastName: {
      value: orderForm.clientProfileData?.lastName ?? '',
      isValid: true,
    },
    phone: { value: orderForm.clientProfileData?.phone ?? '', isValid: true },
    documentType: {
      value: orderForm.clientProfileData?.documentType ?? 'cpf',
      isValid: true,
    },
    document: {
      value: orderForm.clientProfileData?.document ?? '',
      isValid: true,
    },
  })

  const emailRef = useRef(orderForm.clientProfileData?.email)

  const validateField = useCallback(
    <T extends any>(fieldName: keyof ProfileState, field: FieldState<T>) => {
      if (!field.value && (field.isValid ?? true)) {
        dispatch({
          type: 'set_error',
          field: fieldName,
          isValid: false,
          error: messages.fieldRequiredMessage,
        })
      }
    },
    []
  )

  useEffect(() => {
    Object.entries(profileData).forEach(([fieldName, field]) =>
      validateField(fieldName as keyof ProfileState, field)
    )
  }, [profileData, validateField])

  const handleEditEmail = useCallback(() => {
    navigate({ page: 'store.checkout.identification' })
  }, [navigate])

  const handlePersistInfoChange: React.ChangeEventHandler<HTMLInputElement> = evt => {
    setPersistInfo(evt.target.checked)
  }

  const handleOptinNewsletterChange: React.ChangeEventHandler<HTMLInputElement> = evt => {
    setOptInNewsletter(evt.target.checked)
  }

  const handleChange: React.ChangeEventHandler<HTMLInputElement> = evt => {
    dispatch({
      type: 'update',
      field: evt.target.name as keyof ProfileState,
      value: evt.target.value,
      isValid: evt.target.value.length > 0,
    })
  }

  const handleDocumentChange = ({
    document,
    documentType,
    isValid,
  }: {
    document: string
    documentType: string
    isValid: boolean
  }) => {
    dispatch({
      type: 'update',
      field: 'document',
      value: document,
      isValid,
    })

    dispatch({
      type: 'update',
      field: 'documentType',
      value: documentType,
    })

    if (!isValid) {
      dispatch({
        type: 'set_error',
        field: 'document',
        isValid: false,
        error:
          document.length > 0
            ? messages.invalidDocumentMessage
            : messages.fieldRequiredMessage,
      })
    }
  }

  const handleBlur: React.FocusEventHandler<HTMLInputElement> = evt => {
    dispatch({
      type: 'blur',
      field: evt.target.name as keyof ProfileState,
    })
  }

  const handleFocus: React.FocusEventHandler<HTMLInputElement> = evt => {
    dispatch({
      type: 'focus',
      field: evt.target.name as keyof ProfileState,
    })
  }

  const handlePhoneBlur: React.FocusEventHandler<HTMLInputElement> = () => {
    // this timeout is needed because the phone field component focus
    // the listbox button after the change handler, so we need to wait
    // for the next tick when the focus has been potentially changed to it
    setTimeout(() => {
      if (
        document.activeElement == null ||
        // consider that the listbox is also our "input", so we won't trigger
        // the error message if the user is selecting the country calling code
        (document.activeElement !== phoneInputRef.current &&
          !document.activeElement.matches('[data-reach-listbox-list=""]') &&
          !(
            phoneContainerRef.current!.compareDocumentPosition(
              document.activeElement
            ) & Node.DOCUMENT_POSITION_CONTAINED_BY
          ))
      ) {
        dispatch({
          type: 'blur',
          field: 'phone',
        })
      }
    }, 0)
  }

  const handleSubmit: React.FormEventHandler<HTMLFormElement> = async evt => {
    evt.preventDefault()

    setSubmitFailed(false)

    if (Object.values(profileData).some(({ isValid }) => !isValid)) {
      // send blur event to all fields so it's clear to the user which
      // fields are in an invalid state.
      Object.keys(profileData).forEach(field =>
        dispatch({ type: 'blur', field: field as keyof ProfileState })
      )
      return
    }

    setLoading(true)

    const profileDataValues: {
      [field in keyof ProfileState]: ProfileState[field]['value']
    } = Object.keys(profileData).reduce(
      (profile, fieldName) => ({
        ...profile,
        [fieldName]: profileData[fieldName as keyof ProfileState].value,
      }),
      {} as any
    )

    try {
      const [
        { success: profileUpdateSuccess },
        { success: clientPreferencesUpdateSuccess },
      ] = await Promise.all([
        setOrderProfile({
          ...profileDataValues,
          email: emailRef.current,
        }),
        setClientPreferencesData({ optInNewsletter }),
      ])

      if (profileUpdateSuccess && clientPreferencesUpdateSuccess) {
        history.push('/shipping')
      } else {
        setSubmitFailed(true)
        setLoading(false)
      }
    } catch (err) {
      setSubmitFailed(true)
      setLoading(false)
    }
  }

  const handlePhoneChange = ({
    value,
    isValid,
  }: {
    value: string
    isValid: boolean
  }) => {
    dispatch({
      type: 'update',
      field: 'phone',
      value,
      isValid,
    })

    if (!isValid) {
      dispatch({
        type: 'set_error',
        field: 'phone',
        isValid: false,
        error: messages.invalidPhoneMessage,
      })
    }
  }

  const phoneRules = useMemo(
    () =>
      data?.countriesData.map(({ countryISO, phone }: any) => ({
        countryISO,
        ...phone,
      })) ?? [],
    [data]
  )

  return (
    <>
      <div>
        <span className="t-body fw6 flex items-center">
          {intl.formatMessage(messages.emailInfo)}{' '}
          <div className="dib ml4">
            <ButtonPlain onClick={handleEditEmail}>
              <IconEdit solid />
            </ButtonPlain>
          </div>
        </span>
        <span className="dib mt3">{emailRef.current}</span>
      </div>
      <form className="mt6" onSubmit={handleSubmit}>
        <div className="flex flex-column flex-row-ns">
          <div className="w-100" data-testid="profile-first-name-wrapper">
            <Input
              label={intl.formatMessage(messages.firstNameLabel)}
              name="firstName"
              value={profileData.firstName.value}
              errorMessage={
                (profileData.firstName.blur &&
                  !profileData.firstName.isValid &&
                  intl.formatMessage(profileData.firstName.error)) ||
                undefined
              }
              onChange={handleChange}
              onBlur={handleBlur}
              onFocus={handleFocus}
            />
          </div>
          <div
            className="w-100 mt6 mt0-ns ml0 ml5-ns"
            data-testid="profile-last-name-wrapper"
          >
            <Input
              label={intl.formatMessage(messages.lastNameLabel)}
              name="lastName"
              value={profileData.lastName.value}
              errorMessage={
                (profileData.lastName.blur &&
                  !profileData.lastName.isValid &&
                  intl.formatMessage(profileData.lastName.error)) ||
                undefined
              }
              onChange={handleChange}
              onBlur={handleBlur}
              onFocus={handleFocus}
            />
          </div>
        </div>
        <div className="flex flex-column flex-row-ns mt6">
          <div
            className="w-100 flex-auto"
            ref={phoneContainerRef}
            data-testid="profile-phone-wrapper"
          >
            <PhoneContext.PhoneContextProvider rules={phoneRules}>
              <PhoneField
                ref={phoneInputRef}
                label={intl.formatMessage(messages.phoneLabel)}
                value={profileData.phone.value}
                name="phone"
                onChange={handlePhoneChange}
                onBlur={handlePhoneBlur}
                onFocus={handleFocus}
                disabled={!data}
                errorMessage={
                  (profileData.phone.blur &&
                    !profileData.phone.isValid &&
                    intl.formatMessage(profileData.phone.error)) ||
                  undefined
                }
              />
            </PhoneContext.PhoneContextProvider>
          </div>
          <div
            className="w-100 flex-auto mt6 mt0-ns ml0 ml5-ns"
            data-testid="profile-document-wrapper"
          >
            <DocumentField
              document={profileData.document.value}
              documentType={profileData.documentType.value}
              label={intl.formatMessage(messages.documentLabel)}
              name="document"
              errorMessage={
                (profileData.document.blur &&
                  !profileData.document.isValid &&
                  intl.formatMessage(profileData.document.error)) ||
                undefined
              }
              onChange={handleDocumentChange}
              onBlur={handleBlur}
              onFocus={handleFocus}
            />
          </div>
        </div>
        <div className="mv7">
          {orderForm.userProfileId == null && (
            <Checkbox
              id="save-personal-info"
              label={intl.formatMessage(messages.saveInfoLabel)}
              checked={persistInfo}
              onChange={handlePersistInfoChange}
            />
          )}
          <div className="mt6">
            <Checkbox
              id="optin-newsletter"
              label={intl.formatMessage(messages.newsletterOptinLabel)}
              checked={optInNewsletter}
              onChange={handleOptinNewsletterChange}
            />
          </div>
        </div>
        <div data-testid="profile-continue-wrapper">
          <Button
            size="large"
            type="submit"
            block
            disabled={loading}
            isLoading={loading}
          >
            <span className="f5">
              {intl.formatMessage(messages.continueButtonLabel)}
            </span>
          </Button>
        </div>
        {submitFailed && (
          <span className="dib mt5 t-auxiliary c-danger">
            {intl.formatMessage(messages.submitErrorMessage)}
          </span>
        )}
      </form>
    </>
  )
}

export default ProfileForm

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-profile/react/package.json from the checkout-profile VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "checkout-profile",
  "version": "0.3.1",
  "private": true,
  "license": "UNLICENSED",
  "dependencies": {
    "msk": "^1.0.5",
    "react": "^16.13.0",
    "react-apollo": "^3.1.5",
    "react-intl": "^3.12.1"
  },
  "devDependencies": {
    "@types/node": "^13.9.0",
    "@types/react": "^16.9.23",
    "vtex.checkout-container": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-container@0.4.1/public/@types/vtex.checkout-container",
    "vtex.document-field": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.document-field@0.1.1/public/@types/vtex.document-field",
    "vtex.order-manager": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-manager@0.8.5/public/@types/vtex.order-manager",
    "vtex.order-profile": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-profile@0.2.0/public/@types/vtex.order-profile",
    "vtex.phone-field": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.phone-field@0.1.4/public/@types/vtex.phone-field",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.106.0/public/@types/vtex.render-runtime",
    "vtex.styleguide": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.121.0/public/@types/vtex.styleguide"
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-profile/react/typings/vtex.render-runtime.d.ts from the checkout-profile VTEX app.

[Assistant]
Here's the implementation:

```typescript
import * as Runtime from 'vtex.render-runtime'

declare module 'vtex.render-runtime' {
  export const useRuntime: () => Runtime.RenderContext
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-profile/react/typings/graphql.d.ts from the checkout-profile VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module '*.gql' {
  import { DocumentNode } from 'graphql'

  const query: DocumentNode

  export default query
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-profile/react/typings/vtex.styleguide.d.ts from the checkout-profile VTEX app.

[Assistant]
Here's the implementation:

```typescript
/* eslint-disable import/order */

import * as Styleguide from 'vtex.styleguide'

declare module 'vtex.styleguide' {
  import React from 'react'

  export const Input: React.FC

  export const Checkbox: React.FC

  export const Button: React.FC

  export const Dropdown: React.FC

  export const IconEdit: React.FC
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-profile/react/graphql/phoneDataQuery.gql from the checkout-profile VTEX app.

[Assistant]
Here's the implementation:

```graphql
query PhoneData {
  countriesData: allCountriesData {
    countryISO
    phone {
      countryCode
      mask
      pattern
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-components/react/IconCaretRight.tsx from the checkout-components VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'

const IconCaretRight: React.VFC<React.SVGAttributes<SVGSVGElement>> = props => {
  return (
    <svg
      {...props}
      width="9"
      height="12"
      viewBox="0 0 9 12"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
    >
      <path
        d="M8.32257 5.28071L2.29707 0.280712C2.06979 0.0985538 1.76538 -0.00224062 1.4494 3.78026e-05C1.13343 0.00231622 0.831177 0.107485 0.607741 0.292893C0.384306 0.478301 0.257567 0.729114 0.254821 0.991311C0.252076 1.25351 0.373543 1.50611 0.593062 1.69471L5.76656 5.98771L0.593062 10.2807C0.477962 10.373 0.386155 10.4833 0.322997 10.6053C0.259839 10.7273 0.226595 10.8585 0.225204 10.9913C0.223814 11.1241 0.254305 11.2558 0.314898 11.3787C0.375492 11.5016 0.464974 11.6132 0.578124 11.7071C0.691275 11.801 0.825826 11.8753 0.973929 11.9255C1.12203 11.9758 1.28072 12.0011 1.44073 12C1.60074 11.9988 1.75888 11.9712 1.9059 11.9188C2.05293 11.8664 2.18591 11.7902 2.29707 11.6947L8.32257 6.69471C8.5485 6.50718 8.67541 6.25288 8.67541 5.98771C8.67541 5.72255 8.5485 5.46824 8.32257 5.28071Z"
        fill="currentColor"
      />
    </svg>
  )
}

export default IconCaretRight

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-components/react/Listbox.tsx from the checkout-components VTEX app.

[Assistant]
Here's the implementation:

```tsx
import {
  ListboxInput as Input,
  ListboxInputProps as InputProps,
  ListboxButton as Button,
  ListboxButtonProps as ButtonProps,
  ListboxPopover as Popover,
  ListboxPopoverProps as PopoverProps,
  ListboxList as List,
  ListboxListProps as ListProps,
  ListboxOption as Option,
  ListboxOptionProps as OptionProps,
} from '@reach/listbox'
import classNames from 'classnames'
import React, { forwardRef } from 'react'
import { IconCaretDown } from 'vtex.styleguide'

import styles from './Listbox.css'

export const ListboxInput = forwardRef<HTMLDivElement, InputProps>(
  function ListboxInput({ className, ...props }, ref) {
    return (
      <Input {...props} ref={ref} className={classNames(className, 'w-100')} />
    )
  }
)

interface ListboxButtonProps
  extends ButtonProps,
    Omit<React.HTMLAttributes<HTMLSpanElement>, 'children'> {
  variation?: 'default' | 'plain'
}

export const ListboxButton: React.FC<ListboxButtonProps> = ({
  className,
  variation = 'default',
  arrow = (
    <div className="c-action-primary">
      <IconCaretDown />
    </div>
  ),
  ...props
}) => {
  return (
    <Button
      {...props}
      arrow={arrow}
      className={classNames(
        styles.button,
        className,
        'h-100 flex items-center bg-base c-on-base pv4 pv3-ns pl4 pr5 outline-0 pointer',
        { 'ba bw1 br2 b--muted-4 hover-b--muted-3': variation === 'default' }
      )}
    />
  )
}

export const ListboxPopover = forwardRef<
  HTMLElement,
  Omit<PopoverProps, 'unstable_observableRefs'>
>(function ListboxPopover({ className, ...props }, ref) {
  return (
    <Popover
      {...props}
      ref={ref}
      className={classNames(
        className,
        styles.popover,
        'bg-base pv3 mt2 br2 ba bw1 b--muted-4 asbolute outline-0'
      )}
    />
  )
})

export const ListboxList: React.FC<ListProps & { className?: string }> = ({
  className,
  ...props
}) => {
  return (
    <List
      {...props}
      className={classNames(className, 'bg-base list ma0 pa0 outline-0')}
    />
  )
}

const SelectedIcon: React.FC<React.SVGProps<SVGSVGElement>> = props => (
  <svg
    {...props}
    width="10"
    height="8"
    viewBox="0 0 10 8"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
  >
    <path
      d="M8.58484 0.234407L3.32991 5.48934L1.41516 3.57458C1.25767 3.42247 1.04673 3.3383 0.827788 3.34021C0.608842 3.34211 0.399402 3.42993 0.244579 3.58475C0.0897548 3.73958 0.00193415 3.94902 3.15668e-05 4.16796C-0.00187101 4.38691 0.0822967 4.59784 0.234407 4.75533L2.73954 7.26046C2.89613 7.41701 3.10849 7.50495 3.32991 7.50495C3.55134 7.50495 3.76369 7.41701 3.92029 7.26046L9.76559 1.41516C9.9177 1.25767 10.0019 1.04673 9.99997 0.827787C9.99806 0.608842 9.91024 0.399402 9.75542 0.244579C9.6006 0.0897547 9.39116 0.00193415 9.17221 3.15668e-05C8.95327 -0.00187101 8.74233 0.0822966 8.58484 0.234407Z"
      fill="currentColor"
    />
  </svg>
)

export const ListboxOption: React.FC<OptionProps & { className?: string }> = ({
  className,
  children,
  ...props
}) => {
  return (
    <Option
      {...props}
      className={classNames(
        className,
        styles.option,
        'flex items-center pointer bg-action-secondary pv3 pr7'
      )}
    >
      <SelectedIcon className={classNames(styles.selectedIcon, 'dn pl5 pr3')} />
      {children}
    </Option>
  )
}

export default {
  ListboxInput,
  ListboxButton,
  ListboxPopover,
  ListboxList,
  ListboxOption,
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-components/react/SelectedCard.tsx from the checkout-components VTEX app.

[Assistant]
Here's the implementation:

```tsx
import classnames from 'classnames'
import React, { ReactNode } from 'react'
import { IconDelete } from 'vtex.styleguide'

interface Props extends Omit<React.HTMLAttributes<HTMLDivElement>, 'title'> {
  title: ReactNode
  description?: ReactNode
  auxiliaryText?: ReactNode
  onDeselect?: () => void
}

const SelectedCard: React.VFC<Props> = ({
  onDeselect,
  title,
  description,
  auxiliaryText,
  ...props
}) => {
  return (
    <div
      {...props}
      className={classnames(
        props.className,
        'bg-muted-5 pa5 flex items-start lh-copy'
      )}
      role="option"
      aria-selected
    >
      <div className="flex w-100">
        <div className="flex flex-column">
          {title}
          {description}
        </div>
        {auxiliaryText}
      </div>
      <button
        className="flex-shrink-0 c-muted-1 ml5 pa2 flex items-center bg-transparent bn pointer self-start"
        onClick={onDeselect}
      >
        <IconDelete />
      </button>
    </div>
  )
}

export default SelectedCard

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-components/react/Listbox.css from the checkout-components VTEX app.

[Assistant]
Here's the implementation:

```css
:root {
  --reach-listbox: 1;
}

.option:not([aria-selected="true"]) {
  background-color: transparent;
}

.option:not([data-current=""]) {
  padding-left: 2.125rem;
}

.option[data-current=""] {
  padding-left: 0;
}

.option[data-current=""] .selectedIcon {
  display: block;
}

.popover {
  box-shadow: 0px 1px 16px rgba(46, 46, 46, 0.12);
}

.button [data-reach-listbox-arrow] {
  margin-left: auto;
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-components/react/GroupOption.tsx from the checkout-components VTEX app.

[Assistant]
Here's the implementation:

```tsx
import classnames from 'classnames'
import React, { Fragment } from 'react'
import { Divider } from 'vtex.styleguide'

import IconCaretRight from './IconCaretRight'
import styles from './GroupOption.css'
import { useListContext } from './ListGroup'

interface OptionProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  selected?: boolean
  caretAlign?: 'start' | 'center' | 'end'
  lean?: boolean
  isLast?: boolean
}

const GroupOption: React.FC<OptionProps> = ({
  className = '',
  onClick = () => {},
  children,
  selected = false,
  caretAlign = 'start',
  lean = false,
  isLast = false,
}) => {
  const borderPosition = useListContext()?.borderPosition ?? 'top'

  return (
    <Fragment>
      <button
        className={classnames(
          styles.groupOption,
          className,
          'w-100 tl pointer db lh-copy c-on-base bg-base hover-bg-action-secondary ph5 pv5-ns flex items-center justify-between bn',
          {
            pv4: !lean,
            pv3: lean,
          }
        )}
        onClick={onClick}
        role="option"
        aria-selected={selected}
      >
        {children}
        <span
          className={classnames(
            styles.caretWrapper,
            'c-action-primary ml5 inline-flex items-center',
            `self-${caretAlign}`
          )}
        >
          <IconCaretRight />
        </span>
      </button>
      {(!isLast || borderPosition === 'top') && (
        <div className="w-100 pr5 pr0-ns pl5">
          <Divider orientation="horizontal" />
        </div>
      )}
    </Fragment>
  )
}

export default GroupOption

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-components/react/package.json from the checkout-components VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "checkout-components",
  "private": true,
  "license": "UNLICENSED",
  "devDependencies": {
    "@types/classnames": "^2.2.10",
    "@types/node": "^13.13.1",
    "@types/react": "^16.9.34",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.124.3/public/@types/vtex.render-runtime",
    "vtex.styleguide": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.133.1/public/@types/vtex.styleguide"
  },
  "dependencies": {
    "@reach/listbox": "^0.10.2",
    "classnames": "^2.2.6",
    "react": "^16.13.1"
  },
  "version": "0.5.1"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-components/react/ListGroup.tsx from the checkout-components VTEX app.

[Assistant]
Here's the implementation:

```tsx
import classnames from 'classnames'
import React, { useContext, useMemo, createContext } from 'react'

interface ListContext {
  borderPosition: 'top' | 'bottom' | 'none'
}

const ctx = createContext<ListContext | undefined>(undefined)

export const useListContext = () => useContext(ctx)

const ListGroup: React.FC<{ borderPosition?: 'top' | 'bottom' | 'none' }> = ({
  children,
  borderPosition = 'top',
}) => {
  const context = useMemo(
    () => ({
      borderPosition,
    }),
    [borderPosition]
  )

  return (
    <div className="nh5 nh0-ns" role="group">
      <div
        className={classnames({
          'b--muted-4': borderPosition !== 'none',
          bt: borderPosition === 'top',
          bb: borderPosition === 'bottom',
        })}
      >
        <ctx.Provider value={context}>{children}</ctx.Provider>
      </div>
    </div>
  )
}

export default ListGroup

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-components/react/Modal.css from the checkout-components VTEX app.

[Assistant]
Here's the implementation:

```css
.modal :global(.vtex-modal__modal) {
  transition-property: top;
  transition-duration: 200ms;
  transition-timing-function: ease-in-out;
}

.open :global(.vtex-modal__modal) {
  top: 30%;
}

.closed :global(.vtex-modal__modal) {
  top: calc(100% - 2rem);
}

@media only screen and (max-width: 40em) {
  .modal :global(.vtex-modal__overlay) {
    animation-name: none !important;
  }

  .modal :global(.vtex-modal__modal) {
    opacity: 1 !important;
  }

  .modal :global(.vtex-modal__modal) {
    margin: 0;
    width: 100%;
    height: 70%;
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
    align-self: stretch;
  }
}

@media only screen and (min-width: 40em) {
  .modal :global(.vtex-modal__modal) {
    transition-property: opacity;
    top: auto;
  }

  .open :global(.vtex-modal__modal) {
    opacity: 1;
  }

  .closed :global(.vtex-modal__modal) {
    opacity: 0;
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-components/react/Modal.tsx from the checkout-components VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, {
  forwardRef,
  useRef,
  useLayoutEffect,
  useState,
  useEffect,
} from 'react'
import { Props as ModalProps } from 'vtex.styleguide/react/components/EXPERIMENTAL_Modal'
import { EXPERIMENTAL_Modal as StyleguideModal, utils } from 'vtex.styleguide'

import { useFadeEffect } from './hooks/useFadeEffect'
import styles from './Modal.css'

const Modal = forwardRef<
  HTMLDivElement,
  Omit<Partial<ModalProps>, 'container' | 'translate'>
>(function Modal(
  { isOpen = false, onClose = () => {}, children, title, ...props },
  forwardedRef
) {
  const [modalContainer] = useState(() => {
    const container = document.createElement('div')

    container.classList.add(styles.modal)

    document.body.append(container)

    if (isOpen) {
      container.classList.add(styles.open)
    } else {
      container.classList.add(styles.closed)
    }

    return container
  })

  useEffect(() => {
    return () => {
      document.body.removeChild(modalContainer)
    }
  }, [modalContainer])

  const [shouldRender, visible, fadeEffectRef] = useFadeEffect(isOpen)

  const containerRef = useRef<HTMLDivElement>(null)

  const ref = utils.useMergeRefs<HTMLDivElement | null>(
    fadeEffectRef,
    containerRef,
    forwardedRef
  )

  useLayoutEffect(() => {
    if (!containerRef.current) {
      return
    }

    if (visible) {
      modalContainer.classList.remove(styles.closed)
      modalContainer.classList.add(styles.open)
    } else {
      modalContainer.classList.remove(styles.open)
      modalContainer.classList.add(styles.closed)
    }
  }, [visible, modalContainer])

  if (!shouldRender) {
    return null
  }

  return (
    <StyleguideModal
      {...props}
      ref={ref}
      isOpen
      onClose={onClose}
      title={title}
      container={modalContainer}
    >
      {children}
    </StyleguideModal>
  )
})

export default Modal

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-components/react/GroupOption.css from the checkout-components VTEX app.

[Assistant]
Here's the implementation:

```css
.groupOption {
  min-height: 3.625rem;
}

@media only screen and (min-width: 40em) {
  .groupOption {
    min-height: 4.125rem;
  }
}

.optionDivider:last-of-type {
  display: none;
}

.caretWrapper {
  height: 1.5rem;
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-components/react/typings/css.d.ts from the checkout-components VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module '*.css' {
  const styles: { [key: string]: string }
  export default styles
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-components/react/typings/vtex.styleguide.d.ts from the checkout-components VTEX app.

[Assistant]
Here's the implementation:

```typescript
import React from 'react'

declare module 'vtex.styleguide' {
  const IconCaretRight: React.FC<any>

  const IconCaretDown: React.FC<any>

  const IconDelete: React.FC<any>
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of checkout-components/react/hooks/useFadeEffect.ts from the checkout-components VTEX app.

[Assistant]
Here's the implementation:

```typescript
import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useReducer,
  useRef,
} from 'react'

const TRANSITION_DURATION = 1000

interface State {
  isTransitioning: boolean
  shouldBeVisible: boolean
}

type Action = { type: 'start'; shouldBeVisible: boolean } | { type: 'finish' }

function reducer(state: State, action: Action) {
  switch (action.type) {
    case 'start':
      return { isTransitioning: true, shouldBeVisible: action.shouldBeVisible }
    case 'finish':
      return { isTransitioning: false, shouldBeVisible: state.shouldBeVisible }
    default:
      return state
  }
}

export const useFadeEffect = (visible: boolean) => {
  const elementRef = useRef<HTMLElement | null>(null)

  const [state, dispatch] = useReducer(reducer, {
    isTransitioning: false,
    shouldBeVisible: false,
  })

  const { isTransitioning, shouldBeVisible } = state

  const timeoutIdRef = useRef<ReturnType<typeof setTimeout> | null>(null)
  const rafIdRef = useRef<ReturnType<typeof requestAnimationFrame> | null>(null)

  useEffect(
    () => () => {
      if (timeoutIdRef.current != null) {
        clearTimeout(timeoutIdRef.current)
      }

      if (rafIdRef.current != null) {
        window.cancelAnimationFrame(rafIdRef.current)
      }
    },
    [timeoutIdRef]
  )

  const endTransition = useCallback(() => {
    dispatch({ type: 'finish' })

    if (timeoutIdRef.current != null) {
      clearTimeout(timeoutIdRef.current)
    }

    timeoutIdRef.current = null
  }, [])

  const startTransition = useCallback(
    (isVisible: boolean) => {
      if (rafIdRef.current != null) {
        window.cancelAnimationFrame(rafIdRef.current)
      }

      rafIdRef.current = window.requestAnimationFrame(() => {
        dispatch({ shouldBeVisible: isVisible, type: 'start' })

        rafIdRef.current = null

        if (timeoutIdRef.current != null) {
          clearTimeout(timeoutIdRef.current)
        }

        timeoutIdRef.current = setTimeout(endTransition, TRANSITION_DURATION)
      })
    },
    [endTransition]
  )

  const prevVisible = useRef(false)

  useLayoutEffect(() => {
    if (
      prevVisible.current !== visible &&
      (!visible || elementRef.current != null)
    ) {
      startTransition(visible)
    }

    prevVisible.current = visible
  }, [visible, startTransition])

  const ref = useCallback(
    <T extends HTMLElement>(node: T | null) => {
      const prevNode = elementRef.current
      elementRef.current = node

      if (node != null) {
        const handleTransitionEnd = (evt: Event) => {
          if (evt.target !== node) {
            return
          }

          endTransition()
        }

        node.addEventListener?.('transitionend', handleTransitionEnd)
        node.addEventListener?.('webkitTransitionEnd', handleTransitionEnd)

        if (prevVisible.current === true) {
          startTransition(true)
        }
      } else if (prevNode != null) {
        const handleTransitionEnd = (evt: Event) => {
          if (evt.target !== prevNode) {
            return
          }

          endTransition()
        }

        prevNode.removeEventListener?.('transitionend', handleTransitionEnd)
        prevNode.removeEventListener?.(
          'webkitTransitionEnd',
          handleTransitionEnd
        )
      }
    },
    [endTransition, startTransition]
  )

  const shouldShow = isTransitioning || shouldBeVisible || visible

  return [shouldShow, shouldBeVisible, ref] as const
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/messages/pt.json from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "editor.base-store-component.title": "IO Base App",
  "editor.base-store-component.description": "Um componente de demonstração para apps do VTEX IO",
  "editor.base-store-component.title.title": "Título",
  "editor.base-store-component.title.description": "Especifique um título personalizado",
  "base.title": "Olá, Mundo!!",
  "base.change-value": "Troque seu valor: {value}"
}
```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/messages/en.json from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "editor.base-store-component.title": "IO Base App",
  "editor.base-store-component.description": "A demo component for IO apps",
  "editor.base-store-component.title.title": "Title",
  "editor.base-store-component.title.description": "Specify a custom title",
  "base.title": "Hello, World!!",
  "base.change-value": "Change your value: {value}"
}
```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/messages/context.json from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "editor.base-store-component.title": "Title of IO Base App component",
  "editor.base-store-component.description": "Description of IO Base App component",
  "editor.base-store-component.title.title": "Title of title property",
  "editor.base-store-component.title.description": "Description of title property",
  "base.title": "Base title message to be shown when title is not provided via CMS",
  "base.change-value": "Text to be shown beside input component typed value"
}
```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/messages/es.json from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "editor.base-store-component.title": "IO Base App",
  "editor.base-store-component.description": "Un componente de demostración para aplicaciones IO.",
  "editor.base-store-component.title.title": "Título",
  "editor.base-store-component.title.description": "Especifique un título personalizado",
  "base.title": "¡Hola Mundo!",
  "base.change-value": "Cambia tu valor: {value}"
}
```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/docs/README.md from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```markdown
📢 Use this project, [contribute](https://github.com/vtex-apps/locale-switcher) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->

# Locale Switcher

The Locale Switcher app provides a component capable of changing the current language of your store.

![img-locale-switcher](https://user-images.githubusercontent.com/27777263/74359290-c2b5f700-4da1-11ea-8612-c05ccf1988d5.png)

## Configuration

1. Add the Locale Switcher app to your theme's dependencies in the `manifest.json` file:

```diff
 "dependencies": {
+  "vtex.locale-switcher": "0.x"
 }
```

2. Add the `locale-switcher` block to your header. For example:

```jsonc
"header-row#desktop": {
  "children": [
    // (...)
    "locale-switcher",
    "login",
    "minicart.v2"
  ]
},
```

3. Open a ticket to our support team in order to adjust your store's binding with the desired languages.

> ⚠ ***Caution:** The third step is mandatory. If no ticket is opened requiring the desired languages, the selection list may not appear on the Locale Switcher component.*

## Customization

In order to apply CSS customizations in this and other blocks, follow the instructions given in the recipe on [Using CSS Handles for store customization](https://vtex.io/docs/recipes/style/using-css-handles-for-store-customization).

| CSS Handles         |
| :-----------------: |
| `button`            |
| `buttonText`        |
| `container`         |
| `list`              |
| `listElement`       |
| `localeIdText`      |
| `relativeContainer` |

## Contributors ✨

Thanks goes to these wonderful people:

<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->

This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/react/LocaleSwitcher.tsx from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React, { useState } from 'react'
import { Spinner } from 'vtex.styleguide'
import { SupportedLanguage } from 'langs'
import { IconGlobe } from 'vtex.store-icons'
import { useCssHandles } from 'vtex.css-handles'
import { useRuntime, Culture } from 'vtex.render-runtime'

import getLabel from './modules/getLabel'
import LocaleSwitcherList from './components/LocaleSwitcherList'

const CSS_HANDLES = [
  'list',
  'button',
  'container',
  'buttonText',
  'listElement',
  'localeIdText',
  'loadingContainer',
  'relativeContainer',
] as const

function parseToSupportedLang({ language, locale }: Culture) {
  return {
    text: getLabel(language),
    localeId: locale,
  }
}

const LocaleSwitcher: React.FC = () => {
  const { culture, emitter } = useRuntime()
  const [open, setOpen] = useState(false)
  const [shouldRenderList, setShouldRenderList] = useState(false)
  const [changingLocale, setChangingLocale] = useState(false)

  const [selectedLocale, setSelectedLocale] = useState(
    parseToSupportedLang(culture)
  )
  const handles = useCssHandles(CSS_HANDLES)

  const handleLocaleClick = (newLang: SupportedLanguage) => {
    setSelectedLocale(newLang)
    emitter.emit('localesChanged', newLang.localeId)
    setChangingLocale(true)
    setOpen(false)
  }

  const handleClick = () => {
    setOpen(!open)

    if (!shouldRenderList) {
      setShouldRenderList(true)
    }
  }

  const containerClasses = `${handles.container} w3 flex items-center justify-end ml2 mr3 relative`
  const buttonClasses = `${handles.button} link pa0 bg-transparent bn flex items-center pointer mr3 c-on-base`
  const buttonTextClasses = `${handles.buttonText} pl2 t-action--small order-1`

  return (
    <div className={containerClasses}>
      <div className={`${handles.relativeContainer} relative`}>
        <button
          onClick={handleClick}
          className={buttonClasses}
          onBlur={() => setOpen(false)}
        >
          {!changingLocale ? (
            <>
              <IconGlobe />
              <span className={buttonTextClasses}>{selectedLocale.text}</span>
            </>
          ) : (
            <Spinner handles={handles} size={26} />
          )}
        </button>
        {shouldRenderList && (
          <LocaleSwitcherList
            open={open}
            onItemClick={handleLocaleClick}
            selectedLocale={selectedLocale}
          />
        )}
      </div>
    </div>
  )
}

export default LocaleSwitcher

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/react/package.json from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "scripts": {
    "test": "vtex-test-tools test",
    "lint": "tsc --noEmit && eslint --ext ts ."
  },
  "dependencies": {
    "@vtex/css-handles": "^1.0.0",
    "classnames": "^2.2.6",
    "ramda": "^0.26.1",
    "react": "^16.8.3",
    "react-intl": "3.9.1",
    "react-dom": "^16.8.3",
    "react-apollo": "^3.0.0"
  },
  "devDependencies": {
    "@types/classnames": "^2.2.7",
    "@types/graphql": "^14.2.0",
    "@types/jest": "^24.0.11",
    "@types/node": "^11.13.0",
    "@types/ramda": "^0.26.5",
    "@types/react": "^16.8.10",
    "@types/react-intl": "^2.3.17",
    "@vtex/test-tools": "^0.2.0",
    "apollo-client": "^2.5.1",
    "prettier": "^1.16.4",
    "typescript": "3.8.3"
  },
  "version": "0.5.6"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/store/interfaces.json from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "locale-switcher": {
    "component": "LocaleSwitcher"
  }
}
```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/react/typings/storefront.d.ts from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { FunctionComponent } from 'react'

declare global {
  interface StorefrontFunctionComponent<P = {}> extends FunctionComponent<P> {
    getSchema?(props: P): object
    schema?: object
  }

  interface StorefrontComponent<P = {}, S = {}> extends Component<P, S> {
    getSchema?(props: P): object
    schema: object
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/react/typings/vtex.css-handles.d.ts from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.css-handles' {
  export function useCssHandles<ClassKey extends string = string>(
    handles: readonly ClassKey[]
  ): Record<ClassKey, string>
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/react/typings/vtex.render-runtime.d.ts from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```typescript
/* eslint-disable func-names */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* Typings for `render-runtime` */
declare module 'vtex.render-runtime' {
  import { Component, ComponentType, ReactElement, ReactType } from 'react'

  export interface NavigationOptions {
    page: string
    params?: any
  }

  export interface RenderContextProps {
    runtime: {
      navigate: (options: NavigationOptions) => void
    }
  }

  interface ExtensionPointProps {
    id: string
    [key: string]: any
  }

  export const ExtensionPoint: ComponentType<ExtensionPointProps>

  interface ChildBlockProps {
    id: string
  }

  export interface Culture {
    availableLocales: string[]
    locale: string
    language: string
    country: string
    currency: string
  }

  interface RenderContext {
    culture: Culture
    emitter: any
  }

  export const ChildBlock: ComponentType<ChildBlockProps>
  export const useChildBlock = function({ id: string }): object {}

  export const Helmet: ReactElement
  export const Link: ReactType
  export const NoSSR: ReactElement
  export const RenderContextConsumer: ReactElement
  export const canUseDOM: boolean
  export const useRuntime: () => RenderContext
  export const withRuntimeContext: <TOriginalProps extends {}>(
    Component: ComponentType<TOriginalProps & RenderContextProps>
  ) => ComponentType<TOriginalProps>
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/react/typings/langs.d.ts from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'langs' {
  export interface SupportedLanguage {
    text: string
    localeId: string
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/react/typings/vtex.store-icons.d.ts from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.store-icons' {
  export const IconGlobe: React.FC
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/react/typings/css.d.ts from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```typescript
/* eslint-disable @typescript-eslint/no-explicit-any */
declare module '*.css' {
  const css: any
  export default css
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/react/typings/graphql.d.ts from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module '*.gql' {
  import { DocumentNode } from 'graphql'

  const value: DocumentNode
  export default value
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/react/typings/vtex.styleguide.d.ts from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```typescript
/* eslint-disable @typescript-eslint/no-explicit-any */
declare module 'vtex.styleguide' {
  import { ComponentType } from 'react'

  export const Input: ComponentType<Props>
  export const Spinner: ComponentType<Props>

  interface Props {
    [key: string]: any
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/react/components/LocaleSwitcherList.tsx from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { useQuery } from 'react-apollo'
import { SupportedLanguage } from 'langs'
import { useCssHandles } from 'vtex.css-handles'

import Spinner from './Spinner'
import getLabel from '../modules/getLabel'
import LOCALES from '../graphql/locales.gql'
import getSupportedLangs from '../modules/getSupportedLangs'

interface Props {
  open?: boolean
  selectedLocale: SupportedLanguage
  onItemClick: (selectedLang: SupportedLanguage) => void
}

interface LocalesQuery {
  languages: {
    default: string
    supported: string[]
  }
  currentBinding: {
    supportedLocales: string[]
  } | null
}

function getLocale(supportedLangs: SupportedLanguage[], locale: string) {
  const localeObj = supportedLangs.find(
    ({ localeId }) => getLabel(localeId) === getLabel(locale)
  )

  return (
    localeObj ??
    (supportedLangs?.[0] || {
      text: getLabel(locale),
      localeId: locale,
    })
  )
}

const CSS_HANDLES = [
  'list',
  'listElement',
  'localeIdText',
  'loadingContainer',
] as const

export default function LocaleSwitcherList(props: Props) {
  const { open = false, onItemClick, selectedLocale } = props
  const handles = useCssHandles(CSS_HANDLES)
  const { data, loading, error } = useQuery<LocalesQuery>(LOCALES)

  const supportedLanguages =
    data?.currentBinding?.supportedLocales ?? data?.languages?.supported ?? []
  const supportedLangs = getSupportedLangs(supportedLanguages)

  if (loading && open) {
    return <Spinner handles={handles} />
  }

  if (error || supportedLangs.length === 0) {
    return null
  }

  const handleItemClick = (id: SupportedLanguage['localeId']) => {
    onItemClick(getLocale(supportedLangs, id))
  }

  const listClasses = `${handles.list} absolute z-5 list top-1 w3 ph0 mh0 mt4 bg-base`
  const listElementClasses = `${handles.listElement} t-action--small pointer f5 pa3 hover-bg-muted-5 tc`

  return (
    <ul hidden={!open} className={listClasses}>
      {supportedLangs
        .filter(({ localeId }) => localeId !== selectedLocale.localeId)
        .map(({ localeId, text }) => (
          // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
          <li
            // eslint-disable-next-line jsx-a11y/no-noninteractive-element-to-interactive-role
            role="link"
            tabIndex={-1}
            key={localeId}
            className={listElementClasses}
            onClick={() => handleItemClick(localeId)}
            onKeyDown={() => handleItemClick(localeId)}
            onMouseDown={e => e.preventDefault()}
          >
            <span className={`${handles.localeIdText} w-100`}>{text}</span>
          </li>
        ))}
    </ul>
  )
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/react/components/Spinner.tsx from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { Spinner } from 'vtex.styleguide'
import classnames from 'classnames'

interface Props {
  handles: Record<string, string>
}

export default function Loading(props: Props) {
  const { handles } = props

  const classes = classnames(
    handles.loadingContainer,
    'absolute z-5 list top-1 pa6 mh0 mt4 bg-base flex items-center justify-center'
  )

  return (
    <div className={classes}>
      <Spinner color="currentColor" size={26} />
    </div>
  )
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/react/graphql/locales.gql from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```graphql
query Locales {
  languages @context(provider: "vtex.messages") {
    default
    supported
  }
  currentBinding @context(provider: "vtex.tenant-graphql") {
    supportedLocales
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/react/modules/getLabel.ts from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```typescript
export default function getLabel(localeId: string) {
  return localeId.split('-')[0]
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of locale-switcher/react/modules/getSupportedLangs.ts from the locale-switcher VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { SupportedLanguage } from 'langs'

import getLabel from './getLabel'

export default function getSupportedLangs(langs: string[]) {
  return langs.reduce((acc: SupportedLanguage[], lang: string) => {
    if (!lang.includes('-')) {
      return acc
    }

    return acc.concat({
      text: getLabel(lang),
      localeId: lang,
    })
  }, [])
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of list-context/docs/README.md from the list-context VTEX app.

[Assistant]
Here's the implementation:

```markdown
# List Context

<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->

[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)

<!-- ALL-CONTRIBUTORS-BADGE:END -->

The List Context app creates lists of product images that can be added, reordered, or deleted via Site Editor. This app aims to be used with other apps to create new interfaces that use the context of product images. For example: `list-context.image-list`, implemented by `vtex.store-image`, and `list-context.product-list`, implemented by `vtex.product-summary`.

The only interface exposed by `vtex.list-context` is `list-context`, which is supposed to be extended by other apps that want to implement this architecture.

## Setting up the `list-context-renderer`

The `list-context-renderer` is a block that renders the list present in the `list-context`.

1. Import the `vtex.list-context` app to your theme's dependencies in the `manifest.json`;

```json
  "dependencies": {
    "vtex.list-context": "0.x"
  }
```

2. Add the block `list-context-renderer` as a children of a `list-context` block. For example:

```json
{
  "list-context.product-list#demo1": {
    "blocks": ["product-summary.shelf"],
    "children": ["list-context-renderer#wrapped"],
    "props": {
      "orderBy": "OrderByTopSaleDESC"
    }
  },
  "list-context-renderer#wrapped": {
    "props": {
      "listElement": "ul",
      "itemElement": "li"
    }
  }
}
```

| Prop name     | Type     | Description                                                              | Default value |
| ------------- | -------- | ------------------------------------------------------------------------ | ------------- |
| `listElement` | `String` | HTML element used to render the list (ex: `div`, `ul`, etc)              | `Fragment`    |
| `itemElement` | `String` | HTML element used to render the items of the list (ex: `div`, `li`, etc) | `Fragment`    |
## Creating a new list-context

To extend `list-context` interface and create a new list, follow the next steps:

1. Choose the app you want to implement the `list-context`.

2. In you store theme code, go to the `store` folder and in `interfaces.json` file, declare a new interface.

```json
  "list-context.image-list": {
    "component": "ImageList",
    "composition": "children",
    "allowed": "*",
    "content": {
      "properties": {
        "images": {
          "$ref": "app:vtex.store-image#/definitions/Images"
        }
      }
    }
  }
```

> ⚠
>
> We recommend to use `"composition": "children"` for this new interface so that you can compose it with other `list-context` interface.

3. Implement the React component to be rendered by this interface. In the example below we are using the `ImageList` for example:

```typescript
import { useListContext, ListContextProvider } from 'vtex.list-context'

(...)

const ImageList: StorefrontFunctionComponent<Props> = ({
  images,
  height = 420,
  children,
}) => {
  const { isMobile } = useDevice()
  const { list } = useListContext() || []

  const imageListContent = images.map(
    ({ link, image, mobileImage, description }, idx) => (
      <Image
        key={idx}
        src={isMobile && mobileImage ? mobileImage : image}
        alt={description}
        link={link}
        maxHeight={height}
        width="100%"
      />
    )
  )

  const newListContextValue = list.concat(imageListContent)

  return (
    <ListContextProvider list={newListContextValue}>
      {children}
    </ListContextProvider>
  )
}

(...)
```

>
>
> Notice that this app exports a React hook and a React component: `useListContext` and `<ListContextProvider />`. Also notice that this component should wrap its `children` a new `<ListContextProvider />` containing the new list which you just appended to.

## Adding a schema to the `list-context`

To edit the `list-context` app via Site Editor, add a `schema` to the component that you have chosen. In the example below, we are using the `ImageList` component, so we are using the `ImageList` schema:
```tsx
ImageList.schema = {
  title: messages.title.id,
  description: messages.description.id,
  type: 'object',
  properties: {
    images: {
      type: 'array',
      title: 'admin/editor.image-list.images.title',
      items: {
        properties: {
          image: {
            $ref: 'app:vtex.native-types#/definitions/url',
            default: '',
            title: 'admin/editor.image-list.images.image.title',
            widget: {
              'ui:widget': 'image-uploader',
            },
          },
          mobileImage: {
            $ref: 'app:vtex.native-types#/definitions/url',
            default: '',
            title: 'admin/editor.image-list.images.mobileImage.title',
            widget: {
              'ui:widget': 'image-uploader',
            },
          },
          description: {
            $ref: 'app:vtex.native-types#/definitions/text',
            default: '',
            title: 'admin/editor.image-list.images.description.title',
          },
          link: {
            default: '',
            title: '',
            $ref: 'app:vtex.native-types#/definitions/link',
          },
        },
      },
    },
    height: {
      default: 420,
      enum: [420, 440],
      isLayout: true,
      title: messages.heightTitle.id,
      type: 'number',
    },
  },
}
```

## Contributors ✨

Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):

<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->

<!-- ALL-CONTRIBUTORS-LIST:END -->

This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!

```